本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// ─────────────────────────────────────────────────────────────────
// ███████╗██████╗ ██████╗ ██╗ █████╗ ██████╗
// ██╔════╝██╔══██╗██╔═══██╗██║ ██╔══██╗██╔══██╗
// █████╗ ██║ ██║██║ ██║██║ ███████║██████╔╝
// ██╔══╝ ██║ ██║██║ ██║██║ ██╔══██║██╔══██╗
// ███████╗██████╔╝╚██████╔╝███████╗██║ ██║██████╔╝
// ╚══════╝╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═════╝
// ─────────────────────────────────────────────────────────────────
// ███╗ ███╗ █████╗ ██████╗ ██╗ ██╗███████╗████████╗███████╗
// ████╗ ████║██╔══██╗██╔══██╗██║ ██╔╝██╔════╝╚══██╔══╝██╔════╝
// ██╔████╔██║███████║██████╔╝█████╔╝ █████╗ ██║ ███████╗
// ██║╚██╔╝██║██╔══██║██╔══██╗██╔═██╗ ██╔══╝ ██║ ╚════██║
// ██║ ╚═╝ ██║██║ ██║██║ ██║██║ ██╗███████╗ ██║ ███████║
// ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚══════╝
// ─────────────────────────────────────────────────────────────────
// © Edolab Markets
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("Edo Range State", overlay = true, behind_chart = false, max_boxes_count = 20, max_lines_count = 20, max_labels_count = 30)
// What changes when a new bar arrives (read before judging the drawing):
// 1. Every decision is taken on CLOSED bars only. While a bar is forming, the state, the box,
// the counters and the alerts stay as they were at the previous close. Nothing is judged intrabar.
// 2. A range is confirmed on the close of the bar that completes the detection window. Its box is
// drawn from the first bar of that window: the box starts in the past, but it only appears
// on the confirmation bar and its top and bottom never move afterwards.
// 3. The box of a FORMING range (not yet confirmed) is provisional: it is drawn on the last bar only,
// follows the latest bars and disappears if the range is not confirmed. No forming box is kept.
// 4. Breakouts, failed breakouts and confirmations are judged against the fixed box of the range.
// Markers and finished boxes never move.
// 5. Efficiency, height and volatility use bars up to the current close. No higher timeframe data,
// no future bars.
// 6. The origin bias (green or red) is read once, from the first candle of the detection window, when the
// range is confirmed. It never changes afterwards. The history counters (how many ranges ended, their
// average length, the share that broke the way of their origin candle) only count ranges that ENDED
// inside the loaded history, so they depend on how many candles the chart has loaded.
// 7. The right-edge labels and the panel corner follow the visible part of the chart, so they can change
// when you scroll or zoom. The state, the boxes, the markers and the alerts do not.
// ================== CONSTANTS ==================
const string EDGE_W = "Wicks (high / low)"
const string EDGE_B = "Bodies (open / close)"
const int ATR_SLOW = 50 // yardstick for heights and distances
const int ATR_FAST = 14 // short-term volatility, compared with the slow one
const int FAIL_BARS = 3 // closed bars the failed-breakout state stays on screen
const int BUF_SIZE = 210 // closed bars kept for the window scan (longest window + margin)
const float HYST = 0.10 // efficiency margin that keeps Forming and Trend from flickering around their thresholds
const float HYST_H = 1.15 // height margin (x Maximum Range Height) that keeps a forming range alive
const float SIDE_SHARE = 0.35 // part of the visible chart, at each side, that a panel can cover
const float LOGO_PCT = 9.0 // bottom-left: empty row under the panel (% of the pane) so the TradingView logo does not cover its last row
const float ICON_PCT = 6.0 // bottom-right: the same for the round TradingView button in that corner
const float LEGEND_PCT = 10.0 // top-left: empty row above the panel so the TradingView legend does not cover it
const float ROW_SHARE = 0.035 // height of one panel row as a share of the visible price span (Medium); Small = 0.028
const int MAX_BODY = 7 // body rows in Full; with title, footer and one spacer the table never passes 10 rows
const int MAX_BODY_C = 4 // body rows in Compact
gDet = "Detection"
gBrk = "Breakouts"
gSt = "States"
gDsp = "Display"
gSty = "Style"
gPan = "Panel"
// ================== SETTINGS — DETECTION ==================
winLen = input.int(20, "Detection Window (bars)", minval = 8, maxval = 200, group = gDet, tooltip = "Number of closed bars examined to recognise a range. The range is confirmed on the close of the bar that completes a window meeting the three rules below, and its box covers the whole window. Shorter windows find small pauses; 40-60 finds the larger trading ranges. The height and efficiency limits below are set for 20 bars and adjust on their own to other windows, so you can change the window alone.")
maxH = input.float(5.0, "Maximum Range Height (ATR)", minval = 1.0, maxval = 20.0, step = 0.5, group = gDet, tooltip = "Rule 1 · compact. Distance between the highest and the lowest edge of the window, measured in 50-bar ATR, for a 20-bar window. Taller windows are a move, not a range. With other windows the limit is scaled by the square root of window / 20 (about 7.9 ATR for 50 bars); the panel shows the value in use.")
maxEff = input.float(0.30, "Maximum Efficiency", minval = 0.05, maxval = 0.80, step = 0.05, group = gDet, tooltip = "Rule 2 · no net direction. Efficiency = net change of the close over the window divided by the sum of every close-to-close change. 0 = price went back and forth and ended where it started; 1 = a straight line. Ranges sit low; trends sit high. Set for a 20-bar window and divided by the square root of window / 20 for other windows; the panel shows the value in use.")
minTests = input.int(2, "Tests Required per Edge", minval = 1, maxval = 5, group = gDet, tooltip = "Rule 3 · rotation. Separate visits of price to the top zone and to the bottom zone inside the window. A visit is one or more consecutive candles whose wick reaches the zone. 2 = price has gone from one side to the other and back at least once.")
edgeMode = input.string(EDGE_W, "Range Edges", options = [EDGE_W, EDGE_B], group = gDet, tooltip = "Wicks: the box goes from the lowest low to the highest high of the window. Bodies: it uses the highest and lowest candle bodies, so a single long wick does not stretch the box; wicks beyond the box are then tests, not breakouts.")
zonePct = input.int(20, "Edge Zone (% of range height)", minval = 5, maxval = 40, group = gDet, tooltip = "Depth of the top and bottom zones where a wick counts as a test of the edge, as a percentage of the box height.")
extWick = input.bool(false, "Grow Range with Inside Closes", group = gDet, tooltip = "Off (default) = the box never moves after it is confirmed. On = a candle that closes inside the box but whose wick (or body, in Bodies mode) goes beyond it stretches the box to that extreme; only candles that close inside can stretch it, a close beyond the edge never does. The tests, the breakout levels and the labels then follow the stretched edges.")
// ================== SETTINGS — BREAKOUTS ==================
brkBuf = input.float(0.10, "Breakout Buffer (ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = gBrk, tooltip = "A breakout starts when a candle CLOSES beyond the top or bottom by at least this distance in 50-bar ATR. Closes inside the buffer are still treated as inside the range.")
holdBars = input.int(3, "Closes Needed to Confirm", minval = 1, maxval = 20, group = gBrk, tooltip = "Consecutive closes beyond the edge, counting the breakout candle, that confirm the breakout and end the range. If a close comes back inside the box before that, the breakout is marked as failed and the range goes on.")
fastConf = input.float(1.0, "Early Confirmation Distance (ATR)", minval = 0.0, maxval = 5.0, step = 0.25, group = gBrk, tooltip = "A close this far beyond the edge, in 50-bar ATR, confirms the breakout at once without waiting for the closes above. 0 = off.")
// ================== SETTINGS — STATES ==================
matureX = input.float(2.0, "Mature After (x Detection Window)", minval = 1.0, maxval = 10.0, step = 0.5, group = gSt, tooltip = "A confirmed range becomes Mature once it has lasted this many times the detection window (default 2 x 20 = 40 bars).")
trendEff = input.float(0.45, "Trend Efficiency", minval = 0.20, maxval = 1.0, step = 0.05, group = gSt, tooltip = "Outside a range, the market is read as trending up or down when the efficiency of the detection window reaches this value (set for 20 bars and scaled like Maximum Efficiency). It holds until efficiency drops 0.10 below it. Between the two thresholds the state is No range, transition.")
// ================== SETTINGS — DISPLAY ==================
showForm = input.bool(true, "Show Forming Range", group = gDsp, tooltip = "Dashed provisional box while a range is forming. It follows the latest bars and disappears if the range is not confirmed.")
showHist = input.bool(true, "Show Finished Ranges", group = gDsp, tooltip = "Finished ranges stay on the chart, filled green if they broke up and red if they broke down.")
histKeep = input.int(3, "Finished Ranges Kept", minval = 1, maxval = 10, group = gDsp, tooltip = "How many finished ranges stay on the chart. The oldest is removed first.")
showSum = input.bool(true, "Show Range Summary", group = gDsp, tooltip = "Label above each finished range with its length and how it ended.")
showTests = input.bool(true, "Show Edge Tests", group = gDsp, tooltip = "Small dots on the candles that test the top or the bottom of a confirmed range. Legend: dot = edge test, triangle = first close beyond the box, orange cross = failed breakout.")
showMarks = input.bool(true, "Show Breakout Markers", group = gDsp, tooltip = "Triangles on the first close beyond the box; crosses when that breakout fails and price closes back inside. Legend: dot = edge test, triangle = first close beyond the box, orange cross = failed breakout.")
markGap = input.int(5, "Min Bars Between Markers", minval = 1, maxval = 100, group = gDsp, tooltip = "A marker is skipped when another marker of the same kind (edge test, breakout, failed breakout) was drawn less than this many bars before, so a zoomed-out chart is not covered with dots. The panel and the alerts keep every event.")
extR = input.int(10, "Projection (bars)", minval = 0, maxval = 50, group = gDsp, tooltip = "The active box is extended this many bars to the right of the last candle.")
showLbl = input.bool(true, "Show Edge Labels", group = gDsp, tooltip = "Price of the top, the midline and the bottom at the right edge, with their distance to the close in 50-bar ATR. The labels end where the projection ends and grow to the left, so nothing passes the right edge.")
labelSep = input.float(0.8, "Label Spacing (ATR)", minval = 0.2, maxval = 5.0, step = 0.1, group = gDsp, tooltip = "Minimum vertical gap between the right-edge labels, in 50-bar ATR. It also grows when the chart is zoomed out, so the labels never overlap. A label moved off its level is joined to it by a dotted connector.")
labelSize = input.string("Medium", "Label Size", options = ["Small", "Medium", "Large"], group = gDsp, tooltip = "Text size of the right-edge labels and of the summary above each finished range.")
// ================== SETTINGS — STYLE ==================
rangeCol = input.color(#6e7ff3, "Range", group = gSty, tooltip = "Colour of a forming range and of an active range whose first candle is a doji. An active range takes green or red from the first candle of its detection window (its origin bias), not as a forecast.")
bullCol = input.color(#4caf50, "Up", inline = "c1", group = gSty)
bearCol = input.color(#e53935, "Down", inline = "c1", group = gSty, tooltip = "Origin bias, breakouts, finished ranges and trends take green when up and red when down.")
warnCol = input.color(#f5a623, "Failed Breakout", group = gSty)
flatCol = input.color(#9598a1, "No Range", group = gSty)
fillTr = input.int(85, "Range Fill Transparency", minval = 50, maxval = 100, group = gSty, tooltip = "Fill of the active range in the dark theme (the light theme is drawn 10 points stronger so it stays visible; a forming range is a little stronger than this too). The study is drawn in front of the candles, so keep it high enough to see them through it. 100 = no fill.")
histTr = input.int(90, "Finished Range Fill Transparency", minval = 50, maxval = 100, group = gSty, tooltip = "Fill of the finished ranges (green if they broke up, red if down). The light theme is drawn 10 points stronger. 100 = no fill.")
// ================== SETTINGS — PANEL ==================
showPanel = input.bool(true, "Show Panel", group = gPan, tooltip = "Small table with the range state, the box, its age, the position of price, the tests, the origin bias and the last event.")
panelDetail = input.string("Full", "Panel Detail", options = ["Full", "Compact"], group = gPan, tooltip = "Compact keeps only the state, the range (or the window), the position of price and the last event.")
panelPos = input.string("Top Right", "Panel Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = gPan, tooltip = "Preferred corner. With Keep Panel Off the Drawing on, the panel moves when this corner would cover the latest candles, the box or the labels.")
panelAvoid = input.bool(true, "Keep Panel Off the Drawing", group = gPan, tooltip = "The panel stays in the corner chosen while it has room; otherwise it moves to the other corner of the same side, then to the other side (left corners cover the oldest candles). Off = the panel never moves.")
panelSize = input.string("Medium", "Panel Size", options = ["Small", "Medium"], group = gPan, tooltip = "Text size of the panel.")
themeMode = input.string("Dark", "Theme Mode", options = ["Dark", "Light"], group = gPan, tooltip = "Match your TradingView background theme.")
panelOpacity = input.int(70, "Panel Opacity (%)", minval = 0, maxval = 100, group = gPan, tooltip = "100 = solid background, 0 = transparent.")
// ================== THEME ==================
isDark = themeMode == "Dark"
textCol = isDark ? #ffffff : #131722
headerBg = isDark ? #2a2e39 : #d1d4dc
subHeaderBg = isDark ? #363a45 : #e0e3eb
cellBg = isDark ? #1e222d : #f0f3fa
cellTxt = isDark ? #d1d4dc : #363a45
numTxt = isDark ? #b2b5be : #555a67
panelTransp = 100 - panelOpacity
// Fills are stronger in the light theme so the boxes do not vanish on a white chart
fillA = isDark ? fillTr : math.max(fillTr - 10, 50)
histA = isDark ? histTr : math.max(histTr - 10, 50)
formA = math.max(fillA - 8, 50)
midW = isDark ? 1 : 2
lblSz = labelSize == "Small" ? size.small : labelSize == "Large" ? size.large : size.normal
panSz = panelSize == "Small" ? size.tiny : size.small
// ================== SERIES (every bar) ==================
atrS = ta.atr(ATR_SLOW)
atrF = ta.atr(ATR_FAST)
edgeHi = edgeMode == EDGE_W ? high : math.max(open, close)
edgeLo = edgeMode == EDGE_W ? low : math.min(open, close)
formLen = math.max(5, int(math.round(winLen * 0.6)))
// The thresholds are set for a 20-bar window and scaled with the square root of the window,
// the way the height and the efficiency of a random walk change with its length
float wScale = math.sqrt(winLen / 20.0)
float maxHx = maxH * wScale
float maxEx = maxEff / wScale
float trendX = trendEff / wScale
// Detection window (the latest winLen closed bars, this one included)
hiW = ta.highest(edgeHi, winLen)
loW = ta.lowest(edgeLo, winLen)
netW = close - close[winLen - 1]
pathW = math.sum(math.abs(close - close[1]), winLen - 1)
effW = pathW > 0 ? math.abs(netW) / pathW : 1.0
startT = time[winLen - 1]
// Origin candle: the first candle of the detection window (bias read once, at confirmation)
oW = open[winLen - 1]
cW = close[winLen - 1]
biasW = cW > oW ? 1 : cW < oW ? -1 : 0
// Shorter window used to spot a range while it is still forming
hiF = ta.highest(edgeHi, formLen)
loF = ta.lowest(edgeLo, formLen)
pathF = math.sum(math.abs(close - close[1]), formLen - 1)
effF = pathF > 0 ? math.abs(close - close[formLen - 1]) / pathF : 1.0
// ================== TYPES ==================
// Drawings of one range
type Rng
box bx
line md
label lb
// ================== HELPERS ==================
fmt(float v) => na(v) ? "—" : str.tostring(v, format.mintick)
plural(int n, string one, string many) => str.tostring(n) + " " + (n == 1 ? one : many)
dateTxt(int t) => str.format_time(t, timeframe.isintraday ? "dd MMM HH:mm" : "dd MMM yyyy", syminfo.timezone)
agoTxt(int b) => b == bar_index ? "this bar" : plural(bar_index - b, "bar", "bars") + " ago"
biasCol(int b) => b == 1 ? bullCol : b == -1 ? bearCol : rangeCol
addRow(array<string> ks, array<string> vs, array<color> cs, string k, string v, color c) =>
ks.push(k)
vs.push(v)
cs.push(c)
delRng(Rng r) =>
box.delete(r.bx)
line.delete(r.md)
label.delete(r.lb)
// ================== CLOSED-BAR BUFFER ==================
var bH = array.new<float>()
var bL = array.new<float>()
var bC = array.new<float>()
// Separate visits to the top (side 1) or bottom (side -1) zone over the last n stored bars
visits(float top, float bot, int n, int side) =>
int sz = bC.size()
float tz = zonePct / 100.0 * (top - bot)
int cnt = 0
bool prv = false
if sz >= n and n > 0
for i = sz - n to sz - 1
bool at = side == 1 ? bH.get(i) >= top - tz : bL.get(i) <= bot + tz
if at and not prv
cnt += 1
prv := at
cnt
// Closes at or above the midline over the last n stored bars
upperCount(float mid, int n) =>
int sz = bC.size()
int cnt = 0
if sz >= n and n > 0
for i = sz - n to sz - 1
if bC.get(i) >= mid
cnt += 1
cnt
// ================== RANGE STATE (closed bars only) ==================
// Active range
var bool inRange = false
var float rTop = na
var float rBot = na
var int rStart = na
var int rStartT = na
var int nTop = 0
var int nBot = 0
var int nFail = 0
var int nInside = 0
var int nUpper = 0
var bool atTopPrv = false
var bool atBotPrv = false
// Breakout in progress: side 1 up, -1 down, 0 none
var int pendSide = 0
var int pendBar = na
var int pendCnt = 0
var int failSide = 0
var int failBar = na
// Last finished range
var int endSide = 0
var int rBias = 0
var int endBias = 0
// Finished ranges (counters over the loaded history): how many, total length, how many had an origin bias,
// how many of those broke the way of their origin candle
var int hN = 0
var int hLen = 0
var int hNb = 0
var int hAl = 0
var int endBar = na
var float endTop = na
var float endBot = na
var int endLen = 0
var bool endBack = false
// Last event: 1 range confirmed · 2 top test · -2 bottom test · 3/-3 breakout started · 4/-4 failed breakout
// 5/-5 range ended up/down · 6/-6 back inside the broken range
var int lastEv = 0
var int lastEvB = na
var int state = 0
var bool forming = false
var int trendDir = 0
var int okStreak = 0
var int noStreak = 0
var rngs = array.new<Rng>()
var Rng curR = na
bool evConfirm = false
bool evTestTop = false
bool evTestBot = false
bool evBrkUp = false
bool evBrkDn = false
bool evFailUp = false
bool evFailDn = false
bool evEndUp = false
bool evEndDn = false
bool evBackIn = false
bool evMature = false
bool evEndAl = false
bool evEndAg = false
if barstate.isconfirmed
bH.push(high)
bL.push(low)
bC.push(close)
while bC.size() > BUF_SIZE
bH.shift()
bL.shift()
bC.shift()
if barstate.isconfirmed and not na(atrS) and atrS > 0
float buf = brkBuf * atrS
if inRange
float rMid = (rTop + rBot) / 2
// A breakout in progress either fails back inside the box or adds one more close beyond it
if pendSide == 1
if close <= rTop
evFailUp := true
nFail += 1
pendSide := 0
failSide := 1
failBar := bar_index
else
pendCnt += 1
else if pendSide == -1
if close >= rBot
evFailDn := true
nFail += 1
pendSide := 0
failSide := -1
failBar := bar_index
else
pendCnt += 1
// A new breakout starts with a close beyond the edge plus the buffer
if pendSide == 0
if close > rTop + buf
evBrkUp := true
pendSide := 1
pendBar := bar_index
pendCnt := 1
else if close < rBot - buf
evBrkDn := true
pendSide := -1
pendBar := bar_index
pendCnt := 1
// Confirmation: enough consecutive closes beyond the edge, or one close far enough
bool confUp = pendSide == 1 and (pendCnt >= holdBars or (fastConf > 0 and close >= rTop + fastConf * atrS))
bool confDn = pendSide == -1 and (pendCnt >= holdBars or (fastConf > 0 and close <= rBot - fastConf * atrS))
// Occupancy and edge tests (a candle that is breaking out does not count as a test)
if close >= rBot and close <= rTop
nInside += 1
if close >= rMid
nUpper += 1
float tz = zonePct / 100.0 * (rTop - rBot)
bool atTop = pendSide == 0 and high >= rTop - tz
bool atBot = pendSide == 0 and low <= rBot + tz
if atTop and not atTopPrv
nTop += 1
evTestTop := true
if atBot and not atBotPrv
nBot += 1
evTestBot := true
atTopPrv := atTop
atBotPrv := atBot
// Optional: a candle that closes inside but pokes beyond an edge stretches the box (off by default)
if extWick and pendSide == 0 and close >= rBot and close <= rTop and (edgeHi > rTop or edgeLo < rBot)
rTop := math.max(rTop, edgeHi)
rBot := math.min(rBot, edgeLo)
if not na(curR)
box.set_top(curR.bx, rTop)
box.set_bottom(curR.bx, rBot)
line.set_y1(curR.md, (rTop + rBot) / 2)
line.set_y2(curR.md, (rTop + rBot) / 2)
if not na(curR)
box.set_right(curR.bx, bar_index)
line.set_x2(curR.md, bar_index)
if confUp or confDn
evEndUp := confUp
evEndDn := confDn
endSide := confUp ? 1 : -1
endBar := bar_index
endTop := rTop
endBot := rBot
endLen := bar_index - rStart + 1
endBack := false
endBias := rBias
hN += 1
hLen += endLen
if rBias != 0
hNb += 1
if (confUp and rBias == 1) or (confDn and rBias == -1)
hAl += 1
evEndAl := rBias != 0 and ((confUp and rBias == 1) or (confDn and rBias == -1))
evEndAg := rBias != 0 and ((confUp and rBias == -1) or (confDn and rBias == 1))
inRange := false
pendSide := 0
failSide := 0
if not na(curR)
color rc = confUp ? bullCol : bearCol
box.set_border_color(curR.bx, color.new(rc, 30))
box.set_bgcolor(curR.bx, color.new(rc, histA))
line.set_color(curR.md, color.new(rc, 60))
if showSum
string sTxt = "Range · " + plural(endLen, "bar", "bars") + " · broke " + (confUp ? "up" : "down") + (evEndAl ? " · with its origin" : evEndAg ? " · against its origin" : "")
curR.lb := label.new(int(math.round((rStart + bar_index) / 2.0)), rTop, sTxt, style = label.style_label_down, color = color.new(rc, 25), textcolor = #ffffff, size = lblSz)
if not showHist
rngs.pop()
delRng(curR)
while rngs.size() > histKeep
delRng(rngs.shift())
curR := na
else
// Within the window after a confirmed breakout, a close back inside the old box cancels the breakout reading
if endSide != 0 and not endBack and bar_index - endBar < winLen and close <= endTop and close >= endBot
endBack := true
evBackIn := true
// A new range can only use bars after the end of the previous one
bool freeW = na(endBar) or bar_index - winLen + 1 > endBar
bool freeF = na(endBar) or bar_index - formLen + 1 > endBar
bool okW = freeW and bC.size() >= winLen and hiW - loW <= maxHx * atrS and effW <= maxEx
bool okF = freeF and bC.size() >= formLen and hiF - loF <= maxHx * atrS and effF <= maxEx
int tv = okW ? visits(hiW, loW, winLen, 1) : 0
int bv = okW ? visits(hiW, loW, winLen, -1) : 0
if okW and tv >= minTests and bv >= minTests
evConfirm := true
inRange := true
rTop := hiW
rBot := loW
rStart := bar_index - winLen + 1
rStartT := startT
rBias := biasW
nTop := tv
nBot := bv
nFail := 0
nInside := winLen
nUpper := upperCount((hiW + loW) / 2, winLen)
pendSide := 0
failSide := 0
float tz0 = zonePct / 100.0 * (hiW - loW)
atTopPrv := high >= hiW - tz0
atBotPrv := low <= loW + tz0
color ac = biasCol(biasW)
box bx = box.new(rStart, rTop, bar_index, rBot, border_color = ac, border_width = 2, bgcolor = color.new(ac, fillA))
line md = line.new(rStart, (rTop + rBot) / 2, bar_index, (rTop + rBot) / 2, color = color.new(ac, 30), style = line.style_dashed, width = midW)
curR := Rng.new(bx, md, na)
rngs.push(curR)
while rngs.size() > histKeep + 1
delRng(rngs.shift())
// Forming starts on the strict rules and holds on slightly looser ones, so it does not flicker
bool keepF = freeF and bC.size() >= formLen and hiF - loF <= maxHx * HYST_H * atrS and effF <= maxEx + HYST
// Two closes in a row are needed both to start and to stop a forming range
okStreak := okW or okF ? okStreak + 1 : 0
noStreak := keepF or okW ? 0 : noStreak + 1
forming := not inRange and (okW or okStreak >= 2 or (forming and noStreak < 2))
if inRange
forming := false
// State code
// 0 no range · 1 forming · 2 range · 3 mature range · 4/-4 breakout in progress · 5/-5 failed breakout, back inside
// 6/-6 breakout confirmed, range ended · 7/-7 trend
int st = 0
if inRange
int age = bar_index - rStart + 1
st := pendSide != 0 ? 4 * pendSide : failSide != 0 and bar_index - failBar < FAIL_BARS ? 5 * failSide : age >= matureX * winLen ? 3 : 2
else if forming
st := 1
else if endSide != 0 and not endBack and bar_index - endBar < winLen
st := 6 * endSide
else
// Trend starts at the Trend Efficiency and holds until efficiency drops a margin below it or the direction flips
int dirNow = netW > 0 ? 1 : -1
bool tOn = effW >= trendX or (trendDir == dirNow and effW >= trendX - HYST)
st := tOn ? 7 * dirNow : 0
trendDir := st == 7 ? 1 : st == -7 ? -1 : 0
evMature := st == 3 and state == 2
state := st
int ev = evEndUp ? 5 : evEndDn ? -5 : evFailUp ? 4 : evFailDn ? -4 : evBrkUp ? 3 : evBrkDn ? -3 : evConfirm ? 1 : evBackIn ? (endSide == 1 ? 6 : -6) : evTestTop ? 2 : evTestBot ? -2 : 0
if ev != 0
lastEv := ev
lastEvB := bar_index
// ================== VISIBLE RANGE (display only: nothing in the state or the alerts reads it) ==================
int visL = chart.left_visible_bar_time
int visR = chart.right_visible_bar_time
bool inVis = not na(visL) and not na(visR) and time >= visL and time <= visR
float sideW = inVis ? (visR - visL) * SIDE_SHARE : na
bool inRgt = inVis and time >= visR - sideW
bool inLft = inVis and time <= visL + sideW
var float visHi = na
var float visLo = na
var float rgtHi = na
var float rgtLo = na
var float lftHi = na
var float lftLo = na
if inVis
visHi := na(visHi) ? high : math.max(visHi, high)
visLo := na(visLo) ? low : math.min(visLo, low)
if inRgt
rgtHi := na(rgtHi) ? high : math.max(rgtHi, high)
rgtLo := na(rgtLo) ? low : math.min(rgtLo, low)
if inLft
lftHi := na(lftHi) ? high : math.max(lftHi, high)
lftLo := na(lftLo) ? low : math.min(lftLo, low)
float visSpan = not na(visHi) and not na(visLo) ? visHi - visLo : na
// Approximate height of one label as a share of the visible price span (pane of about 600 px)
float lblH = not na(visSpan) and visSpan > 0 ? visSpan * (labelSize == "Small" ? 0.045 : labelSize == "Large" ? 0.08 : 0.06) : 0.0
// ================== DRAWING (last bar only) ==================
var tmpLines = array.new<line>()
var tmpLabels = array.new<label>()
var box formBox = na
float lblTop = na // top and bottom of the label stack, read by the panel to choose its corner
float lblBot = na
edgeText(string name, float lvl) =>
float d = (lvl - close) / atrS
string t = name + " · " + fmt(lvl)
t + (math.abs(d) < 0.05 ? " · at price" : " · " + str.tostring(math.abs(d), "0.0") + " ATR " + (d > 0 ? "above" : "below") + " price")
// Levels labelled at the right edge: price, text, colour
array<float> lvP = array.new<float>()
array<string> lvT = array.new<string>()
array<color> lvC = array.new<color>()
if barstate.islast
while tmpLines.size() > 0
line.delete(tmpLines.pop())
while tmpLabels.size() > 0
label.delete(tmpLabels.pop())
box.delete(formBox)
formBox := na
int xe = bar_index + extR
if inRange and not na(curR)
box.set_right(curR.bx, xe)
line.set_x2(curR.md, xe)
if showLbl and atrS > 0
color ac = biasCol(rBias)
lvP.push(rTop)
lvT.push(edgeText("Range top", rTop))
lvC.push(ac)
lvP.push((rTop + rBot) / 2)
lvT.push(edgeText("Midline", (rTop + rBot) / 2))
lvC.push(color.new(ac, 25))
lvP.push(rBot)
lvT.push(edgeText("Range bottom", rBot))
lvC.push(ac)
else if forming and showForm
float fT = hiF
float fB = loF
int fS = bar_index - formLen + 1
if hiW - loW <= maxHx * atrS and effW <= maxEx and (na(endBar) or bar_index - winLen + 1 > endBar)
fT := hiW
fB := loW
fS := bar_index - winLen + 1
formBox := box.new(fS, fT, xe, fB, border_color = color.new(rangeCol, 0), border_width = 2, border_style = line.style_dashed, bgcolor = color.new(rangeCol, formA))
if showLbl
lvP.push(fT)
lvT.push("Range forming · " + fmt(fT) + " to " + fmt(fB))
lvC.push(color.new(rangeCol, 15))
else if math.abs(state) == 6 and showLbl and atrS > 0
lvP.push(state == 6 ? endTop : endBot)
lvT.push(edgeText(state == 6 ? "Broken range top" : "Broken range bottom", state == 6 ? endTop : endBot))
lvC.push(state == 6 ? bullCol : bearCol)
if lvP.size() > 0
// Gap between label centres: Label Spacing in ATR, never less than one label height plus a margin
float sep = math.max(labelSep * nz(atrS), lblH * 1.25)
array<int> ord = lvP.sort_indices(order.descending)
float prevY = na
for k = 0 to ord.size() - 1
int i = ord.get(k)
float p = lvP.get(i)
float y = na(prevY) ? p : math.min(p, prevY - sep)
prevY := y
lblTop := na(lblTop) ? y + lblH / 2 : math.max(lblTop, y + lblH / 2)
lblBot := na(lblBot) ? y - lblH / 2 : math.min(lblBot, y - lblH / 2)
if y != p
tmpLines.push(line.new(xe, p, xe, y, color = color.new(lvC.get(i), 30), style = line.style_dotted, width = 1))
// style_label_right: the label ends at the end of its level and grows to the left, never past the right edge
tmpLabels.push(label.new(xe, y, lvT.get(i), style = label.style_label_right, color = color.new(lvC.get(i), 15), textcolor = #ffffff, size = lblSz, tooltip = lvT.get(i)))
// The box and its edges also count as drawing for the panel corner
if inRange
lblTop := math.max(nz(lblTop, rTop), rTop)
lblBot := math.min(nz(lblBot, rBot), rBot)
// ================== READINGS (one value per bar, for external tools) ==================
int rsState = state
int rsInRange = inRange ? 1 : 0
float rsPos = inRange and rTop > rBot ? (close - rBot) / (rTop - rBot) * 100 : na
float rsDistTop = inRange and atrS > 0 ? (rTop - close) / atrS : 999.0
float rsDistBot = inRange and atrS > 0 ? (close - rBot) / atrS : 999.0
float rsHeight = inRange and atrS > 0 ? (rTop - rBot) / atrS : na
int rsAge = inRange ? bar_index - rStart + 1 : 0
float rsInside = inRange ? nInside / (bar_index - rStart + 1.0) * 100 : na
float rsUpper = inRange ? nUpper / (bar_index - rStart + 1.0) * 100 : na
float rsComp = atrS > 0 ? atrF / atrS : na
float rsEff = effW
int rsLastEv = lastEv
int rsBarsEv = na(lastEvB) ? 999 : bar_index - lastEvB
int rsBias = inRange ? rBias : 0
float rsSameWay = hNb > 0 ? hAl * 100.0 / hNb : na
// ================== PANEL ==================
stateTxt(int st) => st == 1 ? "Range forming" : st == 2 ? "Range active" : st == 3 ? "Mature range" : st == 4 ? "Breakout up in progress" : st == -4 ? "Breakout down in progress" : st == 5 ? "Failed breakout up · back inside" : st == -5 ? "Failed breakout down · back inside" : st == 6 ? "Breakout up confirmed · range ended" : st == -6 ? "Breakout down confirmed · range ended" : st == 7 ? "Trend up · no range" : st == -7 ? "Trend down · no range" : "No range · transition"
stateCol(int st) => st >= 1 and st <= 3 ? rangeCol : st == 4 or st == 6 or st == 7 ? bullCol : st == -4 or st == -6 or st == -7 ? bearCol : math.abs(st) == 5 ? warnCol : flatCol
evTxt(int c) => c == 1 ? "Range confirmed" : c == 2 ? "Top tested" : c == -2 ? "Bottom tested" : c == 3 ? "Close above the top" : c == -3 ? "Close below the bottom" : c == 4 ? "Failed breakout up" : c == -4 ? "Failed breakout down" : c == 5 ? "Range ended · broke up" : c == -5 ? "Range ended · broke down" : c == 6 ? "Back inside the broken range from above" : c == -6 ? "Back inside the broken range from below" : "None yet"
evCol(int c) => c == 1 or math.abs(c) == 2 ? rangeCol : c == 3 or c == 5 ? bullCol : c == -3 or c == -5 ? bearCol : math.abs(c) == 4 or math.abs(c) == 6 ? warnCol : textCol
biasName(int b) => b == 1 ? "Green" : b == -1 ? "Red" : "Neutral"
// What the finished ranges say: how many, how long, how many broke the way of their origin candle
histTxt() => hN == 0 ? "No finished range yet in the loaded history" : plural(hN, "range", "ranges") + " · average " + plural(int(math.round(hLen / (hN * 1.0))), "bar", "bars") + (hNb > 0 ? " · " + str.tostring(hAl * 100.0 / hNb, "0") + " % broke the way of their origin candle" : "")
panelRow(table t, int r, string k, string v, color vc, color bg) =>
table.cell(t, 0, r, k, text_color = cellTxt, bgcolor = bg, text_size = panSz, text_halign = text.align_left)
table.cell(t, 1, r, v, text_color = vc, bgcolor = bg, text_size = panSz, text_halign = text.align_left)
varip int lastCorner = -1 // corner used on the previous tick of the live candle (display only)
if showPanel
panelPosTV = switch panelPos
"Top Right" => position.top_right
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
=> position.top_right
// Created ONCE (var) and moved with table.set_position: changing the corner never leaves a ghost panel
var table panel = table.new(panelPosTV, 2, 10, frame_color = isDark ? #363a45 : #b2b5be, frame_width = 1, border_color = isDark ? #434651 : #c8cbda, border_width = 1)
if barstate.islast
table.clear(panel, 0, 0, 1, 9)
bool full = panelDetail == "Full"
color bgMain = color.new(cellBg, panelTransp)
color bgHead = color.new(headerBg, panelTransp)
color bgSub = color.new(subHeaderBg, panelTransp)
// 1. Rows first, drawn once the corner is known
array<string> rowK = array.new<string>()
array<string> rowV = array.new<string>()
array<color> rowC = array.new<color>()
string stTxt = stateTxt(state)
if state == 4 or state == -4
stTxt := stTxt + " · " + str.tostring(pendCnt) + " of " + str.tostring(holdBars) + " closes"
else if state == 6 or state == -6
stTxt := stTxt + " " + agoTxt(endBar)
addRow(rowK, rowV, rowC, "State", stTxt, stateCol(state))
string chk = str.tostring(winLen) + " bars · " + (na(atrS) or atrS <= 0 ? "height not measurable yet (needs 50 bars of history)" : str.tostring((hiW - loW) / atrS, "0.0") + " ATR tall (max " + str.tostring(maxHx, "0.0") + ")") + " · efficiency " + str.tostring(effW, "0.00") + " (max " + str.tostring(maxEx, "0.00") + ")"
if inRange
int age = bar_index - rStart + 1
float h = rTop - rBot
float posPct = h > 0 ? (close - rBot) / h * 100 : 50.0
addRow(rowK, rowV, rowC, "Range", fmt(rTop) + " to " + fmt(rBot) + " · " + str.tostring(h / atrS, "0.0") + " ATR tall", textCol)
if full
int matBars = int(math.ceil(matureX * winLen))
addRow(rowK, rowV, rowC, "Age", plural(age, "bar", "bars") + " · since " + dateTxt(rStartT) + (age < matBars ? " · mature at " + str.tostring(matBars) : ""), textCol)
string posTxt = close > rTop ? str.tostring((close - rTop) / atrS, "0.0") + " ATR above the top" : close < rBot ? str.tostring((rBot - close) / atrS, "0.0") + " ATR below the bottom" : str.tostring(posPct, "0") + " % of the range · " + str.tostring((rTop - close) / atrS, "0.0") + " ATR to top · " + str.tostring((close - rBot) / atrS, "0.0") + " ATR to bottom"
addRow(rowK, rowV, rowC, "Position", posTxt, textCol)
if full
addRow(rowK, rowV, rowC, "Tests", "Top " + str.tostring(nTop) + " · bottom " + str.tostring(nBot) + " · failed breakouts " + str.tostring(nFail) + " · " + str.tostring(nInside / (age * 1.0) * 100, "0") + " % of closes inside", textCol)
addRow(rowK, rowV, rowC, "Origin", biasName(rBias) + " first candle" + (hNb > 0 and rBias != 0 ? " · " + str.tostring(hAl) + " of " + str.tostring(hNb) + " past ranges (" + str.tostring(hAl * 100.0 / hNb, "0") + " %) broke that way" : hN > 0 ? " · " + histTxt() : ""), rBias == 1 ? bullCol : rBias == -1 ? bearCol : textCol)
else if state == 6 or state == -6
addRow(rowK, rowV, rowC, "Last range", fmt(endTop) + " to " + fmt(endBot) + " · lasted " + plural(endLen, "bar", "bars"), textCol)
float dOut = state == 6 ? (close - endTop) / atrS : (endBot - close) / atrS
addRow(rowK, rowV, rowC, "Position", str.tostring(dOut, "0.0") + " ATR " + (state == 6 ? "above the old top" : "below the old bottom"), textCol)
if full
addRow(rowK, rowV, rowC, "Origin", biasName(endBias) + " first candle" + (endBias == 0 ? "" : (endBias == state / 6 ? " · broke the same way" : " · broke the other way")), endBias == 1 ? bullCol : endBias == -1 ? bearCol : textCol)
addRow(rowK, rowV, rowC, "History", histTxt(), textCol)
addRow(rowK, rowV, rowC, "Window", chk, numTxt)
else
addRow(rowK, rowV, rowC, "Window", chk, numTxt)
if state == 1 and full
addRow(rowK, rowV, rowC, "Forming", "Needs " + str.tostring(minTests) + " tests of each edge over " + str.tostring(winLen) + " bars", rangeCol)
if full
addRow(rowK, rowV, rowC, "History", histTxt(), textCol)
if full and not inRange and not na(atrS) and atrS > 0
float comp = atrF / atrS
addRow(rowK, rowV, rowC, "Volatility", "ATR 14 at " + str.tostring(comp, "0.00") + "x ATR 50 · " + (comp < 0.8 ? "compressed" : comp > 1.2 ? "expanding" : "normal"), comp < 0.8 ? rangeCol : comp > 1.2 ? warnCol : textCol)
addRow(rowK, rowV, rowC, "Last event", lastEv == 0 ? "None yet" : evTxt(lastEv) + " · " + agoTxt(lastEvB), evCol(lastEv))
// The last event always stays: when the body is full, it replaces the last body row
int nAll = rowK.size()
int nBody = math.min(nAll, full ? MAX_BODY : MAX_BODY_C)
int nRows = nBody + 2 // title + body + footer
string foot = full ? "Closed bars only · ATR = 50-bar · edges: " + (edgeMode == EDGE_W ? "wicks" : "bodies") + " · dot test, triangle break, x fail" : "Closed bars only · not a signal"
// 2. Corner. Room per corner as a share of the visible span: 0 top right, 1 bottom right, 2 top left, 3 bottom left,
// minus the empty row kept for the TradingView legend (top left), icon (bottom right) or logo (bottom left)
int cs = panelPos == "Top Right" ? 0 : panelPos == "Bottom Right" ? 1 : panelPos == "Top Left" ? 2 : 3
if panelAvoid and not na(visSpan) and visSpan > 0 and not na(rgtHi) and not na(lftHi)
bool lastIn = visR >= time
float scHi = math.max(visHi, nz(lblTop, visHi))
float scLo = math.min(visLo, nz(lblBot, visLo))
float scSpan = scHi - scLo
float rgT = lastIn and not na(lblTop) ? math.max(rgtHi, lblTop) : rgtHi
float rgB = lastIn and not na(lblBot) ? math.min(rgtLo, lblBot) : rgtLo
array<float> room = array.from((scHi - rgT) / scSpan, (rgB - scLo) / scSpan - ICON_PCT / 100, (scHi - lftHi) / scSpan - LEGEND_PCT / 100, (lftLo - scLo) / scSpan - LOGO_PCT / 100)
float need = (nRows + 1) * (panelSize == "Small" ? ROW_SHARE * 0.8 : ROW_SHARE)
int pi = cs
// Corners tried in order: the chosen one, the other one on the same side, then the other side
array<int> tryOrd = array.from(pi, pi % 2 == 0 ? pi + 1 : pi - 1, (pi + 2) % 4, pi % 2 == 0 ? (pi + 3) % 4 : (pi + 1) % 4)
int pick = -1
int best = -1
for k = 0 to 3
int cn = tryOrd.get(k)
if pick < 0 and room.get(cn) >= need
pick := cn
if best < 0 or room.get(cn) > room.get(best)
best := cn
int p0 = pick >= 0 ? pick : best
// Live candle: keep the corner of the previous tick while it still fits, so the panel does not jump
if lastCorner >= 0 and lastCorner != p0 and room.get(lastCorner) >= need and not (p0 == pi and room.get(pi) >= need * 1.15)
p0 := lastCorner
lastCorner := p0
cs := p0
string pos = cs == 0 ? position.top_right : cs == 1 ? position.bottom_right : cs == 2 ? position.top_left : position.bottom_left
// 3. Draw. Top left: transparent spacer row 0 (TradingView legend). Bottom corners: spacer under the footer
bool atTopLeft = pos == position.top_left
bool atBottom = pos == position.bottom_left or pos == position.bottom_right
int r0 = atTopLeft ? 1 : 0
if atTopLeft
table.cell(panel, 0, 0, "", height = LEGEND_PCT)
table.merge_cells(panel, 0, 0, 1, 0)
table.cell(panel, 0, r0, "EDO RANGE STATE", text_color = textCol, bgcolor = bgHead, text_size = panSz)
table.merge_cells(panel, 0, r0, 1, r0)
for i = 0 to nBody - 1
// Last body row = Last event, even when the rows were cut
int src = i == nBody - 1 ? nAll - 1 : i
panelRow(panel, r0 + 1 + i, rowK.get(src), rowV.get(src), rowC.get(src), bgMain)
int rFoot = r0 + nBody + 1
table.cell(panel, 0, rFoot, foot, text_color = numTxt, bgcolor = bgSub, text_size = panSz)
table.merge_cells(panel, 0, rFoot, 1, rFoot)
if atBottom and rFoot < 9
table.cell(panel, 0, rFoot + 1, "", height = pos == position.bottom_left ? LOGO_PCT : ICON_PCT)
table.merge_cells(panel, 0, rFoot + 1, 1, rFoot + 1)
// With a spacer row the outer frame is hidden so it does not box the legend, the logo or the icon
table.set_frame_width(panel, atBottom or atTopLeft ? 0 : 1)
table.set_position(panel, pos)
// ================== MARKERS ==================
// Minimum spacing per kind of marker (display only: the panel and the alerts keep every event)
var int lastTstB = na
var int lastBrkB = na
var int lastFlB = na
bool mkTestTop = false
bool mkTestBot = false
bool mkBrkUp = false
bool mkBrkDn = false
bool mkFailUp = false
bool mkFailDn = false
if showTests and (evTestTop or evTestBot) and (na(lastTstB) or bar_index - lastTstB >= markGap)
mkTestTop := evTestTop
mkTestBot := evTestBot
lastTstB := bar_index
if showMarks and (evBrkUp or evBrkDn) and (na(lastBrkB) or bar_index - lastBrkB >= markGap)
mkBrkUp := evBrkUp
mkBrkDn := evBrkDn
lastBrkB := bar_index
if showMarks and (evFailUp or evFailDn) and (na(lastFlB) or bar_index - lastFlB >= markGap)
mkFailUp := evFailUp
mkFailDn := evFailDn
lastFlB := bar_index
plotshape(mkTestTop, "Top test", shape.circle, location.abovebar, rangeCol, size = size.tiny)
plotshape(mkTestBot, "Bottom test", shape.circle, location.belowbar, rangeCol, size = size.tiny)
plotshape(mkBrkUp, "Close above the range", shape.triangleup, location.belowbar, bullCol, size = size.small)
plotshape(mkBrkDn, "Close below the range", shape.triangledown, location.abovebar, bearCol, size = size.small)
plotshape(mkFailUp, "Failed breakout up", shape.xcross, location.abovebar, warnCol, size = size.small)
plotshape(mkFailDn, "Failed breakout down", shape.xcross, location.belowbar, warnCol, size = size.small)
// ================== ALERTS ==================
alertcondition(evConfirm, "Range confirmed", "Edo Range State — A new trading range was confirmed on {{ticker}}")
alertcondition(evMature, "Range became mature", "Edo Range State — The active range became mature on {{ticker}}")
alertcondition(evTestTop, "Range top tested", "Edo Range State — Price tested the top of the range on {{ticker}}")
alertcondition(evTestBot, "Range bottom tested", "Edo Range State — Price tested the bottom of the range on {{ticker}}")
alertcondition(evBrkUp, "Close above the range", "Edo Range State — A bar closed above the top of the range, breakout in progress on {{ticker}}")
alertcondition(evBrkDn, "Close below the range", "Edo Range State — A bar closed below the bottom of the range, breakout in progress on {{ticker}}")
alertcondition(evFailUp, "Failed breakout up", "Edo Range State — The upside breakout failed and price closed back inside the range on {{ticker}}")
alertcondition(evFailDn, "Failed breakout down", "Edo Range State — The downside breakout failed and price closed back inside the range on {{ticker}}")
alertcondition(evEndUp, "Range ended up", "Edo Range State — Upside breakout confirmed, the range has ended on {{ticker}}")
alertcondition(evEndDn, "Range ended down", "Edo Range State — Downside breakout confirmed, the range has ended on {{ticker}}")
alertcondition(evEndUp or evEndDn, "Range ended", "Edo Range State — A breakout was confirmed and the range has ended on {{ticker}}")
alertcondition(evEndAl, "Range ended with its origin", "Edo Range State — The range broke out the way of its origin candle on {{ticker}}")
alertcondition(evEndAg, "Range ended against its origin", "Edo Range State — The range broke out against its origin candle on {{ticker}}")
alertcondition(evBackIn, "Back inside the broken range", "Edo Range State — Price closed back inside the range that had just broken out on {{ticker}}")