本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OlympusCipher
// Season Timed Range Breakout (STRB)
// Version: 1.0
// DISCLAIMER: For educational purposes only. Not financial advice.
// Past performance does not guarantee future results.
//@version=6
indicator("Season Timed Range Breakout (STRB)", shorttitle="STRB", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)
// ============================================================
// INPUTS
// ============================================================
const string G1 = "1. General"
const string G2 = "2. Window 1"
const string G3 = "3. Window 2 (multi-window)"
const string G4 = "4. Window 3 (multi-window)"
const string G5 = "5. Levels & Extensions"
const string G6 = "6. Breakout, Failure & Retest"
const string G7 = "7. Styling"
const string G8 = "8. Stop Loss"
const string G9 = "9. Signal Filters"
const string G10 = "10. Statistics Table"
// --- General ---
tzInput = input.string("America/New_York", "Timezone", options=["Exchange", "UTC", "America/New_York", "America/Chicago", "Europe/London", "Europe/Berlin", "Asia/Karachi", "Asia/Kolkata", "Asia/Dubai", "Asia/Tokyo", "Asia/Singapore", "Australia/Sydney"], group=G1,
tooltip="Timezone used for all session inputs. 'Exchange' = the symbol's own timezone. The default windows are written in New York time.")
rangeMode = input.string("Session String", "Range Mode", options=["Session String", "First N Candles"], group=G1,
tooltip="Session String: the range is the window typed in each window's 'Range Window' box (example 0930-0931, end exclusive).\nFirst N Candles: the range is the first N candles of each window's trading session.")
orbBarCount = input.int(6, "Number of Candles", minval=1, group=G1, tooltip="Used only in 'First N Candles' mode.")
multiMode = input.bool(true, "Multi-Window Mode", group=G1, tooltip="OFF: only Window 1 is tracked.\nON: Window 2 and Window 3 are tracked too (if enabled in their groups). Each window has its own range, levels, signals and statistics.")
// --- Window 1 ---
w1Name = input.string("NY", "Name", group=G2)
w1Range = input.session("0930-0945", "Range Window", group=G2, tooltip="A candle is part of the range if its open time is inside this session. End is exclusive. Midnight-crossing is allowed. Use a chart timeframe that lines up with the window start.")
w1Full = input.session("0930-1600", "Trading Session", group=G2, tooltip="Levels extend and breakouts are tracked only inside this session.")
w1Col = input.color(#2962FF, "Window Color", group=G2)
// --- Window 2 ---
w2On = input.bool(true, "Enable Window 2", group=G3, tooltip="Only active when Multi-Window Mode is ON.")
w2Name = input.string("LON", "Name", group=G3)
w2Range = input.session("0400-0500", "Range Window", group=G3)
w2Full = input.session("0300-1100", "Trading Session", group=G3)
w2Col = input.color(#AB47BC, "Window Color", group=G3)
// --- Window 3 ---
w3On = input.bool(true, "Enable Window 3", group=G4, tooltip="Only active when Multi-Window Mode is ON.")
w3Name = input.string("ASIA", "Name", group=G4)
w3Range = input.session("2000-2100", "Range Window", group=G4)
w3Full = input.session("2000-0400", "Trading Session", group=G4)
w3Col = input.color(#00ACC1, "Window Color", group=G4)
// --- Levels & extensions ---
extMode = input.string("To Session End", "Extend Levels", options=["To Session End", "Until Breakout", "No Extension"], group=G5,
tooltip="To Session End: lines run to the end of the trading session.\nUntil Breakout: lines stop at the breakout candle.\nNo Extension: levels are drawn only across the range window itself.")
showMid = input.bool(true, "Show Midpoint (50%)", group=G5)
tgt1 = input.float(0.5, "Target 1 (x range)", minval=0.0, step=0.25, group=G5, tooltip="Projects targets above and below the range. Set to 0 to disable a target.")
tgt2 = input.float(1.0, "Target 2 (x range)", minval=0.0, step=0.25, group=G5)
tgt3 = input.float(2.0, "Target 3 (x range)", minval=0.0, step=0.25, group=G5)
showHistory = input.bool(true, "Show Previous Days", group=G5, tooltip="Turn off to keep only the latest range of each window on the chart.\nWith all levels on, each window-day uses up to 11 lines and 11 labels (fewer after a breakout removes the opposite side). TradingView allows 500 of each, so with 3 windows about 15-20 days fit.")
// --- Breakout, failure, retest ---
showSignals = input.bool(true, "Show Breakout Signals", group=G6)
confirmMode = input.string("Candle Close", "Confirmation", options=["Candle Close", "Wick Touch"], group=G6,
tooltip="Everything is evaluated on closed candles, so nothing repaints.\nCandle Close: the close must clear the range.\nWick Touch: the high/low must clear the range (checked at candle close).")
signalMode = input.string("First Breakout Only", "Signals Per Session", options=["First Breakout Only", "Once Per Side"], group=G6)
bufTicks = input.float(0.0, "Breakout Buffer (ticks)", minval=0.0, step=1.0, group=G6, tooltip="Price must clear the range high/low by this many ticks.")
colorByBrk = input.bool(true, "Tint Box on Breakout", group=G6)
showFail = input.bool(false, "Show Failed Breakout Markers", group=G6, tooltip="Marks the candle that closes back inside the range after the first breakout.")
showRetest = input.bool(false, "Show Retest Markers", group=G6, tooltip="After the first breakout, a retest is a candle that touches the broken level and closes back on the breakout side. Only the first retest is marked, and not after the breakout has failed.")
rtTol = input.float(0.0, "Retest Tolerance (ticks)", minval=0.0, step=1.0, group=G6, tooltip="How close to the broken level the candle must come. 0 = it must touch or cross the level.")
// --- Styling ---
highLineCol = input.color(#089981, "High / Long", group=G7)
lowLineCol = input.color(#F23645, "Low / Short", group=G7)
midLineCol = input.color(#9598A1, "Midpoint", group=G7)
tpLongCol = input.color(#00E676, "Target Color (Long side)", group=G7)
tpShortCol = input.color(#FF5252, "Target Color (Short side)", group=G7)
lineStyleStr = input.string("Solid", "Level Line Style", options=["Solid", "Dashed", "Dotted"], group=G7)
tgtStyleStr = input.string("Dotted", "Target Line Style", options=["Solid", "Dashed", "Dotted"], group=G7)
lineWidth = input.int(2, "Level Thickness", minval=1, maxval=5, group=G7)
showLabels = input.bool(true, "Show Level Names", group=G7)
lblSize = input.string(size.small, "Label Size", options=[size.tiny, size.small, size.normal], group=G7)
// --- Stop loss ---
showSL = input.bool(true, "Show Stop Loss Lines", group=G8)
slMode = input.string("Range Multiple", "SL Method", options=["Range Multiple", "Percent of Price"], group=G8,
tooltip="Range Multiple: SL distance = range x the multiple below.\nPercent of Price: SL distance = the % below, measured from the entry level.\nLong entry = range high, Short entry = range low.")
slRangeMult = input.float(1.20, "SL Range Multiple (x range)", minval=0.05, step=0.25, group=G8, tooltip="Used only in 'Range Multiple' mode. 1.0 puts a long's SL at the range low.")
slPct = input.float(1.0, "SL Percent (%)", minval=0.01, step=0.05, group=G8, tooltip="Used only in 'Percent of Price' mode. Examples: 1 = 1%, 0.75 = 0.75%.")
slCol = input.color(#FF9800, "SL Line Color", group=G8)
slStyleStr = input.string("Dashed", "SL Line Style", options=["Solid", "Dashed", "Dotted"], group=G8)
// --- Signal filters ---
atrLen = input.int(14, "Daily ATR Length", minval=1, group=G9, tooltip="ATR of the PREVIOUS completed daily candle, used to judge the size of the range.")
minRangeAtr = input.float(10.0, "Narrow Below (% of daily ATR)", minval=0.0, step=1.0, group=G9, tooltip="Ranges smaller than this are treated as Narrow. Very short windows (like 1 minute) are often Narrow, so adjust to your window.")
maxRangeAtr = input.float(60.0, "Wide Above (% of daily ATR)", minval=1.0, step=1.0, group=G9, tooltip="Ranges larger than this are treated as Wide.")
useRangeFilter = input.bool(false, "Filter: Only Normal-Size Ranges", group=G9, tooltip="When on, breakouts are ignored if the range is Narrow or Wide. Ignored breakouts do not use up the session's signal.")
useVolFilter = input.bool(false, "Filter: Relative Volume", group=G9, tooltip="Breakout candle volume must be at least the multiple below times its recent average.")
volLen = input.int(20, "Volume Average Length", minval=1, group=G9)
volMult = input.float(1.2, "Min Relative Volume (x)", minval=0.1, step=0.1, group=G9)
useVwapFilter = input.bool(false, "Filter: VWAP Alignment", group=G9, tooltip="Longs need the close above VWAP, shorts need it below.")
// --- Statistics table ---
showStats = input.bool(true, "Show Statistics Table", group=G10, tooltip="Statistics cover only the history loaded on your chart and track the first breakout of each window session.")
statsPos = input.string(position.top_right, "Position", options=[position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], group=G10)
tblSize = input.string(size.small, "Text Size", options=[size.tiny, size.small, size.normal], group=G10)
// ============================================================
// GUARDS & HELPERS
// ============================================================
if not timeframe.isintraday
runtime.error("Season Timed Range Breakout (STRB) only works on intraday timeframes (seconds / minutes / hours).")
string tz = tzInput == "Exchange" ? syminfo.timezone : tzInput
f_style(string s) =>
s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
string lineStyle = f_style(lineStyleStr)
string tgtStyle = f_style(tgtStyleStr)
string slStyle = f_style(slStyleStr)
// Stop loss distance (price units) for a given entry level and range
f_slDist(float entry, float rng) =>
slMode == "Range Multiple" ? rng * slRangeMult : entry * slPct / 100.0
f_pct(int a, int b) =>
b > 0 ? str.tostring(a * 100.0 / b, "#.#") + "%" : "-"
// ============================================================
// FILTER DATA (shared by all windows)
// ============================================================
// Previous completed daily ATR (lookahead_on with [1] is the standard non-repainting pattern)
float dAtr = request.security(syminfo.tickerid, "D", ta.atr(atrLen)[1], lookahead = barmerge.lookahead_on)
float volAvg = ta.sma(volume, volLen)
float relVol = volAvg > 0 ? volume / volAvg : na
float vwapVal = ta.vwap(hlc3)
// ============================================================
// WINDOW TYPE
// ============================================================
type Win
string name
color col
bool wasInside = false
bool wasFull = false
int cnt = 0
float hi
float lo
float atrPct
int startBar
box bx
bool done = false
bool armed = false
bool extending = false
bool longFired = false
bool shortFired = false
int dir = 0
array<line> lns
array<label> lbs
array<int> sides // 0 = neutral (range lines), 1 = long side, -1 = short side
// tracked breakout (first of each session)
bool trActive = false
int trDir = 0
float trEntry
float trSL
float trT1
float trT2
float trT3
float trRef
bool hit1 = false
bool hit2 = false
bool hit3 = false
int first = 0 // 1 = a target came first, -1 = stop came first, 0 = neither
bool failed = false
bool retest = false
int rtRes = 0 // after retest: 1 = first target reached, -1 = stop touched first
// statistics
int total = 0
int nLong = 0
int nShort = 0
int nWin = 0
int nLoss = 0
int nNone = 0
int nR1 = 0
int nR2 = 0
int nR3 = 0
int nFail = 0
int nRt = 0
int nRtWin = 0
int nRtLoss = 0
// Adds a level line (and a name-only label). side: 0 neutral, 1 long side, -1 short side
method addLevel(Win w, float price, string txt, color col, string sty, int wd, int side) =>
line ln = line.new(w.startBar, price, bar_index, price, color=col, style=sty, width=wd)
label lb = na
if showLabels
lb := label.new(bar_index, price, w.name + " " + txt, style=label.style_label_left, color=color.new(col, 100), textcolor=col, size=lblSize)
array.push(w.lns, ln)
array.push(w.lbs, lb)
array.push(w.sides, side)
method clearLevels(Win w, bool del) =>
if del
for l in w.lns
line.delete(l)
for lb in w.lbs
if not na(lb)
label.delete(lb)
array.clear(w.lns)
array.clear(w.lbs)
array.clear(w.sides)
// Deletes every level that belongs to one side (used after a breakout)
method removeSide(Win w, int side) =>
int n = array.size(w.lns)
if n > 0
for i = n - 1 to 0
if array.get(w.sides, i) == side
line.delete(array.get(w.lns, i))
label lb = array.get(w.lbs, i)
if not na(lb)
label.delete(lb)
array.remove(w.lns, i)
array.remove(w.lbs, i)
array.remove(w.sides, i)
// Closes the tracked breakout and adds it to the statistics
method finish(Win w) =>
w.total := w.total + 1
if w.trDir == 1
w.nLong := w.nLong + 1
else
w.nShort := w.nShort + 1
if w.first == 1
w.nWin := w.nWin + 1
else if w.first == -1
w.nLoss := w.nLoss + 1
else
w.nNone := w.nNone + 1
if w.hit1
w.nR1 := w.nR1 + 1
if w.hit2
w.nR2 := w.nR2 + 1
if w.hit3
w.nR3 := w.nR3 + 1
if w.failed
w.nFail := w.nFail + 1
if w.retest
w.nRt := w.nRt + 1
if w.rtRes == 1
w.nRtWin := w.nRtWin + 1
else if w.rtRes == -1
w.nRtLoss := w.nRtLoss + 1
w.trActive := false
// ============================================================
// MAIN WINDOW ENGINE (runs once per window per bar, closed bars only)
// Returns: long breakout, short breakout, failed long, failed short,
// long retest, short retest, range completed
// ============================================================
f_run(Win w, bool enabled, bool inR, bool inF) =>
bool longB = false
bool shortB = false
bool failL = false
bool failS = false
bool rtL = false
bool rtS = false
bool rngDone = false
if enabled and barstate.isconfirmed
// ---- candle counter (First N Candles mode) ----
if inF and not w.wasFull
w.cnt := 0
if inF
w.cnt := w.cnt + 1
bool inside = rangeMode == "Session String" ? inR : (inF and w.cnt <= orbBarCount)
bool rStart = inside and not w.wasInside
bool rEnd = not inside and w.wasInside
// trading session just ended: signals from this range stop
if not inF and w.wasFull
w.armed := false
// ---- build the range ----
if rStart
if w.trActive
w.finish()
if not showHistory and not na(w.bx)
box.delete(w.bx)
w.clearLevels(not showHistory)
w.hi := high
w.lo := low
w.atrPct := na
w.startBar := bar_index
w.done := false
w.armed := false
w.extending := false
w.longFired := false
w.shortFired := false
w.dir := 0
w.bx := box.new(bar_index, high, bar_index, low, bgcolor=color.new(w.col, 88), border_color=w.col, border_width=1)
else if inside and not na(w.hi)
w.hi := math.max(w.hi, high)
w.lo := math.min(w.lo, low)
if inside and not na(w.bx)
box.set_top(w.bx, w.hi)
box.set_bottom(w.bx, w.lo)
box.set_right(w.bx, bar_index)
// ---- levels (created when the range completes) ----
if rEnd and not na(w.hi) and not w.done
w.done := true
w.armed := true
rngDone := true
float rng = w.hi - w.lo
w.atrPct := (na(dAtr) or dAtr == 0) ? na : rng / dAtr * 100
w.addLevel(w.hi, "RH", highLineCol, lineStyle, lineWidth, 0)
w.addLevel(w.lo, "RL", lowLineCol, lineStyle, lineWidth, 0)
if showMid
w.addLevel((w.hi + w.lo) / 2, "MID", midLineCol, line.style_dashed, 1, 0)
if tgt1 > 0
w.addLevel(w.hi + rng * tgt1, "T1 +" + str.tostring(tgt1) + "x", tpLongCol, tgtStyle, 1, 1)
w.addLevel(w.lo - rng * tgt1, "T1 -" + str.tostring(tgt1) + "x", tpShortCol, tgtStyle, 1, -1)
if tgt2 > 0
w.addLevel(w.hi + rng * tgt2, "T2 +" + str.tostring(tgt2) + "x", tpLongCol, tgtStyle, 1, 1)
w.addLevel(w.lo - rng * tgt2, "T2 -" + str.tostring(tgt2) + "x", tpShortCol, tgtStyle, 1, -1)
if tgt3 > 0
w.addLevel(w.hi + rng * tgt3, "T3 +" + str.tostring(tgt3) + "x", tpLongCol, tgtStyle, 1, 1)
w.addLevel(w.lo - rng * tgt3, "T3 -" + str.tostring(tgt3) + "x", tpShortCol, tgtStyle, 1, -1)
if showSL
w.addLevel(w.hi - f_slDist(w.hi, rng), "SL Long", slCol, slStyle, 1, 1)
w.addLevel(w.lo + f_slDist(w.lo, rng), "SL Short", slCol, slStyle, 1, -1)
w.extending := inF and extMode != "No Extension"
// ---- extend levels (before detection so the breakout candle is included) ----
if w.extending and not inF
w.extending := false
if w.extending and array.size(w.lns) > 0
for i = 0 to array.size(w.lns) - 1
line.set_x2(array.get(w.lns, i), bar_index)
label lbl = array.get(w.lbs, i)
if not na(lbl)
label.set_x(lbl, bar_index)
// ---- track the first breakout: failure, retest, targets, stop ----
// (runs BEFORE detection, so the entry candle itself is never evaluated)
if w.trActive
bool endNow = not inF
bool slTouch = false
bool hadRt = w.retest
if not endNow
slTouch := w.trDir == 1 ? low <= w.trSL : high >= w.trSL
if not w.failed
if w.trDir == 1 and close < w.trEntry
failL := true
w.failed := true
else if w.trDir == -1 and close > w.trEntry
failS := true
w.failed := true
if not w.retest and not w.failed and not slTouch
float tol = rtTol * syminfo.mintick
if w.trDir == 1 and low <= w.trEntry + tol and close > w.trEntry
rtL := true
w.retest := true
else if w.trDir == -1 and high >= w.trEntry - tol and close < w.trEntry
rtS := true
w.retest := true
if slTouch
// stop counted first if a target is touched on the same candle (conservative)
if w.first == 0
w.first := -1
if hadRt and w.rtRes == 0
w.rtRes := -1
else
bool h1 = not na(w.trT1) and (w.trDir == 1 ? high >= w.trT1 : low <= w.trT1)
bool h2 = not na(w.trT2) and (w.trDir == 1 ? high >= w.trT2 : low <= w.trT2)
bool h3 = not na(w.trT3) and (w.trDir == 1 ? high >= w.trT3 : low <= w.trT3)
bool hRef = not na(w.trRef) and (w.trDir == 1 ? high >= w.trRef : low <= w.trRef)
if h1
w.hit1 := true
if h2
w.hit2 := true
if h3
w.hit3 := true
if (h1 or h2 or h3) and w.first == 0
w.first := 1
if hadRt and hRef and w.rtRes == 0
w.rtRes := 1
if endNow or slTouch
w.finish()
// ---- breakout detection (this session's range only) ----
if w.armed and w.done and inF and not inside and not na(w.hi)
float buf = bufTicks * syminfo.mintick
float upSrc = confirmMode == "Candle Close" ? close : high
float dnSrc = confirmMode == "Candle Close" ? close : low
bool upOk = upSrc > w.hi + buf
bool dnOk = dnSrc < w.lo - buf
if upOk and dnOk // both sides hit on one candle (wick mode): use candle direction
upOk := close >= open
dnOk := not upOk
// Optional filters (a filtered-out breakout does not use up the session's signal)
bool passRange = not useRangeFilter or na(w.atrPct) or (w.atrPct >= minRangeAtr and w.atrPct <= maxRangeAtr)
bool passVol = not useVolFilter or na(relVol) or relVol >= volMult
bool passLongTrnd = not useVwapFilter or na(vwapVal) or close > vwapVal
bool passShortTrnd = not useVwapFilter or na(vwapVal) or close < vwapVal
upOk := upOk and passRange and passVol and passLongTrnd
dnOk := dnOk and passRange and passVol and passShortTrnd
bool allowLong = not w.longFired and (signalMode == "Once Per Side" or not w.shortFired)
bool allowShort = not w.shortFired and (signalMode == "Once Per Side" or not w.longFired)
if upOk and allowLong
longB := true
w.longFired := true
if dnOk and allowShort
shortB := true
w.shortFired := true
if (longB or shortB) and w.dir == 0
w.dir := longB ? 1 : -1
if colorByBrk and not na(w.bx)
box.set_bgcolor(w.bx, color.new(longB ? highLineCol : lowLineCol, 85))
box.set_border_color(w.bx, longB ? highLineCol : lowLineCol)
if extMode == "Until Breakout"
w.extending := false
// remove the opposite side's targets and stop
w.removeSide(longB ? -1 : 1)
// start tracking this session's first breakout
float rngB = w.hi - w.lo
w.trActive := true
w.trDir := w.dir
w.trEntry := longB ? w.hi : w.lo
w.trSL := longB ? w.hi - f_slDist(w.hi, rngB) : w.lo + f_slDist(w.lo, rngB)
w.trT1 := tgt1 > 0 ? (longB ? w.hi + rngB * tgt1 : w.lo - rngB * tgt1) : na
w.trT2 := tgt2 > 0 ? (longB ? w.hi + rngB * tgt2 : w.lo - rngB * tgt2) : na
w.trT3 := tgt3 > 0 ? (longB ? w.hi + rngB * tgt3 : w.lo - rngB * tgt3) : na
w.trRef := not na(w.trT1) ? w.trT1 : not na(w.trT2) ? w.trT2 : w.trT3
w.hit1 := false
w.hit2 := false
w.hit3 := false
w.first := 0
w.failed := false
w.retest := false
w.rtRes := 0
w.wasInside := inside
w.wasFull := inF
[longB, shortB, failL, failS, rtL, rtS, rngDone]
// ============================================================
// WINDOW OBJECTS & SESSION FLAGS
// ============================================================
var Win w1 = Win.new(name = w1Name, col = w1Col, lns = array.new<line>(), lbs = array.new<label>(), sides = array.new<int>())
var Win w2 = Win.new(name = w2Name, col = w2Col, lns = array.new<line>(), lbs = array.new<label>(), sides = array.new<int>())
var Win w3 = Win.new(name = w3Name, col = w3Col, lns = array.new<line>(), lbs = array.new<label>(), sides = array.new<int>())
bool en1 = true
bool en2 = multiMode and w2On
bool en3 = multiMode and w3On
bool inR1 = not na(time(timeframe.period, w1Range, tz))
bool inF1 = not na(time(timeframe.period, w1Full, tz))
bool inR2 = not na(time(timeframe.period, w2Range, tz))
bool inF2 = not na(time(timeframe.period, w2Full, tz))
bool inR3 = not na(time(timeframe.period, w3Range, tz))
bool inF3 = not na(time(timeframe.period, w3Full, tz))
[lg1, st1, fl1, fs1, rl1, rs1, rd1] = f_run(w1, en1, inR1, inF1)
[lg2, st2, fl2, fs2, rl2, rs2, rd2] = f_run(w2, en2, inR2, inF2)
[lg3, st3, fl3, fs3, rl3, rs3, rd3] = f_run(w3, en3, inR3, inF3)
bool longAny = lg1 or lg2 or lg3
bool shortAny = st1 or st2 or st3
bool failLAny = fl1 or fl2 or fl3
bool failSAny = fs1 or fs2 or fs3
bool rtLAny = rl1 or rl2 or rl3
bool rtSAny = rs1 or rs2 or rs3
bool doneAny = rd1 or rd2 or rd3
// ============================================================
// PLOTS & ALERTS
// ============================================================
plotshape(showSignals and longAny, "Long Breakout", shape.triangleup, location.belowbar, highLineCol, size=size.small, text="STRB", textcolor=highLineCol)
plotshape(showSignals and shortAny, "Short Breakout", shape.triangledown, location.abovebar, lowLineCol, size=size.small, text="STRB", textcolor=lowLineCol)
plotshape(showFail and failLAny, "Failed Long Breakout", shape.xcross, location.abovebar, slCol, size=size.tiny)
plotshape(showFail and failSAny, "Failed Short Breakout", shape.xcross, location.belowbar, slCol, size=size.tiny)
plotshape(showRetest and rtLAny, "Long Retest", shape.diamond, location.belowbar, highLineCol, size=size.tiny, text="RT", textcolor=highLineCol)
plotshape(showRetest and rtSAny, "Short Retest", shape.diamond, location.abovebar, lowLineCol, size=size.tiny, text="RT", textcolor=lowLineCol)
// Everything is confirmed at bar close, so set alerts to "Once Per Bar Close"
alertcondition(doneAny, "STRB Range Complete", "STRB range is set on {{ticker}}")
alertcondition(longAny, "STRB Long Breakout", "STRB LONG breakout on {{ticker}} @ {{close}}")
alertcondition(shortAny, "STRB Short Breakout", "STRB SHORT breakout on {{ticker}} @ {{close}}")
alertcondition(failLAny or failSAny, "STRB Failed Breakout", "STRB breakout FAILED (closed back inside range) on {{ticker}} @ {{close}}")
alertcondition(rtLAny or rtSAny, "STRB Retest", "STRB retest held on {{ticker}} @ {{close}}")
// ============================================================
// STATISTICS TABLE
// ============================================================
f_val(Win w, int r) =>
switch r
0 => str.tostring(w.total)
1 => str.tostring(w.nLong) + " / " + str.tostring(w.nShort)
2 => f_pct(w.nWin, w.total)
3 => f_pct(w.nLoss, w.total)
4 => f_pct(w.nNone, w.total)
5 => tgt1 > 0 ? f_pct(w.nR1, w.total) : "off"
6 => tgt2 > 0 ? f_pct(w.nR2, w.total) : "off"
7 => tgt3 > 0 ? f_pct(w.nR3, w.total) : "off"
8 => f_pct(w.nFail, w.total)
9 => f_pct(w.nRt, w.total) + " (" + str.tostring(w.nRt) + ")"
10 => f_pct(w.nRtWin, w.nRt)
11 => f_pct(w.nRtLoss, w.nRt)
=> "-"
f_rc(int r) =>
switch r
2 => highLineCol
3 => lowLineCol
4 => color.gray
8 => slCol
10 => highLineCol
11 => lowLineCol
=> color.white
f_all(array<Win> ws) =>
Win t = Win.new(name = "All", col = color.white)
for x in ws
t.total := t.total + x.total
t.nLong := t.nLong + x.nLong
t.nShort := t.nShort + x.nShort
t.nWin := t.nWin + x.nWin
t.nLoss := t.nLoss + x.nLoss
t.nNone := t.nNone + x.nNone
t.nR1 := t.nR1 + x.nR1
t.nR2 := t.nR2 + x.nR2
t.nR3 := t.nR3 + x.nR3
t.nFail := t.nFail + x.nFail
t.nRt := t.nRt + x.nRt
t.nRtWin := t.nRtWin + x.nRtWin
t.nRtLoss := t.nRtLoss + x.nRtLoss
t
var table stat = na
if showStats and barstate.islast
array<Win> act = array.new<Win>()
array.push(act, w1)
if en2
array.push(act, w2)
if en3
array.push(act, w3)
int nW = array.size(act)
int cols = nW + 1 + (nW > 1 ? 1 : 0)
array<string> labels = array.from("Trades", "Long / Short", "Target before SL", "SL before target", "Neither (session end)", "Reached T1", "Reached T2", "Reached T3", "Failed breakouts", "Retested (count)", "Retest → target first", "Retest → SL first")
if not na(stat)
table.delete(stat)
stat := table.new(statsPos, cols, 14, bgcolor=color.new(#131722, 12), border_color=color.new(color.gray, 70), border_width=1, frame_color=color.new(color.gray, 60), frame_width=1)
table.cell(stat, 0, 0, "STRB STATS (loaded history)", text_color=color.white, text_size=tblSize, bgcolor=color.new(color.gray, 35))
table.merge_cells(stat, 0, 0, cols - 1, 0)
table.cell(stat, 0, 1, "Window", text_color=color.new(color.white, 25), text_size=tblSize, text_halign=text.align_left)
for r = 0 to 11
table.cell(stat, 0, r + 2, array.get(labels, r), text_color=color.new(color.white, 25), text_size=tblSize, text_halign=text.align_left)
for c = 0 to nW - 1
Win ww = array.get(act, c)
table.cell(stat, c + 1, 1, ww.name, text_color=ww.col, text_size=tblSize, text_halign=text.align_right)
for r = 0 to 11
table.cell(stat, c + 1, r + 2, f_val(ww, r), text_color=f_rc(r), text_size=tblSize, text_halign=text.align_right)
if nW > 1
Win tt = f_all(act)
table.cell(stat, nW + 1, 1, "All", text_color=color.white, text_size=tblSize, text_halign=text.align_right)
for r = 0 to 11
table.cell(stat, nW + 1, r + 2, f_val(tt, r), text_color=f_rc(r), text_size=tblSize, text_halign=text.align_right)