//@version=6 // Automatic Supply and Demand Zone Identifier // Detects leg-in / base / leg-out formations, draws supply and demand zones and tracks their life cycle // (fresh -> tested -> broken when the distal line is touched). All rule values are inputs. indicator("Automatic Supply and Demand Zone Identifier", "S&D Zones", overlay = true, max_boxes_count = 500, max_labels_count = 500, max_bars_back = 60) // ── settings: zone rules string GR = "Zone rules" float BASE_MAX = input.float(40.0, "Base candle: body % at most", minval = 1, maxval = 99, step = 5, group = GR, tooltip = "A candle whose body is at most this share of its range counts as a base candle.") float DEC_MIN = input.float(40.0, "Decisive candle: body % above", minval = 1, maxval = 99, step = 5, group = GR, tooltip = "Used for a leg-out made of two candles in the same direction.") float EXPL_MIN = input.float(65.0, "Explosive candle: body % above", minval = 1, maxval = 99, step = 5, group = GR, tooltip = "A single candle above this value can form the leg-out on its own.") int MAX_BASE = input.int(8, "Base candles at most", minval = 1, maxval = 20, group = GR) string proxType = input.string("Body (preferred)", "Proximal line", options = ["Body (preferred)", "Wick (wider)"], group = GR, tooltip = "Body: outermost candle body of the base (narrower zone). Wick: outermost wick of the base (wider zone).") float STICK_MIN = input.float(50.0, "Leg-out must stick out past the base body (% of its range)", minval = 0, maxval = 100, step = 5, group = GR) float H_MAX = input.float(1.25, "Zone height at most (x range of the leg-out run)", minval = 0.1, step = 0.05, group = GR) float DUP_TOL = input.float(0.33, "Skip near-duplicate zones (tolerance x zone height)", minval = 0, step = 0.01, group = GR, tooltip = "A new zone is skipped when an existing zone of the same side has both lines within this tolerance. 0 = keep every zone.") bool useWick = proxType == "Wick (wider)" float EPS = 1e-9 // tolerance for threshold comparisons (65.00000000000006 counts as 65) // ── settings: display string GD = "Display" string M_LIVE = "Valid zones only" string M_ALL = "All zones in the visible range (incl. broken)" string showS = input.string(M_LIVE, "Zones to show", options = [M_LIVE, M_ALL], group = GD, tooltip = "Valid zones only: zones that are not broken yet.\n\nAll zones in the visible range: every zone from its creation to the bar that broke it, for the part of the chart you are looking at. The script redraws when you scroll.") int MAX_ACTIVE = input.int(3, "Valid zones: nearest per side (0 = all)", minval = 0, group = GD, tooltip = "Applies to 'Valid zones only'. 3 = the three demand and the three supply zones nearest to the current price.") string F_BOTH = "Fresh and tested" string F_FRESH = "Fresh only" string F_TEST = "Tested only" string stateS = input.string(F_BOTH, "Valid zones: state", options = [F_BOTH, F_FRESH, F_TEST], group = GD, tooltip = "Applies to 'Valid zones only'. A zone is tested once price has returned to its proximal line.") string L_FULL = "Full (Drop-Base-Rally · Demand Zone · Fresh)" string L_SHORT = "Short (DBR · Fresh)" string L_OFF = "Off" string labelS = input.string(L_FULL, "Labels", options = [L_FULL, L_SHORT, L_OFF], group = GD) string sizeS = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = GD) bool showBase = input.bool(true, "Highlight the base", group = GD) int EXT_BARS = input.int(80, "Extend valid zones to the right (bars)", minval = 1, maxval = 400, group = GD) color C_DEM = input.color(color.new(#26A69A, 78), "Demand", group = GD, inline = "c1") color C_SUP = input.color(color.new(#EF5350, 78), "Supply", group = GD, inline = "c1") color C_TEST = input.color(color.new(#9598A1, 85), "Tested", group = GD, inline = "c2") color C_BASE = input.color(color.new(#42A5F5, 70), "Base", group = GD, inline = "c2") color C_TEXT = input.color(#D1D4DC, "Text", group = GD, inline = "c2") bool histMode = showS == M_ALL bool showLabel = labelS != L_OFF string LSIZE = sizeS == "Tiny" ? size.tiny : sizeS == "Small" ? size.small : sizeS == "Normal" ? size.normal : size.large // labels start at the last leg-out candle and run to the right, so they stay inside the zone at every zoom level // bar interval = time[1] - time[2] (measured on the closed bars, so it is 3 days after a weekend) color C_HIDE = color.new(#9598A1, 100) // hidden fill color C_BORDER = #B2B5BE // zone border (dotted) color C_NOLINE = color.new(#B2B5BE, 100) // invisible border type Zone bool dem float prox float distal int zi int tzi int tbs int tbe string pat bool gap float pb // base-body proximal (used by the duplicate check in both variants) bool tested = false bool active = true box zb box bb label lb var array zones = array.new() var int lastZi = -1 // bar index of the last leg-out candle of the most recently created zone // body % of range; the range is floored at one tick (matters for instruments whose daily range is below a tick) bp(int k) => 100.0 * math.abs(close[k] - open[k]) / math.max(high[k] - low[k], syminfo.mintick) isBase(int k) => bp(k) <= BASE_MAX + EPS dirOf(int k) => math.sign(close[k] - open[k]) patName(string p) => p == "RBR" ? "Rally-Base-Rally" : p == "DBR" ? "Drop-Base-Rally" : p == "RBD" ? "Rally-Base-Drop" : "Drop-Base-Drop" zoneText(Zone z) => string state = z.tested ? "Tested" : "Fresh" labelS == L_SHORT ? z.pat + " · " + state : patName(z.pat) + " · " + (z.dem ? "Demand Zone" : "Supply Zone") + " · " + state + (z.gap ? " · Gap" : "") // state filter of the "valid zones" view stateOk(Zone z) => stateS == F_BOTH or (stateS == F_FRESH and not z.tested) or (stateS == F_TEST and z.tested) zoneColor(Zone z) => z.tested ? C_TEST : z.dem ? C_DEM : C_SUP // Height check. The leg-out "move" is the run of same-colour candles that ends with the leg-out: // it starts at the first leg-out candle and extends back through the base while the base candles have the // leg-out colour (bullish = close >= open, bearish = close < open). ziO = offset of the last leg-out candle. heightOk(bool D, float bbody, int ziO, int po, int so, int loo) => int j = po while j + 1 <= so and (D ? close[j + 1] >= open[j + 1] : close[j + 1] < open[j + 1]) j += 1 float hi = -1e100 float lo = 1e100 for k = ziO to j hi := math.max(hi, high[k]) lo := math.min(lo, low[k]) float dist = D ? 1e100 : -1e100 for k = ziO to loo dist := D ? math.min(dist, low[k]) : math.max(dist, high[k]) math.abs(bbody - dist) <= H_MAX * math.max(hi - lo, syminfo.mintick) + EPS // run range floored at one tick // Formation whose leg-out ends 2 - sh bars ago (confirmed by the bar 1 - sh bars ago). // sh = 0: drawings (evaluated on the closed previous bar); sh = 1: state one bar ahead, used by the plots. detect(int sh) => Zone res = na for m = 1 to 2 int po = 1 + m - sh // offset of the first leg-out candle int eo = po + 1 // offset of the last base candle if isBase(eo) and not isBase(po) and dirOf(po) != 0 int so = eo while isBase(so + 1) and (so - eo + 1) < MAX_BASE so += 1 int lio = so + 1 if lio <= bar_index and not isBase(lio) bool D = dirOf(po) > 0 float sg = D ? 1.0 : -1.0 float bbody = D ? -1e100 : 1e100 float bwick = D ? -1e100 : 1e100 for k = eo to so bbody := D ? math.max(bbody, math.max(open[k], close[k])) : math.min(bbody, math.min(open[k], close[k])) bwick := D ? math.max(bwick, high[k]) : math.min(bwick, low[k]) bool rev = (dirOf(lio) > 0) != D int loo = rev ? lio : so float rng1 = math.max(high[po] - low[po], syminfo.mintick) // range floored at one tick float st1 = 100.0 * sg * ((D ? high[po] : low[po]) - bbody) / rng1 // a single explosive leg-out that fails the height check is not valid -> the 2-candle leg-out is tried bool singleOk = bp(po) > EXPL_MIN + EPS and st1 >= STICK_MIN - EPS and heightOk(D, bbody, po, po, so, loo) // the 2-candle leg-out is skipped only if the 1-candle version is valid AND actually became a zone bool ok = false if m == 1 ok := singleOk else if not (singleOk and lastZi == bar_index - 3 + sh) and dirOf(po - 1) == dirOf(po) and bp(po - 1) > DEC_MIN + EPS float hi2 = math.max(high[po], high[po - 1]) float lo2 = math.min(low[po], low[po - 1]) float rng2 = math.max(hi2 - lo2, syminfo.mintick) float st2 = 100.0 * sg * ((D ? hi2 : lo2) - bbody) / rng2 ok := st2 >= STICK_MIN - EPS and heightOk(D, bbody, po - 1, po, so, loo) if ok float dist = D ? 1e100 : -1e100 for k = 2 - sh to loo dist := D ? math.min(dist, low[k]) : math.max(dist, high[k]) string pat = (dirOf(lio) > 0 ? "R" : "D") + "B" + (D ? "R" : "D") bool gp = D ? open[po] > math.max(open[eo], close[eo]) : open[po] < math.min(open[eo], close[eo]) res := Zone.new(D, useWick ? bwick : bbody, dist, bar_index - 2 + sh, time[2 - sh], time[so], time[eo], pat, gp, bbody) res // Duplicate check: the new zone nearly duplicates an alive zone of the same side (body proximals and distals both within // DUP_TOL x the new zone's height). nxt = true: check against the state one bar ahead (zones broken on this bar excluded). isDup(Zone nz, bool nxt) => float h = math.max(math.abs(nz.prox - nz.distal), syminfo.mintick) // zone height floored at one tick bool d = false for z in zones bool gone = nxt and (z.dem ? low <= z.distal : high >= z.distal) and bar_index > z.zi if not gone and z.dem == nz.dem and math.abs(z.pb - nz.pb) <= DUP_TOL * h and math.abs(z.distal - nz.distal) <= DUP_TOL * h d := true d if bar_index >= 2 int barMs = time[1] - time[2] // 1) life cycle, evaluated on the closed previous bar int k = bar_index - 1 if zones.size() > 0 for i = zones.size() - 1 to 0 Zone z = zones.get(i) bool viol = z.dem ? low[1] <= z.distal : high[1] >= z.distal if viol and k > z.zi // broken: in the history view the zone stays, ending on the bar that broke it (if it lies in the visible range) if histMode and z.tzi <= chart.right_visible_bar_time and time[1] >= chart.left_visible_bar_time z.zb.set_right(time[1]) if time[1] - z.tzi < 20 * barMs // short-lived zone: short label z.lb.set_text(showLabel ? z.pat : "") else box.delete(z.zb) box.delete(z.bb) label.delete(z.lb) zones.remove(i) else if not z.tested and k >= z.zi + 2 bool touch = z.dem ? low[1] <= z.prox : high[1] >= z.prox if touch z.tested := true if histMode z.zb.set_bgcolor(C_TEST) z.lb.set_text(showLabel ? zoneText(z) : "") // 2) new zone (leg-out ended 2 bars ago, confirmation bar must not touch the distal line) Zone nz = detect(0) if not na(nz) bool confViol = nz.dem ? low[1] <= nz.distal : high[1] >= nz.distal if not confViol and not isDup(nz, false) float top = math.max(nz.prox, nz.distal) float bot = math.min(nz.prox, nz.distal) // the zone box starts at the base; the base is highlighted on top of it nz.zb := box.new(nz.tbs - barMs, top, time[1] + EXT_BARS * barMs, bot, xloc = xloc.bar_time, border_color = C_BORDER, border_width = 1, border_style = line.style_dotted, bgcolor = nz.dem ? C_DEM : C_SUP) nz.lb := label.new(nz.tzi, (top + bot) / 2, showLabel ? zoneText(nz) : "", xloc = xloc.bar_time, style = label.style_label_left, color = C_NOLINE, textcolor = C_TEXT, size = LSIZE, textalign = text.align_left) nz.bb := box.new(nz.tbs - barMs, top, nz.tbe + barMs, bot, xloc = xloc.bar_time, border_color = C_NOLINE, border_width = 0, bgcolor = showBase ? C_BASE : C_HIDE) zones.push(nz) lastZi := nz.zi // 3) display of the valid zones: all of them (history view) or per side the MAX_ACTIVE nearest to the close if barstate.islast and bar_index >= 2 int barMs = time[1] - time[2] for z in zones bool show = true if not histMode show := stateOk(z) if show and MAX_ACTIVE > 0 float d0 = math.abs(z.prox - close) int rank = 0 for o in zones if o.dem == z.dem and stateOk(o) and math.abs(o.prox - close) < d0 rank += 1 show := rank < MAX_ACTIVE z.active := show z.zb.set_right(z.active ? time[1] + EXT_BARS * barMs : z.tzi) z.zb.set_bgcolor(z.active ? zoneColor(z) : C_HIDE) z.zb.set_border_color(z.active ? C_BORDER : C_NOLINE) z.bb.set_bgcolor(z.active and showBase ? C_BASE : C_HIDE) z.lb.set_text(z.active and showLabel ? zoneText(z) : "") // 4) plots: nearest fresh zone to the close, using the zone state one bar ahead of the drawings // (life cycle on the current bar, new zone confirmed by the current bar). Close inside a fresh zone = distance 0. // Exact ties (float noise only) go to the older zone. float TOL = 1e-10 float pProx = na float pDist = na float best = na pick(Zone z, float b) => float lo = math.min(z.prox, z.distal) float hi = math.max(z.prox, z.distal) float d = close >= lo and close <= hi ? 0.0 : math.abs(z.prox - close) na(b) or d < b - TOL ? d : na // On the still-forming realtime bar there is no look-ahead: the zones are used exactly as drawn. bool la = barstate.isconfirmed if bar_index >= 2 for z in zones bool gone = la and (z.dem ? low <= z.distal : high >= z.distal) and bar_index > z.zi bool tnext = z.tested or (la and bar_index >= z.zi + 2 and (z.dem ? low <= z.prox : high >= z.prox)) if not gone and not tnext float d = pick(z, best) if not na(d) best := d pProx := z.prox pDist := z.distal Zone nx0 = detect(1) Zone nx = la ? nx0 : na if not na(nx) bool nViol = nx.dem ? low <= nx.distal : high >= nx.distal if not nViol and not isDup(nx, true) float d = pick(nx, best) if not na(d) best := d pProx := nx.prox pDist := nx.distal plot(pProx, "Nearest zone · proximal", color.blue, display = display.data_window) plot(pDist, "Nearest zone · distal", color.blue, display = display.data_window)