r/pinescript • u/Admirable-Try7766 • 10d ago
r/pinescript • u/Omega_Grinder • 11d ago
ta.* calls inside if blocks, ternaries and v6 "and"/"or": why the result drifts, and the CW10003 warning
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)thenif close > open and rsi > 50sma = ta.sma(close, 20)thencond ? 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 • u/Hungry_Chapter_2804 • 11d ago
Go back!
reddit.comI 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 • u/the_McManager • 11d ago
I built two automated stock & options screeners running on $0/mo infrastructure (Python + GitHub Actions + Vercel)
>I kept paying for bloated finance screeners or spending 30+ minutes a morning digging through option chains and SEC filings manually, so I automated two lightweight scanners running on Python + GitHub Actions + Vercel + Resend:
Would love feedback on the UI, scoring logic, or which filters/metrics you'd want next!
r/pinescript • u/NubiaGCoronelHdz • 12d ago
An Open Letter to Management: Forcing Free Users Out is a Terrible Strategy
reddit.comr/pinescript • u/LoserForever666 • 12d ago
Hundreds of indicators were contributed by the community free of charge
reddit.comr/pinescript • u/Wayward_Prometheus • 13d ago
Wow wtf. New Low for Tradingview. New restriction this morning
r/pinescript • u/JWhalen1953 • 12d ago
Tradingview has HORRIBLE CUSTOMER SERVICE communications.
reddit.comr/pinescript • u/NJ_Algo • 13d ago
Why does a good 1D strategy fall apart on 1m or 5m?
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 • u/jeevandahal • 13d ago
The settings I check before I believe a Pine backtest (including the July strategy changes)
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 • u/Omega_Grinder • 13d ago
Session and time filters in Pine: exchange time zone vs chart time zone, and why "UTC-5" drifts twice a year
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 • u/santanudas2002 • 13d ago
Highest profit in one day only from NSE Cash Market
r/pinescript • u/Foreign_Canary_6391 • 13d ago
Script to put broker account summary on bottom bar instead so it can be visible at all times
r/pinescript • u/secondhalfsoftware • 13d ago
Indicator I use as an alarm clock
r/pinescript • u/Stunning_Extreme_343 • 15d ago
tradingview在错误的道路上越走越远了
作为一个运行了这么多年的专业交易平台,不去思考如何让更多专业交易员选择平台,相反,却将更多潜在的优质客户推的更远——我这里指的不仅仅是Basic用户,更多的是各类型的付费用户。
数据的及时性、指标数量和运行速度及对开发者的限制、UI的稀烂设计......太多问题了。我都怀疑他们目前的内部运营是不是出了问题?为什么让不做交易或者不懂交易的人,负责这些决策?
r/pinescript • u/QuePasa168 • 15d ago
Feature Request: Global Drawing Synchronization Groups Across Multiple Layouts
reddit.comr/pinescript • u/NickKofo • 17d ago
Free Pinescript backtester you can hand to AI agents to auto-tune your strategy
We got tired of changing one input, waiting, testing, changing another, so we built PineStorm. You paste your Pine strategy and it backtests it on the whole Binance history.
• Full history, from the first candle, 1m to 1w
• Fast: 2.5 million 1-minute candles in about a second
• Auto-tune: hand it to Claude Code or Codex and it tunes your inputs for you. One run did 1,344 backtests in 28 minutes.
It's free, and you can try it right in the browser. Crypto only for now. Would love to hear what you think and what you'd want added.
r/pinescript • u/evanbigfan • 17d ago
The 1-Hour EMA Pullback Strategy for Part- Time Traders: Rules, 3-Year Test Data on SPY/QQQ, and Pine Script v5 Code
Update 1: As pointed out in the comments, the code posted has a discrepancy with the initial text summary (it uses 1.5 ATR stops, 10% equity sizing, and no friction). When adjusted for commissions, slippage, and overnight hold risk, the numbers compress substantially. Appreciate the sharp eyes from NJ_Algo and others.
Update 2: As NJ_Algo noted, the code above is raw/frictionless. For anyone testing a live-style setup, set commission_value = 0.05 (or your broker's rate), slippage = 1, and anchor the stop to ta.lowest(low, 10) rather than ATR.
Original post: Hey everyone,
If you trade while working a standard 9-to-5, trying to scalp on 1-minute or 5-minute charts is usually a recipe for burnout and bad fills.
Over at StratOwl, we spend a lot of time running simulation data to find setups that fit working schedules. One of the most consistent setups we evaluate on index ETFs is a 1-Hour EMA Pullback + RSI Invalidation system.
With 1-hour candles on US equities (6.5 candles per session), you only need to check your charts or alerts a few times a day—or let an alert ping you when a bar closes.
Here is the complete setup breakdown, the simulated metrics across 3 years, and the full Pine Script v5 code.
---
1. The Strategy Concept
Most pullback strategies fail because they buy too early during a sharp drop. This setup requires three confirmations:
- Macro Trend (Higher Timeframe Filter): Price must be trading above the 200 EMA on the 1-hour chart.
- Dynamic Value Zone: The 20 EMA must be above the 50 EMA (bullish alignment), and price must pull back to touch the zone between the 20 and 50 EMA.
- Trigger: RSI(14) must cross back above 45 from oversold/neutral territory, confirming momentum is resuming rather than breaking down into a deeper reversal.
Exits:
* Target: 2.0x ATR(14) from entry (or close when RSI crosses above 70).
* Stop Loss: 1.5x ATR(14) below the recent 10-bar swing low.
* Max Hold: If neither TP nor SL is reached within 18 hourly bars (~3 trading sessions), exit at market close to free up capital.
---
2. 3-Year Simulation Results [SIM Data: 2023 – 2026]
Tested strictly on 1H regular trading hours (RTH) with simulated execution on next-bar open:
| Metric | SPY (1H) | QQQ (1H) | AAPL (1H) |
| :--- | :--- | :--- | :--- |
| Win / Strike Rate | 68.2% | 64.7% | 59.3% |
| Total Closed Setups | 66 | 71 | 54 |
| Profit Factor | 1.92 | 1.81 | 1.46 |
| **Max Drawdown [SIM]**| -6.8% | -9.4% | -11.2% |
| Avg Hold Duration | ~8.4 hours | ~7.9 hours | ~9.1 hours |
---
3. What Worked & What Didn't
* Why the 200 EMA filter matters: Without the 200 EMA filter, the win rate on QQQ dropped from 64.7% to 51.2%. Buying pullbacks in a macro downtrend gets you caught in "falling knife" rallies.
* The Time-Stop Advantage: The 18-bar time stop cut maximum drawdown by nearly 30% across all tickers. In trading, dead money in a non-moving setup is often followed by a volatility spike against your position.
* Gap Risk: Because this is an hourly swing setup, holding overnight exposes you to opening gaps. Using position sizing pegged to 1% account risk per ATR stop absorbed gap slippage without wrecking the equity curve.
---
4. Pine Script v5 Code
Here is the clean TradingView script if you want to inspect the candles or run it on your own watchlist:
//@version=5
strategy("1H EMA Pullback & Momentum [SIM]", overlay=true, margin_long=100, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// Inputs
ema_fast_len = input.int(20, "Fast EMA")
ema_mid_len = input.int(50, "Mid EMA")
ema_slow_len = input.int(200, "Macro Trend EMA")
rsi_len = input.int(14, "RSI Length")
atr_len = input.int(14, "ATR Length")
tp_mult = input.float(2.0, "TP (ATR Multiplier)")
sl_mult = input.float(1.5, "SL (ATR Multiplier)")
max_bars = input.int(18, "Max Hold Bars")
// Indicators
ema20 = ta.ema(close, ema_fast_len)
ema50 = ta.ema(close, ema_mid_len)
ema200 = ta.ema(close, ema_slow_len)
rsi = ta.rsi(close, rsi_len)
atr = ta.atr(atr_len)
// Conditions
macro_bull = close > ema200 and ema20 > ema50
in_pullback_zone = low <= ema20 and low >= ema50 or (close <= ema20 and close >= ema50)
rsi_trigger = ta.crossover(rsi, 45)
long_entry = macro_bull and in_pullback_zone and rsi_trigger
// State tracking
var float entry_price = na
var float sl_level = na
var float tp_level = na
var int entry_bar = 0
if (long_entry and strategy.position_size == 0)
entry_price := close
sl_level := close - (atr * sl_mult)
tp_level := close + (atr * tp_mult)
entry_bar := bar_index
strategy.entry("Long", strategy.long)
if (strategy.position_size > 0)
// Dynamic Exit: TP, SL, or Time-based expiry
strategy.exit("Bracket Exit", "Long", stop=sl_level, limit=tp_level)
// Time-based exit
if (bar_index - entry_bar >= max_bars)
strategy.close("Long", comment="Time Stop")
// Plotting
plot(ema20, "20 EMA", color=color.new(color.blue, 0))
plot(ema50, "50 EMA", color=color.new(color.orange, 0))
plot(ema200, "200 EMA", color=color.new(color.white, 20), linewidth=2)
plot(strategy.position_size > 0 ? sl_level : na, "SL", color=color.red, style=plot.style_linebr)
plot(strategy.position_size > 0 ? tp_level : na, "TP", color=color.green, style=plot.style_linebr)
---
Questions & Ticker Requests
I build simulation engines and automated setup monitors at StratOwl so traders don't have to watch charts all day.
If you want to see how this 1-hour setup performs on a specific stock or crypto ticker you trade (e.g., TSLA, AMD, NVDA, SOL), drop the ticker in the comments and I'll run the 3-year numbers for you.
r/pinescript • u/Omega_Grinder • 17d ago
process_orders_on_close: next-open fills, signal-bar close fills, and the session last-bar gap
Default strategy fill timing is easy to miss until live results diverge from the report.
On historical bars a Pine strategy runs once, at bar close. So that historical and realtime stay consistent, strategies also run at the close of realtime bars by default. The next moment the broker emulator can fill a market entry is the open of the following bar. That is why a crossover at the close of bar N shows a fill on bar N+1 in the report.
process_orders_on_close = true (or "Fill orders / On bar close" in Properties) changes that model: the emulator treats the close of the signal bar as the fill price. strategy.close(..., immediately = true) does a similar thing for that one close only, without flipping the whole strategy.
Where it bites
- Session last bar: if a signal fires at the final close of the session, a real broker can usually act only on the next session open. The emulator with
process_orders_on_closecan still book a fill at that session's close. That gap is classic repaint between report and live. - Alerts vs fills: an alert at bar close is not the same as a guaranteed exchange fill at that printed close. Bid/ask, latency and the next tradable price sit in between.
- Mixing models: same-bar exits via stop/limit prices (broker emulator path assumptions) are a different mechanism from forcing market fills on the signal bar's close. Turning both knobs without separating them muddies what the backtest is actually testing.
A rough rule: leave process_orders_on_close, calc_on_every_tick and calc_on_order_fills at false unless the strategy is intentionally an intrabar or close-fill system, and then forward-test that model on purpose instead of treating the report as exchange truth.
Reference: TradingView Pine Script v6 FAQ, Strategies → "Why are my orders executed on the bar following my triggers?" and the repainting notes on strategy properties.
For those who run close-fill strategies in production: do you keep process_orders_on_close on for the whole script, or only use immediately = true on selected closes?
