AI Pine Script request.security for Multi-Timeframe Indicators
How to prompt an AI for Pine Script v6 multi-timeframe indicators, then audit its request.security() calls for future leaks, repainting and v6 timeframe mistakes.
Marketing
The safest way to use AI Pine Script request.security code is to give the assistant an exact Pine Script v6 contract, then audit every higher-timeframe request for confirmed-bar behavior. Start with the broader best AI for Pine Script guide if you are still choosing an assistant or establishing a code-review workflow.
The central issue is not whether generated code compiles. A script can compile while reading fluctuating higher-timeframe values in realtime or leaking future values across historical bars. This guide covers precise prompting, a corrected v6 example, common AI mistakes, and the checks to complete before connecting an alert to automated execution.
What Multi-Timeframe Scripts Cover
Higher-Timeframe Confirmation Filters
The request.security() function retrieves data from another symbol, timeframe, or context. It is the core mechanism for bringing a higher-timeframe value onto a lower-timeframe chart.1 An AI-generated trend filter might request a weekly moving average while calculating entries on a daily chart, or request a daily trend while processing hourly signals.
Alexander Elder's multiple-timeframe approach illustrates the design. StockCharts summarizes it in its Elder Impulse System article: set your trading timeframe, multiply it by five for the long-term timeframe, and treat a daily buy signal as valid only when the weekly chart shows a clear uptrend.2 The code must encode both the trend rule and the point at which that higher-timeframe value becomes confirmed.
Multi-Timeframe Dashboards
A dashboard commonly requests one dataset for each displayed symbol or timeframe. In Pine Script v6, request.*() calls can execute inside loops and conditional structures because dynamic requests are available by default.3
Scripts can perform up to 40 unique request.*() calls, or 64 for users on the Ultimate plan. Calls with identical functions and arguments typically reuse the first request rather than consuming another unique request.1 Ask AI to identify the expected request count when generating a multi-symbol dashboard.
Where request.security Fits
The full signature is request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency, calc_bars_count). The gaps parameter defaults to barmerge.gaps_off, while lookahead defaults to barmerge.lookahead_off.1
Use request.security() for timeframes equal to or higher than the chart timeframe. For intrabar data, TradingView provides request.security_lower_tf(), which returns an array of lower-timeframe values; a plain request.security() call on a lower timeframe returns the value from only the first or last intrabar of each chart bar, depending on lookahead.1 The repainting page adds that intrabar techniques built that way only work on historical bars, because realtime intrabars are not yet sorted.4
Write a Precise AI Prompt
Pin the Pine Script Version
Start the prompt with //@version=6. Tell the assistant not to add dynamic_requests = true merely to place requests inside loops. Dynamic requests default to true in v6, and the compiler can disable them automatically when they are unnecessary.3
Also state that timeframe.period includes a multiplier in v6. Daily, weekly, and monthly chart periods return strings such as "1D", "1W", and "1M", rather than "D", "W", and "M".3
Name Exact Inputs and Conditions
Do not ask for a generic higher-timeframe filter. Specify the timeframe input, indicator lengths, signal conditions, chart symbol behavior, plots, alerts, and invalid-timeframe handling.
- Use input.timeframe("1D", "Higher timeframe").
- Use syminfo.tickerid so the request follows the chart symbol.
- Reject an input below the chart timeframe.
- Calculate entries from confirmed chart and higher-timeframe bars.
- Create alertcondition() calls for the final signals.
Avoid words such as "current" and "latest" unless you explicitly want developing values. Those terms can lead an assistant to request the open higher-timeframe bar.
Require Confirmed-Bar Logic Explicitly
Ask for this pattern by name: request.security(symbol, timeframe, expression[1], lookahead = barmerge.lookahead_on). TradingView's repainting page explains that offsetting the expression by at least one bar and using barmerge.lookahead_on makes higher-timeframe requests return only confirmed values on all bars, and that the offset and the lookahead setting are interdependent.4
Explicitly prohibit barstate.isconfirmed inside the requested expression: the Bar states page says it will not work when used in a request.security() call.5 Require the assistant to explain whether any value can remain unconfirmed on realtime bars.
Write a Pine Script v6 overlay indicator.
Use input.timeframe("1D", "Higher timeframe") and syminfo.tickerid.
Reject inputs below the chart timeframe.
Request the last confirmed HTF close and 50-period EMA using expression[1] with lookahead = barmerge.lookahead_on.
Do not use barstate.isconfirmed inside request.security().
Generate a long signal when the chart close crosses above its 20-period EMA while the confirmed HTF close is above the confirmed HTF EMA.
Require the chart bar to close.
Add plots and an alertcondition() whose message is a JSON signal with ticker, action and price.
Explain whether any requested value can fluctuate on realtime bars.
Worked Example: Prompt to Code
The Initial AI Output
A typical first draft uses request.security(syminfo.tickerid, htf, close). This returns confirmed requested values on historical bars but can return a developing value on realtime bars. When the script restarts, the former realtime bars become historical, and the displayed result can change.4
The same draft might compare timeframe.period == "D" or attempt request.security(syminfo.tickerid, htf, barstate.isconfirmed ? close : na). The first condition misses v6's "1D" value. The second incorrectly assumes the chart bar-state check can confirm the requested context.
Reviewing the Draft Against Docs
Review generated code in this order:
- Find every request.security() call.
- Determine whether each request is higher, equal, or lower than the chart timeframe.
- Check that confirmed HTF expressions use a [1] offset with lookahead_on.
- Reject unoffset lookahead_on requests.
- Remove barstate.isconfirmed from requested expressions.
- Update timeframe.period comparisons to multiplier-included strings.
Do not add lookahead_on alone. Without the historical offset, it exposes final higher-timeframe values on earlier historical bars, before those values were available in realtime.
The Corrected v6 Code
//@version=6
indicator("Confirmed HTF Trend Filter", overlay = true)
string htf = input.timeframe("1D", "Higher timeframe")
int localLength = input.int(20, "Chart EMA length", minval = 1)
int htfLength = input.int(50, "HTF EMA length", minval = 1)
if timeframe.in_seconds() > timeframe.in_seconds(htf)
runtime.error("Higher timeframe must be equal to or above chart timeframe.")
float localEma = ta.ema(close, localLength)
float confirmedHtfClose = request.security(
syminfo.tickerid,
htf,
close[1],
lookahead = barmerge.lookahead_on
)
float confirmedHtfEma = request.security(
syminfo.tickerid,
htf,
ta.ema(close, htfLength)[1],
lookahead = barmerge.lookahead_on
)
bool htfBullish = confirmedHtfClose > confirmedHtfEma
bool longSignal = ta.crossover(close, localEma) and htfBullish and barstate.isconfirmed
bool isDailyChart = timeframe.period == "1D"
plot(localEma, "Chart EMA", color = color.orange)
plot(confirmedHtfEma, "Confirmed HTF EMA", color = color.blue, linewidth = 2)
plotshape(longSignal, title = "Long signal", style = shape.triangleup, location = location.belowbar, color = color.lime, size = size.small)
bgcolor(isDailyChart ? color.new(color.blue, 94) : na)
alertcondition(longSignal, "Confirmed HTF long", '{"ticker": "{{ticker}}", "action": "buy", "price": {{close}}}')
Both requests use the previous higher-timeframe value with lookahead_on. This introduces a deliberate delay, but the requested series behaves consistently across historical and realtime bars. The chart-level signal separately uses barstate.isconfirmed so it triggers only when the chart bar closes. Because alertcondition() messages must be constant strings, the JSON uses TradingView's {{ticker}} and {{close}} placeholders for the values that change.
Common AI Mistakes With request.security
Lookahead Without an Offset
An unoffset lookahead_on request can display the final higher-timeframe high on historical bars before that high was available. TradingView's Other timeframes page calls scripts that use lookahead to leak future data into the past "extremely misleading", and says using lookahead this way is not allowed in script publications.1
The fix requires both components: offset the expression by at least one bar and enable lookahead_on. Removing either part compromises the confirmed-value pattern.
Dynamic Requests and Bar Checks
A model relying on v5 conventions may claim requests cannot run inside loops, or add dynamic_requests = true automatically. The v6 migration guide says the dynamic_requests parameter is true by default, so request.*() calls can run inside loops and conditional structures without it. It also warns that a converted v5 script can behave differently in v6.3
Another common mistake is placing barstate.isconfirmed inside request.security(). Use it for chart-level conditions, as in the corrected example, but not as a substitute for the HTF offset and lookahead pattern.
Stale Timeframe Period Strings
A v6 comparison against timeframe.period == "D" silently misses a daily chart because timeframe.period now returns "1D". The same correction applies to "1W" and "1M". Pine also has no hour unit, so one hour is "60", not "1H".6
Session Strings and Named Sessions
Only time(), time_close(), and input.session() accept time-based session strings such as "0930-1600". Scripts cannot request data from tickers created with time-based sessions. To request a particular exchange session, construct a ticker with ticker.new() or ticker.modify() and use a named session such as session.regular or session.extended.7
Review Checklist for MTF Scripts
Compile and Count Requests
Compile the script under //@version=6 before interpreting any output. Then count unique requests across the entire request.*() namespace, including calls reached through loops and functions. Keep the total within 40 unique requests, or 64 on the Ultimate plan.
Ask Repainting Audit Questions
- Do calculations and plots behave the same on historical and realtime bars?
- Can any request return a developing higher-timeframe value?
- Does lookahead leak future data into historical bars?
- Do markers wait for the chart bar to close?
- Do alerts use the same final condition as plotted signals?
These questions are more useful than asking only whether a script repaints, because repainting includes several forms with different consequences.4
Check Timeframes and Sessions
Validate every timeframe input before requesting it. Valid minute multipliers run from 1 to 1440, day multipliers from 1 to 365, week multipliers from 1 to 52, and month multipliers from 1 to 12.6 Keep time-based session strings in time(), time_close(), or input.session(), and use named sessions when constructing a session-specific ticker for requests.
From Indicator to TradersPost Alert
Build Confirmed Alert Logic
Create the TradingView alert from the "Confirmed HTF long" condition and paste your TradersPost webhook URL into the alert's webhook field. The alertcondition() message already holds the JSON, and the signal only becomes true on a closed chart bar. If a marker appears on the chart but the matching alert is missing, check TradingView's alert log, which records each alert that fired with its time and message. Comparing those entries with the chart separates repainting problems from alert configuration problems.
Send the Signal
A TradersPost webhook payload can include ticker, action, quantity, orderType, and optional stopLoss or takeProfit objects. After receiving the signal, the platform processes it according to the strategy and subscription configuration, then submits the resulting trade to the connected broker or exchange. Subscription settings can use incoming values or replace fields such as quantity, order type, stop loss, and take profit when the corresponding Allow signal override setting is disabled.
Paper Trade Before Going Live
Compare each alert's logged time and price with the chart before enabling automatic submission, and check the strategy's Signals page in TradersPost to confirm each alert arrived. Paper testing should cover normal signals, duplicate conditions, market-session boundaries, and transitions between higher-timeframe bars.
Once the script passes the repainting audit, connect the confirmed-bar alert to a TradersPost webhook and paper trade it before enabling live execution.
Bottom Line
- Prompt for Pine Script v6, exact inputs, and confirmed-bar requirements.
- Pair expression[1] with lookahead_on for confirmed higher-timeframe values.
- Never use unoffset lookahead_on or barstate.isconfirmed inside request.security().
- Audit timeframe strings, session handling, and unique request counts.
- Verify alert log entries and paper trades before live automation.
AI can accelerate scripts for trend and moving average indicators, momentum and oscillator indicators, or volatility indicators. It does not replace compilation, documentation review, and realtime validation. Return to the best AI for Pine Script guide for the broader prompting and review process.
Frequently Asked Questions
Why does my AI indicator repaint?
Historical and realtime calculations are behaving differently. A plain HTF request can read an unconfirmed value in realtime, while the same bar displays only confirmed information after becoming historical. AI often omits the [1] and lookahead_on pairing that prevents this inconsistency.
Can request.security safely use lookahead?
Yes, when the requested expression is offset by at least one bar, as in expression[1] with lookahead = barmerge.lookahead_on. Without the offset, lookahead_on on a higher timeframe leaks future values into historical bars.
Why does barstate.isconfirmed fail?
TradingView states that barstate.isconfirmed does not work inside request.security(). Use the offset-plus-lookahead_on pattern for confirmed HTF data, then apply barstate.isconfirmed separately to the chart-level alert condition.
Which security function should I use?
Use request.security() for equal or higher timeframes. Use request.security_lower_tf() when you need lower-timeframe intrabars returned as an array. A plain lower-timeframe request.security() call returns limited intrabar information and may not reproduce its historical behavior in realtime.
How many requests are allowed?
A script can perform up to 40 unique request.*() calls, or 64 on the Ultimate plan. Identical redundant calls typically reuse data from the first request instead of counting again.
References
1 TradingView: Other timeframes and data
2 StockCharts ChartSchool: Elder Impulse System
3 TradingView: To Pine Script version 6
4 TradingView: Repainting
5 TradingView: Bar states
6 TradingView: Timeframes
7 TradingView: Sessions