本页源码来自 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/
// Original "ORB Algo | Flux Charts" © fluxchart
// Modifications © Kami2010388 — released under the same license (MPL 2.0)
// ORB Algo PRO [Kami] — opening range breakout + retest signals with an honest built-in backtest.
// Added to the original: up to 4 ORB times at once (+ custom session), symbol-based defaults (Gold / BTC), fixed ATR targets
// (1 TP with a minimum of 0.5x the stop, or 2 / 3 TPs), TP/SL boxes on every trade, per-slot dashboard, results board, ORB time scanner, alerts.
// Defaults: Gold = NY 09:30 · 60m (1 TP: 1x ATR, at least 0.5x the stop; Safer stop) | BTC = London 08:00 · 15m (Dynamic TP, middle stop).
// Honest backtest: stop/TP checked from the bar after entry, stop first on same-bar hits, gaps fill at the open, round-trip costs deducted.
// Signals are decided on bar close only (no repaint, no lookahead).
//@version=6
indicator('ORB Algo PRO [Kami]', shorttitle = 'ORB PRO', overlay = true, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500, max_bars_back = 5000)
//#region ───── Constants (original)
const bool DEBUG = false
int renderMaxBarsBack = 5000
const float minimumProfitPercent = 0.20
const float minimumProfitIncrementPercent = 0.075
const float atrTP1Mult = 0.75
const float atrTP2Mult = 1.5
const float atrTP3Mult = 2.25
const float atrTotalMult = 1.0
//#endregion
//#region ───── Inputs
const string GS = 'ORB Setup'
setupMode = input.string('Auto (by symbol)', 'Setup', options = ['Auto (by symbol)', 'Gold / Slots', 'BTC'], group = GS, display = display.none, tooltip = 'Auto: crypto charts use the BTC settings group; gold and all other charts use the two Gold / Slots groups. Every setting in the groups in use changes the chart.')
oneAtATime = input.bool(false, 'One Trade At A Time (all slots)', group = GS, display = display.none, tooltip = 'ON = skip a new signal while another slot still has a trade open.')
const string GM = 'Gold / Slots — ORB times'
s1On = input.bool(true, 'S1', inline = 's1', group = GM, display = display.none)
s1P = input.string('NY 09:30', '', options = ['London 08:00', 'London 07:00', 'NY 08:00', 'NY 08:30', 'NY 09:30', 'Gold Open 18:00 NY', 'Tokyo 09:00 (00:00 UTC)', 'Exchange Open (original)'], inline = 's1', group = GM, display = display.none)
s1L = input.int(60, 'min', options = [5, 15, 30, 60], inline = 's1', group = GM, display = display.none)
s2On = input.bool(false, 'S2', inline = 's2', group = GM, display = display.none)
s2P = input.string('London 08:00', '', options = ['London 08:00', 'London 07:00', 'NY 08:00', 'NY 08:30', 'NY 09:30', 'Gold Open 18:00 NY', 'Tokyo 09:00 (00:00 UTC)', 'Exchange Open (original)'], inline = 's2', group = GM, display = display.none)
s2L = input.int(30, 'min', options = [5, 15, 30, 60], inline = 's2', group = GM, display = display.none)
s3On = input.bool(false, 'S3', inline = 's3', group = GM, display = display.none)
s3P = input.string('London 08:00', '', options = ['London 08:00', 'London 07:00', 'NY 08:00', 'NY 08:30', 'NY 09:30', 'Gold Open 18:00 NY', 'Tokyo 09:00 (00:00 UTC)', 'Exchange Open (original)'], inline = 's3', group = GM, display = display.none)
s3L = input.int(15, 'min', options = [5, 15, 30, 60], inline = 's3', group = GM, display = display.none)
s4On = input.bool(false, 'S4', inline = 's4', group = GM, display = display.none)
s4P = input.string('NY 09:30', '', options = ['London 08:00', 'London 07:00', 'NY 08:00', 'NY 08:30', 'NY 09:30', 'Gold Open 18:00 NY', 'Tokyo 09:00 (00:00 UTC)', 'Exchange Open (original)'], inline = 's4', group = GM, display = display.none)
s4L = input.int(15, 'min', options = [5, 15, 30, 60], inline = 's4', group = GM, display = display.none)
const string GT = 'Gold / Slots — Trade settings'
tpMethod = input.string('ATR Single', 'TP Method', options = ['ATR Single', 'ATR 2 TPs', 'ATR', 'Dynamic'], group = GT, display = display.none, tooltip = 'ATR Single = one target, the whole trade closes there (best tested for gold). ATR 2 TPs = part closes at TP1, the rest at TP2. ATR = 3 targets (Backtesting exit ratios). Dynamic = EMA trail.')
tpSingleMult = input.float(1.0, 'TP / TP1 (x ATR)', minval = 0.25, step = 0.25, group = GT, display = display.none, tooltip = 'Target distance in ATR (ATR Single), or TP1 (ATR 2 TPs). Best tested for gold: 1.0 — 1.25 and 1.5 made less.')
tpMinR = input.float(0.5, 'TP at least (x stop) · 1 TP', minval = 0.0, step = 0.05, group = GT, display = display.none, tooltip = 'Only with ATR Single. TP = TP (x ATR), but never less than this many times the stop distance (example: stop 16 pts → TP at least 8 pts). 0 = off. Gold test (5m, 8 months): 0.5 = +22.8R vs +19.4R.')
tp2Mult = input.float(1.5, 'TP2 (x ATR) · 2 TPs', minval = 0.25, step = 0.25, group = GT, display = display.none, tooltip = 'Only with TP Method = ATR 2 TPs.')
tp1Pct = input.int(70, 'TP1 close % · 2 TPs', minval = 10, maxval = 100, step = 10, group = GT, display = display.none, tooltip = 'Only with TP Method = ATR 2 TPs: part of the trade closed at TP1; the rest closes at TP2.')
slMethod = input.string('Safer', 'Stop-Loss', options = ['Safer', 'Balanced', 'Risky'], group = GT, display = display.none, tooltip = 'Safer = between the middle and the broken edge of the range (best tested for gold). Balanced = middle of the range. Risky = between the middle and the far edge.')
adaptiveSL = input.bool(false, 'Stop to entry after TP1 · 2+ TPs', group = GT, display = display.none, tooltip = 'Only with ATR 2 TPs, ATR or Dynamic: moves the stop to entry once TP1 is hit. Tested worse for gold, so OFF.')
minTPR = input.float(0.0, 'Skip trade if TP1 < (x stop)', minval = 0.0, step = 0.1, group = GT, display = display.none, tooltip = '0 = off (recommended). Skips trades whose TP1 is smaller than this many times the stop distance. In gold tests this cut total profit, because the skipped trades were mostly winners.')
const string GB = 'BTC settings (crypto charts)'
btcP = input.string('London 08:00', 'ORB', options = ['London 08:00', 'London 07:00', 'NY 08:00', 'NY 08:30', 'NY 09:30', 'Gold Open 18:00 NY', 'Tokyo 09:00 (00:00 UTC)', 'Exchange Open (original)'], inline = 'b1', group = GB, display = display.none)
btcL = input.int(15, 'min', options = [5, 15, 30, 60], inline = 'b1', group = GB, display = display.none)
btcTP = input.string('Dynamic', 'TP Method', options = ['Dynamic', 'ATR Single'], group = GB, display = display.none, tooltip = 'Dynamic = EMA trail (best tested for BTC). ATR Single = one target at TP (x ATR).')
btcTPx = input.float(1.0, 'TP (x ATR) · ATR Single', minval = 0.25, step = 0.25, group = GB, display = display.none, tooltip = 'Only with TP Method = ATR Single.')
btcSL = input.string('Balanced', 'Stop-Loss', options = ['Safer', 'Balanced', 'Risky'], group = GB, display = display.none, tooltip = 'Balanced = middle of the range (best tested for BTC).')
btcBE = input.bool(true, 'Stop to entry after TP1', group = GB, display = display.none)
const string GR = 'ORB Rules'
tradeWeekends = input.bool(true, 'Trade Saturday & Sunday', group = GR, display = display.none, tooltip = 'BTC trades 7 days a week. Keep ON for BTC.')
exitAfterH = input.float(0.0, 'Close Trade After (hours)', minval = 0.0, step = 0.5, group = GR, display = display.none, tooltip = '0 = hold until that slot\'s next ORB starts (original). Example: 8 = close 8 hours after the ORB start.')
lastEntryH = input.float(0.0, 'No New Entry After (hours)', minval = 0.0, step = 0.5, group = GR, display = display.none, tooltip = '0 = off (original). Example: 4 = only take breakouts in the first 4 hours after the ORB start.')
userTz = input.string('Asia/Dubai', 'Your Timezone (dashboard)', options = ['Asia/Dubai', 'Asia/Karachi', 'UTC', 'Europe/London', 'America/New_York'], group = GR, display = display.none)
sensitivity = input.string('Medium', 'Sensitivity', options = ['High', 'Medium', 'Low', 'Lowest'], group = 'Algorithm', display = display.none, tooltip = 'Retests of the broken level needed before entry: High 0, Medium 1, Low 2, Lowest 3.')
breakoutCondition = input.string('Close', 'Breakout Condition', options = ['Close', 'EMA'], group = 'Algorithm', display = display.none)
emaLength = input.int(9, 'EMA Length', options = [4, 9, 13, 20, 34], group = 'Algorithm', display = display.none, tooltip = 'Used by Dynamic TP, Breakout Condition = EMA, and Plot EMA.')
customSessionEnabled = input.bool(false, 'Enabled', group = 'Custom Session', display = display.none, tooltip = 'ON = add this session as an extra slot (C), with any Setup.')
customSessionTime = input.session('1000-1100', 'Session', group = 'Custom Session', display = display.none)
orbTimeStr = input.timeframe('15', 'Range length', group = 'Custom Session', display = display.none, tooltip = 'Opening range length for the custom session slot (C).')
customTzIn = input.string('Exchange', 'Session Timezone', options = ['Exchange', 'UTC', 'Europe/London', 'America/New_York', 'Asia/Tokyo', 'Asia/Dubai'], group = 'Custom Session', display = display.none)
const string GC = 'Costs (honest backtest)'
costMode = input.string('Auto', 'Cost Model', options = ['Auto', 'Percent', 'Points'], group = GC, display = display.none, tooltip = 'Round-trip cost per trade, deducted from every result. Auto: crypto = 0, other symbols = 0.40 points (gold CFD spread estimate). Use Percent or Points to set your own broker cost.')
costPctIn = input.float(0.0, 'Cost % (Percent model)', minval = 0.0, step = 0.01, group = GC, display = display.none)
costPtsIn = input.float(0.40, 'Cost Points (Points model)', minval = 0.0, step = 0.05, group = GC, display = display.none)
orbDisplayEnabled = input.bool(true, 'Enabled', group = 'ORB Dashboard', display = display.none)
orbLocation = input.string('Bottom Right', 'Position', options = ['Top Right', 'Right Center', 'Top Center', 'Top Left', 'Bottom Right', 'Bottom Center', 'Bottom Left'], group = 'ORB Dashboard', display = display.none)
backtestDisplayEnabled = input.bool(false, 'Enabled', group = 'Backtesting', display = display.none, tooltip = 'Full results board (per slot + TOTAL). OFF by default — the ORB Dashboard shows a one-line result.')
backtestingLocation = input.string('Top Left', 'Position', options = ['Top Right', 'Right Center', 'Top Center', 'Top Left', 'Bottom Right', 'Bottom Center', 'Bottom Left'], group = 'Backtesting', display = display.none)
backtestingExitRatios = input.string('90% | 5% | 5%', 'Backtesting Exit Ratios', ['75% | 15% | 10%', '50% | 25% | 25%', '34% | 33% | 33%', '90% | 5% | 5%', '100% | 0% | 0%', '0% | 100% | 0%', '0% | 0% | 100%'], tooltip = 'TP 1 | TP 2 | TP 3 — used by Dynamic TP (BTC) and TP Method = ATR.', group = 'Backtesting', display = display.none)
scanEnabled = input.bool(false, 'Enabled', group = 'ORB Time Scanner', display = display.none, tooltip = 'Research table: tests 7 ORB times x 4 lengths (5/15/30/60 min) on this chart with the same rules and costs, ranked by Avg R. OFF by default.')
scanLocation = input.string('Bottom Left', 'Position', options = ['Top Right', 'Right Center', 'Top Center', 'Top Left', 'Bottom Right', 'Bottom Center', 'Bottom Left'], group = 'ORB Time Scanner', display = display.none)
scanRows = input.int(10, 'Rows', minval = 3, maxval = 28, group = 'ORB Time Scanner', display = display.none)
showORBZones = input.bool(true, 'Draw ORB Zones', group = 'Visuals', display = display.none, inline = 'group1')
plotEMA = input.bool(false, 'Plot EMA', group = 'Visuals', display = display.none, inline = 'group1')
showTradeLines = input.bool(true, 'Trade Lines', group = 'Visuals', display = display.none, inline = 'group1')
highlightSignal = input.bool(true, 'Highlight Signal Candle', group = 'Visuals', display = display.none)
showTPSL = input.bool(true, 'TP / SL Boxes (every trade)', group = 'Visuals', display = display.none, tooltip = 'Green box = entry → TP (✓ = TP hit). With TP2: first green box = TP1, second green box = TP2. Red box = entry → SL (✗ = stop hit). Each box runs from the BUY/SELL candle to the exit candle, like the Long/Short Position tool. Drawing only — results do not change.')
showHistoricZones = DEBUG ? input.bool(true, 'Show Historic Zones', group = 'Visuals', display = display.none) : true
highColor = input.color(color.green, 'High', inline = 'colors', group = 'Visuals')
lowColor = input.color(color.red, 'Low', inline = 'colors', group = 'Visuals')
//#endregion
//#region ───── Settings derived from inputs
array<string> ratioParts = str.split(backtestingExitRatios, ' | ')
float backtestTP1Exit = str.tonumber(str.replace(ratioParts.get(0), '%', '')) / 100.0
float backtestTP2Exit = str.tonumber(str.replace(ratioParts.get(1), '%', '')) / 100.0
float backtestTP3Exit = str.tonumber(str.replace(ratioParts.get(2), '%', '')) / 100.0
int retestsNeededForEntry = sensitivity == 'High' ? 0 : sensitivity == 'Medium' ? 1 : sensitivity == 'Low' ? 2 : 3
if timeframe.in_seconds() > timeframe.in_seconds('15')
runtime.error('ORB Algo only works on timeframes of 15 min or lower. Use the 5 min chart.')
int exitAfterMs = int(exitAfterH * 3600000.0)
int lastEntryMs = int(lastEntryH * 3600000.0)
int customLenMin = int(timeframe.in_seconds(orbTimeStr) / 60)
bool isCrypto = syminfo.type == 'crypto'
string effSetup = setupMode == 'Auto (by symbol)' ? (isCrypto ? 'BTC' : 'Gold / Slots') : setupMode
bool isBTC = effSetup == 'BTC'
// every setting of the group in use goes straight into the engine (no hidden preset values)
string tpEff = isBTC ? btcTP : tpMethod
string slEff = isBTC ? btcSL : slMethod
float tpSingleEff = isBTC ? btcTPx : tpSingleMult
float tp2Eff = math.max(tp2Mult, tpSingleEff)
float tp1PartEff = tp1Pct / 100.0
bool adaptEff = isBTC ? btcBE : adaptiveSL
float tpMinEff = isBTC ? 0.0 : tpMinR
float minTPREff = isBTC ? 0.0 : minTPR
bool costInPts = costMode == 'Points' or (costMode == 'Auto' and not isCrypto)
float cPct = costMode == 'Percent' ? costPctIn : 0.0
float cPts = costMode == 'Points' ? costPtsIn : costMode == 'Auto' and not isCrypto ? 0.40 : 0.0
float sPct = costInPts ? 0.0 : 0.02
float sPts = costInPts ? 0.20 : 0.0
string costTxt = costInPts ? str.tostring(cPts, '#.##') + ' pts' : str.tostring(cPct, '#.###') + '%'
string stressTxt = costInPts ? '+0.20 pts' : '+0.02%'
// ORB time presets (index 0-6). 7 = Exchange Open (original), 8 = Custom Session
var array<string> P_NAME = array.from('London 08:00', 'London 07:00', 'NY 08:00', 'NY 08:30', 'NY 09:30', 'Gold 18:00 NY', 'Tokyo 09:00')
var array<int> S_LEN = array.from(5, 15, 30, 60)
string customTz = customTzIn == 'Exchange' ? syminfo.timezone : customTzIn
string customSess = str.contains(customSessionTime, ':') ? customSessionTime : customSessionTime + ':1234567'
array<string> tzParts = str.split(userTz, '/')
string userTzShort = tzParts.get(tzParts.size() - 1)
color BG = #0d0d0d
color GREEN = #00e676
color RED = #ff5252
//#endregion
//#region ───── Helpers
getPosition(string positionText) =>
switch positionText
'Top Right' => position.top_right
'Top Center' => position.top_center
'Right Center' => position.middle_right
'Top Left' => position.top_left
'Bottom Right' => position.bottom_right
'Bottom Center' => position.bottom_center
'Bottom Left' => position.bottom_left
=> position.middle_left
presetIdx(string p) =>
switch p
'London 08:00' => 0
'London 07:00' => 1
'NY 08:00' => 2
'NY 08:30' => 3
'NY 09:30' => 4
'Gold Open 18:00 NY' => 5
'Tokyo 09:00 (00:00 UTC)' => 6
=> 7
isWeekend(int t, string tz) =>
int dw = dayofweek(t, tz)
dw == dayofweek.saturday or dw == dayofweek.sunday
// today's session start in that city's own clock (summer/winter time safe)
anchorOf(simple string tz, int hh, int mm) =>
timestamp(tz, year(time, tz), month(time, tz), dayofmonth(time, tz), hh, mm, 0)
sessionBegins(string sess, string tz) =>
int t = time('1440', sess, tz)
bool isFirst = (na(t[1]) and not na(t)) or t[1] < t
isFirst
fmtR(float r) =>
na(r) ? '—' : (r >= 0 ? '+' : '') + str.tostring(r, '#.##') + 'R'
numCol(float v) =>
na(v) ? color.gray : v > 0 ? GREEN : v < 0 ? RED : color.white
verdictOf(int n, float avgR) =>
n < 30 ? 'LOW SAMPLE' : avgR >= 0.15 and n >= 50 ? 'PASS' : avgR > 0 ? 'WEAK' : 'FAIL'
//#endregion
//#region ───── Engine (one object = one ORB time; slots + scanner use the same code)
type Eng
string name
int pIdx
int orbMs
int lenMin
string state = 'Idle'
int startTime
int anchorTime
float h
float l
bool bBull = false
int bStart
int retests = 0
bool inTrade = false
bool tBull = false
float entry
float sl
float sl0
float risk
float atr0
int entryBar
float rem = 0.0
float gross = 0.0
bool tp1 = false
bool tp2 = false
bool tp3 = false
float ref1
float ref2
float tp1Px
float tp1D
float tp2Px
float tp3Px
string exitWhy = ''
float exitPx
float lastR
bool evStart = false
bool evEnd = false
bool evEntry = false
bool evTP1 = false
bool evTP2 = false
bool evTP3 = false
bool evSL = false
bool evExitPrev = false
bool evExitNow = false
bool evClosed = false
bool evSkip = false
int days = 0
int trades = 0
int wins = 0
int losses = 0
float sumR = 0.0
float gw = 0.0
float gl = 0.0
float sumPct = 0.0
float eq = 0.0
float peak = 0.0
float maxDD = 0.0
float sumStressR = 0.0
type ORBRec
float h
float l
int startIndex
int endIndex
bool hasEntry = false
bool entryBullish = false
int entryIndex
float entryPrice
float entryATR
float slPrice
float tp1D
bool closed = false
int exitIndex
float exitPrice
string exitWhy = ''
float resR
bool tpHit = false
bool tp2Hit = false
bool tp3Hit = false
bool slHit = false
float tp1Fill
line hLine
line lLine
label entryLabel
box tpBox
box slBox
line tp2Ln
line tp3Ln
box tp2Box
type Slot
string tag
string name
int pIdx
int lenMin
string style
int width
Eng eng
array<ORBRec> recs
line lnEntry
line lnSL
line lnTP1
line lnTP2
line lnTP3
label lbSL
label lbEntry
label lbTP1
label lbTP2
label lbTP3
method resetEvents(Eng e) =>
e.evStart := false
e.evEnd := false
e.evEntry := false
e.evTP1 := false
e.evTP2 := false
e.evTP3 := false
e.evSL := false
e.evExitPrev := false
e.evExitNow := false
e.evClosed := false
e.evSkip := false
// Books a closed trade: net R after costs, % result, drawdown, stress test.
method finishTrade(Eng e, float cPctV, float cPtsV, float sPctV, float sPtsV) =>
float costPx = cPtsV + e.entry * cPctV / 100.0
float stressPx = sPtsV + e.entry * sPctV / 100.0
float netPx = e.gross - costPx
float r = netPx / e.risk
e.trades += 1
if r > 0
e.wins += 1
e.gw += r
else
e.losses += 1
e.gl -= r
e.sumR += r
e.sumPct += netPx / e.entry * 100.0
e.eq += r
e.peak := math.max(e.peak, e.eq)
e.maxDD := math.max(e.maxDD, e.peak - e.eq)
e.sumStressR += (netPx - stressPx) / e.risk
e.lastR := r
e.inTrade := false
e.rem := 0.0
e.evClosed := true
e.state := 'Done'
// One confirmed bar of the Flux ORB logic for this engine.
method run(Eng e, bool isStart, int anchorT, bool dayOK, float pC, float emaV, float atrV, float cPctV, float cPtsV, float sPctV, float sPtsV) =>
e.resetEvents()
// New ORB → the previous ORB ends; an open trade closes at the previous bar's close (original behaviour)
if isStart
e.evEnd := true
if e.inTrade
float dPrev = e.tBull ? 1.0 : -1.0
e.gross += e.rem * (pC - e.entry) * dPrev
e.exitWhy := 'Session End'
e.exitPx := pC
e.evExitPrev := true
e.finishTrade(cPctV, cPtsV, sPctV, sPtsV)
if dayOK
e.state := 'Opening Range'
e.startTime := time
e.anchorTime := anchorT
e.h := na
e.l := na
e.retests := 0
e.days += 1
e.evStart := true
else
e.state := 'Idle'
// ORB High & Low
if e.state == 'Opening Range'
if time < e.startTime + e.orbMs
e.h := math.max(nz(e.h, high), high)
e.l := math.min(nz(e.l, low), low)
else
e.state := 'Waiting For Breakouts'
bool canEnter = true
if exitAfterMs > 0
canEnter := time_close < e.anchorTime + exitAfterMs
if lastEntryMs > 0
canEnter := canEnter and time < e.anchorTime + lastEntryMs
// Wait for breakouts
if e.state == 'Waiting For Breakouts' and canEnter
float cp = breakoutCondition == 'EMA' ? emaV : close
if cp > e.h or cp < e.l
e.bBull := cp > e.h
e.bStart := bar_index
e.retests := 0
e.state := 'In Breakout'
// Handle breakouts: failed breakout, retests, entry
if e.state == 'In Breakout'
if (e.bBull and close < e.h) or (not e.bBull and close > e.l)
e.state := 'Waiting For Breakouts'
if bar_index > e.bStart and ((e.bBull and close > e.h and low < e.h) or (not e.bBull and close < e.l and high > e.l))
e.retests += 1
if e.retests >= retestsNeededForEntry and canEnter
float center = (e.h + e.l) / 2.0
float slp = slEff == 'Safer' ? (e.bBull ? (center + e.h) / 2.0 : (center + e.l) / 2.0) : slEff == 'Risky' ? (e.bBull ? (center + e.l) / 2.0 : (center + e.h) / 2.0) : center
float rk = (close - slp) * (e.bBull ? 1.0 : -1.0)
// v3.4: skip 'tiny' trades — TP1 too small compared with the stop distance (fixed ATR targets only)
// v3.6: 1 TP distance = 1x ATR, but at least tpMinR x the stop distance
float tp1Single = tpEff == 'ATR Single' and tpMinEff > 0 and rk > 0 ? math.max(atrV * tpSingleEff, tpMinEff * rk) : atrV * tpSingleEff
float tp1Dist = tpEff == 'ATR' ? atrV * atrTP1Mult * atrTotalMult : tpEff == 'Dynamic' ? na : tp1Single
bool smallTP = minTPREff > 0 and rk > 0 and not na(tp1Dist) and tp1Dist / rk < minTPREff
if rk > 0 and not na(atrV) and not smallTP
e.inTrade := true
e.tBull := e.bBull
e.entry := close
e.sl := slp
e.sl0 := slp
e.risk := rk
e.atr0 := atrV
e.tp1D := tp1Single
e.entryBar := bar_index
e.rem := 1.0
e.gross := 0.0
e.tp1 := false
e.tp2 := false
e.tp3 := false
e.ref1 := na
e.ref2 := na
e.tp1Px := na
e.tp2Px := na
e.tp3Px := na
e.exitWhy := ''
e.exitPx := na
e.state := 'Entry Taken'
e.evEntry := true
else
e.state := 'Done'
e.exitWhy := smallTP ? 'Skip: TP1 ' + str.tostring(tp1Dist / rk, '#.##') + 'R' : 'Skipped'
e.lastR := na
e.evSkip := smallTP
// Manage the trade from the bar AFTER entry (honest: no pre-entry wicks)
if e.inTrade and bar_index > e.entryBar
float d = e.tBull ? 1.0 : -1.0
bool done = false
// Stop first: it is an intrabar order (gap through stop → filled at open)
if (e.tBull and low < e.sl) or (not e.tBull and high > e.sl)
float fill = e.tBull ? math.min(open, e.sl) : math.max(open, e.sl)
e.gross += e.rem * (fill - e.entry) * d
e.rem := 0.0
e.exitWhy := e.sl != e.sl0 ? 'Breakeven' : 'Stop Loss'
e.exitPx := fill
e.evSL := true
done := true
else if tpEff == 'ATR Single'
// one target, whole trade closes there (stop already checked first this bar)
float t1s = e.entry + d * e.tp1D
if (e.tBull and high >= t1s) or (not e.tBull and low <= t1s)
e.tp1 := true
e.tp1Px := t1s
e.gross += e.rem * (t1s - e.entry) * d
e.rem := 0.0
e.evTP1 := true
e.exitWhy := 'TP'
e.exitPx := t1s
done := true
else if tpEff == 'ATR 2 TPs'
// TP1 closes part of the trade, TP2 closes the rest (stop already checked first this bar)
float u1 = e.entry + d * e.atr0 * tpSingleEff
float u2 = e.entry + d * e.atr0 * tp2Eff
if not e.tp1
if (e.tBull and high >= u1) or (not e.tBull and low <= u1)
e.tp1 := true
e.tp1Px := u1
e.gross += tp1PartEff * (u1 - e.entry) * d
e.rem -= tp1PartEff
e.evTP1 := true
if adaptEff
e.sl := e.entry
if e.tp1 and not e.tp2 and e.rem > 1e-9
if (e.tBull and high >= u2) or (not e.tBull and low <= u2)
e.tp2 := true
e.tp2Px := u2
e.gross += e.rem * (u2 - e.entry) * d
e.rem := 0.0
e.evTP2 := true
if e.tp1 and e.rem <= 1e-9
e.rem := 0.0
e.exitWhy := e.tp2 ? 'TP2' : 'TP1'
e.exitPx := e.tp2 ? u2 : u1
done := true
else if e.tp1 and adaptEff and ((e.tBull and low < e.sl) or (not e.tBull and high > e.sl))
// same bar hit TP1 and came back to entry: assume the worse order
e.gross += e.rem * (e.sl - e.entry) * d
e.rem := 0.0
e.exitWhy := 'Breakeven'
e.exitPx := e.sl
e.evSL := true
done := true
else if tpEff == 'ATR'
float t1 = e.entry + d * e.atr0 * atrTP1Mult * atrTotalMult
float t2 = e.entry + d * e.atr0 * atrTP2Mult * atrTotalMult
float t3 = e.entry + d * e.atr0 * atrTP3Mult * atrTotalMult
bool halt = false
if not e.tp1
if (e.tBull and high >= t1) or (not e.tBull and low <= t1)
e.tp1 := true
e.tp1Px := t1
e.gross += backtestTP1Exit * (t1 - e.entry) * d
e.rem -= backtestTP1Exit
e.evTP1 := true
if adaptEff
e.sl := e.entry
else
halt := true
if not halt and not e.tp2
if (e.tBull and high >= t2) or (not e.tBull and low <= t2)
e.tp2 := true
e.tp2Px := t2
e.gross += backtestTP2Exit * (t2 - e.entry) * d
e.rem -= backtestTP2Exit
e.evTP2 := true
else
halt := true
if not halt and not e.tp3
if (e.tBull and high >= t3) or (not e.tBull and low <= t3)
e.tp3 := true
e.tp3Px := t3
e.gross += backtestTP3Exit * (t3 - e.entry) * d
e.rem -= backtestTP3Exit
e.evTP3 := true
if e.tp3 or e.rem <= 1e-9
e.rem := 0.0
e.exitWhy := e.tp3 ? 'TP3' : e.tp2 ? 'TP2' : 'TP1'
e.exitPx := close
done := true
else if e.tp1 and adaptEff and ((e.tBull and low < e.sl) or (not e.tBull and high > e.sl))
// same bar hit TP1 and came back to entry: assume the worse order
e.gross += e.rem * (e.sl - e.entry) * d
e.rem := 0.0
e.exitWhy := 'Breakeven'
e.exitPx := e.sl
e.evSL := true
done := true
else
// Dynamic TP (EMA cross-back once the EMA is >= 0.20% in profit), filled at the bar close
bool prof = e.tBull ? emaV > e.entry : emaV < e.entry
if prof and math.abs(emaV - e.entry) / e.entry * 100.0 >= minimumProfitPercent
bool crossBack = e.tBull ? close < emaV : close > emaV
if crossBack
if not e.tp1
e.tp1 := true
e.ref1 := emaV
e.tp1Px := close
e.gross += backtestTP1Exit * (close - e.entry) * d
e.rem -= backtestTP1Exit
e.evTP1 := true
if adaptEff
e.sl := e.entry
else if not e.tp2
if (e.tBull ? emaV > e.ref1 : emaV < e.ref1) and math.abs(emaV - e.ref1) / e.ref1 * 100.0 >= minimumProfitIncrementPercent
e.tp2 := true
e.ref2 := emaV
e.tp2Px := close
e.gross += backtestTP2Exit * (close - e.entry) * d
e.rem -= backtestTP2Exit
e.evTP2 := true
else if not e.tp3
if (e.tBull ? emaV > e.ref2 : emaV < e.ref2) and math.abs(emaV - e.ref2) / e.ref2 * 100.0 >= minimumProfitIncrementPercent
e.tp3 := true
e.tp3Px := close
e.gross += backtestTP3Exit * (close - e.entry) * d
e.rem -= backtestTP3Exit
e.evTP3 := true
if e.tp3 or e.rem <= 1e-9
e.rem := 0.0
e.exitWhy := e.tp3 ? 'TP3' : e.tp2 ? 'TP2' : 'TP1'
e.exitPx := close
done := true
// Optional time exit
if not done and exitAfterMs > 0 and time_close >= e.anchorTime + exitAfterMs
e.gross += e.rem * (close - e.entry) * d
e.rem := 0.0
e.exitWhy := 'Time Exit'
e.exitPx := close
e.evExitNow := true
done := true
if done
e.finishTrade(cPctV, cPtsV, sPctV, sPtsV)
e.state
newSlot(string tag, int pIdx, int lenMin, string st, int w) =>
string nm = 'Exchange Open'
if pIdx == 8
nm := 'Custom ' + customSessionTime
else if pIdx >= 0 and pIdx <= 6
nm := P_NAME.get(pIdx)
Slot.new(tag = tag, name = nm, pIdx = pIdx, lenMin = lenMin, style = st, width = w, eng = Eng.new(name = tag, pIdx = pIdx, orbMs = lenMin * 60000, lenMin = lenMin), recs = array.new<ORBRec>())
statusOf(Eng e) =>
string r = 'Waiting for ORB'
if e.inTrade
r := (e.tBull ? 'LONG' : 'SHORT') + (e.sl != e.sl0 ? ' · BE' : e.tp1 ? ' · TP1 ✓' : '')
else if e.state == 'Opening Range'
r := 'Building range'
else if e.state == 'Waiting For Breakouts'
r := 'Waiting breakout'
else if e.state == 'In Breakout'
r := 'Breakout → retest?'
else if e.state == 'Done'
r := e.exitWhy
r
//#endregion
//#region ───── Objects & series
var array<Slot> slots = array.new<Slot>()
if barstate.isfirst
if isBTC
slots.push(newSlot('S1', presetIdx(btcP), btcL, line.style_solid, 2))
else
if s1On
slots.push(newSlot('S1', presetIdx(s1P), s1L, line.style_solid, 2))
if s2On
slots.push(newSlot('S2', presetIdx(s2P), s2L, line.style_dashed, 2))
if s3On
slots.push(newSlot('S3', presetIdx(s3P), s3L, line.style_dotted, 2))
if s4On
slots.push(newSlot('S4', presetIdx(s4P), s4L, line.style_solid, 1))
if customSessionEnabled
slots.push(newSlot('C', 8, customLenMin, line.style_dotted, 1))
var array<Eng> scan = array.new<Eng>()
if barstate.isfirst and scanEnabled
for pi = 0 to P_NAME.size() - 1
for li = 0 to S_LEN.size() - 1
int ln = S_LEN.get(li)
scan.push(Eng.new(name = P_NAME.get(pi), pIdx = pi, orbMs = ln * 60000, lenMin = ln))
var array<int> pAnchor = array.new<int>(7, 0)
var array<bool> pDayOK = array.new<bool>(7, true)
var int firstTime = time
var float cEq = 0.0
var float cPeak = 0.0
var float cDD = 0.0
ema = ta.ema((high + low) / 2.0, emaLength)
atr = ta.atr(12)
plot(plotEMA ? ema : na, 'EMA')
int prevT = time[1]
float prevC = close[1]
bool customStart = sessionBegins(customSess, customTz)
// clear last bar's signal flags on every tick (they are set again only when a bar closes)
for sR in slots
sR.eng.resetEvents()
//#endregion
//#region ───── Run on confirmed bars only
if barstate.isconfirmed
pAnchor.set(0, anchorOf('Europe/London', 8, 0))
pAnchor.set(1, anchorOf('Europe/London', 7, 0))
pAnchor.set(2, anchorOf('America/New_York', 8, 0))
pAnchor.set(3, anchorOf('America/New_York', 8, 30))
pAnchor.set(4, anchorOf('America/New_York', 9, 30))
pAnchor.set(5, anchorOf('America/New_York', 18, 0))
pAnchor.set(6, anchorOf('Asia/Tokyo', 9, 0))
pDayOK.set(0, tradeWeekends or not isWeekend(pAnchor.get(0), 'Europe/London'))
pDayOK.set(1, tradeWeekends or not isWeekend(pAnchor.get(1), 'Europe/London'))
pDayOK.set(2, tradeWeekends or not isWeekend(pAnchor.get(2), 'America/New_York'))
pDayOK.set(3, tradeWeekends or not isWeekend(pAnchor.get(3), 'America/New_York'))
pDayOK.set(4, tradeWeekends or not isWeekend(pAnchor.get(4), 'America/New_York'))
pDayOK.set(5, tradeWeekends or not isWeekend(pAnchor.get(5), 'America/New_York'))
pDayOK.set(6, tradeWeekends or not isWeekend(pAnchor.get(6), 'Asia/Tokyo'))
if scanEnabled
for e in scan
int aS = pAnchor.get(e.pIdx)
bool stS = time >= aS and (na(prevT) or prevT < aS) and time < aS + e.orbMs
e.run(stS, aS, pDayOK.get(e.pIdx), prevC, ema, atr, cPct, cPts, sPct, sPts)
// (a) run every slot
for s in slots
Eng g = s.eng
bool st = false
int aG = time
bool dOK = true
if s.pIdx <= 6
aG := pAnchor.get(s.pIdx)
st := time >= aG and (na(prevT) or prevT < aG) and time < aG + g.orbMs
dOK := pDayOK.get(s.pIdx)
else if s.pIdx == 7
st := session.isfirstbar_regular
dOK := tradeWeekends or not isWeekend(time, syminfo.timezone)
else
st := customStart
dOK := tradeWeekends or not isWeekend(time, customTz)
g.run(st, aG, dOK, prevC, ema, atr, cPct, cPts, sPct, sPts)
// (b) one trade at a time: cancel a new entry while another trade stays open (slot order = priority)
if oneAtATime
bool busy = false
for sb in slots
if sb.eng.inTrade and sb.eng.entryBar < bar_index
busy := true
for sb in slots
Eng gb = sb.eng
if gb.evEntry
if busy
gb.inTrade := false
gb.evEntry := false
gb.rem := 0.0
gb.state := 'Done'
gb.exitWhy := 'Blocked'
gb.lastR := na
else
busy := true
// (c) bookkeeping, drawing history, alerts
for s in slots
Eng g = s.eng
// combined equity (TOTAL row)
if g.evClosed
cEq += g.lastR
cPeak := math.max(cPeak, cEq)
cDD := math.max(cDD, cPeak - cEq)
// v3.2: save how the trade ended on its ORB record (for the TP / SL boxes)
if s.recs.size() > 0
ORBRec xr = s.recs.get(0)
if xr.hasEntry and not xr.closed
xr.closed := true
xr.exitIndex := g.evExitPrev ? bar_index - 1 : bar_index
xr.exitPrice := g.exitPx
xr.exitWhy := g.exitWhy
xr.resR := g.lastR
xr.tpHit := g.tp1
xr.tp2Hit := g.tp2
xr.tp3Hit := g.tp3
xr.slHit := g.exitWhy == 'Stop Loss'
xr.tp1Fill := g.tp1Px
// ORB history for drawing (zones + Buy/Sell labels)
if g.evEnd and s.recs.size() > 0
ORBRec pr = s.recs.get(0)
if na(pr.endIndex)
pr.endIndex := bar_index - 1
if g.evStart
s.recs.unshift(ORBRec.new(startIndex = bar_index))
if s.recs.size() > 300
ORBRec od = s.recs.pop()
line.delete(od.hLine)
line.delete(od.lLine)
label.delete(od.entryLabel)
box.delete(od.tpBox)
box.delete(od.slBox)
box.delete(od.tp2Box)
line.delete(od.tp2Ln)
line.delete(od.tp3Ln)
if s.recs.size() > 0 and g.state != 'Idle'
ORBRec cr = s.recs.get(0)
if na(cr.endIndex)
cr.h := g.h
cr.l := g.l
if g.evEntry
cr.hasEntry := true
cr.entryBullish := g.tBull
cr.entryIndex := bar_index
cr.entryPrice := g.entry
cr.entryATR := g.atr0
cr.slPrice := g.sl0
cr.tp1D := g.tp1D
// alert() messages (use "Any alert() function call" when creating the alert)
string tag = 'ORB PRO | ' + syminfo.ticker + ' | ' + s.tag + ' ' + s.name + ' ' + str.tostring(s.lenMin) + 'm | '
if g.evEntry
float dA = g.tBull ? 1.0 : -1.0
string tpTxt = tpEff == 'ATR Single' ? ' | TP ' + str.tostring(g.entry + dA * g.tp1D, format.mintick) : tpEff == 'ATR 2 TPs' ? ' | TP1 ' + str.tostring(g.entry + dA * g.atr0 * tpSingleEff, format.mintick) + ' (' + str.tostring(tp1PartEff * 100, '#') + '%) | TP2 ' + str.tostring(g.entry + dA * g.atr0 * tp2Eff, format.mintick) : tpEff == 'ATR' ? ' | TP1 ' + str.tostring(g.entry + dA * g.atr0 * atrTP1Mult * atrTotalMult, format.mintick) : ' | TP1 = EMA exit'
alert(tag + (g.tBull ? 'BUY' : 'SELL') + ' @ ' + str.tostring(g.entry, format.mintick) + ' | SL ' + str.tostring(g.sl0, format.mintick) + tpTxt, alert.freq_once_per_bar_close)
if g.evTP1
alert(tag + (tpEff == 'ATR Single' ? 'TP HIT @ ' + str.tostring(g.tp1Px, format.mintick) + ' | trade closed ' + fmtR(g.lastR) : 'TP1 @ ' + str.tostring(g.tp1Px, format.mintick) + (tpEff == 'ATR 2 TPs' ? ' | ' + str.tostring(tp1PartEff * 100, '#') + '% closed' : '') + (g.sl != g.sl0 ? ' | SL moved to entry' : '')), alert.freq_once_per_bar_close)
if g.evTP2
alert(tag + 'TP2 @ ' + str.tostring(g.tp2Px, format.mintick) + (tpEff == 'ATR 2 TPs' ? ' | trade closed ' + fmtR(g.lastR) : ''), alert.freq_once_per_bar_close)
if g.evTP3
alert(tag + 'TP3 @ ' + str.tostring(g.tp3Px, format.mintick) + ' | trade done ' + fmtR(g.lastR), alert.freq_once_per_bar_close)
if g.evSL
alert(tag + (g.exitWhy == 'Breakeven' ? 'BREAKEVEN EXIT' : 'STOP LOSS') + ' @ ' + str.tostring(g.exitPx, format.mintick) + ' | ' + fmtR(g.lastR), alert.freq_once_per_bar_close)
if g.evExitPrev or g.evExitNow
alert(tag + 'CLOSE (' + g.exitWhy + ') @ ' + str.tostring(g.exitPx, format.mintick) + ' | ' + fmtR(g.lastR), alert.freq_once_per_bar_close)
if g.evSkip
alert(tag + 'NO TRADE: breakout ' + (g.bBull ? 'up' : 'down') + ' skipped, TP1 only ' + str.replace(g.exitWhy, 'Skip: TP1 ', '') + ' of the stop', alert.freq_once_per_bar_close)
//#endregion
//#region ───── Plots (original markers, all slots)
isClose = bar_index > last_bar_index - renderMaxBarsBack
bool aTP1L = false
bool aTP1S = false
bool aTP2L = false
bool aTP2S = false
bool aTP3L = false
bool aTP3S = false
bool aSLL = false
bool aSLS = false
bool aBEL = false
bool aBES = false
bool aXPL = false
bool aXPS = false
bool aXNL = false
bool aXNS = false
bool anyEntry = false
bool entL = false
bool entS = false
bool aSkL = false
bool aSkS = false
for sP in slots
Eng q = sP.eng
bool lng = q.tBull
bool isBE = q.exitWhy == 'Breakeven'
anyEntry := anyEntry or q.evEntry
entL := entL or (q.evEntry and lng)
entS := entS or (q.evEntry and not lng)
aSkL := aSkL or (q.evSkip and q.bBull)
aSkS := aSkS or (q.evSkip and not q.bBull)
aTP1L := aTP1L or (q.evTP1 and lng)
aTP1S := aTP1S or (q.evTP1 and not lng)
aTP2L := aTP2L or (q.evTP2 and lng)
aTP2S := aTP2S or (q.evTP2 and not lng)
aTP3L := aTP3L or (q.evTP3 and lng)
aTP3S := aTP3S or (q.evTP3 and not lng)
aSLL := aSLL or (q.evSL and not isBE and lng)
aSLS := aSLS or (q.evSL and not isBE and not lng)
aBEL := aBEL or (q.evSL and isBE and lng)
aBES := aBES or (q.evSL and isBE and not lng)
aXPL := aXPL or (q.evExitPrev and lng)
aXPS := aXPS or (q.evExitPrev and not lng)
aXNL := aXNL or (q.evExitNow and lng)
aXNS := aXNS or (q.evExitNow and not lng)
plotshape(aTP1L and isClose and tpEff != 'ATR Single', 'TP 1', shape.xcross, location.abovebar, size = size.tiny, text = 'TP 1', textcolor = color.white)
plotshape(aTP1S and isClose and tpEff != 'ATR Single', 'TP 1', shape.xcross, location.belowbar, size = size.tiny, text = 'TP 1', textcolor = color.white)
plotshape(aTP1L and isClose and tpEff == 'ATR Single', 'TP', shape.xcross, location.abovebar, color = color.green, size = size.tiny, text = 'TP', textcolor = color.white)
plotshape(aTP1S and isClose and tpEff == 'ATR Single', 'TP', shape.xcross, location.belowbar, color = color.green, size = size.tiny, text = 'TP', textcolor = color.white)
plotshape(aTP2L and isClose, 'TP 2', shape.xcross, location.abovebar, size = size.tiny, text = 'TP 2', textcolor = color.white)
plotshape(aTP2S and isClose, 'TP 2', shape.xcross, location.belowbar, size = size.tiny, text = 'TP 2', textcolor = color.white)
plotshape(aTP3L and isClose, 'TP 3', shape.xcross, location.abovebar, size = size.tiny, text = 'TP 3', textcolor = color.white)
plotshape(aTP3S and isClose, 'TP 3', shape.xcross, location.belowbar, size = size.tiny, text = 'TP 3', textcolor = color.white)
plotshape(aSLL and isClose, 'SL', shape.xcross, location.belowbar, color = color.red, size = size.tiny, text = 'SL', textcolor = color.white)
plotshape(aSLS and isClose, 'SL', shape.xcross, location.abovebar, color = color.red, size = size.tiny, text = 'SL', textcolor = color.white)
plotshape(aBEL and isClose, 'BE', shape.xcross, location.belowbar, color = color.gray, size = size.tiny, text = 'BE', textcolor = color.white)
plotshape(aBES and isClose, 'BE', shape.xcross, location.abovebar, color = color.gray, size = size.tiny, text = 'BE', textcolor = color.white)
plotshape(aXPL and isClose, 'Exit', shape.xcross, location.belowbar, color = color.red, size = size.tiny, text = 'Exit', textcolor = color.white, offset = -1)
plotshape(aXPS and isClose, 'Exit', shape.xcross, location.abovebar, color = color.red, size = size.tiny, text = 'Exit', textcolor = color.white, offset = -1)
plotshape(aXNL and isClose, 'Time Exit', shape.xcross, location.belowbar, color = color.orange, size = size.tiny, text = 'Exit', textcolor = color.white)
plotshape(aXNS and isClose, 'Time Exit', shape.xcross, location.abovebar, color = color.orange, size = size.tiny, text = 'Exit', textcolor = color.white)
// v3.4: breakout seen but skipped (TP1 too small vs the stop)
plotshape(aSkL and isClose, 'Skipped (tiny TP)', shape.circle, location.belowbar, color = color.gray, size = size.tiny, text = 'skip', textcolor = color.gray)
plotshape(aSkS and isClose, 'Skipped (tiny TP)', shape.circle, location.abovebar, color = color.gray, size = size.tiny, text = 'skip', textcolor = color.gray)
// signal candle highlight (the candle where the Buy/Sell label sits)
bgcolor(highlightSignal and entL ? color.new(color.green, 75) : highlightSignal and entS ? color.new(color.red, 75) : na, title = 'Signal Candle')
bool foundEntryTick = anyEntry
bool foundTPTick = aTP1L or aTP1S or aTP2L or aTP2S or aTP3L or aTP3S
bool foundSLTick = aSLL or aSLS or aBEL or aBES
alertcondition(foundEntryTick, 'Buy / Sell', 'ORB PRO: new Buy / Sell signal')
alertcondition(foundTPTick, 'Take Profit', 'ORB PRO: take profit hit')
alertcondition(foundSLTick, 'Stop Loss', 'ORB PRO: stop loss / breakeven hit')
//#endregion
//#region ───── Drawing: ORB zones, Buy/Sell labels, live trade lines (per slot)
if barstate.islast
for sD in slots
Eng g = sD.eng
if sD.recs.size() > 0
int lim = showHistoricZones ? sD.recs.size() - 1 : 0
for i = lim to 0
ORBRec r = sD.recs.get(i)
line.delete(r.hLine)
line.delete(r.lLine)
label.delete(r.entryLabel)
box.delete(r.tpBox)
box.delete(r.slBox)
box.delete(r.tp2Box)
line.delete(r.tp2Ln)
line.delete(r.tp3Ln)
if r.startIndex > last_bar_index - renderMaxBarsBack and not na(r.h)
if showORBZones
r.hLine := line.new(r.startIndex, r.h, nz(r.endIndex, last_bar_index), r.h, color = highColor, width = sD.width, style = sD.style)
r.lLine := line.new(r.startIndex, r.l, nz(r.endIndex, last_bar_index), r.l, color = lowColor, width = sD.width, style = sD.style)
if r.hasEntry
bool bl = r.entryBullish
float dr = bl ? 1.0 : -1.0
// open trade reads the live engine; closed trade reads what was saved at exit
bool live = i == 0 and not r.closed and g.inTrade
bool h1 = live ? g.tp1 : r.tpHit
bool h2 = live ? g.tp2 : r.tp2Hit
bool h3 = live ? g.tp3 : r.tp3Hit
float fill1 = live ? g.tp1Px : r.tp1Fill
// TP levels: fixed at entry (ATR Single / ATR 2 TPs / ATR). Dynamic has no fixed TP → shown at the real EMA-exit price once it happened.
float tpA = na
float tpB = na
float tpC = na
if tpEff == 'ATR Single'
tpA := r.entryPrice + dr * r.tp1D
else if tpEff == 'ATR 2 TPs'
tpA := r.entryPrice + dr * r.entryATR * tpSingleEff
tpB := r.entryPrice + dr * r.entryATR * tp2Eff
else if tpEff == 'ATR'
tpA := r.entryPrice + dr * r.entryATR * atrTP1Mult * atrTotalMult
tpB := r.entryPrice + dr * r.entryATR * atrTP2Mult * atrTotalMult
tpC := r.entryPrice + dr * r.entryATR * atrTP3Mult * atrTotalMult
else if h1
tpA := fill1
string tpLvl = tpEff == 'ATR Single' ? 'TP ' + str.tostring(tpA, format.mintick) : tpEff == 'ATR 2 TPs' ? 'TP1 ' + str.tostring(tpA, format.mintick) + ' (' + str.tostring(tp1PartEff * 100, '#') + '%) · TP2 ' + str.tostring(tpB, format.mintick) : tpEff == 'ATR' ? 'TP1 ' + str.tostring(tpA, format.mintick) + ' · TP2 ' + str.tostring(tpB, format.mintick) + ' · TP3 ' + str.tostring(tpC, format.mintick) : 'TP = EMA exit'
string resTxt = r.closed ? 'Result ' + fmtR(r.resR) + ' (' + r.exitWhy + ')' : 'Trade open'
r.entryLabel := label.new(r.entryIndex, r.entryPrice, (bl ? 'BUY ' : 'SELL ') + sD.tag, yloc = bl ? yloc.belowbar : yloc.abovebar, color = bl ? color.green : color.red, textcolor = color.white, style = bl ? label.style_label_up : label.style_label_down, size = size.small, tooltip = sD.tag + ' ' + sD.name + ' · ' + str.tostring(sD.lenMin) + 'm | Entry ' + str.tostring(r.entryPrice, format.mintick) + ' | SL ' + str.tostring(r.slPrice, format.mintick) + ' | ' + tpLvl + ' | ' + resTxt)
if showTPSL
// box runs from the signal candle to the exit candle (open trade: to the current candle)
int xe = r.closed ? math.max(r.exitIndex, r.entryIndex + 1) : last_bar_index
// red box = entry → stop loss (✗ = stop hit)
string slTxt = 'SL ' + str.tostring(r.slPrice, format.mintick) + (r.slHit ? ' ✗ ' + fmtR(r.resR) : '')
r.slBox := box.new(r.entryIndex, math.max(r.entryPrice, r.slPrice), xe, math.min(r.entryPrice, r.slPrice), border_color = color.new(color.red, 40), bgcolor = color.new(color.red, r.slHit ? 72 : 88), text = slTxt, text_size = size.small, text_color = color.red, text_halign = text.align_center, text_valign = bl ? text.align_bottom : text.align_top, text_wrap = text.wrap_none)
// green box = entry → take profit (✓ = TP hit)
if not na(tpA)
string tpBoxTxt = ''
if tpEff == 'ATR Single'
tpBoxTxt := 'TP ' + str.tostring(tpA, format.mintick) + (h1 ? ' ✓' : '')
else if tpEff == 'ATR 2 TPs'
tpBoxTxt := 'TP1 ' + str.tostring(tpA, format.mintick) + (h1 ? ' ✓' : '')
else if tpEff == 'ATR'
tpBoxTxt := 'TP1 ' + str.tostring(tpA, format.mintick) + (h1 ? ' ✓' : '') + ' · TP2 ' + str.tostring(tpB, format.mintick) + (h2 ? ' ✓' : '') + ' · TP3 ' + str.tostring(tpC, format.mintick) + (h3 ? ' ✓' : '')
else
tpBoxTxt := 'TP (EMA exit) ' + str.tostring(tpA, format.mintick) + ' ✓'
// trade result: on this box, unless it shows on the TP2 box or the red box
if r.closed and h1 and not r.slHit and not (tpEff == 'ATR 2 TPs' and h2)
tpBoxTxt := tpBoxTxt + ' ' + fmtR(r.resR)
r.tpBox := box.new(r.entryIndex, math.max(r.entryPrice, tpA), xe, math.min(r.entryPrice, tpA), border_color = color.new(color.green, 40), bgcolor = color.new(color.green, h1 ? 72 : 88), text = tpBoxTxt, text_size = size.small, text_color = color.green, text_halign = text.align_center, text_valign = bl ? text.align_top : text.align_bottom, text_wrap = text.wrap_none)
// ATR 2 TPs: second green box = TP1 → TP2
if tpEff == 'ATR 2 TPs'
string tp2BoxTxt = 'TP2 ' + str.tostring(tpB, format.mintick) + (h2 ? ' ✓' : '') + (r.closed and h2 ? ' ' + fmtR(r.resR) : '')
r.tp2Box := box.new(r.entryIndex, math.max(tpA, tpB), xe, math.min(tpA, tpB), border_color = color.new(color.green, 40), bgcolor = color.new(color.green, h2 ? 72 : 92), text = tp2BoxTxt, text_size = size.small, text_color = color.green, text_halign = text.align_center, text_valign = bl ? text.align_top : text.align_bottom, text_wrap = text.wrap_none)
// ATR (3 targets): TP2 and TP3 as dotted lines
if tpEff == 'ATR'
r.tp2Ln := line.new(r.entryIndex, tpB, xe, tpB, color = color.new(color.green, 30), style = line.style_dotted)
r.tp3Ln := line.new(r.entryIndex, tpC, xe, tpC, color = color.new(color.green, 30), style = line.style_dotted)
line.delete(sD.lnEntry)
line.delete(sD.lnSL)
line.delete(sD.lnTP1)
line.delete(sD.lnTP2)
line.delete(sD.lnTP3)
label.delete(sD.lbSL)
label.delete(sD.lbEntry)
label.delete(sD.lbTP1)
label.delete(sD.lbTP2)
label.delete(sD.lbTP3)
if showTradeLines and g.inTrade
int x1 = g.entryBar
int x2 = bar_index + 10
float dd = g.tBull ? 1.0 : -1.0
sD.lnEntry := line.new(x1, g.entry, x2, g.entry, color = color.gray, style = line.style_dashed)
sD.lnSL := line.new(x1, g.sl, x2, g.sl, color = color.red, style = line.style_dashed, width = 2)
// price labels on the right: Entry (gray), TP (green), SL (red)
if g.sl != g.entry
sD.lbEntry := label.new(x2, g.entry, sD.tag + ' Entry ' + str.tostring(g.entry, format.mintick) + (tpEff == 'Dynamic' ? ' · TP = EMA exit' : ''), style = label.style_label_left, color = color.new(color.gray, 20), textcolor = color.white, size = size.small)
if tpEff == 'ATR Single'
float tpLive = g.entry + dd * g.tp1D
sD.lnTP1 := line.new(x1, tpLive, x2, tpLive, color = color.green, style = line.style_dashed, width = 2)
sD.lbTP1 := label.new(x2, tpLive, sD.tag + ' TP ' + str.tostring(tpLive, format.mintick), style = label.style_label_left, color = color.new(color.green, 20), textcolor = color.white, size = size.small)
if tpEff == 'ATR 2 TPs'
float w1 = g.entry + dd * g.atr0 * tpSingleEff
float w2 = g.entry + dd * g.atr0 * tp2Eff
sD.lnTP1 := line.new(x1, w1, x2, w1, color = color.green, style = line.style_dashed, width = 2)
sD.lnTP2 := line.new(x1, w2, x2, w2, color = color.green, style = line.style_dashed, width = 2)
sD.lbTP1 := label.new(x2, w1, sD.tag + ' TP1 ' + str.tostring(w1, format.mintick) + (g.tp1 ? ' ✓' : ' (' + str.tostring(tp1PartEff * 100, '#') + '%)'), style = label.style_label_left, color = color.new(color.green, 20), textcolor = color.white, size = size.small)
sD.lbTP2 := label.new(x2, w2, sD.tag + ' TP2 ' + str.tostring(w2, format.mintick), style = label.style_label_left, color = color.new(color.green, 20), textcolor = color.white, size = size.small)
if tpEff == 'ATR'
float t1L = g.entry + dd * g.atr0 * atrTP1Mult * atrTotalMult
float t2L = g.entry + dd * g.atr0 * atrTP2Mult * atrTotalMult
float t3L = g.entry + dd * g.atr0 * atrTP3Mult * atrTotalMult
sD.lnTP1 := line.new(x1, t1L, x2, t1L, color = color.green, style = line.style_dotted)
sD.lnTP2 := line.new(x1, t2L, x2, t2L, color = color.green, style = line.style_dotted)
sD.lnTP3 := line.new(x1, t3L, x2, t3L, color = color.green, style = line.style_dotted)
sD.lbTP1 := label.new(x2, t1L, sD.tag + ' TP1 ' + str.tostring(t1L, format.mintick) + (g.tp1 ? ' ✓' : ''), style = label.style_label_left, color = color.new(color.green, 20), textcolor = color.white, size = size.small)
sD.lbTP2 := label.new(x2, t2L, sD.tag + ' TP2 ' + str.tostring(t2L, format.mintick) + (g.tp2 ? ' ✓' : ''), style = label.style_label_left, color = color.new(color.green, 20), textcolor = color.white, size = size.small)
sD.lbTP3 := label.new(x2, t3L, sD.tag + ' TP3 ' + str.tostring(t3L, format.mintick) + (g.tp3 ? ' ✓' : ''), style = label.style_label_left, color = color.new(color.green, 20), textcolor = color.white, size = size.small)
sD.lbSL := label.new(x2, g.sl, sD.tag + (g.sl != g.sl0 ? ' SL (BE) ' : ' SL ') + str.tostring(g.sl, format.mintick), style = label.style_label_left, color = color.new(color.red, 20), textcolor = color.white, size = size.small)
//#endregion
//#region ───── ORB Dashboard (live, one row per slot)
dashCell(table t, int c, int r, string txt, color tc, color bg) =>
table.cell(t, c, r, txt, text_color = tc, bgcolor = bg, text_size = size.small)
if barstate.islast and orbDisplayEnabled
var table ORBDisplay = table.new(getPosition(orbLocation), 8, 8, bgcolor = BG, frame_width = 2, frame_color = color.black, border_width = 1, border_color = #222222)
table.merge_cells(ORBDisplay, 0, 0, 7, 0)
table.cell(ORBDisplay, 0, 0, 'ORB Dashboard · ' + effSetup + ' · TP ' + tpEff + ' · SL ' + slEff + (tpEff == 'ATR Single' and tpMinEff > 0 ? ' · TP ≥ ' + str.tostring(tpMinEff, '#.##') + 'x stop' : '') + (minTPREff > 0 and tpEff != 'Dynamic' ? ' · skip TP1 < ' + str.tostring(minTPREff, '#.##') + 'x stop' : ''), text_color = color.white, bgcolor = BG)
array<string> dh = array.from('Slot', 'ORB', 'Your time', 'Status', 'Entry', 'SL', tpEff == 'ATR Single' ? 'TP' : tpEff == 'ATR 2 TPs' ? 'TP1 / TP2' : 'TP1', 'Result')
for c = 0 to 7
dashCell(ORBDisplay, c, 1, dh.get(c), color.gray, BG)
int rr = 2
for sB in slots
if rr <= 7
Eng g = sB.eng
ORBRec cr = na
if sB.recs.size() > 0
cr := sB.recs.get(0)
bool hasE = not na(cr) and cr.hasEntry
bool entBull = false
float entP = na
float entATR = na
float slP = na
float entTPD = na
if hasE
entBull := cr.entryBullish
entP := cr.entryPrice
entATR := cr.entryATR
slP := cr.slPrice
entTPD := cr.tp1D
float dirE = entBull ? 1.0 : -1.0
string clk = na(g.anchorTime) ? '—' : str.format_time(g.anchorTime, 'HH:mm', userTz) + '–' + str.format_time(g.anchorTime + g.orbMs, 'HH:mm', userTz)
string stTxt = statusOf(g)
color stBg = g.inTrade ? (g.tBull ? color.green : color.red) : BG
float slNow = g.inTrade ? g.sl : slP
string tp1Txt = not hasE ? '—' : tpEff == 'ATR Single' ? str.tostring(entP + dirE * entTPD, format.mintick) : tpEff == 'ATR 2 TPs' ? str.tostring(entP + dirE * entATR * tpSingleEff, format.mintick) + ' / ' + str.tostring(entP + dirE * entATR * tp2Eff, format.mintick) : tpEff == 'ATR' ? str.tostring(entP + dirE * entATR * atrTP1Mult * atrTotalMult, format.mintick) : 'EMA exit'
float liveR = g.inTrade ? (close - g.entry) * (g.tBull ? 1.0 : -1.0) / g.risk : na
float resR = g.inTrade ? liveR : hasE and g.state == 'Done' ? g.lastR : na
dashCell(ORBDisplay, 0, rr, sB.tag, color.white, BG)
dashCell(ORBDisplay, 1, rr, sB.name + ' · ' + str.tostring(sB.lenMin) + 'm', color.white, BG)
dashCell(ORBDisplay, 2, rr, clk, color.gray, BG)
dashCell(ORBDisplay, 3, rr, stTxt, color.white, stBg)
dashCell(ORBDisplay, 4, rr, hasE ? (entBull ? 'Buy ' : 'Sell ') + str.tostring(entP, format.mintick) : '—', hasE ? (entBull ? GREEN : RED) : color.gray, BG)
dashCell(ORBDisplay, 5, rr, na(slNow) ? '—' : str.tostring(slNow, format.mintick), na(slNow) ? color.gray : RED, BG)
dashCell(ORBDisplay, 6, rr, tp1Txt, hasE ? GREEN : color.gray, BG)
dashCell(ORBDisplay, 7, rr, fmtR(resR), numCol(resR), BG)
rr += 1
// one-line result (full board: Backtesting section → Enabled)
int nAll = 0
int wAll = 0
float rAll = 0.0
for sQ in slots
nAll += sQ.eng.trades
wAll += sQ.eng.wins
rAll += sQ.eng.sumR
float avgAll = nAll > 0 ? rAll / nAll : na
string vdAll = verdictOf(nAll, avgAll)
int dAll = int((time - firstTime) / 86400000)
if rr <= 7
table.merge_cells(ORBDisplay, 0, rr, 7, rr)
table.cell(ORBDisplay, 0, rr, 'Result ' + str.tostring(dAll) + ' days: ' + str.tostring(nAll) + ' trades · ' + (nAll > 0 ? str.tostring(100.0 * wAll / nAll, '#') + '% win · ' : '') + fmtR(avgAll) + ' per trade · Net ' + (nAll > 0 ? fmtR(rAll) : '—') + ' · ' + vdAll, text_color = vdAll == 'PASS' ? GREEN : vdAll == 'WEAK' ? color.orange : vdAll == 'FAIL' ? RED : color.gray, bgcolor = BG, text_size = size.small)
//#endregion
//#region ───── Backtesting board (honest, per slot + TOTAL)
if barstate.islast and backtestDisplayEnabled
var table bt = table.new(getPosition(backtestingLocation), 9, 9, bgcolor = BG, frame_width = 2, frame_color = color.black, border_width = 1, border_color = #222222)
int daysTested = int((time - firstTime) / 86400000)
table.merge_cells(bt, 0, 0, 8, 0)
table.cell(bt, 0, 0, 'ORB Backtesting (honest) · ' + str.tostring(daysTested) + ' days', text_color = color.white, bgcolor = BG)
array<string> bh = array.from('Slot', 'ORB', 'Trades', 'Win %', 'Avg R', 'Net R', 'PF', 'Max DD', 'Verdict')
for c = 0 to 8
dashCell(bt, c, 1, bh.get(c), color.gray, BG)
int br = 2
int tN = 0
int tW = 0
float tR = 0.0
float tGW = 0.0
float tGL = 0.0
float tS = 0.0
for sT in slots
Eng g = sT.eng
tN += g.trades
tW += g.wins
tR += g.sumR
tGW += g.gw
tGL += g.gl
tS += g.sumStressR
if br <= 6
float av = g.trades > 0 ? g.sumR / g.trades : na
float pfv = g.gl > 0 ? g.gw / g.gl : na
float wrv = g.trades > 0 ? 100.0 * g.wins / g.trades : na
string vd = verdictOf(g.trades, av)
dashCell(bt, 0, br, sT.tag, color.white, BG)
dashCell(bt, 1, br, sT.name + ' · ' + str.tostring(sT.lenMin) + 'm', color.white, BG)
dashCell(bt, 2, br, str.tostring(g.trades), g.trades < 30 ? color.orange : color.white, BG)
dashCell(bt, 3, br, na(wrv) ? '—' : str.tostring(wrv, '#.#') + '%', color.white, BG)
dashCell(bt, 4, br, fmtR(av), numCol(av), BG)
dashCell(bt, 5, br, g.trades > 0 ? fmtR(g.sumR) : '—', numCol(g.trades > 0 ? g.sumR : na), BG)
dashCell(bt, 6, br, na(pfv) ? '—' : str.tostring(pfv, '#.##'), na(pfv) ? color.gray : pfv >= 1 ? GREEN : RED, BG)
dashCell(bt, 7, br, g.trades > 0 ? '-' + str.tostring(g.maxDD, '#.##') + 'R' : '—', g.maxDD > 0 ? RED : color.gray, BG)
dashCell(bt, 8, br, vd, vd == 'PASS' ? GREEN : vd == 'WEAK' ? color.orange : vd == 'FAIL' ? RED : color.gray, BG)
br += 1
float tAvg = tN > 0 ? tR / tN : na
float tPF = tGL > 0 ? tGW / tGL : na
float tWR = tN > 0 ? 100.0 * tW / tN : na
string tVd = verdictOf(tN, tAvg)
dashCell(bt, 0, 7, 'ALL', color.yellow, BG)
dashCell(bt, 1, 7, 'TOTAL (' + str.tostring(slots.size()) + ' slots)', color.yellow, BG)
dashCell(bt, 2, 7, str.tostring(tN), color.yellow, BG)
dashCell(bt, 3, 7, na(tWR) ? '—' : str.tostring(tWR, '#.#') + '%', color.yellow, BG)
dashCell(bt, 4, 7, fmtR(tAvg), numCol(tAvg), BG)
dashCell(bt, 5, 7, tN > 0 ? fmtR(tR) : '—', numCol(tN > 0 ? tR : na), BG)
dashCell(bt, 6, 7, na(tPF) ? '—' : str.tostring(tPF, '#.##'), na(tPF) ? color.gray : tPF >= 1 ? GREEN : RED, BG)
dashCell(bt, 7, 7, tN > 0 ? '-' + str.tostring(cDD, '#.##') + 'R' : '—', cDD > 0 ? RED : color.gray, BG)
dashCell(bt, 8, 7, tVd, tVd == 'PASS' ? GREEN : tVd == 'WEAK' ? color.orange : tVd == 'FAIL' ? RED : color.gray, BG)
table.merge_cells(bt, 0, 8, 8, 8)
table.cell(bt, 0, 8, 'Costs ' + costTxt + ' · TP ' + tpEff + (tpEff == 'ATR Single' ? ' ' + str.tostring(tpSingleEff, '#.##') + 'xATR' + (tpMinEff > 0 ? ' (min ' + str.tostring(tpMinEff, '#.##') + 'x stop)' : '') : tpEff == 'ATR 2 TPs' ? ' ' + str.tostring(tpSingleEff, '#.##') + 'x (' + str.tostring(tp1PartEff * 100, '#') + '%) + ' + str.tostring(tp2Eff, '#.##') + 'xATR' + (adaptEff ? ', SL to entry after TP1' : '') : '') + ' · SL ' + slEff + (minTPREff > 0 and tpEff != 'Dynamic' ? ' · skip TP1 < ' + str.tostring(minTPREff, '#.##') + 'x stop' : '') + (oneAtATime ? ' · one trade at a time' : '') + ' · TOTAL Avg R with ' + stressTxt + ' extra cost: ' + fmtR(tN > 0 ? tS / tN : na) + ' · Verdict = +0.15R & 50 trades', text_color = color.gray, bgcolor = BG, text_size = size.tiny)
//#endregion
//#region ───── ORB Time Scanner
if barstate.islast and scanEnabled and scan.size() > 0
var table sc = table.new(getPosition(scanLocation), 8, scanRows + 3, bgcolor = BG, frame_width = 1, frame_color = #333333, border_width = 1, border_color = #1e1e1e)
array<float> keyArr = array.new<float>()
for e in scan
keyArr.push(e.trades > 0 ? e.sumR / e.trades : -999.0)
array<int> ord = keyArr.sort_indices(order.descending)
int nShow = math.min(scanRows, scan.size())
int daysT = int((time - firstTime) / 86400000)
table.merge_cells(sc, 0, 0, 7, 0)
table.cell(sc, 0, 0, 'ORB TIME SCANNER · ' + syminfo.ticker + ' · ' + str.tostring(daysT) + ' days · TP ' + tpEff + ' · SL ' + slEff + ' · ranked by Avg R', text_color = color.white, bgcolor = BG, text_size = size.small)
array<string> hdr = array.from('#', 'ORB Time', 'Len', 'Trades', 'Win %', 'Avg R', 'Net R', 'PF')
for c = 0 to 7
table.cell(sc, c, 1, hdr.get(c), text_color = color.gray, bgcolor = BG, text_size = size.small)
for k = 0 to nShow - 1
Eng se = scan.get(ord.get(k))
bool isMine = false
for sM in slots
if sM.pIdx == se.pIdx and sM.lenMin == se.lenMin
isMine := true
float av = se.trades > 0 ? se.sumR / se.trades : na
float pfv = se.gl > 0 ? se.gw / se.gl : na
float wrv = se.trades > 0 ? 100.0 * se.wins / se.trades : na
float netv = se.trades > 0 ? se.sumR : na
color tc = isMine ? color.yellow : color.white
int row = k + 2
table.cell(sc, 0, row, (isMine ? '▶ ' : '') + str.tostring(k + 1), text_color = tc, bgcolor = BG, text_size = size.small)
table.cell(sc, 1, row, se.name, text_color = tc, bgcolor = BG, text_halign = text.align_left, text_size = size.small)
table.cell(sc, 2, row, str.tostring(se.lenMin) + 'm', text_color = tc, bgcolor = BG, text_size = size.small)
table.cell(sc, 3, row, str.tostring(se.trades), text_color = se.trades < 30 ? color.orange : tc, bgcolor = BG, text_size = size.small)
table.cell(sc, 4, row, na(wrv) ? '—' : str.tostring(wrv, '#') + '%', text_color = tc, bgcolor = BG, text_size = size.small)
table.cell(sc, 5, row, fmtR(av), text_color = numCol(av), bgcolor = BG, text_size = size.small)
table.cell(sc, 6, row, fmtR(netv), text_color = numCol(netv), bgcolor = BG, text_size = size.small)
table.cell(sc, 7, row, na(pfv) ? '—' : str.tostring(pfv, '#.##'), text_color = na(pfv) ? color.gray : pfv >= 1 ? GREEN : RED, bgcolor = BG, text_size = size.small)
table.merge_cells(sc, 0, nShow + 2, 7, nShow + 2)
table.cell(sc, 0, nShow + 2, 'Same rules & costs as your slots · orange = small sample (<30 trades) · ▶ = your slots', text_color = color.gray, bgcolor = BG, text_size = size.tiny)
//#endregion