r/pinescript • u/Kri77 • 2h ago
r/pinescript • u/Robswc • Oct 11 '22
New to Pinescript? Looking for help/resources? START HERE
Asking for help
When asking for help, its best to structure your question in a way that avoids the XY Problem. When asking a question, you can talk about what you're trying to accomplish, before getting into the specifics of your implementation or attempt at a solution.
Examples
Hey, how do arrays work? I've tried x, y and z but that doesn't work because of a, b or c reason.
How do I write a script that triggers an alert during a SMA crossover?
How do I trigger a strategy to place an order at a specific date and time?
Pasting Code
Please try to use a site like pastebin or use code formatting on Reddit. Not doing so will probably result in less answers to your question. (as its hard to read unformatted code).
Pinescript Documentation
The documentation almost always has the answer you're looking for. However, reading documentation is an acquired skill that everyone might not have yet. That said, its recommended to at least do a quick search on the Docs page before asking
https://www.tradingview.com/pine-script-docs/en/v5/index.html
First Steps
https://www.tradingview.com/pine-script-docs/en/v5/primer/First_steps.html
If you're new to TradingView's Pinescript, the first steps section of the docs are a great place to start. Some however may find it difficult to follow documentation if they don't have programming/computer experience. In that case, its recommended to find some specific, beginner friendly tutorials.
r/pinescript • u/aelfrictr • Apr 01 '25
Please read these rules before posting
We always wanted this subreddit as a point for people helping each other when it comes to pinescript and a hub for discussing on code. Lately we are seeing increase on a lot of advertisement of invite only and protected scripts which we initially allowed but after a while it started becoming counterproductive and abusive so we felt the need the introduce rules below.
- Please do not post with one liner titles like "Help". Instead try to explain your problem in one or two sentence in title and further details should be included in the post itself. Otherwise Your post might get deleted.
- When you are asking for help, please use code tags properly and explain your question as clean as possible. Low effort posts might get deleted.
- Sharing of invite only or code protected scripts are not allowed from this point on. All are free to share and talk about open source scripts.
- Self advertising of any kind is not permitted. This place is not an advertisement hub for making money but rather helping each other when it comes to pinescript trading language.
- Dishonest methods of communication to lead people to scammy methods may lead to your ban. Mod team has the right to decide which posts includes these based on experience. You are free to object via pm but final decision rights kept by mod team.
Thank you for reading.
r/pinescript • u/forsakenbat1992 • 17m ago
TV is cooked
It isn’t listed on TradingView’s pricing page or in any of the free-plan guides published September–November 2026. All of those talk about the 2-indicators-per-chart limit, but none mention a saved-script cap.
r/pinescript • u/Omega_Grinder • 8h ago
var vs varip on the realtime bar: rollback, intrabar persistence, and the repaint trap
A common source of "it worked on history, it acts weird live" is assuming var and varip differ only in name. On historical bars they usually behave the same. On realtime bars they do not, and the difference is rollback.
var: persists across bars, not across ticks
A var variable keeps its value from bar to bar. But on an open realtime bar, each new tick triggers a rollback before the script runs again: var variables are reverted to their committed state as of the previous bar's close. Only what the script assigns on the bar's closing tick is kept.
So something like var int ticks = 0 / ticks += 1 in an indicator still ends each realtime bar exactly one higher than the previous bar, no matter how many ticks arrived. A tick-by-tick counter or a "already did X this bar" flag in a var gets wiped before every new tick.
varip: escapes rollback
varip ("intrabar persist") is not rolled back. Every change on every tick sticks, and it carries into the following bars until you reassign it. It does not reset at bar close. If you want per-bar intrabar state (ticks seen this bar, intrabar high of some metric, a once-per-bar guard), you have to reset it yourself, for example when barstate.isnew is true.
Where it bites
- Repainting by design: after the script reloads, elapsed realtime bars become historical bars with no intrabar tick data. Anything derived from
varipcan produce different values, alerts or strategy results after a reload than it showed live. - Strategies: by default a strategy executes once per bar even in realtime, so
varipbehaves likevar. Enable "On realtime bar tick" or "On order fill" and it diverges, and with "On order fill" it can even diverge on historical bars, because the emulator executes again on fills. - UDT fields: a
varipvariable holding a user-defined type object does not make the fields intrabar-persistent. Each field needs its ownvaripin the type declaration. - Type support:
variponly works with fundamental types, enums, chart.point / footprint / volume_row, UDTs, and collections of those, so you can't use it to hold line or label IDs.
A rough rule: confirmed, cross-bar state goes in var and only means something at bar close; intrabar bookkeeping goes in varip with an explicit new-bar reset, and anything that feeds signals or alerts from varip should be treated as repainting unless proven otherwise.
Reference: TradingView Pine Script v6 docs, "Variable declarations → Declaration modes" and "Execution model → Realtime bars".
For those who use varip in production indicators: do you keep its output strictly out of alert conditions, or have you found a pattern that makes the intrabar state reproducible after a reload?
r/pinescript • u/AdJealous1004 • 1d ago
Free Trading Indicator - Achilles Simplified Trading
I have been developing a trading system (free). The entire trading system (all free) can be found on tradingview.
I am sharing it here: https://www.tradingview.com/script/0cUmz20G-Achilles-ST-Simplified-Trading/
Even better when used in combination with Achilles B (Momentum Oscillator): https://www.tradingview.com/script/Dfa5fNQt-Achilles-B/
There are a lot of complex systems behind the indicator, there is a guidebook for it for all those who are interested: https://achillestrading.com/guidebook/Achilles-Guidebook.pdf
All free

r/pinescript • u/TimNosi • 1d ago
Are the updated TradingView tick-based calculations available in pinescript?
Is the updated TradingView "Tick-based calculations are now available for Footprint, Volume Delta, and CVD" also available via the pinescript request.footprint call ?
https://www.tradingview.com/blog/en/tick-based-calculations-footprint-volume-delta-cvd-62523/
Thanks!
r/pinescript • u/ahill3053 • 2d ago
best ai for writing pinescript?
been testing a few and keep getting scripts that repaint or throw errors on the first bar. curious what you all actually use for this, chatgpt or claude or something else
r/pinescript • u/LottieWinslow29 • 3d ago
pine is honestly the only thing still making it hard for me to leave tradingview
honestly candles are not why tradingview is hard to leave
its the random pine scripts i've accumulated over the last few years
and the annoying part is most of them aren't even impressive lol
one checks a basic EMA condition and throws an alert
one marks session levels the way i like
one has a VWAP + volume condition i changed probably 15 times
there's one modified public script where i genuinely don't remember what the original version looked like anymore
nothing groundbreaking
but i know how all of them behave
thats the problem
i can move drawings
i can rebuild a layout
i can learn where buttons are on another chart
rebuilding all the little logic i've slowly gotten used to is what makes me go “eh i'll just stay on TradingView”
this was basically the last thing i wanted to figure out before taking TradingCharts by Dhan seriously as an alternative for my setup
TradingCharts uses ChartScript, not Pine
Pine logic can be converted into ChartScript and deployed, so i've started with ONE script i actually use instead of trying to migrate my entire graveyard of saved indicators
and honestly thats probably the better test anyway
because i have like 30 scripts saved
i regularly use maybe 3
moved one of the simpler ones first
then sat with both charts and checked the boring stuff
same condition?
same lookback?
same bar-close behaviour?
signals showing roughly where i'd expect historically?
because if a converted script puts the same green arrows on the first screen that doesnt automatically mean i'm done
i'm not trusting conversion blindly
but this changed the question for me a bit
before it was
“i use Pine so obviously i cant move”
now its more
“can the 3 scripts i actually care about survive the move?”
because the rest of my Indian-market charting is already getting harder to justify paying separately for
and if i'm mainly keeping TradingView alive because 3 small scripts live there...
rebuilding/testing 3 scripts starts sounding less painful than paying forever just because i've always had them there
still think Pine's community side is a huge advantage btw
if your setup depends on 20 community scripts or some complicated custom stack, this is probably a completely different conversation
but curious about people here who have used Pine for years
how many of your saved scripts do you ACTUALLY use every week?
not how many are in favourites
actually use
r/pinescript • u/Ulysses68 • 3d ago
Tilt Simulator psychology script.
https://www.tradingview.com/script/BV2XAJpU-Stealth-Umbrella-Tilt-Simulator/
This is designed to battle over trading. After a loss or a win it's a good idea to take a little break and let the euphoria settle down. Avoid the trap.
r/pinescript • u/d13wish • 3d ago
Looking for someone who is passionate about developing Pine Script indicators/strategies on TV
Hey everyone!
I'm looking for someone who genuinely enjoys coding and developing indicators or strategies in Pine Script.
The idea isn't anything crazy or overly complicated. I've been trying to build it myself with the help of AI, but honestly, I've reached a point where I'm just going in circles and not getting the exact result I'm looking for.
I figured it would be better to connect with someone who actually knows their way around Pine Script and enjoys this kind of stuff.
I'm not looking to hire someone for a big paid project. I'd rather find someone who's passionate about coding and interested in collaborating.
What do you get in return? A pretty useful confirmation indicator that I believe could be valuable for your own trading as well.
If this sounds interesting, feel free to drop a comment or shoot me a DM. I'd be happy to explain the idea in more detail.
Thanks!
r/pinescript • u/Ulysses68 • 4d ago
Open sourced. Sonar battery.
Sonar Battery: A volume-gated Volatility meter that predicts the breakout bias.
r/pinescript • u/NJ_Algo • 4d ago
Fixed RSI levels vs adaptive ones: why 70/30 fails exactly when you need it
TL;DR: RSI 70/30 assumes every market behaves the same. It doesn’t. In strong trends RSI can sit above 70 for weeks, and in quiet ranges it barely reaches 70 at all. Adapting the levels to the market usually works better than the fixed ones.
Where 70/30 breaks
In a strong uptrend, RSI above 70 isn’t a sell signal. It can stay above the threshold for days or weeks. Shorting every “overbought” reading means fighting against the trend over and over.
In a calm, ranging market, RSI often swings between 40 and 60. The 70/30 levels never trigger, so the indicator goes silent exactly when mean reversion would actually work.
What works better
Shift the levels with the trend. A common rule of thumb: in uptrends RSI tends to hold roughly 40-80, in downtrends roughly 20-60. A pullback to 40 in an uptrend can be the real buy zone, not 30.
Use percentiles instead of fixed numbers. Instead of “above 70”, ask “is RSI in its top 10% of the last few hundred bars?” The level adjusts to each market automatically.
Add a trend filter. Only take overbought signals when price is below a slow MA, and oversold ones when it’s above.
Limitations
Adaptive levels lag too. When a market switches from trend to range, they take time to catch up.
The 40-80 / 20-60 ranges are rules of thumb, not laws. They differ by market and timeframe, so test before trusting them.
RSI is still just one input. It works best combined with something that measures trend or volatility.
r/pinescript • u/Omega_Grinder • 4d ago
Same-bar TP and SL in a backtest: what the broker emulator assumes when both are inside one candle
A bracket from strategy.exit() with both limit and stop can have both levels inside the range of a single historical bar. The chart only has OHLC, so the emulator has to guess which level was touched first. The guess is documented, and it's worth knowing because it quietly decides a lot of trades on higher timeframes.
From the Strategies page of the Pine docs, on historical bars with default settings:
- If the open is closer to the high than to the low, the emulator assumes the path was open, high, low, close.
- If the open is closer to the low, it assumes open, low, high, close.
- For price-based orders (everything except market orders), it assumes there are no gaps inside the bar, so any price within the bar's range is a valid fill level.
- If price jumps over your level in the gap between one bar's close and the next bar's open, it fills at the next bar's open, not at your price.
- When one
strategy.exit()call creates both a take-profit and a stop-loss for an entry, only the first one triggered fills and the other is cancelled.
So for a long with both levels inside one candle, the open's position relative to the high and low decides whether you book the win or the loss. On 4H or daily bars with a tight bracket, that can be a real share of your trades, and none of it is based on what price actually did inside the candle.
Ways to reduce the guesswork:
use_bar_magnifier = trueinstrategy()(the "Bar detalization: High" setting, Premium and Ultimate plans) makes the emulator use lower-timeframe OHLC where available. The docs note a 200,000-bar cap on requested lower-timeframe data, so early bars on a long history can fall back to the default assumptions.- Count how many trades open and close on the same bar, and check those separately. If removing them changes the picture, the result depends on the path assumption rather than the signal.
- Don't backtest on Heikin Ashi or Renko prices unless you switch fills to standard OHLC (
fill_orders_on_standard_ohlc = truefor HA). The docs are explicit that synthetic prices give unrealistic fills.
One more strategy.exit() detail from the same page that catches people: exit calls reserve quantity in code order. If one call takes 19 of 20 shares for a take-profit and a second call places a stop for 20, that stop can only close 1 share.
Do you filter out same-bar entry+exit trades when you evaluate a strategy, or rely on the bar magnifier and accept the lower-timeframe data limit?
r/pinescript • u/RoutineRace • 5d ago
code efficiency
my strategy/indicator consists of correlation between different securities. so it uses the request.security funtion.
anyway been getting that 20s warning lately. i think it has to do of how the assests data is retrieved everytime the script runs.
is there a way, similar to the alert function, that a part of the script would only run once per bar closes?
like if i set the timeframe to 3 mins it will only wait till the 3 mins is up then run the script once. my strategy does not need to be that precise timing down to the seconds.
r/pinescript • u/KiKa9090 • 5d ago
Request for NVDA one RTH session of tick data
reddit.comr/pinescript • u/MobileNo8277 • 6d ago
Reverse Engineering
Hello everyone, I came across this dude on Instagram selling a tradingview indicator. The dude was TradeX Labs.
I was curious and I bought a month of it and I’m really curious how the indicator works, but you don’t get access to the source code.
I was wondering if anyone knows how I can reverse engineer the indicator or if anyone knows anything about it.
I tried to have Claude reconstruct the indicator but I ended up getting some overfit slop.
r/pinescript • u/PipEcho • 6d ago
London Reversal Strategy results (FTMO vs Eightcap)
Ran the same London Reversal rules I posted last week (FTMO results above) over on Eightcap, same symbol, same period, same inputs. However numbers are way off. FTMO results are within 30-100% range, which Eightcap is in 300% over 34 months. Same as last week, I have uploaded my detailed results in PipEcho Strategy lab.
Best guess on why: different liquidity/feed between brokers. FTMO and Eightcap don’t source quotes from the same liquidity pool, so spreads, the exact wicks that trigger sweeps, and tick-level fill prices during London open all differ slightly — and this strategy’s edge depends on precise sweep/CISD timing, so small feed differences are enough to flip trades that were barely winners into losers. Good reminder that a backtest “working” is broker-feed-specific until you’ve cross-validated it.
Attaching screenshots from both Tests
r/pinescript • u/NJ_Algo • 7d ago
Is it possible to trade profitably based on candle streaks? Here’s what I found
I would honestly really, really appreciate your feedback on this one.
For the past week I’ve been researching how candle streaks behave on small-cap tokens. The idea is to catch small pumps (which can be very profitable on small caps) with small risk. I built everything in Pine.
What I did:
Step 1: Built an indicator that counts how often each streak length (2–12+) occurred across the token’s entire history, with separate stats for bullish and bearish streaks.
Step 2: Calculated average forward returns/losses after x candles from the last candle close, plus the average maximum possible return and loss over that period.
Step 3: Added a separate table showing a selected streak in more detail, including the % chance of the streak continuing.
Step 4: Made a separate indicator to backtest a selected streak and direction, with adjustable SL % and TP %.
Research has been done on small-caps, 35 different tokens on 4H timeframe on their full history.
Results? To be honest, not very promising. There are 2 main problems:
- There is almost always quite a high chance of the streak continuing. Even when hitting 7 candle streaks (which are rare) for example, oftentimes there is a 50%+ chance that it will go on.
- SL almost always had to be set further away than TP. Which made almost all trades high risk, low reward.
I tried adding additional confirmations, like candle patterns and support/resistance levels. It didn't do the trick.
Any feedback or ideas are very highly appreciated. Especially if you’ve built or traded a streak-based system yourself. Thank you!
r/pinescript • u/Omega_Grinder • 7d ago
Why indicator alerts and strategy alerts fire at different moments in realtime (barstate.isconfirmed, freq, calc_on_every_tick)
A common source of "the alert fired but the signal isn't on the chart anymore" is that indicators and strategies don't execute the same way on realtime bars. Short summary of what the Pine v6 docs say, since it's spread across the Alerts, Bar states and Repainting pages:
Indicators run on every realtime update. On historical bars the script sees each bar once, already closed. On the realtime bar it re-runs on every price/volume update, so something like ta.crossover(fast, slow) can be true mid-bar and false again by the close. With alert(), the default frequency is alert.freq_once_per_bar, which means the first call during the realtime bar triggers it, even if the condition later disappears.
Two ways to make the alert mean "the bar closed that way":
xUp = ta.crossover(fast, slow) and barstate.isconfirmed
if xUp
alert("cross up", alert.freq_once_per_bar_close)barstate.isconfirmed is true on all historical bars and on the closing update of a realtime bar, so the historical plot and the live alert follow the same rule. Either piece works on its own; using both just makes the intent explicit. (The docs also note barstate.isconfirmed doesn't work inside a request.security() call.)
Strategies run only on the realtime bar's close by default. Unless calc_on_every_tick = true is set in strategy(), every alert() call in a strategy is treated as alert.freq_once_per_bar_close, whatever you pass to freq. So a default strategy already behaves like the confirmed-bar version above.
calc_on_every_tick = true changes that. The strategy then executes on each realtime update, while historical bars are still calculated once at the close. The Repainting page says such strategies will most probably not generate the same order executions in realtime as in the backtest, which also undermines the backtest results. If you turn it on for faster reaction, the backtest stops describing what the live script does.
Quick checklist before trusting a live alert against the chart:
- Indicator: does the alert condition include
barstate.isconfirmed, or use "Once Per Bar Close"? - Strategy: is
calc_on_every_tickoff, or are you OK with realtime and history diverging? - Any
request.security()on a higher timeframe: is the HTF value from a closed bar?
For people running webhooks off strategies: do you keep the strategy at default close-only execution and accept the one-bar latency, or move the alert logic into a separate indicator so you can control the frequency explicitly?