r/pinescript • • 21h ago

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

4 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 • • 21h 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 • • 1d 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 • • 1d ago

MOR stddev Indicator

Post image
9 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 • • 1d ago

TradingView, Is This Really Fair to Basic Users? Let me make one thing clear: I have no problem with TradingView offering paid subscriptions or giving premium users extra features. That's their business, and they have every right to do so. But does that mean Basic users should face unnecessary res

Thumbnail gallery
1 Upvotes

r/pinescript • • 1d ago

TradingView’s October update: live earnings calls, AI crypto screening, Desktop tab groups, and more

Thumbnail
reddit.com
1 Upvotes

r/pinescript • • 2d 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.


r/pinescript • • 2d ago

Feature Request: Expanding the 500 Future Bar Drawing Limit (xloc.bar_index) in Pine Script v6

Post image
2 Upvotes

Dear TradingView Support Team,

I am writing to submit a feature request regarding the current line and label drawing limitations in Pine Script, specifically concerning projectable drawing limits into future bars using xloc.bar_index.

Currently, Pine Script imposes a strict hard limit of 500 bars when drawing lines into the future beyond the current real-time bar (bar_index + 500).

While developing advanced long-term projection tools—such as 4-cycle Gann Boxes (e.g., 4 x 144 = 576 bars) and multi-timeframe geometric cycle models—we frequently run into this 500-bar ceiling. To prevent scripts from failing or throwing runtime rendering errors, developers currently have to implement complex custom math algorithms to dynamically calculate slopes and clip lines at bar_index + 490.

While these workarounds keep the scripts functional, they restrict full structural visualization for long-term strategic cycle analysis.

If technically feasible within your rendering pipeline and engine architecture, we kindly request the following enhancements in upcoming Pine Script updates:

  1. Increased Future Bar Projection Limit: Expanding the future bar drawing limit beyond 500 bars (e.g., to 1,000 bars or higher, especially for premium/pro tier users).
  2. Dynamic Limit Option: Providing a configurable parameter or native function in line.new() that allows drawing to project uninterruptedly across long timeframes without requiring manual line-clipping logic.

Thank you for your continuous dedication to improving Pine Script and supporting the developer community.


r/pinescript • • 2d ago

Whats this supposed to mean?

Post image
1 Upvotes

r/pinescript • • 3d ago

ta.* calls inside if blocks, ternaries and v6 "and"/"or": why the result drifts, and the CW10003 warning

2 Upvotes

If you've ever seen "The function ... should be called on each calculation for consistency" and ignored it, this is what it's actually warning about.

Local scopes don't get a history entry on every bar

Pine commits a value to a series' historical buffer only when the scope containing it is evaluated on the bar's closing tick. Global variables get a new entry on every bar, so x[1] always means "one bar ago". Code inside an if, a loop, a function body, or the unused branch of a ternary may not run on a given bar, and then nothing gets committed for that bar.

Per the docs (Execution model > Time series in scopes), [] on a local series therefore means "last committed value as of N bars back", not "value from N bars back". If the scope last ran 10 bars ago, localVar[1] through localVar[9] all return that 10-bar-old value.

Function parameters count as local too: each call site has its own buffer for its arguments, even when you pass a global like close.

Same thing applies to built-ins

Anything in ta.* that looks at past values internally (ta.sma, ta.rsi, ta.ema, ta.crossover, ...) keeps its own history of the source you pass. Call ta.sma(close, 20) only on bars where some condition is true and you get an average of the last 20 calls, not the last 20 bars. It compiles fine and looks plausible on the chart, which is why it's easy to miss.

The v6 trap: lazy and / or

In v5, and/or evaluated both operands every time. In v6 they short-circuit. The migration guide's own example: if close > open and ta.rsi(close, 14) > 50 gave correct RSI values in v5, but in v6 ta.rsi is skipped whenever close > open is false, so its internal history has gaps and the values are wrong. A script ported from v5 can change behavior with no compile error. The ternary ?: was already lazy in v5, so cond ? ta.sma(close, 20) : na has the same problem in both versions.

The fix is boring

Evaluate history-dependent calls once per bar in the global scope, store the result, and use the variable in your conditions:

  • rsi = ta.rsi(close, 14) then if close > open and rsi > 50
  • sma = ta.sma(close, 20) then cond ? sma : na
  • Same for your own functions that use [] on a parameter.

Lazy evaluation is still useful where you want to skip work, e.g. array.size(a) > 0 and array.first(a) > 0 no longer throws on an empty array in v6. The rule of thumb is just: guards can be lazy, anything with memory can't.

A couple of edge cases I'd like to hear how people handle: loops that call a history-dependent function per iteration (one buffer per call site, so iterations overwrite each other), and switch arms that each call a different ta.* function. Do you precompute every variant globally, or restructure some other way?


r/pinescript • • 3d ago

Go back!

Thumbnail reddit.com
1 Upvotes

I pay good money for Trading View. The recent updates to the Phone app are terrible. The timeframe and stock swipe left and right are a terrible idea. Also, the horizontal screen size got smaller. It wasn’t broken, are you just looking for reasons to screw it up? Go back or tell me how to get the older version back.


r/pinescript • • 3d ago

Sonar battery squeeze indicator freebie

Thumbnail
gallery
11 Upvotes

r/pinescript • • 3d ago

Go back!

Thumbnail reddit.com
1 Upvotes

r/pinescript • • 3d ago

An Open Letter to Management: Forcing Free Users Out is a Terrible Strategy

Thumbnail reddit.com
1 Upvotes

r/pinescript • • 4d ago

Hundreds of indicators were contributed by the community free of charge

Thumbnail reddit.com
3 Upvotes

r/pinescript • • 4d ago

Wow wtf. New Low for Tradingview. New restriction this morning

Post image
11 Upvotes

r/pinescript • • 4d ago

Tradingview has HORRIBLE CUSTOMER SERVICE communications.

Thumbnail reddit.com
1 Upvotes

r/pinescript • • 4d ago

Why does a good 1D strategy fall apart on 1m or 5m?

3 Upvotes

A lot of the time the logic isn't the problem. The costs are.

A simple way to see it is to compare a typical move with what one trade costs you.

On my BTC chart, ATR(14) on the daily is about 3% of price. On the 1m it's about 0.08%. If a round trip costs around 0.1% in fees and slippage, that's a small part of a daily move, but more than an entire typical 1m move.

So the same rules that capture, say, a fifth of the typical move can be profitable on the daily and below zero on the 1m. That's also why so many low-timeframe backtests look great with zero costs and go flat or negative once you add them.

Before tuning anything on a low timeframe, I'd check how big the average move is compared to the costs. If costs eat a big part of it, more optimization won't fix it.


r/pinescript • • 4d ago

Subject: Extremely Disappointed with the New 30 Drawing Limit on the Free Plan Dear TradingView Team, I am extremely disappointed with the new 30-drawing limit on the Free Plan. TradingView has been an essential platform for my daily market analysis. I use multiple drawings to mark important mark

0 Upvotes

r/pinescript • • 4d ago

The settings I check before I believe a Pine backtest (including the July strategy changes)

1 Upvotes

I used to trust the strategy report a lot more than I should have. [One line of your own here: the strategy or setting that fooled you.]

These days I go through the same short list before I get excited about any result. Posting it in case it saves someone a bad week, and because I'd like to know what I'm still missing.

Fees first. Commission and slippage are zero unless you set them, and for anything that trades often that's the whole result. I set both, then run it again at double the commission. If it only works at the cheap number, it doesn't work.

Then fills. By default your order fills at the next bar's open, which is honest. Filling on the same bar's close looks better and is a price you mostly couldn't have had. Since July this lives under "Order execution delay" in Properties; process_orders_on_close still sets the default.

History and live don't run the same way. On past bars your script runs once per bar; live, with calc_on_every_tick, it runs on every tick. That gap is where a lot of "it worked in the tester" comes from. The new calc_on_every_history_tick closes some of it if you're on Premium or Ultimate.

Watch request.security(). Higher-timeframe data with lookahead on and no offset hands your script tomorrow's close. If you use lookahead_on, offset by one bar:

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

Heikin Ashi will lie to you. Orders fill at prices that never traded. Test on a standard chart, or set fill_orders_on_standard_ohlc=true (now "Heikin Ashi mode").

And size. 100% of equity with compounding makes almost any curve look steep. I start with a small fixed fraction so I'm looking at the strategy and not the leverage.

Where I start from:

//@version=6

strategy("Honest defaults", overlay=true,

initial_capital=10000,

default_qty_type=strategy.percent_of_equity,

default_qty_value=10,

commission_type=strategy.commission.percent,

commission_value=0.05,

slippage=2,

process_orders_on_close=false,

calc_on_every_tick=false,

use_bar_magnifier=true,

fill_orders_on_standard_ohlc=true)

None of this proves a strategy is good. It just stops the settings from flattering it.

The one I still don't have a clean answer for is walk-forward testing, since Pine can't hold data back. How are you all handling that?


r/pinescript • • 5d ago

Session and time filters in Pine: exchange time zone vs chart time zone, and why "UTC-5" drifts twice a year

2 Upvotes

A common source of "my session filter is off by an hour" reports is mixing up the three time contexts Pine actually uses.

1. Timestamps are zone-agnostic. time, time_close and the values returned by time() are UNIX milliseconds since 1970-01-01 UTC. They don't carry a time zone; the zone only matters when you turn them into calendar fields or text.

2. Calendar variables use the exchange time zone. hour, dayofweek, month etc. are always expressed in syminfo.timezone, and every time function with a timezone parameter defaults to that same exchange zone.

3. The chart time zone is invisible to the script. The "Timezone" setting on the chart only changes how the axis and Pine Logs prefixes display time. Scripts can't read it. So if you switch the chart to your local zone and your hour == 9 filter "moves", it didn't move; it was never in your zone. If you want users to think in their own zone, expose a timezone input and pass it explicitly.

Session strings

time(timeframe.period, "0930-1600:23456", tz) returns a timestamp only for bars inside the session and na outside it, so not na(time(...)) is the usual in-session test. The timezone argument defines the zone of the session string itself (the returned timestamp is still plain UTC ms). Leave it out and the session is read in the exchange zone, which is easy to forget when you're copying a "London open" window onto a crypto or US symbol.

UTC offsets vs IANA names

"UTC-4" / "GMT+0100" are fixed offsets. "America/New_York" / "Europe/London" follow DST and historical rule changes. The docs show it directly: hour(time, "UTC-4") matches New York only during DST and is off by one hour the rest of the year, while hour(time, "America/New_York") is always right. For anything defined by a real market's local clock, IANA names are the safer default. Also note that two regions don't switch DST on the same date, so the offset between, say, New York and Sydney changes more than once a year.

Overnight sessions

For symbols whose session spans two calendar days (FX is the docs' example: the "Monday" EURUSD session starts Sunday 17:00 exchange time), dayofweek on early bars still says Sunday. time_tradingday gives the 00:00 UTC timestamp of the trading day the session belongs to, which is usually what you want for "one trade per day" or daily resets. For "new day / new month" detection, timeframe.change("1D") or ta.change(time("1D")) > 0 tends to be cleaner than comparing calendar fields.

Quick checklist when a time filter looks wrong:

  • Which zone is the session string in? (Explicit timezone, or exchange zone by default?)
  • Fixed offset or IANA name?
  • Is the chart zone fooling your eyes?
  • Does the session cross midnight?

Curious how people handle multi-market session windows (e.g. London + NY overlap) on 24/7 crypto symbols: one time() call per window with explicit IANA zones, or something else?


r/pinescript • • 4d ago

Highest profit in one day only from NSE Cash Market

1 Upvotes

My highest profit in one day only from NSE Cash Market. The actual broker gross profit is slightly (around ₹100 less).


r/pinescript • • 5d ago

Script to put broker account summary on bottom bar instead so it can be visible at all times

Thumbnail
reddit.com
1 Upvotes