Prompting AI for a Pine Script Support and Resistance Indicator
How to prompt an AI assistant for a Pine Script v6 support and resistance indicator, then catch the pivot-delay, repainting and drawing-limit mistakes in what it returns.
Marketing
A prompt for an AI Pine Script support and resistance indicator must define what “pivot” means, pin Pine Script v6, and specify how confirmed levels, crossed lines, and drawing limits should work. Otherwise, an AI assistant may return valid-looking code that plots the wrong kind of pivot, repaints, or silently loses older drawings.
This tutorial shows how to prompt, review, and correct that code. It complements the broader Best AI for Pine Script guide and focuses on the mistakes specific to swing pivots, floor-trader levels, support and resistance drawings, and webhook-ready alerts.
Two Things Called Pivots
Swing Pivots
ta.pivothigh() and ta.pivotlow() identify price-structure turning points. They return na on bars without an identified pivot. A pivot is confirmed only after the specified number of right-side bars has elapsed, so a five-bar right lookback identifies the pivot five bars after its actual high or low.1
These functions do not calculate levels from a prior day, week, or month. They inspect surrounding bars. A prompt requesting “pivot support and resistance” without naming these functions leaves room for the assistant to choose an unrelated calculation.
Floor-Trader Pivot Levels
ta.pivot_point_levels() calculates floor-trader style levels. TradingView supports Traditional, Fibonacci, Woodie, Classic, DM, and Camarilla calculation types.2 Traditional pivots use the previous period’s high, low, and close:
P = (prevHigh + prevLow + prevClose) / 3
R1 = 2 * P - prevLow
S1 = 2 * P - prevHigh
R2 = P + (prevHigh - prevLow)
S2 = P - (prevHigh - prevLow)
StockCharts notes that floor traders originally used these levels, calculating each one from the prior period's high, low and close.3 They are unrelated to swing detection, so name ta.pivot_point_levels() and the calculation type explicitly.
Support, Resistance, and Zones
Support describes an area where demand is believed strong enough to halt a decline. Resistance is the corresponding area where supply may halt an advance. Broken support can become resistance, while broken resistance can become support.4
Exact lines are convenient for code, but zones can better represent noisy reactions. Technical analysis is not exact, and wider trading ranges may be better modeled with support and resistance zones than with one precise price.4 If you want zones, ask for boxes with a defined width, such as an ATR multiple or percentage of price.
Writing a Precise Support and Resistance Prompt
Pin Version and Built-In
Start the prompt with //@version=6. Do not ask generally for “modern Pine Script.” Name ta.pivothigh() and ta.pivotlow() for swing pivots, or ta.pivot_point_levels() for floor-trader levels.
Also instruct the assistant not to invent functions. Ask it to flag any syntax it cannot verify instead of substituting a plausible function name.
Specify Inputs and Type
For swing pivots, state separate leftbars and rightbars values. “Use a five-bar lookback on both sides” is more precise than “find recent pivots.”
For floor pivots, specify Traditional, Fibonacci, Woodie, Classic, DM, or Camarilla, then define the anchor timeframe. TradingView’s Auto setting uses 1D through 15-minute chart resolutions, 1W above 15 minutes and below one day, and 1M from one day upward.2
Require Confirmed-Bar Logic
Ask whether the indicator repaints, whether it draws into the past, and whether alerts wait for the realtime bar to close. Request barstate.isconfirmed gating or a written explanation of why it is omitted.
The prompt should also require explicit max_lines_count, max_boxes_count, or max_polylines_count settings. This prevents a visually correct first test from losing history later.
- Declare Pine Script v6.
- Name the exact pivot built-in.
- Set left and right pivot bars.
- Define crossing and invalidation rules.
- Require confirmed-bar behavior.
- Set drawing limits explicitly.
Worked Example: Prompt to Code
The Prompt and First Output
A useful prompt is: “Write a Pine Script v6 overlay indicator using ta.pivothigh(5, 5) and ta.pivotlow(5, 5). Draw resistance from confirmed pivot highs and support from confirmed pivot lows. Extend each line right until a confirmed close crosses it. Store high and low lines in separate arrays. Declare the drawing limit explicitly and explain repainting behavior.”
A typical first response creates a line for each pivot but omits max_lines_count. TradingView then displays approximately the last 50 lines rather than preserving a larger requested history.5
Reviewing the Flawed Response
Check whether every line extends forever. A level should normally stop when the script’s invalidation condition occurs. Also check whether old lines disappear after enough pivots accumulate. That is usually garbage collection, not a random rendering bug.
Resistance and support should use separate array<line> collections. That makes direction-specific crossing rules clear: a close crossing above resistance deactivates a resistance line, while a close crossing below support deactivates a support line.
The Corrected v6 Code
This version declares the 500-line cap, creates lines at the actual pivot bars, and stops extending crossed levels. It removes crossed IDs from their arrays but leaves those completed drawings on the chart, because removing an object from an array does not delete the drawing itself.1 The previous close is read once in the global scope and passed into the helper, so the function does not reference history inside a conditional block.
//@version=6
indicator("Confirmed Pivot Support Resistance", overlay = true, max_lines_count = 500)
int leftBars = input.int(5, "Left bars", minval = 1)
int rightBars = input.int(5, "Right bars", minval = 1)
int maxActive = input.int(50, "Max active levels per side", minval = 1)
color resistanceColor = input.color(color.red, "Resistance color")
color supportColor = input.color(color.green, "Support color")
var array<line> resistanceLines = array.new<line>()
var array<line> supportLines = array.new<line>()
// Stops each level that the closing price crossed on this bar and drops it from the active list.
checkCrosses(array<line> lines, bool isResistance, float prevClose) =>
int i = array.size(lines) - 1
while i >= 0
line levelLine = array.get(lines, i)
float levelPrice = line.get_y1(levelLine)
bool crossed = isResistance
? close > levelPrice and prevClose <= levelPrice
: close < levelPrice and prevClose >= levelPrice
if crossed
line.set_x2(levelLine, bar_index)
line.set_extend(levelLine, extend.none)
array.remove(lines, i)
i -= 1
// Adds a level and deletes the oldest active one once the list is longer than `limit`.
addLevel(array<line> lines, line newLine, int limit) =>
array.push(lines, newLine)
if array.size(lines) > limit
line.delete(array.shift(lines))
float pivotHigh = ta.pivothigh(leftBars, rightBars)
float pivotLow = ta.pivotlow(leftBars, rightBars)
float prevClose = close[1]
if barstate.isconfirmed
int pivotBar = bar_index - rightBars
if not na(pivotHigh)
line newResistance = line.new(
pivotBar, pivotHigh, bar_index, pivotHigh,
extend = extend.right,
color = resistanceColor,
width = 2)
addLevel(resistanceLines, newResistance, maxActive)
if not na(pivotLow)
line newSupport = line.new(
pivotBar, pivotLow, bar_index, pivotLow,
extend = extend.right,
color = supportColor,
width = 2)
addLevel(supportLines, newSupport, maxActive)
checkCrosses(resistanceLines, true, prevClose)
checkCrosses(supportLines, false, prevClose)
Active levels are capped per side by an input. When a side holds more than that number, the helper takes the oldest ID with array.shift() and erases it with line.delete(), the first-in, first-out pattern TradingView's FAQ uses to keep only the last few drawings.1 Crossed lines stay visible until the total passes 500 and garbage collection removes the oldest.
The Pivot Confirmation Delay
Why Pivots Plot Backward
TradingView lists most pivot-based scripts and scripts that plot values into the past among potentially misleading repainting behaviors.6 With ta.pivothigh(5, 5), the high is known only after five following bars have completed. The script then anchors the drawing five bars back, where the high occurred.
That visual placement can look predictive even though the information was unavailable on the pivot bar. The correct review question is not simply “Does it repaint?” Ask when the pivot becomes actionable and whether historical markers reveal that delay.
Using barstate.isconfirmed
Adding barstate.isconfirmed to a condition requires the script to be on the bar's last execution, when it closes and prices are confirmed. TradingView calls this a simple way to avoid repainting.6
For alerts, gate the cross condition rather than only the drawing. A line created from a confirmed pivot can still produce a fluctuating intrabar cross if the current close moves above and below it before the bar closes.
The Unavoidable Trade-Off
Methods that avoid repainting trigger signals later than scripts that act on fluid realtime prices. TradingView calls this delay an inevitable compromise.6 No prompt can produce both an earlier signal and later confirmation of the same event without changing what the signal means.
Make the choice explicit: intrabar responsiveness for visual monitoring, or confirmed-bar consistency for historical comparison and automation.
Drawing Limits AI Scripts Miss
Drawing Object Caps
A script instance can display up to 500 lines, 500 boxes, and 100 polylines. If the corresponding maximum is omitted, the default is approximately 50. Once a configured limit is exceeded, garbage collection deletes the oldest drawings first.5
Increasing the declaration limit does not fix unbounded object creation. A script that creates lines on every bar still needs lifecycle rules for crossed, expired, or duplicate levels.
Managing Drawings with Arrays
Store IDs in typed arrays and decide whether an inactive line should remain visible. For a strict last-N policy, use array.shift() to retrieve the oldest ID and line.delete() to remove its drawing. Calling only array.shift() drops the reference but does not erase the object.
For a ZigZag-style visualization, a polyline can reduce the number of independent objects. When line coordinates use xloc.bar_index, the minimum permitted x-coordinate is bar_index - 10000. Use xloc.bar_time when drawings must reach further into history.5
Developing Floor Pivot Levels
Floor pivots need a separate design decision: fixed levels from a completed prior period or levels that update during the current anchor period. ta.pivot_point_levels() controls this with its developing parameter. When it is false, the levels stay constant until the anchor condition is true again; when it is true, they constantly recalculate from the last anchor to the current bar. It cannot be true when the type is "Woodie".7 Ask the assistant to state which behavior it implements.
Even TradingView’s Pivot Points Standard indicator can draw no more than 500 lines, regardless of its Number of Pivots Back setting.2 An AI-generated equivalent must operate within the same script drawing limits.
A Review Checklist
Before You Trust Output
- Confirm the first line declares
//@version=6. - Compile the script without deprecated or invented syntax.
- Verify swing pivots are not confused with floor pivots.
- Check leftbars, rightbars, timeframe, and pivot type.
- Set every relevant drawing maximum explicitly.
- Confirm crossed drawings stop or delete as intended.
- Document when pivots become known.
- Test alerts on confirmed realtime bars.
Recurring Prompt Failures
AI assistants often mix pivot terminology when the prompt does not name a built-in. They also omit drawing limits because a short chart sample does not create enough objects to expose the problem. Finally, they may describe a pivot as non-repainting without explaining that its marker is drawn back on the earlier pivot bar.
Use the same audit discipline for trend and moving average indicators, momentum and divergence indicators, volatility indicators, and volume and VWAP indicators. The exact failure modes differ, but versioning, confirmation, and resource limits remain important.
Turning Levels Into Alerts
Drawings Cannot Trigger Alerts
Pine drawings do not have external uses such as creating alerts. Plot outputs do, and any plot*() call executing on the chart can serve as an alert trigger.8 Therefore, a line object alone is insufficient.
Keep each active level’s numeric price in a variable or array. Compute a Boolean cross condition, expose it through plotshape(), plotchar(), or alertcondition(), and use the same confirmed-bar rule applied to the visual line.
Routing a Pivot Break
After the cross condition exists, a TradingView alert can send JSON containing ticker, action, and quantity to TradersPost. The platform processes the signal according to the configured strategy and subscriptions, then submits the trade to the connected broker or exchange.
{
"ticker": "{{ticker}}",
"action": "buy",
"quantity": 1,
"price": {{close}},
"test": true,
"stopLoss": {
"type": "stop",
"percent": 1
},
"takeProfit": {
"percent": 2
}
}
With test set to true, the signal is processed as a test and no order is sent to the broker. Optional stopLoss and takeProfit objects can carry risk instructions in the same payload. Review the TradersPost webhook setup documentation, verify the alert in test mode, and paper trade the complete workflow before considering live execution.
Bottom Line
A reliable AI-generated pivot indicator starts with precise terminology and ends with realtime validation. Compiling code is only the first test.
- Distinguish swing pivots from floor-trader pivot levels.
- Pin Pine Script v6 and name the required built-ins.
- Treat pivot confirmation delay as part of the specification.
- Manage drawing limits and object lifecycles explicitly.
- Build alerts from computed series, not drawing objects.
Use the Best AI for Pine Script guide for the broader prompting workflow. When the indicator is ready for automation, follow the webhook setup documentation and validate the payload with test signals before connecting the alert to live order execution.
Frequently Asked Questions
How Do Pivot Types Differ?
A swing pivot from ta.pivothigh() or ta.pivotlow() is a price-structure high or low confirmed by bars on both sides. A floor-trader pivot is calculated from prior-period price data. Support and resistance are broader concepts that either method may approximate.
Why Do Old Lines Disappear?
If max_lines_count is omitted, the script displays approximately 50 lines. When the limit is exceeded, TradingView’s garbage collector removes the oldest drawings. Setting the declaration value as high as 500 preserves more history, but the script should still manage old objects.
Can Floor Pivots Use Intraday Charts?
Yes. TradingView’s Auto timeframe uses daily pivots through 15-minute charts, weekly pivots above 15 minutes and below one day, and monthly pivots from one day upward. Specify fixed or automatic timeframe selection in the prompt.
Why Does My Alert Fire Late?
ta.pivothigh() and ta.pivotlow() confirm only after rightbars have elapsed. Requiring barstate.isconfirmed also waits for the current bar to close. Those delays are the cost of confirmation, not an error that AI can remove.
Can a Drawn Line Alert?
No. Lines, boxes, and labels are drawing objects, not alert-triggering series. Compute the level cross separately and expose it through a plot or alert condition alongside the drawing.
References
1 TradingView Pine Script Visuals FAQ
2 TradingView Pivot Points Standard
3 StockCharts ChartSchool Pivot Points
4 StockCharts Support and Resistance
5 TradingView Lines and Boxes
6 TradingView Repainting
7 TradingView Pine Script Release Notes
8 TradingView Visuals Overview