r/pinescript • • Oct 11 '22

New to Pinescript? Looking for help/resources? START HERE

32 Upvotes

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 • • Apr 01 '25

Please read these rules before posting

22 Upvotes

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 • • 17m ago

I built a free Pine Script v5/v6 editor that runs in the browser, no account. Which built-ins do you miss?

1 Upvotes

I built this, so read it as a builder asking for feedback and not as a neutral review.

It's a Pine Script editor: https://sidechair.trading/pine?ref=rd-pinescript

You open the page and you're in the editor next to an ES 5m chart. There's no login. Write a script, hit Add to chart, and it plots. Change an input, hit Update on chart, and it redraws.

What works today:

  • v5 and v6. v4 and older don't compile.
  • Errors show while you type, with line and column. Misspell a function and you get Error at 3:6 Could not find function or function reference 'ta.smaa' before you run anything.
  • strategy() scripts compile and draw their entries on the chart.
  • A reference with 700+ pages. Examples on those pages open in the editor and run.
  • It works on a phone.

What doesn't, so you don't lose time on it:

  • It isn't a TradingView clone and it doesn't run everything. Some built-ins still return na, mostly in syminfo.* and request.*, plus footprint.*, volume_row.* and a few in box.*, label.* and chart.*. The docs list them.
  • Signed out, ES is 10 minutes delayed.
  • Signed out, your scripts stay in that browser. A free account is only there to save them across devices.

What I'd like to know: which built-ins would you need before you could paste in one of your own scripts and have it run? If you try one and it breaks, the function name or the error text is all I need.


r/pinescript • • 18h ago

Fib retracement is where its at!

Post image
16 Upvotes

https://www.tradingview.com/script/wq9Pib49-STRYK-SESSION-SWEEP-MSS/ this my indicator if you wanna know what im using. Draw a fib retracement tool levels 1,.80,.75,.70,.60,.55,.50,.45,.40,.30,.25,.20, 0 then toggle off .75 .50 .25 remove background change upper and lower ranges red and center ranges yellow then draw the tool on any pivot, then notice how price reacts to them thank me later


r/pinescript • • 23h ago

Unpopular take: Price structure sets up before the news drops—and Golden Ratio math might explain part of it

2 Upvotes

Hey fellow traders and developers,

Across 8+ years of building and automating trading strategies in Pine Script, one conviction has only grown stronger for me: there are underlying mechanics behind price action and bar flow that most of us barely scratch the surface of.

I’m not talking about EMAs or lagging formulas that follow price. I’m talking about the hidden rules that price itself follows—mathematical expressions of human psychology, crowd behavior, and collective reaction.

Old-school traders have always said that if you truly know how to read a chart, you can see the move setting up before the news even drops. The longer I’ve been in this space, the more I believe that—price structure often anticipates the catalyst rather than just reacting to it.

So hear me out: what about the Golden Ratio (0.618 / 1.618)?

This proportion shows up everywhere in nature and geometry. If it’s woven into natural systems and human behavior, I believe it’s imprinted into market charts too—not just as a static Fib tool drawn by hand, but as a deeper structural framework that, if properly harnessed, could anticipate key turning points before they fully unfold. I’m currently deep in research testing how to model that systematically in Pine Script.

Curious to hear from both traders and devs here: have you ever uncovered a hidden rule, pattern, or mathematical quirk in the charts that completely changed how you see price movements?

This should be an interesting thread.


r/pinescript • • 21h ago

Maximum Adverse Excursion Disappeared please bring it back

1 Upvotes

That’s a clear feature suggestion: add Maximum Adverse Excursion beside closed profit or loss in Replay Trading’s trade history. I can’t confirm how many other users have requested it, but our suggested place for feature requests is the TradingView Reddit community.

Also, please make Market Replay default to opening on the trade history. There, one could see the profit or loss of the closed trade, and one could see the maximum adverse excursion and maximum favorable excursion right there, like it was before.

Understood—you’re asking for both Maximum Adverse Excursion and Maximum Favorable Excursion to be restored in Replay Trading’s trade history, alongside closed profit or loss, since they were there before. Our Help Center points feature requests to the TradingView community on Reddit.

That’s a second clear request: have Replay Trading open on Trade history by default, rather than Orders or Positions. You can include it with your request to restore the Maximum Adverse and Favorable Excursion columns. Our suggested place for feature requests is the TradingView community on Reddit.

Sources:

IT USED TO BE THAT WY WHY WOULD THEY CHANGE IT


r/pinescript • • 1d ago

Squeeze indicator. With phone alerts. https://www.tradingview.com/script/jSoHDxka-Stealth-Umbrella-Sonar-Battery/

Thumbnail
gallery
15 Upvotes

r/pinescript • • 1d ago

Any webhook trading options left for EU users?

Thumbnail reddit.com
1 Upvotes

r/pinescript • • 1d ago

RSI 30/70 won 2 of every 3 trades on ETH over 9 years and still lost money. I tested it on 5 coins.

Thumbnail gallery
1 Upvotes

It won at least half its trades on every coin, but lost money on 3 of 5 and beat holding only on XRP.


r/pinescript • • 2d ago

Win rate means nothing on its own

1 Upvotes

TL;DR: Win rate only tells you half the story. You need it together with average win vs average loss, and the break-even point moves a lot depending on that ratio.

A lot of strategies get shared here with a big win rate in the title. The problem is that win rate on its own can't tell you if a strategy makes money.

The win rate you need to break even depends on your reward:risk. The formula is simple: break-even win rate = 1 / (1 + R), where R is average win divided by average loss.

At 1:1 you need 50%. At 2:1 you only need about 33%. At 1:3 (winning 1, losing 3) you need 75% just to break even.

Two examples:
47% win rate at 2:1 → profit factor about 1.77, roughly +0.41R per trade.
70% win rate at 1:3 → profit factor about 0.78. It loses money while looking great on the win rate line.

A high win rate isn't bad on its own. It just only works when the average loss stays close to the average win.

Costs make this worse for high win rate systems. They usually have small targets, so a fixed fee and slippage eat a much bigger share of each win than on a 2:1 or 3:1 system.

Limitations: average win and loss aren't fixed numbers, they move with the market. On a small sample the win rate itself can be way off, so I wouldn't trust any of these numbers with under about 100 trades. And a low win rate system has long losing streaks that are hard to sit through, even if the math works.


r/pinescript • • 2d ago

Карты Таро для трейдеров от TradingView

Thumbnail
ru.tradingview.com
0 Upvotes

r/pinescript • • 2d ago

request.security() on a 24/7 symbol from a US stock chart is one day late (BTCUSD vs SPY correlation: 0.03, IBIT: 0.50)

1 Upvotes

Ran into this while building a correlation matrix and it's easy to miss, so writing it up.

On a SPY (or any US stock/ETF) daily chart, request.security("BITSTAMP:BTCUSD", timeframe.period, close) doesn't return the BTC close of the same day. A crypto daily bar closes at 00:00 UTC, about three hours after the US close, and with the default lookahead_off Pine only uses another symbol's bar once it has closed. So on day D you get BTC's close from day D-1.

Nothing errors and the series looks fine on the chart, but anything built on daily returns quietly breaks. Over the last year, daily-return correlation with SPY:

  • BTCUSD: 0.03
  • IBIT (spot bitcoin ETF, trades US hours): 0.50
  • IBIT vs BTCUSD: 0.18, for what is essentially the same asset

I checked it outside TradingView too: aligning BTC to the same calendar day gives ~0.47 against SPY, shifting BTC back one day gives ~0.03.

Workarounds that worked for me:

  • Use a US-listed proxy that trades the same session (IBIT for bitcoin).
  • Measure correlation on weekly returns, where a one-day offset matters much less.

Worth checking for any symbol whose daily bar closes after your chart symbol's session.


r/pinescript • • 3d ago

Golden Cross on 9 years of BTC: +623% with fees, but buy-and-hold did +1,155% (script included)

Thumbnail gallery
1 Upvotes

r/pinescript • • 3d ago

PO3, CISD, FVG Set.

Post image
7 Upvotes

Estou utilizando estes indicadores que encontrei principalmente no Github através das traderskills diversas disponíveis na plataforma, é muito bom saber que por trás dos Scripts sempre existem pessoas com boas intenções de compartilhar seus trabalhos gratuitamente sem cobrarem por mensalidades ou compra única por um preço absurdo. Sem palavras

Estou me familiarizando com esses conceitos e estou gostando muito, vejo muitos comentários depreciativos sobre esses conceitos, porém ao testarmos percebi uma grande oportunidade de utilizar essas ferramentas ao meu favor, acho muito interessante como todos os textos e vídeos que assitir estão todos os dias detalhados na tela do meu celular e PC é como um dejavu de todos os conteúdos assistidos.


r/pinescript • • 4d ago

Integrate options chain data

2 Upvotes

As a futures trader I would love to see the options chain data available in pinescript so I can model GEX levels and show the open interest ladder. Is this something that's on the roadmap?


r/pinescript • • 7d ago

building a Pine script... logic failure

5 Upvotes

I'm trying to build a "flip-flop level" indicator, where the script would look for the peak low, retested by a peak high, but...

My knowledge of Pine is below minimal.
Thus, I rely on google assistance, and, its logic is failing me by only looking at 5 bars behind, 5 bars ahead.

Truth is, I find that limiting such a search to just a number of bars defeats the logic.

Any ideas, please?


r/pinescript • • 7d ago

Three reasons your Pine backtest looks better than reality — and the exact lines to check

5 Upvotes

I've been going through public strategies for a while now. The same three bugs show up again and again, and all three make the equity curve look better than it can possibly be.

  1. request.security() that leaks the future

// leaks: you are reading a bar that had not closed yet

htfClose = request.security(syminfo.tickerid, "D", close)

The default is barmerge.lookahead_off, so this one is usually fine on its own. The problem starts when people copy a snippet that passes lookahead_on explicitly, or when they write close[1] inside the call "to avoid repainting" — which does the opposite of what they think on historical bars.

// correct: last COMPLETED higher-timeframe bar, no leak

htfClose = request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on)

Yes — lookahead_on together with close[1] is the correct combination. It looks backwards. That is the whole point.

2. Signal on the close, fill on the close

strategy.entry() fills at the open of the next bar by default. If your entry condition uses close and you assume you got that price, you are buying at a price you could not have known when the decision was made. On a fast 5m or 15m signal this alone can turn a losing system into a "profitable" one.

Check: you did not set process_orders_on_close = true, and your entry price in the list of trades matches the next bar's open, not the signal bar's close.

3. No costs at all

If commission_type and slippage are unset, TradingView assumes zero. A strategy that fires 40 times a month on a 15m chart pays 40 × (spread + commission) whether or not you model it.

strategy("x",

commission_type = strategy.commission.percent,

commission_value = 0.05,

slippage = 2)

Those three explain most of the gap between backtest and reality. What's left is repainting: barstate.isconfirmed never checked, ta.* called inside an if block so it only updates on some bars, calc_on_every_tick = true.

If you want a second pair of eyes: paste the relevant part of your script in the comments (or DM me) and I'll tell you which of these I'd check first. No charge, no link, nothing to buy — I'm just trying to find out how often each one actually shows up in the wild.


r/pinescript • • 9d ago

4 exact reasons profitable PineScript strategies diverge when ported to MT5 (MQL5)

5 Upvotes

Porting a TradingView PineScript strategy to MetaTrader 5 looks straightforward until the MT5 backtest or live demo starts taking different trades than the TradingView chart. Almost every parity mismatch I have traced comes from four structural differences between the two engines.

  1. Bar-close evaluation in Pine vs intra-bar tick reads in MQL5 By default, PineScript evaluates conditions on bar close (unless calc_on_every_tick is enabled). A very common bug when translating to MQL5 is reading CopyBuffer() or price arrays at index 0 inside OnTick(). That evaluates an unfinished candle on every tick, triggers early entries that disappear before the bar closes, and creates heavy live divergence. Clean parity requires detecting a new bar via iTime(_Symbol, tf, 0) and reading every indicator buffer and OHLC value strictly at shift >= 1.
  2. Indicator math is not always identical between TradingView and MT5 Even with the same period length, several built-in functions differ under the hood. Pine's ta.rsi() and ta.atr() use Wilder's RMA smoothing, whereas some MT5 custom ports accidentally substitute EMA or SMA. Pine's ta.stdev() uses population standard deviation (dividing by N) by default, while some MQL5 implementations use sample standard deviation (N - 1). Before trusting any converted EA, export 20 to 30 closed-bar values from TradingView and compare them side by side against the MQL5 buffer values at shift=1.
  3. Chart-price fills vs real Bid/Ask spreads and rollover widening TradingView backtests fill long and short orders off the single chart price stream with a flat slippage setting unless you manually model spread. In MT5, buys open at Ask and close at Bid, while sells open at Bid and close at Ask. Strategies with tight stops or small targets that look fine on TradingView often degrade once real ECN commissions and 00:00 server rollover spread spikes hit the MT5 fills.
  4. Broker execution rules and Hedging vs Netting position logic PineScript never rejects an order for broker constraints. In live MT5, an EA will silently drop entries or exits if it ignores SYMBOL_TRADE_STOPS_LEVEL, SYMBOL_TRADE_FREEZE_LEVEL, OrderCalcMargin(), or the broker's supported filling mode (ORDER_FILLING_FOK, IOC, or RETURN). Account mode also matters: Pine's pyramiding and reversal rules behave differently when mapped to an MT5 Hedging account (separate position tickets) versus a Netting account (single aggregated position per symbol).

If you have ported Pine strategies to MT5, which mismatch gave you the hardest time to track down: indicator math (RMA/stdev/bar history) or live Bid/Ask execution differences?


r/pinescript • • 9d ago

Volume bubbles: trading buyer/seller absorption

1 Upvotes

Do you have any experience trading with indicators that highlight unusually large buy/sell volume? That's basically what volume bubbles are.

I've been backtesting a strategy based on absorption of either side. When price is going up, a large buy bubble appears, but price fails to hold that level and a big wick forms. That's my long/short signal.

Entry: the level of the bubble.
SL: discretionary, based on previous support/resistance zones or volume profile key levels.
TP: same logic as SL, at least 2R.

This type of strategy seems to have some potential, but it definitely needs improvement.

I'd appreciate any advice or ideas. If you've tried coding absorption in Pine, how did you define it?


r/pinescript • • 9d ago

strategy() defaults that quietly shape a backtest: zero commission, zero slippage, touch-fills on limits, 1:1 margin

2 Upvotes

A lot of "why does my backtest look so much better than live" questions come down to properties nobody set. Here is what the current v6 docs say the broker emulator does when you leave the strategy() declaration alone, and what each setting actually changes.

Commission: none by default. If you don't pass commission_type and commission_value, every fill is free. You can model a flat fee per order, a fee per contract/share/lot/unit, or a percentage of the transaction value. Cost scales with trade count, so high-turnover strategies are the ones most distorted by leaving this at zero.

Slippage: 0 ticks by default. slippage is a fixed number of ticks applied in the unfavorable direction (higher fills for longs, lower for shorts). Because it is constant, the docs point out it can push simulated fills outside the candle's range, so piling on slippage makes results unrealistically worse rather than more honest. Pick a value you can justify for the instrument's tick size and liquidity.

Limit orders: touch = fill by default. backtest_fill_limits_assumption defaults to 0, meaning a limit order fills as soon as price reaches its level. Setting it to N requires price to move N ticks beyond the level before the order fills. The "Limit order execution" input in Settings/Properties can override it. Strategies built on limit entries near local extremes are the most sensitive to this, since a level that was only touched is exactly where a real queue may not have filled you.

Margin: 100% by default (1:1). margin_long and margin_short default to 100; lower values show up as the "Long/Short leverage" inputs. If available funds drop below the required margin, the emulator generates a margin call and liquidates four times the quantity needed to cover the loss, to avoid repeated margin calls on the following bars. strategy.margin_liquidation_price returns the price at which that would trigger. The docs also flag margin below about 0.2% (leverage above 500:1) as typically unrealistic, and 0% as equivalent to infinite leverage.

Pyramiding: 1 by default. Repeated strategy.entry() calls in the same direction won't add to an open position until you raise pyramiding. One documented exception: if several strategy.entry() calls create limit, stop or stop-limit orders on the same tick, the emulator fills each one that price triggers, which can exceed the limit.

Order size: qty beats the defaults. A non-na qty in strategy.entry() or strategy.order() ignores default_qty_type / default_qty_value. Pass na when you want the default size to apply.

The declaration is only a default. All of the above can be overridden in Settings/Properties. When comparing your numbers with a published strategy, check the publication's "Properties" tab first: it lists the initial capital, order size, leverage, pyramiding, commission and slippage the author used.

A simple habit that helps: set commission, slippage and the limit-fill assumption explicitly in the declaration, even with rough first guesses, so the zero-cost case is a choice rather than an accident.

For those running limit-order strategies: do you use backtest_fill_limits_assumption = 1, or something larger tied to the instrument's typical spread?

Reference: TradingView Pine Script v6 docs, Concepts > Strategies (sections on commission, slippage and unfilled limits, margin and leverage, pyramiding, position sizing).


r/pinescript • • 10d ago

MOR stddev Indicator

Post image
11 Upvotes

Encontrei este indicador que gera sinais e a 3 semana ele vem alcançando todos os alvos da abertura de 00:00 NY vocês o conhecem ?


r/pinescript • • 10d ago

Reproducing a closed-source TradingView indicator's 3 levels (high, mid, low) from a 4H window

1 Upvotes

I'm trying to reproduce the behavior of a closed-source TradingView indicator that draws 3 horizontal levels (high, mid, low) from a 4H window. I can read the levels from the chart for given days and timeframes, but I can't see the source. Fixed grids (Murrey Math) and standard pivot indicators did not match. Has anyone modeled this kind of rule (which bars define the window, how the mid is computed) or know open-source scripts that behave similarly? Any pointers welcome.