We use cookies to understand how the site is used and improve it. We only load analytics after you accept. Privacy Policy
Maps historical pullback-depth percentiles onto the current confirmed swing leg.
Published by AlgoNexta, who builds and documents these tools so you can inspect the logic before using it. About AlgoNexta · Trading Scripts · AlgoNexta Research
Pullback Map measures how far completed pullbacks retraced their preceding swing legs. It uses those historical depths to draw a percentile zone, median, and deep-pullback level on the current confirmed leg. These are descriptive levels, not trade entries or targets.
01 · When a swing is recognized
The overlay uses confirmed pivot highs and lows with `Swing length` 8 bars on each side. It ignores legs shorter than 1.5 × ATR(14); a later confirmed swing can also replace a less-extreme pivot of the same type.
02 · How depths become a map
For an eligible current leg, the script selects its directional pullback sample, using the all-legs fallback for a non-breaking leg under the default mode. With at least 20 retained depths, it projects the 25th, 50th, 75th, and 90th percentiles from the leg endpoint toward its origin.
This script's logic could not be confidently reconstructed into an automated reference backtest, so no performance figures are shown rather than estimated ones.
Verify it in TradingView's Strategy Tester (or the equivalent tool for tradingview) before relying on it.
Vision Grade requires a reference backtest with enough reconstructed entries to measure — not available for this script yet.
Published by AlgoNexta, an evidence-first platform for building, reviewing, and documenting algorithmic trading tools. This page explains the script's actual logic and intended use; it does not promise profitability or replace verification in TradingView.
Pullback Map measures how far completed pullbacks retraced their preceding swing legs. It uses those historical depths to draw a percentile zone, median, and deep-pullback level on the current confirmed leg. These are descriptive levels, not trade entries or targets.
Swing length defaults to 8 bars on each side of a pivot, so a swing is recognized only after eight subsequent bars. Same-direction pivots can replace the latest swing if they are more extreme. Ignore legs smaller than (ATR) defaults to 1.5 times the current 14-period ATR; smaller legs are excluded. A map also requires at least Pullbacks needed before levels are drawn (default 20) eligible depths in its selected directional sample.Pullbacks in the sample (per direction) caps retained depths at 200 by default.Legs to measure defaults to Legs that broke the previous swing. A leg qualifies for that sample only when its endpoint exceeds the preceding swing of the same type. If the current leg did not break that swing, its map instead uses the all-legs sample and appears muted. Switching the input to All legs measures every otherwise eligible leg.Zone starts at percentile 25 to Zone ends at percentile 75; a thicker line marks the 50th-percentile median, and a dashed line marks Deep pullback percentile 90. An origin line marks the start of the leg. Default up-leg maps use Pullback after an up leg teal; down-leg maps use Pullback after a down leg red. Show swing legs, Show level labels, and Show statistics table default to on. Show 38.2 / 50 / 61.8 for comparison defaults to off; those optional dotted lines are fixed fractions, not measured percentiles.For example, if an eligible up leg has enough samples, its measured levels extend downward from the confirmed swing high. If price never reaches the zone start, no zone-touch alert occurs. If that leg is too small or its selected sample has fewer than 20 depths, no map is drawn. You can change the swing sensitivity, ATR filter, sample limits, percentiles, leg selection, and display options; percentile inputs must satisfy zone start < zone end < deep.
The calculations use the chart’s own market and timeframe; the code specifies no preferred symbol or interval. Pivot confirmation introduces delay, and confirmed swing markers can appear eight bars behind the bar on which they become known. A more extreme same-direction pivot or a new confirmed swing can replace or rebuild the displayed map. Once price trades beyond the leg endpoint, the current levels stop extending until another swing change. The script does not place orders, set stops, identify an entry rule, or test returns. No native compilation, historical Strategy Tester result, paper-trading result, or live-trading result is supplied here.
pullback-map-measured-retracement-levels-algonexta.pine · 350 lines · 18.4 KB
Not yet verified on the native platform — test it before relying on it.
The original uploaded source.
// ============================================================================
// © algonexta
// This script is for education and research; it does not guarantee results.
// Verify this source in TradingView before use.
// ============================================================================
// Pullback Map: Measured Retracement Levels. Research indicator, not a strategy: it measures how deep
// past pullbacks went on this chart and draws those depths, as percentiles, on the current swing leg.
// It does not place, manage or simulate orders.
//@version=6
indicator("Pullback Map: Measured Retracement Levels [AlgoNexta]", shorttitle = "Pullback Map", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 200)
//──────────────────────────────────────────────────────────────────────────────
// Inputs
//──────────────────────────────────────────────────────────────────────────────
string G_SW = "1. Swings"
string G_ST = "2. Statistics"
string G_VI = "3. Display"
int swingLen = input.int(8, "Swing length", minval = 2, maxval = 50, group = G_SW, tooltip = "Bars on each side of a swing high or low. Swings are used only after they are confirmed.")
float minLegAtr = input.float(1.5, "Ignore legs smaller than (ATR)", minval = 0.0, step = 0.25, group = G_SW)
string legMode = input.string("Legs that broke the previous swing", "Legs to measure", options = ["Legs that broke the previous swing", "All legs"], group = G_SW, tooltip = "Legs that broke the previous swing: an up leg counts only if it ended above the previous swing high, and a down leg only if it ended below the previous swing low. If the current leg did not break, its map uses the all-legs sample and is drawn in a muted colour. All legs: every leg counts.")
int sampleMax = input.int(200, "Pullbacks in the sample (per direction)", minval = 20, maxval = 500, group = G_ST)
int minSample = input.int(20, "Pullbacks needed before levels are drawn", minval = 5, maxval = 500, group = G_ST)
float qLo = input.float(25, "Zone starts at percentile", minval = 1, maxval = 99, group = G_ST)
float qHi = input.float(75, "Zone ends at percentile", minval = 1, maxval = 99, group = G_ST)
float qDeep = input.float(90, "Deep pullback percentile", minval = 1, maxval = 99, group = G_ST)
bool showZig = input.bool(true, "Show swing legs", group = G_VI)
bool showFib = input.bool(false, "Show 38.2 / 50 / 61.8 for comparison", group = G_VI)
bool showLbl = input.bool(true, "Show level labels", group = G_VI)
bool showTable = input.bool(true, "Show statistics table", group = G_VI)
string tblPos = input.string("Top right", "Table position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G_VI)
color upCol = input.color(#22ab94, "Pullback after an up leg", group = G_VI)
color dnCol = input.color(#f23645, "Pullback after a down leg", group = G_VI)
if barstate.isfirst and not (qLo < qHi and qHi < qDeep)
runtime.error("Pullback Map: percentiles must satisfy zone start < zone end < deep.")
//──────────────────────────────────────────────────────────────────────────────
// State
//──────────────────────────────────────────────────────────────────────────────
var array<float> zp = array.new<float>() // swing prices
var array<int> zb = array.new<int>() // swing bars
var array<int> zd = array.new<int>() // 1 = swing high, -1 = swing low
var array<float> upR = array.new<float>() // pullback depth after up legs, as a fraction of the leg
var array<float> dnR = array.new<float>() // pullback depth after down legs
var array<int> cnt = array.new<int>(6, 0) // up legs: all, origin lost, new extreme | down legs: same
// Second sample with every leg. Used for the projection when the current leg did not break the
// previous swing, so a sideways market still gets a map (drawn fainter and labelled).
var array<float> upAll = array.new<float>()
var array<float> dnAll = array.new<float>()
var array<int> cntAll = array.new<int>(6, 0)
var array<line> zzLines = array.new<line>()
float atr = ta.atr(14)
float ph = ta.pivothigh(high, swingLen, swingLen)
float pl = ta.pivotlow(low, swingLen, swingLen)
float recentLo = ta.lowest(low, swingLen)
float recentHi = ta.highest(high, swingLen)
f_pos(string s) =>
s == "Top left" ? position.top_left : s == "Bottom right" ? position.bottom_right : s == "Bottom left" ? position.bottom_left : position.top_right
bool breakOnly = legMode == "Legs that broke the previous swing"
// Adds a confirmed swing. Returns 1 for a new point, 2 if it replaced the last point, 0 if ignored.
f_add(float price, int b, int dir) =>
int res = 0
int n = zp.size()
if n == 0
zp.push(price)
zb.push(b)
zd.push(dir)
res := 1
else
int lastDir = zd.get(n - 1)
float lastP = zp.get(n - 1)
if lastDir == dir
if (dir == 1 and price > lastP) or (dir == -1 and price < lastP)
zp.set(n - 1, price)
zb.set(n - 1, b)
res := 2
else
zp.push(price)
zb.push(b)
zd.push(dir)
res := 1
res
// Adds one measured pullback to a sample and its counters.
f_store(array<float> dst, array<int> cn, int dirB, float r, bool cont) =>
int o = dirB == 1 ? 0 : 3
cn.set(o, cn.get(o) + 1)
if r >= 1.0
cn.set(o + 1, cn.get(o + 1) + 1)
else
if cont
cn.set(o + 2, cn.get(o + 2) + 1)
dst.push(r)
if dst.size() > sampleMax
dst.shift()
true
// Called when a new point is added. Points A, B, C, D are then final:
// leg A to B, pullback B to C, and D shows whether price made a new extreme beyond B.
f_record() =>
int n = zp.size()
if n >= 5
float a = zp.get(n - 5)
float b = zp.get(n - 4)
float c = zp.get(n - 3)
float d = zp.get(n - 2)
int dirB = zd.get(n - 4)
float leg = math.abs(b - a)
// The swing before A has the same type as B. The leg broke it if B went beyond it.
bool broke = n >= 6 and (dirB == 1 ? b > zp.get(n - 6) : b < zp.get(n - 6))
if leg > 0 and leg >= minLegAtr * nz(atr)
float r = math.abs(c - b) / leg
bool cont = dirB == 1 ? d > b : d < b
f_store(dirB == 1 ? upAll : dnAll, cntAll, dirB, r, cont)
if broke or not breakOnly
f_store(dirB == 1 ? upR : dnR, cnt, dirB, r, cont)
n
f_feed(float price, int dir) =>
int res = f_add(price, bar_index - swingLen, dir)
int n = zp.size()
if res == 1
f_record()
if showZig and n >= 2
zzLines.push(line.new(zb.get(n - 2), zp.get(n - 2), zb.get(n - 1), zp.get(n - 1), color = color.new(chart.fg_color, 55), width = 1))
if res == 2 and showZig and zzLines.size() > 0
line l = zzLines.last()
l.set_xy2(zb.get(n - 1), zp.get(n - 1))
res
// Share of past pullbacks that were equal to or shallower than v, in percent.
f_rank(array<float> a, float v) =>
int c = 0
for x in a
if x <= v
c += 1
a.size() > 0 ? 100.0 * c / a.size() : na
//──────────────────────────────────────────────────────────────────────────────
// Swings: confirmed bars only
//──────────────────────────────────────────────────────────────────────────────
int chg = 0
if barstate.isconfirmed
if not na(ph) and not na(pl)
bool lastHigh = zd.size() > 0 and zd.get(zd.size() - 1) == 1
int r1 = f_feed(lastHigh ? ph : pl, lastHigh ? 1 : -1)
int r2 = f_feed(lastHigh ? pl : ph, lastHigh ? -1 : 1)
chg := math.max(r1, r2)
else if not na(ph)
chg := f_feed(ph, 1)
else if not na(pl)
chg := f_feed(pl, -1)
if zp.size() > 60
zp.shift()
zb.shift()
zd.shift()
if zzLines.size() > 200
zzLines.shift()
//──────────────────────────────────────────────────────────────────────────────
// Projection on the current leg
//──────────────────────────────────────────────────────────────────────────────
var array<line> pLines = array.new<line>()
var array<label> pLabels = array.new<label>()
var box pZone = na
var int projDir = 0
var float legA = na
var float legB = na
var float lvStart = na
var float lvMid = na
var float lvEnd = na
var float lvDeep = na
var float sinceExt = na
var bool hitZone = false
var bool hitMid = false
var bool hitDeep = false
var bool hitOrig = false
var bool projDone = false
var bool projFallback = false
var array<float> projSrc = array.new<float>()
f_line(int x1, float y, color c, string style, int width, string txt) =>
pLines.push(line.new(x1, y, bar_index, y, color = c, style = style, width = width))
if showLbl and txt != ""
pLabels.push(label.new(bar_index, y, txt, style = label.style_label_left, color = color.new(c, 100), textcolor = c, size = size.small))
y
if chg != 0
for l in pLines
l.delete()
for lb in pLabels
lb.delete()
pLines.clear()
pLabels.clear()
if not na(pZone)
pZone.delete()
pZone := na
projDir := 0
lvStart := na
lvMid := na
lvEnd := na
lvDeep := na
hitZone := false
hitMid := false
hitDeep := false
hitOrig := false
projDone := false
projFallback := false
int n = zp.size()
if n >= 2
float B = zp.get(n - 1)
float A = zp.get(n - 2)
int bB = zb.get(n - 1)
int dir = zd.get(n - 1)
float leg = math.abs(B - A)
bool brokeNow = n >= 3 and (dir == 1 ? B > zp.get(n - 3) : B < zp.get(n - 3))
bool useMain = brokeNow or not breakOnly
array<float> src = useMain ? (dir == 1 ? upR : dnR) : (dir == 1 ? upAll : dnAll)
if src.size() >= minSample and leg > 0 and leg >= minLegAtr * nz(atr)
float sgn = dir == 1 ? -1.0 : 1.0
float q1 = src.percentile_linear_interpolation(qLo)
float q2 = src.percentile_linear_interpolation(50)
float q3 = src.percentile_linear_interpolation(qHi)
float q4 = src.percentile_linear_interpolation(qDeep)
color c0 = dir == 1 ? upCol : dnCol
// Fallback projections use a muted colour so they read as the weaker case.
color c = useMain ? c0 : color.rgb((color.r(c0) + 128) / 2, (color.g(c0) + 128) / 2, (color.b(c0) + 128) / 2)
projFallback := not useMain
projSrc := src
projDir := dir
legA := A
legB := B
lvStart := B + sgn * q1 * leg
lvEnd := B + sgn * q3 * leg
pZone := box.new(bB, math.max(lvStart, lvEnd), bar_index, math.min(lvStart, lvEnd), border_color = color(na), bgcolor = color.new(c, 86))
f_line(bB, lvStart, color.new(c, 50), line.style_solid, 1, "P" + str.tostring(qLo, "#") + " " + str.tostring(q1, "0.00"))
f_line(bB, lvEnd, color.new(c, 50), line.style_solid, 1, "P" + str.tostring(qHi, "#") + " " + str.tostring(q3, "0.00"))
lvMid := f_line(bB, B + sgn * q2 * leg, c, line.style_solid, 2, "median " + str.tostring(q2, "0.00"))
lvDeep := f_line(bB, B + sgn * q4 * leg, color.new(c, 25), line.style_dashed, 1, "P" + str.tostring(qDeep, "#") + " " + str.tostring(q4, "0.00"))
f_line(bB, A, color.new(chart.fg_color, 45), line.style_dotted, 1, useMain ? "origin" : "origin (all-legs sample)")
if showFib
color fc = color.new(chart.fg_color, 60)
f_line(bB, B + sgn * 0.382 * leg, fc, line.style_dotted, 1, "0.382")
f_line(bB, B + sgn * 0.5 * leg, fc, line.style_dotted, 1, "0.5")
f_line(bB, B + sgn * 0.618 * leg, fc, line.style_dotted, 1, "0.618")
// Bars after the swing point: the deepest price so far on the pullback side.
sinceExt := dir == 1 ? recentLo : recentHi
bool evZone = false
bool evMid = false
bool evDeep = false
bool evOrig = false
// The projection stays live until price trades beyond the end of the leg. From then on the
// pullback is over, so the levels stop extending and wait for the next confirmed swing.
if projDir != 0 and not projDone
if chg == 0
sinceExt := projDir == 1 ? math.min(sinceExt, low) : math.max(sinceExt, high)
pZone.set_right(bar_index)
for l in pLines
l.set_x2(bar_index)
for lb in pLabels
lb.set_x(bar_index)
if barstate.isconfirmed
bool reachStart = projDir == 1 ? low <= lvStart : high >= lvStart
bool reachMid = projDir == 1 ? low <= lvMid : high >= lvMid
bool reachDeep = projDir == 1 ? low <= lvDeep : high >= lvDeep
bool reachOrig = projDir == 1 ? low <= legA : high >= legA
if reachStart and not hitZone
hitZone := true
evZone := true
if reachMid and not hitMid
hitMid := true
evMid := true
if reachDeep and not hitDeep
hitDeep := true
evDeep := true
if reachOrig and not hitOrig
hitOrig := true
evOrig := true
bool beyond = projDir == 1 ? high > legB : low < legB
if beyond and chg == 0
projDone := true
//──────────────────────────────────────────────────────────────────────────────
// Statistics table
//──────────────────────────────────────────────────────────────────────────────
var table tb = table.new(f_pos(tblPos), 3, 8, bgcolor = color.new(chart.bg_color, 10), border_color = color.new(chart.fg_color, 85), border_width = 1, frame_color = color.new(chart.fg_color, 70), frame_width = 1)
f_cell(int col, int row, string txt, color c) =>
table.cell(tb, col, row, txt, text_color = c, text_size = size.small, text_halign = text.align_left)
f_q(array<float> a, float p) =>
a.size() >= minSample ? str.tostring(a.percentile_linear_interpolation(p), "0.00") : "-"
f_share(int part, int whole) =>
whole >= minSample ? str.tostring(100.0 * part / whole, "#") + "%" : "-"
if showTable and barstate.islast
color fg = chart.fg_color
f_cell(0, 0, "Pullback Map", fg)
f_cell(1, 0, "After up legs", upCol)
f_cell(2, 0, "After down legs", dnCol)
f_cell(0, 1, "Pullbacks in the sample", fg)
f_cell(1, 1, str.tostring(upR.size()), fg)
f_cell(2, 1, str.tostring(dnR.size()), fg)
f_cell(0, 2, "Median depth", fg)
f_cell(1, 2, f_q(upR, 50), fg)
f_cell(2, 2, f_q(dnR, 50), fg)
f_cell(0, 3, "Typical zone (P" + str.tostring(qLo, "#") + " to P" + str.tostring(qHi, "#") + ")", fg)
f_cell(1, 3, f_q(upR, qLo) + " to " + f_q(upR, qHi), fg)
f_cell(2, 3, f_q(dnR, qLo) + " to " + f_q(dnR, qHi), fg)
f_cell(0, 4, "Deep pullback (P" + str.tostring(qDeep, "#") + ")", fg)
f_cell(1, 4, f_q(upR, qDeep), fg)
f_cell(2, 4, f_q(dnR, qDeep), fg)
f_cell(0, 5, "Legs that lost their origin", fg)
f_cell(1, 5, f_share(cnt.get(1), cnt.get(0)), fg)
f_cell(2, 5, f_share(cnt.get(4), cnt.get(3)), fg)
f_cell(0, 6, "Pullbacks followed by a new extreme", fg)
f_cell(1, 6, f_share(cnt.get(2), cnt.get(0) - cnt.get(1)), fg)
f_cell(2, 6, f_share(cnt.get(5), cnt.get(3) - cnt.get(4)), fg)
string cur = "none yet (leg too small or data short)"
if projDir != 0 and legB != legA
float depth = math.abs(legB - sinceExt) / math.abs(legB - legA)
string dTxt = depth >= 1.0 ? str.tostring(depth, "0.00") + " of the leg: past the origin" : str.tostring(depth, "0.00") + " of the leg, deeper than " + str.tostring(f_rank(projSrc, depth), "#") + "% of past"
cur := dTxt + (projFallback ? " · all-legs sample" : "") + (projDone ? " · ended" : "")
f_cell(0, 7, "Current pullback (deepest so far)", fg)
f_cell(1, 7, cur, fg)
table.merge_cells(tb, 1, 7, 2, 7)
//──────────────────────────────────────────────────────────────────────────────
// Data window and alerts
//──────────────────────────────────────────────────────────────────────────────
plot(lvStart, "Zone start", display = display.data_window)
plot(lvMid, "Median pullback", display = display.data_window)
plot(lvEnd, "Zone end", display = display.data_window)
plot(lvDeep, "Deep pullback", display = display.data_window)
alertcondition(evZone, "Price entered the typical pullback zone", "Pullback Map: {{ticker}} {{interval}} entered the typical pullback zone")
alertcondition(evMid, "Price reached the median pullback", "Pullback Map: {{ticker}} {{interval}} reached the median pullback depth")
alertcondition(evDeep, "Price reached the deep pullback level", "Pullback Map: {{ticker}} {{interval}} reached the deep pullback level")
alertcondition(evOrig, "Price reached the origin of the leg", "Pullback Map: {{ticker}} {{interval}} traded back to the origin of the leg")It divides the distance from a swing-leg endpoint to the following opposite swing by that leg’s length, then plots percentiles of retained historical depths on the current leg. Depths reaching or passing the origin are counted separately but excluded from the percentile sample.
The current leg must meet the default 1.5 × ATR(14) size filter, and its selected directional sample must contain at least 20 retained pullbacks. Confirmed pivots and enough completed swing sequences are also needed to build that sample.
Pivots require eight bars to their right by default, so a swing becomes known later than its plotted location. Confirmed swing updates, including a more extreme replacement pivot, can rebuild the current projection; alert-touch checks run on confirmed bars.
The script uses the active chart and does not specify a market or timeframe. Changing timeframe changes its pivots, ATR filter, samples, and levels.
Separate alert conditions detect the first confirmed-bar touch of the zone start, median, deep level, and leg origin for each projection. They are touch notifications, not orders; more than one can occur on the same bar.
No. This is a research indicator, not financial advice, and it does not place or backtest trades. For a defined trading strategy, TradingView Strategy Tester is the source of truth for historical simulation results, which are distinct from paper-trading and live results.
Describe the change in plain English and AlgoNexta rebuilds it as a fresh Pine v6 script — with its own explanation, evidence, and walkthrough.
Build your own versionEducational content only — not financial advice. TradingView is the source of truth for live data, compilation, and Strategy Tester results.