本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Compression Box + Breakout Plan [Rider Algo]", shorttitle="RA Box", overlay=true, max_boxes_count=60, max_lines_count=30, max_labels_count=30)
// Developed by Rider Algo
//
// How it works (measured 2026-10-16 on 16 assets: BTC, ETH, SOL, ADA, XRP, DOGE, LINK, SPY, QQQ, NVDA, AAPL, TSLA,
// MSFT, gold, oil and EURUSD; 1D, 4H and 1W):
// 1. A compression box forms when the last N candles fit inside a range no taller than X times the ATR 50 (how much
// this asset normally moves in one candle) and at least 10 ticks tall. Its top and bottom freeze at the close of
// that candle. Up to 1D the height is compared in price; on weekly and monthly charts, in % of price, because
// over 50 weekly candles price can double and an ATR in price lags behind (measured 2026-10-17: in price, NVDA 1W
// had no box in its whole history; in %, the weekly plan did better on both the design and the control assets).
// 2. The box lives while price trades inside it. The first candle that trades beyond an edge releases it.
// 3. The plan: a buy stop at the top and a sell stop at the bottom, placed in advance. The order that fills is the
// trade; its stop is the other side of the box and the targets are 1, 2 and 3 box heights away.
// 4. Every past box of the chart is replayed with the same rules (commission included) and summarized in the table.
// A candle that touches the stop and a target counts as a stop; a candle that touches both edges is a loss.
// What the tests showed: a compression does NOT make the next move bigger than a normal one, and it does not tell
// the direction. It makes the stop small, so the targets measured in box heights are reached more often than with
// an ordinary range. A stop in the middle of the box lost on every timeframe, so the stop is the other side.
//──────────────────────────────────────────────
// QUICK GUIDE
//──────────────────────────────────────────────
groupGuide = "Quick Guide"
quickGuide = input.string("Hover the (i) on the right", "How to read it", group=groupGuide, display=display.none, tooltip="1. The yellow box appears when price goes quiet: the last candles fit in a range much narrower than usual for this asset.\n2. While the box is alive, its edges are the plan: buy stop at the top, sell stop at the bottom. The first one that fills is the trade, and its stop is the other side of the box.\n3. When it breaks, the entry, the stop and the targets T1, T2 and T3 (1, 2 and 3 box heights) are tracked until a target or the stop is hit, or time runs out.\n4. The table shows how long this box has lasted compared with past boxes on this chart, and how every past box played out here: how often each target came before the stop, and the average result per trade after commission.\n5. A compression does not tell the direction and does not make the move bigger than usual. It tells you where the risk is small.")
//──────────────────────────────────────────────
// 1 · COMPRESSION BOX
//──────────────────────────────────────────────
groupBox = "1 · Compression box"
minBars = input.int(5, "Minimum candles", minval=3, maxval=30, group=groupBox, tooltip="How many candles must fit inside the range before a box is drawn. Validated on 5.")
maxH = input.float(1.0, "Maximum height (× ATR)", minval=0.25, maxval=5.0, step=0.05, group=groupBox, tooltip="How tall the range can be, in ATR 50 (the normal move of one candle on this asset). 1.0 = the last candles together moved no more than one normal candle. Lower = rarer and tighter boxes. Validated on 1.0: on 1D charts that is about one box every 65 candles.")
hMode = input.string("Auto", "Height measured in", options=["Auto", "Price", "Percent"], group=groupBox, tooltip="How the box height is compared with the ATR 50.\nPrice: in the asset's price units (validated on 1D and 4H).\nPercent: in % of price. Over 50 weekly candles price can double, and an ATR in price then lags behind and finds almost no boxes on strongly trending assets (validated on 1W).\nAuto: Price up to 1D, Percent on weekly and monthly charts.")
//──────────────────────────────────────────────
// 2 · BREAKOUT PLAN
//──────────────────────────────────────────────
groupPlan = "2 · Breakout plan"
showPlan = input.bool(true, "Draw the plan", group=groupPlan, tooltip="While a box is alive: buy stop, sell stop and the targets on each side, to the right of the last candle.\nAfter it breaks: the entry, the stop and the targets of the side that filled, with ✓ (target), ✗ (stop) or ⌛ (time) as they resolve.")
t1Mult = input.float(1.0, "Targets (× box height)", minval=0.25, maxval=10, step=0.25, group=groupPlan, inline="tg")
t2Mult = input.float(2.0, "", minval=0.25, maxval=10, step=0.25, group=groupPlan, inline="tg")
t3Mult = input.float(3.0, "", minval=0.25, maxval=10, step=0.25, group=groupPlan, inline="tg", tooltip="Each target is measured from the box edge, in box heights. The stop is the other side of the box, so T1 = 1:1, T2 = 2:1 and T3 = 3:1 reward to risk.")
maxHold = input.int(30, "Max candles in a trade", minval=5, maxval=200, group=groupPlan, tooltip="If neither a target nor the stop is reached after this many candles, the trade is closed at that candle's close.")
commPct = input.float(0.1, "Commission per side (%)", minval=0.0, maxval=1.0, step=0.01, group=groupPlan, tooltip="Charged on the entry and on the exit in the table's results.")
//──────────────────────────────────────────────
// 3 · DISPLAY
//──────────────────────────────────────────────
groupVis = "3 · Display"
boxColor = input.color(#f5b942, "Colors: Box", group=groupVis, inline="c")
upColor = input.color(#1be5a4, "Up", group=groupVis, inline="c")
dnColor = input.color(#f4362a, "Down", group=groupVis, inline="c")
colorBars = input.bool(false, "Color candles inside a box", group=groupVis)
showPast = input.bool(false, "Show past boxes", group=groupVis, inline="past", tooltip="Draws the latest boxes of the chart, colored by the side that broke, with the best result reached: T1, T2, T3, Stop or Time. Gray = both edges touched in one candle.")
pastN = input.int(20, "", minval=1, maxval=50, group=groupVis, inline="past")
//──────────────────────────────────────────────
// 4 · TABLE
//──────────────────────────────────────────────
groupTb = "4 · Table"
showTable = input.bool(true, "Show table", group=groupTb)
tableMode = input.string("Compact", "Content", options=["Compact", "Full"], group=groupTb, tooltip="Compact: the live box, the plan and the results of past boxes on this chart.\nFull: adds the boxes that touched both edges in one candle, the typical box and the rules used.")
tblPosIn = input.string("Bottom Center", "Position", options=["Bottom Center", "Top Center", "Top Right", "Middle Right", "Bottom Right", "Top Left", "Bottom Left"], group=groupTb, inline="tbl")
tblSizeIn = input.string("Small", "Size", options=["Tiny", "Small", "Normal"], group=groupTb, inline="tbl")
tblSize = tblSizeIn == "Tiny" ? size.tiny : tblSizeIn == "Normal" ? size.normal : size.small
tblPos = switch tblPosIn
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Right" => position.middle_right
"Bottom Right" => position.bottom_right
"Top Left" => position.top_left
"Bottom Left" => position.bottom_left
=> position.bottom_center
//──────────────────────────────────────────────
// CORE SERIES
//──────────────────────────────────────────────
WARMUP = 100 // candles skipped at the start of the chart (ATR still warming up)
STRETCH = 10 // candles used to compare the move after a box with a normal stretch
BASECAP = 5000 // normal stretches kept for the comparison
MINTICKS = 10 // a box must be at least this many ticks tall: flat candles in very old history (BTC at cents) make boxes with no risk to measure
usePct = hMode == "Percent" or (hMode == "Auto" and (timeframe.isweekly or timeframe.ismonthly))
atrL = ta.atr(50)
atrPct = ta.rma(ta.tr(true) / close[1], 50) // ATR 50 in % of price
atrEff = usePct ? atrPct * close : atrL // the ruler in price units, measured the chosen way
hhN = ta.highest(high, minBars)
llN = ta.lowest(low, minBars)
rngS = ta.highest(high, STRETCH) - ta.lowest(low, STRETCH)
baseMove = rngS / atrEff[STRETCH] // range of the last 10 candles, in the ATR known before them
//──────────────────────────────────────────────
// FORMATTING
//──────────────────────────────────────────────
f_px(float x) => str.tostring(x, format.mintick)
f_rate(float x) => str.tostring(math.round(x * 100)) + "%"
f_r(float x) => na(x) ? "–" : (x >= 0 ? "+" : "") + str.tostring(x, "0.00") + "R"
f_mark(int s) =>
switch s
1 => "✓"
2 => "✗"
3 => "⌛"
=> "…"
f_best(int s1, int s2, int s3) =>
switch
s3 == 1 => "T3"
s2 == 1 => "T2"
s1 == 1 => "T1"
s1 == 3 => "Time"
=> "Stop"
//──────────────────────────────────────────────
// STATE
//──────────────────────────────────────────────
// Live box
var bool inBox = false
var float bTop = na
var float bBot = na
var float bAtr = na
var int bStart = na
// Past boxes (for percentiles and the move comparison)
var array<int> pastDur = array.new<int>()
var array<float> pastHt = array.new<float>()
var array<float> moveAfter = array.new<float>()
var array<float> moveBase = array.new<float>()
var array<int> expBar = array.new<int>() // release candles still waiting for their 10-candle move
var array<float> expAtr = array.new<float>()
// Open trades (one per released box, until its three targets are resolved). Target state: 0 open, 1 target, 2 stop, 3 time
var array<int> tId = array.new<int>()
var array<int> tDir = array.new<int>()
var array<float> tEnt = array.new<float>()
var array<float> tStop = array.new<float>()
var array<float> tRisk = array.new<float>()
var array<float> tCost = array.new<float>()
var array<int> tBar = array.new<int>()
var array<int> tS1 = array.new<int>()
var array<int> tS2 = array.new<int>()
var array<int> tS3 = array.new<int>()
var int nextId = 0
// Results per side and target: index = side * 3 + target (side 0 = broke up, 1 = broke down)
var array<int> stN = array.new<int>(6, 0)
var array<int> stW = array.new<int>(6, 0)
var array<float> stR = array.new<float>(6, 0.0)
var int nUp = 0
var int nDn = 0
var int nBoth = 0
var float bothR = 0.0
// Latest released box (drawn as the live plan)
var int lpId = -1
var int lpDir = 0
var int lpStart = na
var int lpRel = na
var float lpTop = na
var float lpBot = na
var int lpS1 = 0
var int lpS2 = 0
var int lpS3 = 0
var int lpB1 = na
var int lpB2 = na
var int lpB3 = na
// Past boxes drawn on the chart
var array<box> pastBoxes = array.new<box>()
var array<int> pastIds = array.new<int>()
//──────────────────────────────────────────────
// BOX: RELEASE OR FORMATION
//──────────────────────────────────────────────
bool formedNow = false
bool relUp = false
bool relDn = false
if inBox
bool up = high > bTop
bool dn = low < bBot
if up or dn
relUp := up and not dn
relDn := dn and not up
float risk = bTop - bBot
pastDur.push(bar_index - bStart)
pastHt.push(risk / bAtr)
expBar.push(bar_index)
expAtr.push(bAtr)
int thisId = nextId
nextId += 1
int dir = up and dn ? 0 : up ? 1 : -1
if dir == 0
nBoth += 1
bothR += -1.0 - 2.0 * commPct / 100.0 * bTop / risk
else
float ent = dir == 1 ? math.max(bTop, open) : math.min(bBot, open)
tId.push(thisId)
tDir.push(dir)
tEnt.push(ent)
tStop.push(dir == 1 ? bBot : bTop)
tRisk.push(risk)
tCost.push(2.0 * commPct / 100.0 * ent / risk)
tBar.push(bar_index)
tS1.push(0)
tS2.push(0)
tS3.push(0)
if dir == 1
nUp += 1
else
nDn += 1
lpId := thisId
lpDir := dir
lpStart := bStart
lpRel := bar_index
lpTop := bTop
lpBot := bBot
lpS1 := 0
lpS2 := 0
lpS3 := 0
lpB1 := na
lpB2 := na
lpB3 := na
if showPast
color pc = dir == 1 ? upColor : dir == -1 ? dnColor : color.gray
pastBoxes.push(box.new(bStart, bTop, bar_index, bBot, border_color=color.new(pc, 40), bgcolor=color.new(pc, 85), text=dir == 0 ? "Both" : "", text_size=size.tiny, text_color=chart.fg_color, text_valign=dir == -1 ? text.align_bottom : text.align_top))
pastIds.push(thisId)
if pastBoxes.size() > pastN
box.delete(pastBoxes.shift())
pastIds.shift()
inBox := false
else if barstate.isconfirmed and bar_index >= WARMUP and not na(atrEff) and atrEff > 0 and hhN - llN <= maxH * atrEff and hhN - llN >= MINTICKS * syminfo.mintick
inBox := true
bTop := hhN
bBot := llN
bAtr := atrEff
bStart := bar_index - minBars + 1
formedNow := true
//──────────────────────────────────────────────
// TRADES: RESOLVE TARGETS, STOPS AND TIME
//──────────────────────────────────────────────
int nT = tDir.size()
if nT > 0
for k = nT - 1 to 0
int dir = tDir.get(k)
float ent = tEnt.get(k)
float stp = tStop.get(k)
float rsk = tRisk.get(k)
float cst = tCost.get(k)
int b0 = tBar.get(k)
bool first = bar_index == b0
bool stopHit = dir == 1 ? low <= stp : high >= stp
bool gapHit = not first and (dir == 1 ? open <= stp : open >= stp)
bool timeUp = bar_index - b0 >= maxHold
float edge = stp + dir * rsk
int side = dir == 1 ? 0 : 1
int stillOpen = 0
for j = 0 to 2
int st = j == 0 ? tS1.get(k) : j == 1 ? tS2.get(k) : tS3.get(k)
if st == 0
float mult = j == 0 ? t1Mult : j == 1 ? t2Mult : t3Mult
float tgt = edge + dir * mult * rsk
bool tgtHit = dir == 1 ? high >= tgt : low <= tgt
int newSt = 0
float exitPx = na
if gapHit
newSt := 2
exitPx := open
else if stopHit
newSt := 2
exitPx := stp
else if tgtHit
newSt := 1
exitPx := tgt
else if timeUp
newSt := 3
exitPx := close
if newSt > 0
float rr = (exitPx - ent) * dir / rsk - cst
int ix = side * 3 + j
stN.set(ix, stN.get(ix) + 1)
stW.set(ix, stW.get(ix) + (newSt == 1 ? 1 : 0))
stR.set(ix, stR.get(ix) + rr)
bool isLast = tId.get(k) == lpId
if j == 0
tS1.set(k, newSt)
if isLast
lpS1 := newSt
lpB1 := bar_index
else if j == 1
tS2.set(k, newSt)
if isLast
lpS2 := newSt
lpB2 := bar_index
else
tS3.set(k, newSt)
if isLast
lpS3 := newSt
lpB3 := bar_index
else
stillOpen += 1
if stillOpen == 0
int pi = pastIds.indexof(tId.get(k))
if pi >= 0
pastBoxes.get(pi).set_text(f_best(tS1.get(k), tS2.get(k), tS3.get(k)))
tId.remove(k)
tDir.remove(k)
tEnt.remove(k)
tStop.remove(k)
tRisk.remove(k)
tCost.remove(k)
tBar.remove(k)
tS1.remove(k)
tS2.remove(k)
tS3.remove(k)
//──────────────────────────────────────────────
// MOVE AFTER A BOX VS A NORMAL STRETCH
//──────────────────────────────────────────────
if expBar.size() > 0
if bar_index - expBar.get(0) >= STRETCH - 1
moveAfter.push(rngS / expAtr.get(0))
expBar.shift()
expAtr.shift()
if bar_index >= WARMUP and not na(baseMove)
moveBase.push(baseMove)
if moveBase.size() > BASECAP
moveBase.shift()
//──────────────────────────────────────────────
// DRAWING (last candle only)
//──────────────────────────────────────────────
var array<line> lns = array.new<line>()
var array<label> lbls = array.new<label>()
var array<box> bxs = array.new<box>()
var table tbl = na
if barstate.islast
for ln in lns
ln.delete()
lns.clear()
for lb in lbls
lb.delete()
lbls.clear()
for bx in bxs
bx.delete()
bxs.clear()
int xR = bar_index + 2
float hNow = inBox ? bTop - bBot : na
int dNow = inBox ? bar_index - bStart + 1 : na
bool lpOn = not na(lpRel) and lpDir != 0
bool lpOpen = lpOn and (lpS1 == 0 or lpS2 == 0 or lpS3 == 0)
// Live box and the plan on both sides
if inBox
bxs.push(box.new(bStart, bTop, xR, bBot, border_color=color.new(boxColor, 20), bgcolor=color.new(boxColor, 82), text="QUIET · " + str.tostring(dNow) + " candles", text_size=size.small, text_color=chart.fg_color, text_halign=text.align_left, text_valign=text.align_top))
if showPlan
lbls.push(label.new(xR, bTop, "BUY STOP " + f_px(bTop), style=label.style_label_left, color=color.new(upColor, 100), textcolor=upColor, size=size.small, tooltip="Buy stop at the top of the box. If it fills, the stop is the bottom of the box: " + f_px(bBot) + "."))
lbls.push(label.new(xR, bBot, "SELL STOP " + f_px(bBot), style=label.style_label_left, color=color.new(dnColor, 100), textcolor=dnColor, size=size.small, tooltip="Sell stop at the bottom of the box. If it fills, the stop is the top of the box: " + f_px(bTop) + "."))
for j = 0 to 2
float mult = j == 0 ? t1Mult : j == 1 ? t2Mult : t3Mult
float yU = bTop + mult * hNow
float yD = bBot - mult * hNow
string nm = "T" + str.tostring(j + 1) + " "
lns.push(line.new(bar_index + 1, yU, xR + 6, yU, color=color.new(upColor, 55), style=line.style_dotted, width=1))
lns.push(line.new(bar_index + 1, yD, xR + 6, yD, color=color.new(dnColor, 55), style=line.style_dotted, width=1))
lbls.push(label.new(xR + 6, yU, nm + f_px(yU), style=label.style_label_left, color=color.new(upColor, 100), textcolor=color.new(upColor, 30), size=size.tiny))
lbls.push(label.new(xR + 6, yD, nm + f_px(yD), style=label.style_label_left, color=color.new(dnColor, 100), textcolor=color.new(dnColor, 30), size=size.tiny))
// Latest released box: entry, stop and targets as they resolve
if showPlan and lpOn and (lpOpen or not inBox)
bool isUp = lpDir == 1
color sc = isUp ? upColor : dnColor
float lpH = lpTop - lpBot
float pE = isUp ? lpTop : lpBot
float pS = isUp ? lpBot : lpTop
int endX = lpOpen ? xR : math.max(nz(lpB1, lpRel), nz(lpB2, lpRel), nz(lpB3, lpRel))
int xL = inBox ? xR + 18 : xR // labels in one column right of the last candle, past the live box's labels
bxs.push(box.new(lpStart, lpTop, lpRel, lpBot, border_color=color.new(sc, 30), bgcolor=color.new(sc, 85)))
lns.push(line.new(lpRel, pE, endX, pE, color=sc, width=2))
bool stopped = lpS1 == 2 or lpS2 == 2 or lpS3 == 2
lns.push(line.new(lpRel, pS, endX, pS, color=color.new(chart.fg_color, 40), width=1))
// Values on the right only while the trade is open: a closed trade keeps its lines but must not look active
if lpOpen
lbls.push(label.new(xL, pE, (isUp ? "LONG " : "SHORT ") + f_px(pE), style=label.style_label_left, color=color.new(sc, 100), textcolor=sc, size=size.small))
lbls.push(label.new(xL, pS, "STOP " + f_px(pS) + (stopped ? " ✗" : ""), style=label.style_label_left, color=color.new(color.gray, 100), textcolor=chart.fg_color, size=size.small))
for j = 0 to 2
float mult = j == 0 ? t1Mult : j == 1 ? t2Mult : t3Mult
int s = j == 0 ? lpS1 : j == 1 ? lpS2 : lpS3
int bEnd = j == 0 ? lpB1 : j == 1 ? lpB2 : lpB3
float y = pE + lpDir * mult * lpH
int x2 = s == 0 ? xR : bEnd
lns.push(line.new(lpRel, y, x2, y, color=color.new(sc, s == 1 ? 0 : 50), style=line.style_dashed, width=1))
if lpOpen
lbls.push(label.new(xL, y, "T" + str.tostring(j + 1) + " " + f_px(y) + " " + f_mark(s), style=label.style_label_left, color=color.new(sc, 100), textcolor=color.new(sc, s == 2 ? 50 : 0), size=size.small))
// Table
if not na(tbl)
tbl.delete()
tbl := showTable ? table.new(tblPos, 5, 14, border_width=1) : na
if showTable
color hdrBg = color.new(#1e222d, 0)
color rowBg = color.new(#131722, 10)
color txt = color.white
color pale = color.new(color.white, 55)
bool full = tableMode == "Full"
int nPast = pastDur.size()
int longer = 0
int taller = 0
if inBox and nPast > 0
for i = 0 to nPast - 1
if pastDur.get(i) < dNow
longer += 1
if pastHt.get(i) > hNow / bAtr
taller += 1
string stTxt = inBox ? "quiet for " + str.tostring(dNow) + " candles" : lpOpen ? "broke " + (lpDir == 1 ? "up " : "down ") + str.tostring(bar_index - lpRel) + " candles ago" : "no box right now" + (na(lpRel) ? " · none on this chart yet" : " · last one broke " + str.tostring(bar_index - lpRel) + " candles ago")
tbl.cell(0, 0, "▣ Compression Box · " + stTxt, text_color=txt, bgcolor=hdrBg, text_size=tblSize, tooltip="A box forms when the last " + str.tostring(minBars) + " candles fit in a range of " + str.tostring(maxH) + " ATR or less, measured in " + (usePct ? "% of price" : "price") + ". It does not tell the direction: it shows where the risk is small.")
tbl.merge_cells(0, 0, 4, 0)
int r = 1
if inBox
float hPct = hNow / close * 100
tbl.cell(0, r, "Box", text_color=txt, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize)
tbl.cell(1, r, str.tostring(dNow) + " candles", text_color=txt, bgcolor=rowBg, text_size=tblSize)
tbl.cell(2, r, nPast >= 10 ? "longer than " + f_rate(longer * 1.0 / nPast) + " of " + str.tostring(nPast) + " past boxes" : "only " + str.tostring(nPast) + " past boxes here", text_color=nPast >= 10 ? txt : pale, bgcolor=rowBg, text_size=tblSize, tooltip="How this box's life so far compares with the boxes this chart already had. A long box is unusual for this asset, but in the tests long boxes did not break better than short ones.")
tbl.merge_cells(2, r, 4, r)
r += 1
tbl.cell(0, r, "Height", text_color=txt, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize)
tbl.cell(1, r, str.tostring(hPct, hPct < 1 ? "0.00" : "0.0") + "%", text_color=txt, bgcolor=rowBg, text_size=tblSize, tooltip="Risk per trade: from one edge to the other, in % of price.")
tbl.cell(2, r, str.tostring(hNow / bAtr, "0.00") + " ATR" + (nPast >= 10 ? " · tighter than " + f_rate(taller * 1.0 / nPast) : ""), text_color=txt, bgcolor=rowBg, text_size=tblSize)
tbl.merge_cells(2, r, 4, r)
r += 1
tbl.cell(0, r, "Orders", text_color=txt, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize)
tbl.cell(1, r, "Buy stop " + f_px(bTop), text_color=upColor, bgcolor=rowBg, text_size=tblSize, tooltip="Stop for the long: " + f_px(bBot) + ". T1 / T2 / T3: " + f_px(bTop + t1Mult * hNow) + " / " + f_px(bTop + t2Mult * hNow) + " / " + f_px(bTop + t3Mult * hNow))
tbl.merge_cells(1, r, 2, r)
tbl.cell(3, r, "Sell stop " + f_px(bBot), text_color=dnColor, bgcolor=rowBg, text_size=tblSize, tooltip="Stop for the short: " + f_px(bTop) + ". T1 / T2 / T3: " + f_px(bBot - t1Mult * hNow) + " / " + f_px(bBot - t2Mult * hNow) + " / " + f_px(bBot - t3Mult * hNow))
tbl.merge_cells(3, r, 4, r)
r += 1
if lpOpen
tbl.cell(0, r, (lpDir == 1 ? "Long " : "Short ") + f_px(lpDir == 1 ? lpTop : lpBot), text_color=lpDir == 1 ? upColor : dnColor, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize, tooltip="The latest box broke on this side. Stop: " + f_px(lpDir == 1 ? lpBot : lpTop) + ". Closed by time after " + str.tostring(maxHold) + " candles.")
tbl.cell(1, r, "T1 " + f_mark(lpS1), text_color=txt, bgcolor=rowBg, text_size=tblSize)
tbl.cell(2, r, "T2 " + f_mark(lpS2), text_color=txt, bgcolor=rowBg, text_size=tblSize)
tbl.cell(3, r, "T3 " + f_mark(lpS3), text_color=txt, bgcolor=rowBg, text_size=tblSize)
tbl.cell(4, r, str.tostring(bar_index - lpRel) + "/" + str.tostring(maxHold), text_color=pale, bgcolor=rowBg, text_size=tblSize, tooltip="Candles since the break / max candles in the trade.")
r += 1
// Results of past boxes on this chart
int nAll = nUp + nDn + nBoth
tbl.cell(0, r, "This chart · " + str.tostring(nAll) + " boxes", text_color=txt, bgcolor=hdrBg, text_halign=text.align_left, text_size=tblSize, tooltip="Every past box of this chart replayed with the plan: buy stop and sell stop at the edges, stop at the other side, " + str.tostring(maxHold) + " candles max, " + str.tostring(commPct) + "% commission per side. % = how often the target came before the stop.")
for j = 0 to 2
float mult = j == 0 ? t1Mult : j == 1 ? t2Mult : t3Mult
tbl.cell(j + 1, r, "T" + str.tostring(j + 1) + " (" + str.tostring(mult) + ":1)", text_color=txt, bgcolor=hdrBg, text_size=tblSize)
tbl.cell(4, r, "Boxes", text_color=txt, bgcolor=hdrBg, text_size=tblSize)
r += 1
for side = 0 to 1
tbl.cell(0, r, side == 0 ? "↑ Broke up" : "↓ Broke down", text_color=side == 0 ? upColor : dnColor, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize)
for j = 0 to 2
int ix = side * 3 + j
int n = stN.get(ix)
tbl.cell(j + 1, r, n > 0 ? f_rate(stW.get(ix) * 1.0 / n) : "–", text_color=n >= 20 ? txt : pale, bgcolor=rowBg, text_size=tblSize, tooltip=str.tostring(stW.get(ix)) + " of " + str.tostring(n) + " trades reached the target before the stop." + (n < 20 ? " Fewer than 20: not reliable." : ""))
tbl.cell(4, r, str.tostring(side == 0 ? nUp : nDn), text_color=txt, bgcolor=rowBg, text_size=tblSize)
r += 1
tbl.cell(0, r, "Avg per trade", text_color=txt, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize, tooltip="Average result of each trade in R (1R = the box height you risk), after commission. Includes the " + str.tostring(nBoth) + " boxes that touched both edges in one candle, counted as losses. Above 0 = the plan made money on this chart.")
for j = 0 to 2
int n = stN.get(j) + stN.get(3 + j) + nBoth
float avg = n > 0 ? (stR.get(j) + stR.get(3 + j) + bothR) / n : na
tbl.cell(j + 1, r, f_r(avg), text_color=na(avg) ? txt : n < 20 ? pale : avg >= 0 ? upColor : dnColor, bgcolor=rowBg, text_size=tblSize)
tbl.cell(4, r, "", bgcolor=rowBg, text_size=tblSize)
r += 1
float mA = moveAfter.size() > 0 ? moveAfter.median() : na
float mB = moveBase.size() > 0 ? moveBase.median() : na
tbl.cell(0, r, na(mA) ? "Move after a box: not enough boxes yet" : "10 candles after a break: " + str.tostring(mA, "0.0") + " ATR · any 10 candles: " + str.tostring(mB, "0.0") + " ATR", text_color=pale, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize, tooltip="Median range of the 10 candles after each break, compared with any 10 candles of this chart, both in ATR. Quiet does not mean explosive: what the box gives you is a small stop.")
tbl.merge_cells(0, r, 4, r)
r += 1
if full
tbl.cell(0, r, "Both edges in one candle: " + str.tostring(nBoth) + " (counted as losses)", text_color=pale, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize)
tbl.merge_cells(0, r, 4, r)
r += 1
if nPast > 0
tbl.cell(0, r, "Typical box: " + str.tostring(pastDur.median(), "0") + " candles · " + str.tostring(pastHt.median(), "0.00") + " ATR tall", text_color=pale, bgcolor=rowBg, text_halign=text.align_left, text_size=tblSize)
tbl.merge_cells(0, r, 4, r)
r += 1
tbl.cell(0, r, "Box: " + str.tostring(minBars) + " candles ≤ " + str.tostring(maxH) + " ATR in " + (usePct ? "%" : "price") + " · stop: other side · max " + str.tostring(maxHold) + " candles · commission " + str.tostring(commPct) + "% per side", text_color=pale, bgcolor=rowBg, text_halign=text.align_left, text_size=size.tiny)
tbl.merge_cells(0, r, 4, r)
//──────────────────────────────────────────────
// CANDLES, DATA WINDOW AND ALERTS
//──────────────────────────────────────────────
barcolor(colorBars and inBox ? boxColor : na, title="Candles inside a box")
plot(inBox ? bar_index - bStart + 1 : na, "Box candles", display=display.data_window)
plot(inBox ? (bTop - bBot) / close * 100 : na, "Box height %", display=display.data_window)
plot(inBox ? bTop : na, "Buy stop", display=display.data_window)
plot(inBox ? bBot : na, "Sell stop", display=display.data_window)
if formedNow
alert(syminfo.ticker + ": compression box. Buy stop " + f_px(bTop) + ", sell stop " + f_px(bBot) + " (risk " + str.tostring((bTop - bBot) / close * 100, "0.00") + "% per side).", alert.freq_once_per_bar_close)
if relUp
alert(syminfo.ticker + ": broke UP from the compression box at " + f_px(lpTop) + ". Stop " + f_px(lpBot) + ", T1 " + f_px(lpTop + t1Mult * (lpTop - lpBot)) + ", T2 " + f_px(lpTop + t2Mult * (lpTop - lpBot)) + ".", alert.freq_once_per_bar)
if relDn
alert(syminfo.ticker + ": broke DOWN from the compression box at " + f_px(lpBot) + ". Stop " + f_px(lpTop) + ", T1 " + f_px(lpBot - t1Mult * (lpTop - lpBot)) + ", T2 " + f_px(lpBot - t2Mult * (lpTop - lpBot)) + ".", alert.freq_once_per_bar)
alertcondition(formedNow, "Compression box formed", "{{ticker}}: a compression box formed. Check the buy stop and sell stop on the chart.")
alertcondition(relUp, "Broke up", "{{ticker}}: price broke up from the compression box.")
alertcondition(relDn, "Broke down", "{{ticker}}: price broke down from the compression box.")