Hi HLF!
This is an interesting goal that I've tried in the past but was unable to figure out a solution... until today haha.
Your question reminded me of a recent blog post I read on the TradingView website which explained a new feature that the team recently added to Pine which finally makes this possible.
Normally each new tick resets everything you're doing in your script, and "var" only saves your data across each bar on your chart, not each tick. But the TV team recently added a new variable type called "varip" which does
not reset on each new tick.
Here's the blog post:
What's New in Pine?
And here's some code which will do exactly what you are trying to do. This code will count price ticks (the blue column) and volume changes (the purple histogram). Keep in mind that a new bar tick is detected by Pine whenever price OR volume changes, so if you want to count price movement ticks vs trades executed at a given price, this is how you do it:
Code: Select all
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading / www.PineScriptMastery.com
// @version=4
study("Tick Counter")
// Prepare tick counter variables (varip makes them persistent on real-time bar)
varip ticks = 0
varip volumeChanges = 0
varip lastPrice = close
// Check if price has changed (price tick)
if barstate.isrealtime and lastPrice != close
ticks := ticks + 1
lastPrice := close
// Check if volume has changed (trade executed at current price)
if barstate.isrealtime and lastPrice == close
volumeChanges := volumeChanges + 1
// Reset counters on each new bar
if barstate.isnew
ticks := 0
volumeChanges := 0
lastPrice := close
// Draw data to chart
plot(ticks, style=plot.style_columns, title="Price Ticks")
plot(volumeChanges, style=plot.style_histogram, color=color.purple, title="Volume Ticks")
Have fun, good luck with your coding & trading, and thanks for reminding me of this new feature as I'm sure it'll come in handy for my own scripts someday!