本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// DEVELOPMENT VERSION: core rules changed; original panel results are not comparable.
// Original CHoCH/BOS remains the default; frozen raid-bound structure is an optional comparison.
// CHoCH-only applies to the Legacy setup rule; raid-bound uses its frozen reference.
// Entry-bar target hits are deliberately deferred because OHLC cannot prove ordering.
// See RaidShift Core v2 - Review.md for changed semantics and validation limits.
// This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0
// International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © UgurTash
//
// ── CREDITS ────────────────────────────────────────────────────────────────────────────
// This is a derivative work. The licence above is inherited, not chosen: the ShareAlike term
// of the source below requires it, which also means this script must stay open-source and
// must not be sold.
//
// • Market structure — leg detection, pivot state and the CHoCH / BOS break logic
// (f_leg, f_updateStructure, f_breaks and the pivotPt / trendState types), plus the
// cumulative mean-range Fair Value Gap threshold — adapted from
// "Smart Money Concepts [LuxAlgo]" © LuxAlgo, CC BY-NC-SA 4.0.
//
// • SMT correlated-peer pairing (f_smtAutoPeer) — adapted from
// "PO3 Matrix+ (M1D)" © mayb1dayy, Mozilla Public License 2.0.
//
// Everything else — the raid rule, the setup state machine, the entry triggers, the target
// resolution, the trade management and the performance panel — is original to this script.
// ═══════════════════════════════════════════════════════════════════════════════════════
//@version=6
indicator('RaidShift — Liquidity to FVG Reversal Engine [UgurTash]', 'RaidShift [UgurTash]', overlay = true,
max_bars_back = 1000, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)
const string G_LQ = '1 · Liquidity Raid'
const string G_SMT = '2 · SMT Divergence'
const string G_MS = '3 · Market Structure (CHoCH)'
const string G_FVG = '4 · Fair Value Gap'
const string G_SET = '5 · Trade Setup (Entry / SL / TP)'
const string G_PD = '8 · Previous Day (PDH / PDL)'
const string G_HTF = '9 · Higher Timeframe Candle Block'
const string G_FIL = '6 · Setup Filters (all off by default)'
const string G_MGT = '7 · Trade Management (all off by default)'
const string G_PNL = '10 · Performance Panel'
const string G_AL = '11 · Alerts'
int swingPeriod = input.int(15, 'Swing Period (pivot left/right)', minval = 2, group = G_LQ, tooltip = 'Left and right bar count for the pivot scan. Higher = fewer but more significant liquidity pools. On a 15m chart 10-20 is a good working range.')
int maxScanBack = input.int(20, 'Pivots Scanned Back', minval = 1, maxval = 100, group = G_LQ, tooltip = 'How many of the most recent pivots are checked for a raid on every bar.')
bool showSweeps = input.bool(true, 'Draw Raided Levels', group = G_LQ)
bool showRaidLabels = input.bool(false, 'Draw RAID / BREAK Text', group = G_LQ)
color sweepBuyCol = input.color(#f23645, 'Buyside', inline = 'sw', group = G_LQ)
color sweepSelCol = input.color(#1d4ed8, 'Sellside', inline = 'sw', group = G_LQ)
int maxSweepDraw = input.int(10, 'Max Raids Kept On Chart', minval = 1, maxval = 50, group = G_LQ)
string raidMode = input.string('Wick rejection', 'Raid Mode', options = ['Wick rejection', 'Close-through reversal', 'Both'], group = G_LQ, tooltip = 'Which event at a liquidity pool arms the sequence.\n\nWick rejection (default) — wick beyond the level, body back inside. The level was defended. A body closing through the level is not a signal; it just retires the pool. This preserves the wick-rejection event definition; pool consumption and setup sequencing include Enhanced corrections.\n\nClose-through reversal — the body closes BEYOND the level, and the setup arms only if structure then shifts back against it. This is the failed-breakout read: the break took the stops and trapped the breakout entries, so its failure carries more behind it. Note what this does NOT do: it does not produce fewer raids (bodies close through levels more often than wicks reject them, so the raid count usually rises) and it does not automatically widen the stop. What thins it out is the invalidation rule, because most breaks keep going. Let the panel tell you the numbers rather than assuming them.\n\nBoth — either event can arm a setup. If both directions qualify on one bar, neither starts a setup. Labels can be enabled separately. Useful for seeing them side by side; less useful for measuring one against the other, which is better done one mode at a time.')
float ctMinPen = input.float(0.0, 'Min Close-Through Depth (× ATR)', minval = 0.0, step = 0.05, group = G_LQ, tooltip = 'How far BEYOND the level the body must close before a close-through counts as a signal. 0 = off, so any close through it qualifies.\n\nWithout this, a body closing one tick past the level arms a setup, which is noise wearing the shape of a breakout. Measured in ATR rather than percent, for the same reason the raid quality gates are: ATR rescales itself with the market, a percentage of price does not.\n\nThis gate only decides whether the break SIGNALS. The level is retired by a body closing through it either way, in every mode, exactly as before — a pool that has been closed through is not liquidity any more, however shallow the close was.\n\nOnly read when Raid Mode allows close-through raids.')
float ctInvBuf = input.float(0.0, 'Close-Through Invalidation Buffer (× ATR)', minval = 0.0, step = 0.05, group = G_LQ, tooltip = 'Extra room, in ATR, before a close-through setup is thrown away.\n\nA setup dies when price closes beyond the raiding bar\'s own extreme — the break is working and the reversal thesis is finished. That rule is naturally loose after a WICK raid, because the raiding bar closed back inside the level and left a whole wick of room above the close. After a CLOSE-THROUGH raid there is no such room: the bar closed near its own high, so an ordinary continuation candle trips the rule immediately.\n\nThis buffer gives that case the room the wick case gets for free. 0 = off, and the rule is then identical for both kinds of raid. Raising it keeps setups alive through a second push; raise it too far and the engine sits in setups that have already failed. Watch the Cancelled counter while you move it.\n\nApplies ONLY to setups armed by a close-through raid. Wick setups are never affected by this, whatever it is set to.')
float raidMinPen = input.float(0.0, 'Min Raid Penetration (× ATR)', minval = 0.0, step = 0.05, group = G_LQ, tooltip = 'How far the WICK must trade beyond the level before the sweep counts. 0 = off (any trade beyond it qualifies).\n\nHonest expectation: this mostly just removes setups. The cleanest stop-hunts are frequently shallow — price takes the level by a hair and turns — so a deep-penetration requirement can filter out exactly the raids you want. Measure it against Net R, not win rate.')
float raidMinRej = input.float(0.0, 'Min Rejection (× ATR)', minval = 0.0, step = 0.05, group = G_LQ, tooltip = 'How far back INSIDE the level the candle must close. 0 = off (any close back inside qualifies).\n\nThis is the more informative of the two gates: it measures how hard the level was rejected rather than how far it was pierced. A candle that poked through and closed one tick back inside barely rejected anything; a candle that pierced and closed half an ATR back inside did.')
bool smtOn = input.bool(true, 'Show SMT Divergence', group = G_SMT, tooltip = 'At every raid, the correlated symbol is checked: did it take ITS matching swing at the same time? If it did not, the move lacked participation and the raid is marked SMT.\n\nA sellside raid the peer refused to follow is a BULLISH divergence; a buyside raid it refused to follow is BEARISH. The comparison is made against the peer\'s price at the bar that formed the pivot, so it asks the same question the chart does rather than an approximation of it.')
string smtSymbol = input.symbol('', 'Correlated Symbol (empty = disabled)', group = G_SMT, tooltip = 'No automatic pairing. Enter an explicit different symbol to enable comparison.')
color smtBullCol = input.color(#1d4ed8, 'Bullish', inline = 'sm', group = G_SMT)
color smtBearCol = input.color(#f23645, 'Bearish', inline = 'sm', group = G_SMT)
bool smtLabels = input.bool(true, 'Draw SMT Labels', group = G_SMT)
string structMode = input.string('Internal', 'Structure Used For Setups', options = ['Internal', 'Swing'], group = G_MS, tooltip = 'Internal = fast inner structure (default 5-bar pivot). Swing = major structure (default 50-bar pivot). The setup trigger reads the selected one; the other is only reported as bias in the panel.')
int internalLen = input.int(5, 'Internal Structure Length', minval = 2, group = G_MS)
int swingLen = input.int(50, 'Swing Structure Length', minval = 2, group = G_MS)
string shiftRule = input.string('Legacy CHoCH / BOS', 'Setup Shift Rule', options = ['Raid-bound structure', 'Legacy CHoCH / BOS'], group = G_MS, tooltip = 'Raid-bound: freeze the latest known unbroken opposite pivot before the raid; require its close break on a later bar. This is a structural shift, not necessarily a globally classified CHoCH. Legacy uses the global classification. Both require a later confirmed bar.')
bool chochOnly = input.bool(true, 'CHoCH only (ignore BOS)', group = G_MS, tooltip = 'Applies only to Legacy CHoCH / BOS setup rule. Raid-bound structure uses its own frozen pivot reference.')
bool showStruct = input.bool(true, 'Draw CHoCH / BOS Lines', group = G_MS)
color bullStrCol = input.color(#089981, 'Bullish', inline = 'ms', group = G_MS)
color bearStrCol = input.color(#f23645, 'Bearish', inline = 'ms', group = G_MS)
int maxStrDraw = input.int(10, 'Max Structures Kept On Chart', minval = 1, maxval = 50, group = G_MS)
bool fvgAutoThr = input.bool(true, 'Auto Threshold', group = G_FVG, tooltip = 'Cumulative mean body-change threshold that filters out insignificant gaps.')
float fvgMinAtr = input.float(0.0, 'Min Gap Height (× ATR)', minval = 0.0, step = 0.05, group = G_FVG, tooltip = '0 = disabled.')
bool showFvg = input.bool(true, 'Draw FVG Boxes', group = G_FVG)
color fvgBullCol = input.color(color.new(#089981, 82), 'Bullish', inline = 'fv', group = G_FVG)
color fvgBearCol = input.color(color.new(#f23645, 82), 'Bearish', inline = 'fv', group = G_FVG)
bool showFvgEntry = input.bool(true, 'Draw Entry Level Line', group = G_FVG, tooltip = 'Draws the line where an entry would actually trigger, using the Entry Level chosen in the Trade Setup group.')
int maxFvgKeep = input.int(12, 'FVGs Kept In Memory', minval = 3, maxval = 40, group = G_FVG)
string entryTrigger = input.string('FVG Retracement', 'Entry Trigger', options = ['FVG Retracement', 'CHoCH Candle Close'], group = G_SET, tooltip = 'What actually opens the trade.\n\nFVG Retracement — wait for price to come back into the gap the shift left behind, and fill at the depth chosen below. Better price, but the setup can expire unfilled.\nCHoCH Candle Close — enter at the close of the candle that confirms the structure shift, with no gap and no wait. Every confirmed shift becomes a trade; the entry is worse and the stop is wider.\n\nThe stop sits beyond the raided extreme in both modes, and the target stays the same multiple of R.')
string entryMode = input.string('0% — Proximal edge', 'FVG Entry Depth', options = ['0% — Proximal edge', '25%', '50% — CE', '75%', '100% — Distal edge', 'Custom'], group = G_SET, tooltip = 'How deep into the gap price must travel before the entry triggers, measured from the edge price enters from. Only read in FVG Retracement mode.\n\n0% — the very first touch of the gap. Most fills, widest stop, target furthest away.\n50% — the consequent encroachment, the midpoint of the gap.\n100% — the gap must be fully filled. Fewest fills, tightest stop.\nCustom — any depth you like, set in the field below.')
float entryCustomPct = input.float(40.0, 'Custom Depth (%)', minval = 0, maxval = 100, step = 5, group = G_SET, tooltip = 'Only read when FVG Entry Depth is set to Custom.')
string tpMode = input.string('R Multiple', 'Take Profit', options = ['R Multiple', 'Opposite Liquidity', 'Percent Gain'], group = G_SET, tooltip = 'Where the target sits.\n\nR Multiple — a fixed multiple of the stop distance. Simple, but it ignores what is actually in front of the trade: if the nearest pool of opposite liquidity sits closer than the target, price often raids it and turns before the target is ever reached.\nOpposite Liquidity — the target is the nearest still-unraided pool on the far side. A long after a sellside raid aims at the buyside pool above it, which is where price is actually being drawn. The nearest retained live pool is used. If it is too close after pullback, or no pool is available, the setup is rejected. Nearby pools are not skipped in favor of farther targets.\nPercent Gain — a fixed percentage move from the entry price, ignoring the stop distance entirely. Use it when you think in "I want 1% out of this" rather than in R. The R multiple it happens to produce is whatever the stop width makes it, and the panel reports that real figure — so a wide stop turns a 1% target into a fraction of an R, which is worth watching.')
string tpPctMode = input.string('1%', 'Percent Target', options = ['0.5%', '0.75%', '1%', '1.5%', '2%', '3%', '5%', 'Custom'], group = G_SET, tooltip = 'How far from the entry the target sits, as a percentage of the entry price. Only read in Percent Gain mode.')
float tpPctCustom = input.float(1.25, 'Custom Percent (%)', minval = 0.05, maxval = 50, step = 0.05, group = G_SET, tooltip = 'Only read when Percent Target is set to Custom.')
float tpPct2 = input.float(2.0, 'Second Percent Target (%)', minval = 0.05, maxval = 50, step = 0.05, group = G_SET, tooltip = 'The runner target in Percent Gain mode, used only when Partial Take Profit is on. It must sit beyond the first target; if it does not, it is pushed out automatically.')
float rrTarget = input.float(2.0, 'Risk / Reward (TP in R)', minval = 0.2, step = 0.1, group = G_SET, tooltip = 'Used in R Multiple mode. Opposite Liquidity requires an actual eligible nearest pool.')
float tpMinR = input.float(1.0, 'Min R for Liquidity TP', minval = 0.1, step = 0.1, group = G_SET, tooltip = 'Minimum reward/risk at the nearest live pool after pullback. A closer pool rejects the setup; the engine does not skip it. Only read in Opposite Liquidity mode.')
float tpLiqPullback = input.float(0.0, 'TP Pullback From Pool (× ATR)', minval = 0.0, step = 0.05, group = G_SET, tooltip = 'Places the target slightly IN FRONT of the pool rather than exactly on it — below a buyside pool for a long, above a sellside pool for a short. Price frequently reverses in the last ticks before a level rather than tagging it exactly; a small value here fills those trades instead of watching them turn one tick short. 0 = target sits exactly on the level.')
float slAtrBuf = input.float(0.05, 'SL Buffer (× ATR)', minval = 0.0, step = 0.01, group = G_SET, tooltip = 'Padding added beyond the raided extreme.')
int slTickBuf = input.int(0, 'SL Buffer (ticks)', minval = 0, group = G_SET)
int maxBarsChoCH = input.int(20, 'Raid → CHoCH max bars', minval = 1, group = G_SET)
int maxBarsFvg = input.int(10, 'CHoCH → FVG max bars', minval = 1, group = G_SET)
int maxBarsEntry = input.int(30, 'FVG → Entry max bars', minval = 1, group = G_SET, tooltip = 'How long an armed setup waits for price to return before it is written off. Raising this is the second lever on the fill rate, after the entry depth.')
bool oneAtATime = input.bool(true, 'One trade at a time', group = G_SET, tooltip = 'No new setup is armed while another one is armed or open. Makes the panel statistics more realistic.')
bool showSetups = input.bool(true, 'Draw Setup Boxes', group = G_SET)
bool drawFilled = input.bool(false, 'Draw Only Filled Trades', group = G_SET, tooltip = 'OFF — a setup is drawn the moment it arms, and if price never comes back to the entry it stays on the chart greyed out and marked cancelled. You see everything the engine considered.\n\nON — nothing is drawn until the trade actually FILLS. A setup that arms and expires unfilled leaves no drawing at all, so every box behind price is a real trade that ended at its target, its stop or its trail.\n\nThis also stops cancelled setups from consuming the Max Setups Kept On Chart budget, which means raising that number now buys you real trades rather than more grey boxes.\n\nCounts are untouched either way: an expired setup is still counted under Cancelled in the panel whether or not it was ever drawn.')
color riskCol = input.color(color.new(#f23645, 80), 'Risk', inline = 'st', group = G_SET)
color rewardCol = input.color(color.new(#089981, 80), 'Reward', inline = 'st', group = G_SET)
int maxSetupDraw = input.int(30, 'Max Setups Kept On Chart', minval = 3, maxval = 150, group = G_SET, tooltip = 'How many finished setups stay drawn behind price. Raise it to review the engine\'s history on the chart rather than only the last few trades.\n\nThis is a DRAWING limit, not a statistical one — the panel counts every trade on the loaded history whatever this is set to. Trimming here never changes a number in the panel.\n\nFloor of 3 so a concurrent long + short setup can never have its drawings removed by the trim routine. Ceiling of 150 because Pine allows a script 500 boxes, 500 lines and 500 labels in total, and each setup costs 2 boxes, 1 line and 1 label out of a budget it shares with the raid levels, the structure lines, the FVG boxes and the higher-timeframe block. At 150 there is still comfortable headroom with every other drawing setting at its own maximum.')
float fvgEntryPct = switch entryMode
'25%' => 25.0
'50% — CE' => 50.0
'75%' => 75.0
'100% — Distal edge' => 100.0
'Custom' => entryCustomPct
=> 0.0
bool useFvgEntry = entryTrigger == 'FVG Retracement'
string entryTag = useFvgEntry ? 'FVG ' + str.tostring(math.round(fvgEntryPct)) + '%' : 'CHoCH close'
float tpPercent = switch tpPctMode
'0.5%' => 0.5
'0.75%' => 0.75
'1.5%' => 1.5
'2%' => 2.0
'3%' => 3.0
'5%' => 5.0
'Custom' => tpPctCustom
=> 1.0
bool filtTrendOn = input.bool(false, 'Require HTF Trend Alignment', group = G_FIL, tooltip = 'Longs only while the Main Trend row reads Bullish, shorts only while it reads Bearish. Counter-trend raids are the largest structural leak in a reversal setup, so this is the first filter worth measuring.')
bool filtAllowRanging = input.bool(false, 'Allow trades while Ranging', group = G_FIL, tooltip = 'When the trend filter is on, this decides whether a Ranging read blocks the setup or lets it through. Off = only a clean Bullish/Bearish read trades.')
bool filtPdOn = input.bool(false, 'Require Discount (long) / Premium (short)', group = G_FIL, tooltip = 'The entry must sit in the cheap half of the current dealing range for a long, the expensive half for a short. The range is the last confirmed swing high to swing low. Directly blocks buying the top of a leg just because a shift printed.')
float filtEqPct = input.float(50.0, 'Equilibrium Threshold (%)', minval = 10, maxval = 90, step = 5, group = G_FIL, tooltip = '50 = the true midpoint of the range. Lower it to demand a deeper discount for longs (and a shallower premium for shorts).')
float filtMaxRiskAtr = input.float(0.0, 'Max Risk (× ATR) — 0 = off', minval = 0.0, step = 0.1, group = G_FIL, tooltip = 'Skip any setup whose stop distance exceeds this multiple of ATR. A deep raid wick makes for a wide stop, which pushes the target out of reach — this is a purely mechanical filter that assumes nothing about the market.\n\nWorth recalibrating whenever Raid Mode changes: the stop is measured from a different kind of bar in each mode, so a cap tuned on one will not mean the same thing on the other. Watch the Filtered counter while you move it.')
bool filtSmtOn = input.bool(false, 'Require SMT Divergence', group = G_FIL, tooltip = 'Requires an explicit comparison symbol. Missing or unaligned peer data rejects the setup; the filter never silently passes.')
bool filtKzOn = input.bool(false, 'Killzone / Session Filter', group = G_FIL, tooltip = 'Only arm setups inside the windows below. Times are New York.')
string kzSession1 = input.session('0200-0500', 'Killzone 1 (London)', group = G_FIL)
string kzSession2 = input.session('0830-1100', 'Killzone 2 (New York)', group = G_FIL)
bool beOn = input.bool(false, 'Move Stop To Breakeven', group = G_MGT, tooltip = 'Once the trade is this many R in profit, the stop moves to the entry. It raises the WIN RATE mechanically by converting some losses into scratches — but it usually LOWERS expectancy, because winners that would have run get stopped out on the pullback. The panel counts breakeven exits separately so you can see both effects instead of only the flattering one.')
float beTrigR = input.float(1.0, 'Breakeven Trigger (R)', minval = 0.1, step = 0.1, group = G_MGT)
bool partialOn = input.bool(false, 'Partial Take Profit', group = G_MGT, tooltip = 'Bank part of the position at the first target, run the rest to a second one. When on, the stop moves to breakeven the moment the first target fills, so the runner can only end at +R or flat. Every trade then reports a WEIGHTED R, and the panel totals stay comparable with single-target trades.')
float partialPct = input.float(50.0, 'Partial Size (%)', minval = 10, maxval = 90, step = 5, group = G_MGT)
float rrTarget2 = input.float(3.0, 'Second Target (R)', minval = 0.2, step = 0.1, group = G_MGT, tooltip = 'The runner target in R Multiple mode, and the fallback in Opposite Liquidity mode when no second pool qualifies.')
bool trailOn = input.bool(false, 'Trailing Stop', group = G_MGT, tooltip = 'Once the trade is far enough in profit, the stop stops sitting still and follows the best price reached, staying a fixed percentage behind it. It only ever moves in the direction of the trade — it never gives back ground it has taken.\n\nThis exists for the case the second target creates: price runs to the opposite liquidity, raids it and turns. A fixed 3R target sits through that entire reversal. A trail banks whatever the move actually gave.\n\nWorks with or without partials. When both are on, the trail governs the runner once it activates.')
float trailTrigR = input.float(2.0, 'Trail Activation (R)', minval = 0.1, step = 0.1, group = G_MGT, tooltip = 'How far in profit the trade must go before the trail switches on. Until then the stop stays exactly where it was placed. At the default the trade is chased only after it has already paid for itself twice over.')
float trailPct = input.float(0.5, 'Trail Distance (%)', minval = 0.05, maxval = 20, step = 0.05, group = G_MGT, tooltip = 'How far behind the best price the stop follows, as a percentage of price. 0.5 means the stop sits half a percent under the highest high the trade has seen (over the lowest low, for a short).\n\nTight values react fast to a reversal and are stopped out by ordinary noise; wide values survive noise and give back more at the turn. On a 15m crypto chart 0.3-1.0 is the range worth testing. Measure it — a trail that is too tight converts winners into small winners, which flatters the win rate while lowering Net R.')
bool showPD = input.bool(true, 'Show PDH / PDL', group = G_PD)
bool showPdEq = input.bool(true, 'Show PD EQ (midpoint)', group = G_PD)
color pdCol = input.color(#787b86, 'Color', inline = 'pd', group = G_PD)
int pdWidth = input.int(1, 'Width', minval = 1, maxval = 4, inline = 'pd', group = G_PD)
int pdExtend = input.int(15, 'Extend Right (bars)', minval = 0, maxval = 100, group = G_PD)
bool showPdLbl = input.bool(true, 'Labels', group = G_PD)
string pdLabelMode = input.string('Day + Date', 'PDH Label Shows', options = ['Day', 'Date', 'Day + Date', 'Neither'], group = G_PD, tooltip = 'The stamp carried by the PDH label only — PDL stays clean, since one stamp per session is enough to read the chart. After a weekend or a holiday the previous daily bar can be several calendar days back, which is exactly what the stamp is there to show.')
bool showHtfBlock = input.bool(true, 'Show HTF Candles On The Right', group = G_HTF)
bool htfAuto = input.bool(true, 'Auto-Select Timeframe', group = G_HTF, tooltip = 'Picks one step up automatically: 1H on a 15m chart, 4H on a 1H chart, and so on. Turn this off to use the manual timeframe below.')
string htfManual = input.timeframe('60', 'Manual Timeframe', group = G_HTF)
int htfCount = input.int(8, 'Candles Shown', minval = 1, maxval = 12, group = G_HTF)
int htfOffset = input.int(20, 'Offset From Price (bars)', minval = 1, group = G_HTF)
string htfSize = input.string('Small', 'Candle Width', options = ['Small', 'Medium', 'Large'], group = G_HTF)
int htfGap = input.int(1, 'Candle Spacing', minval = 1, maxval = 4, group = G_HTF)
bool htfShowEq = input.bool(false, 'Candle EQ (50%) Line', group = G_HTF)
bool htfShowTimer = input.bool(true, 'Close Countdown', group = G_HTF)
color htfBullBody = input.color(color.new(#089981, 0), 'Body · Bull', inline = 'hb', group = G_HTF)
color htfBearBody = input.color(color.new(#f23645, 0), 'Bear', inline = 'hb', group = G_HTF)
color htfBullBorder = input.color(color.new(#089981, 0), 'Borders · Bull', inline = 'hbr', group = G_HTF)
color htfBearBorder = input.color(color.new(#f23645, 0), 'Bear', inline = 'hbr', group = G_HTF)
color htfWickCol = input.color(color.new(#787b86, 0), 'Wick · Bull', inline = 'hw', group = G_HTF)
color htfBearWick = input.color(color.new(#787b86, 0), 'Bear', inline = 'hw', group = G_HTF)
color htfTxtCol = input.color(#787b86, 'Text', group = G_HTF)
bool showPanel = input.bool(true, 'Show Panel', group = G_PNL)
string panelPos = input.string('Top Right', 'Position', options = ['Top Right', 'Top Left', 'Bottom Right', 'Bottom Left'], group = G_PNL)
string panelSize = input.string(size.small, 'Text Size', options = [size.tiny, size.small, size.normal, size.large], group = G_PNL)
color panelBg = input.color(color.new(#1e222d, 10), 'Background', inline = 'pn', group = G_PNL)
color panelTxt = input.color(#d1d4dc, 'Text', inline = 'pn', group = G_PNL)
color panelWin = input.color(#089981, 'Win', inline = 'pn2', group = G_PNL)
color panelLoss = input.color(#f23645, 'Loss', inline = 'pn2', group = G_PNL)
bool showTrendRow = input.bool(true, 'Show Main Trend Row', group = G_PNL, tooltip = 'Higher-timeframe directional context, reported in the panel only. Nothing in the setup engine is gated on it — the trend row is a read, not a filter.')
bool trendAuto = input.bool(true, 'Trend Timeframe: Auto', group = G_PNL, tooltip = 'Auto picks a timeframe roughly 16x the chart: 1H from a 1m chart, 4H from 5m/15m, 1D from 30m/1H, 1W from 4H/1D. Turn off to set it yourself.')
string trendManual = input.timeframe('240', 'Trend Timeframe (manual)', group = G_PNL)
int trendLen = input.int(50, 'Trend EMA Length', minval = 2, group = G_PNL, tooltip = 'Bullish = HTF close above the EMA and the EMA rising. Bearish = close below and the EMA falling. Anything else reads Ranging.')
bool alertArmed = input.bool(true, 'Alert: setup armed', group = G_AL, tooltip = 'Fires when a setup arms — after the raid and the CHoCH, with the entry, stop, target and R already resolved. In CHoCH Candle Close mode arming and filling happen on the same bar, so this and the entry alert fire together.')
bool alertEntry = input.bool(true, 'Alert: entry filled', group = G_AL, tooltip = 'Fires when price reaches the entry level (FVG mode) or on the confirming close (CHoCH Candle Close mode).')
bool alertExit = input.bool(true, 'Alert: trade closed', group = G_AL, tooltip = 'Fires on the target, the stop, a breakeven stop, a trailed stop, or a banked partial — carrying the R the trade actually ended at, not a nominal one.')
bool alertRaid = input.bool(false, 'Alert: raid / break', group = G_AL, tooltip = 'Fires the moment a liquidity pool is taken, long before there is a trade. Says WHICH kind of raid it was — wick rejection or close-through — which the old named alerts cannot do.\n\nOff by default: a raid is not a signal on its own, and this is the noisiest event in the script.')
bool alertShift = input.bool(false, 'Alert: CHoCH', group = G_AL, tooltip = 'Fires on every structure shift, whether or not a raid preceded it. Off by default for the same reason as the raid alert.')
string alertFormat = input.string('Text', 'Message Format', options = ['Text', 'JSON'], group = G_AL, tooltip = 'Text — two or three readable lines, for a phone notification or an email.\n\nJSON — a flat object with the same fields, for a webhook. Prices are emitted as bare numbers formatted to the symbol\'s tick size, so a consumer can parse them without cleaning up the string first.')
bool alertOnClose = input.bool(true, 'Only on bar close', group = G_AL, tooltip = 'ON — an alert fires only once the bar has closed, so what it reports is final. This is the honest setting and it matches the advice in the notes at the bottom of the source.\n\nOFF — alerts fire during the forming bar. You hear about a setup sooner, and some of what you hear will un-happen when the bar closes on the other side of the level.')
type pivotPt
float currentLevel = na
float lastLevel = na
bool crossed = false
int barTime = 0
int barIndex = 0
type trendState
int bias = 0
type fvgZone
float top = na
float bot = na
int dir = 0 // +1 bullish, -1 bearish
int bIdx = 0 // bar_index at formation
bool mitigated = false
box bx = na
line ceLine = na
f_tfLabel(simple string tf) =>
int s = timeframe.in_seconds(tf)
s < 60 ? str.tostring(s) + 's' : s < 86400 ? (s % 3600 == 0 ? str.tostring(s / 3600) + 'H' : str.tostring(math.round(s / 60.0)) + 'm') : s % 604800 == 0 ? str.tostring(s / 604800) + 'W' : s % 86400 == 0 ? str.tostring(s / 86400) + 'D' : tf
f_fvgEntry(float top, float bot, bool isBull, float pct) =>
isBull ? top - pct / 100.0 * (top - bot) : bot + pct / 100.0 * (top - bot)
f_dayName(int t) =>
string res = ''
if not na(t)
res := switch dayofweek(t, syminfo.timezone)
dayofweek.monday => 'Mon'
dayofweek.tuesday => 'Tue'
dayofweek.wednesday => 'Wed'
dayofweek.thursday => 'Thu'
dayofweek.friday => 'Fri'
dayofweek.saturday => 'Sat'
=> 'Sun'
res
f_smtAutoPeer() =>
string t = syminfo.ticker
string res = na
string m = str.match(t, '^M?(ES|NQ)[1\\w][!\\d]+$')
if m != ''
int off = str.startswith(m, 'M') ? 1 : 0
string prefix = str.substring(m, off, 2 + off)
string suffix = str.substring(m, 2 + off)
res := 'CME_MINI:' + (off == 1 ? 'M' : '') + (prefix == 'NQ' ? 'ES' : 'NQ') + suffix
else if str.contains(t, 'MYM') or str.contains(t, 'M2K')
res := 'CME_MINI:MES1!'
else if str.contains(t, 'YM') or str.contains(t, 'RTY')
res := 'CME_MINI:ES1!'
else if str.contains(t, 'MGC')
res := 'COMEX:SIL1!'
else if str.contains(t, 'GC')
res := 'COMEX:SI1!'
else if str.contains(t, 'SIL')
res := 'COMEX:MGC1!'
else if str.contains(t, 'SI')
res := 'COMEX:GC1!'
else if str.contains(t, 'MBT')
res := 'CME:MET1!'
else if str.contains(t, 'MET')
res := 'CME:MBT1!'
else if str.startswith(t, 'BTC')
res := syminfo.prefix + ':' + str.replace(t, 'BTC', 'ETH', 0)
else if str.startswith(t, 'ETH')
res := syminfo.prefix + ':' + str.replace(t, 'ETH', 'BTC', 0)
res
f_leg(simple int size) =>
var int legv = 0
bool newLegHigh = high[size] > ta.highest(size)
bool newLegLow = low[size] < ta.lowest(size)
if newLegHigh
legv := 0
else if newLegLow
legv := 1
legv
f_updateStructure(pivotPt pHigh, pivotPt pLow, simple int size) =>
int lg = f_leg(size)
int ch = ta.change(lg)
if ch == 1 // a bullish leg starts → a pivot LOW is confirmed
pLow.lastLevel := pLow.currentLevel
pLow.currentLevel := low[size]
pLow.crossed := false
pLow.barTime := time[size]
pLow.barIndex := bar_index[size]
else if ch == -1 // a bearish leg starts → a pivot HIGH is confirmed
pHigh.lastLevel := pHigh.currentLevel
pHigh.currentLevel := high[size]
pHigh.crossed := false
pHigh.barTime := time[size]
pHigh.barIndex := bar_index[size]
ch // explicit return value
f_breaks(pivotPt pHigh, pivotPt pLow, trendState tr) =>
bool xUp = ta.crossover(close, pHigh.currentLevel)
bool xDn = ta.crossunder(close, pLow.currentLevel)
bool bullCH = false
bool bullBO = false
bool bearCH = false
bool bearBO = false
float bullLvl = na
float bearLvl = na
int bullIdx = 0
int bearIdx = 0
if barstate.isconfirmed and xUp and not pHigh.crossed
bullCH := tr.bias == -1
bullBO := not bullCH
bullLvl := pHigh.currentLevel
bullIdx := pHigh.barIndex
pHigh.crossed := true
tr.bias := 1
if barstate.isconfirmed and xDn and not pLow.crossed
bearCH := tr.bias == 1
bearBO := not bearCH
bearLvl := pLow.currentLevel
bearIdx := pLow.barIndex
pLow.crossed := true
tr.bias := -1
[bullCH, bullBO, bearCH, bearBO, bullLvl, bearLvl, bullIdx, bearIdx]
f_trimBox(array<box> a, int maxN) =>
while a.size() > maxN
box b = a.shift()
b.delete()
a.size()
f_trimLine(array<line> a, int maxN) =>
while a.size() > maxN
line l = a.shift()
l.delete()
a.size()
f_trimLabel(array<label> a, int maxN) =>
while a.size() > maxN
label l = a.shift()
l.delete()
a.size()
f_drawSetup(bool isLong, float entry, float sl, float tp, string tag) =>
box rbx = box.new(bar_index, isLong ? entry : sl, bar_index + 1, isLong ? sl : entry, xloc = xloc.bar_index, border_color = color.new(riskCol, 40), bgcolor = riskCol)
box wbx = box.new(bar_index, isLong ? tp : entry, bar_index + 1, isLong ? entry : tp, xloc = xloc.bar_index, border_color = color.new(rewardCol, 40), bgcolor = rewardCol)
line eln = line.new(bar_index, entry, bar_index + 1, entry, xloc = xloc.bar_index, color = color.new(color.gray, 20), style = line.style_dashed)
label lbl = label.new(bar_index, tp, (isLong ? 'LONG ' : 'SHORT ') + tag, xloc = xloc.bar_index, style = isLong ? label.style_label_down : label.style_label_up, color = color.new(color.white, 100), textcolor = rewardCol, size = size.tiny)
[rbx, wbx, eln, lbl]
f_alertLevel(string evt, string side, string kind, float lvl) =>
string sLvl = na(lvl) ? '' : str.tostring(lvl, format.mintick)
string out = ''
if alertFormat == 'JSON'
out := '{"src":"RaidShift","sym":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","event":"' + evt + '","side":"' + side + '"' + (kind == '' ? '' : ',"kind":"' + kind + '"') + (sLvl == '' ? '' : ',"level":' + sLvl) + '}'
else
out := 'RaidShift · ' + syminfo.ticker + ' · ' + timeframe.period + '\n' + str.upper(evt) + ' · ' + side + (kind == '' ? '' : ' · ' + kind) + (sLvl == '' ? '' : '\nlevel ' + sLvl)
out
f_alertTrade(string evt, string side, string kind, float entry, float sl, float tp, float rVal) =>
string sE = na(entry) ? '' : str.tostring(entry, format.mintick)
string sS = na(sl) ? '' : str.tostring(sl, format.mintick)
string sT = na(tp) ? '' : str.tostring(tp, format.mintick)
string sR = na(rVal) ? '' : str.tostring(rVal, '0.00')
string out = ''
if alertFormat == 'JSON'
out := '{"src":"RaidShift","sym":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","event":"' + evt + '","side":"' + side + '","kind":"' + kind + '","trigger":"' + entryTag + '"' + (sE == '' ? '' : ',"entry":' + sE) + (sS == '' ? '' : ',"sl":' + sS) + (sT == '' ? '' : ',"tp":' + sT) + (sR == '' ? '' : ',"r":' + sR) + '}'
else
out := 'RaidShift · ' + syminfo.ticker + ' · ' + timeframe.period + '\n' + str.upper(side) + ' ' + evt + ' · ' + kind + '\nentry ' + sE + ' · SL ' + sS + ' · TP ' + sT + (sR == '' ? '' : ' · ' + sR + 'R')
out
f_htfCountdown(int openTime, simple string tf) =>
string result = '--:--'
if barstate.isrealtime and not na(openTime)
int remainingSec = math.round((openTime + timeframe.in_seconds(tf) * 1000 - timenow) / 1000)
if remainingSec > 0
int hrs = math.floor(remainingSec / 3600)
int mins = math.floor((remainingSec % 3600) / 60)
int secs = remainingSec % 60
result := (hrs > 0 ? str.tostring(hrs, '00') + ':' : '') + str.tostring(mins, '00') + ':' + str.tostring(secs, '00')
result
float atr14 = ta.atr(14)
float ph = ta.pivothigh(swingPeriod, swingPeriod)
float pl = ta.pivotlow(swingPeriod, swingPeriod)
bool smtConfigured = smtOn and smtSymbol != '' and smtSymbol != syminfo.tickerid
string smtPeerId = smtConfigured ? smtSymbol : syminfo.tickerid
string smtName = smtConfigured ? smtSymbol : 'OFF'
[smtPeerHigh, smtPeerLow, smtPeerTime] = request.security(smtPeerId, timeframe.period, [high, low, time], gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
bool smtLive = smtConfigured and smtPeerTime == time and not na(smtPeerHigh) and not na(smtPeerLow)
if barstate.isfirst and filtSmtOn and not smtConfigured
runtime.error('SMT filter requires SMT enabled and an explicit different comparison symbol.')
var array<string> alQueue = array.new<string>()
alQueue.clear()
var array<float> pvHiP = array.new<float>()
var array<int> pvHiB = array.new<int>()
var array<bool> pvHiOn = array.new<bool>()
var array<float> pvLoP = array.new<float>()
var array<int> pvLoB = array.new<int>()
var array<bool> pvLoOn = array.new<bool>()
var array<float> pvHiPeer = array.new<float>()
var array<float> pvLoPeer = array.new<float>()
var array<float> pvHiPeerMax = array.new<float>()
var array<float> pvLoPeerMin = array.new<float>()
var array<bool> pvHiPeerOk = array.new<bool>()
var array<bool> pvLoPeerOk = array.new<bool>()
float peerWindowMax = ta.highest(smtPeerHigh, swingPeriod + 1)
float peerWindowMin = ta.lowest(smtPeerLow, swingPeriod + 1)
float peerWindowOk = ta.lowest(smtLive ? 1.0 : 0.0, swingPeriod + 1)
if barstate.isconfirmed and not na(ph)
pvHiP.push(high[swingPeriod])
pvHiB.push(bar_index[swingPeriod])
pvHiOn.push(true)
pvHiPeer.push(smtPeerHigh[swingPeriod])
pvHiPeerMax.push(peerWindowMax)
pvHiPeerOk.push(peerWindowOk == 1)
if barstate.isconfirmed and not na(pl)
pvLoP.push(low[swingPeriod])
pvLoB.push(bar_index[swingPeriod])
pvLoOn.push(true)
pvLoPeer.push(smtPeerLow[swingPeriod])
pvLoPeerMin.push(peerWindowMin)
pvLoPeerOk.push(peerWindowOk == 1)
bool sweepBuy = false // buyside liquidity raided (bearish signal)
bool sweepSell = false // sellside liquidity raided (bullish signal)
bool ctBuy = false // that buyside raid was a close-through, not a wick rejection
bool ctSell = false // that sellside raid was a close-through, not a wick rejection
float sweptHiLvl = na
float sweptLoLvl = na
int sweptHiBar = 0
int sweptLoBar = 0
bool smtBear = false // buyside raid the peer refused to follow
bool smtBull = false // sellside raid the peer refused to follow
bool ambiguousRaid = false
bool raidWickOn = raidMode != 'Close-through reversal'
bool raidCtOn = raidMode != 'Wick rejection'
float raidPenAbs = raidMinPen > 0 and not na(atr14) ? atr14 * raidMinPen : 0.0
float raidRejAbs = raidMinRej > 0 and not na(atr14) ? atr14 * raidMinRej : 0.0
float ctPenAbs = ctMinPen > 0 and not na(atr14) ? atr14 * ctMinPen : 0.0
float ctInvAbs = ctInvBuf > 0 and not na(atr14) ? atr14 * ctInvBuf : 0.0
var int nRaidSkip = 0 // levels touched and rejected by the quality gates
int nHi = pvHiP.size()
if barstate.isconfirmed and nHi > 0
int fromI = math.max(0, nHi - maxScanBack)
for i = nHi - 1 to 0
if pvHiOn.get(i)
pvHiPeerOk.set(i, pvHiPeerOk.get(i) and smtLive)
pvHiPeerMax.set(i, math.max(pvHiPeerMax.get(i), smtPeerHigh))
float lvl = pvHiP.get(i)
if high > lvl
pvHiOn.set(i, false)
if lvl < high and lvl > close
bool okPen = high - lvl >= raidPenAbs
bool okRej = lvl - close >= raidRejAbs
if i >= fromI and raidWickOn and okPen and okRej
pvHiOn.set(i, false)
if not sweepBuy or lvl > sweptHiLvl
sweepBuy := true
ctBuy := false
sweptHiLvl := lvl
sweptHiBar := pvHiB.get(i)
float pPk = pvHiPeer.get(i)
smtBear := pvHiPeerOk.get(i) and not na(pPk) and pvHiPeerMax.get(i) <= pPk
else if i >= fromI and raidWickOn
nRaidSkip += 1
else if close > lvl
pvHiOn.set(i, false)
if i >= fromI and raidCtOn and close - lvl >= ctPenAbs and (not sweepBuy or lvl > sweptHiLvl)
sweepBuy := true
ctBuy := true
sweptHiLvl := lvl
sweptHiBar := pvHiB.get(i)
float pPkC = pvHiPeer.get(i)
smtBear := pvHiPeerOk.get(i) and not na(pPkC) and pvHiPeerMax.get(i) <= pPkC
int nLo = pvLoP.size()
if barstate.isconfirmed and nLo > 0
int fromJ = math.max(0, nLo - maxScanBack)
for j = nLo - 1 to 0
if pvLoOn.get(j)
pvLoPeerOk.set(j, pvLoPeerOk.get(j) and smtLive)
pvLoPeerMin.set(j, math.min(pvLoPeerMin.get(j), smtPeerLow))
float lvl = pvLoP.get(j)
if low < lvl
pvLoOn.set(j, false)
if lvl > low and lvl < close
bool okPen = lvl - low >= raidPenAbs
bool okRej = close - lvl >= raidRejAbs
if j >= fromJ and raidWickOn and okPen and okRej
pvLoOn.set(j, false)
if not sweepSell or lvl < sweptLoLvl
sweepSell := true
ctSell := false
sweptLoLvl := lvl
sweptLoBar := pvLoB.get(j)
float pPk = pvLoPeer.get(j)
smtBull := pvLoPeerOk.get(j) and not na(pPk) and pvLoPeerMin.get(j) >= pPk
else if j >= fromJ and raidWickOn
nRaidSkip += 1
else if close < lvl
pvLoOn.set(j, false)
if j >= fromJ and raidCtOn and lvl - close >= ctPenAbs and (not sweepSell or lvl < sweptLoLvl)
sweepSell := true
ctSell := true
sweptLoLvl := lvl
sweptLoBar := pvLoB.get(j)
float pPkC = pvLoPeer.get(j)
smtBull := pvLoPeerOk.get(j) and not na(pPkC) and pvLoPeerMin.get(j) >= pPkC
while pvHiP.size() > 500
pvHiP.shift()
pvHiB.shift()
pvHiOn.shift()
pvHiPeer.shift()
pvHiPeerMax.shift()
pvHiPeerOk.shift()
while pvLoP.size() > 500
pvLoP.shift()
pvLoB.shift()
pvLoOn.shift()
pvLoPeer.shift()
pvLoPeerMin.shift()
pvLoPeerOk.shift()
// OHLC cannot establish which side was raided first. Do not choose a side by code order.
ambiguousRaid := sweepBuy and sweepSell
if ambiguousRaid
sweepBuy := false
sweepSell := false
smtBull := false
smtBear := false
while pvHiPeer.size() > pvHiP.size()
pvHiPeer.shift()
while pvLoPeer.size() > pvLoP.size()
pvLoPeer.shift()
if alertRaid and sweepBuy
alQueue.push(f_alertLevel('raid', 'buyside', ctBuy ? 'close-through' : 'wick', sweptHiLvl))
if alertRaid and sweepSell
alQueue.push(f_alertLevel('raid', 'sellside', ctSell ? 'close-through' : 'wick', sweptLoLvl))
var int nSmt = 0
var string lastSmtDir = '-'
if smtBull
nSmt += 1
lastSmtDir := 'Bullish'
if smtBear
nSmt += 1
lastSmtDir := 'Bearish'
var array<line> swLines = array.new<line>()
var array<label> swLabs = array.new<label>()
if showSweeps and sweepBuy
swLines.push(line.new(sweptHiBar, sweptHiLvl, bar_index, sweptHiLvl, xloc = xloc.bar_index, color = sweepBuyCol, style = ctBuy ? line.style_dashed : line.style_dotted, width = 1))
if showRaidLabels
swLabs.push(label.new(bar_index, sweptHiLvl, ctBuy ? 'BREAK' : 'RAID', xloc = xloc.bar_index, style = label.style_label_down, color = color.new(color.white, 100), textcolor = sweepBuyCol, size = size.tiny))
f_trimLine(swLines, maxSweepDraw)
f_trimLabel(swLabs, maxSweepDraw * 2)
if showSweeps and sweepSell
swLines.push(line.new(sweptLoBar, sweptLoLvl, bar_index, sweptLoLvl, xloc = xloc.bar_index, color = sweepSelCol, style = ctSell ? line.style_dashed : line.style_dotted, width = 1))
if showRaidLabels
swLabs.push(label.new(bar_index, sweptLoLvl, ctSell ? 'BREAK' : 'RAID', xloc = xloc.bar_index, style = label.style_label_up, color = color.new(color.white, 100), textcolor = sweepSelCol, size = size.tiny))
f_trimLine(swLines, maxSweepDraw)
f_trimLabel(swLabs, maxSweepDraw * 2)
if smtLabels and smtBull
swLabs.push(label.new(bar_index, low, '\nSMT vs ' + smtName, xloc = xloc.bar_index, style = label.style_label_up, color = color.new(color.white, 100), textcolor = smtBullCol, size = size.tiny))
f_trimLabel(swLabs, maxSweepDraw * 2)
if smtLabels and smtBear
swLabs.push(label.new(bar_index, high, 'SMT vs ' + smtName + '\n', xloc = xloc.bar_index, style = label.style_label_down, color = color.new(color.white, 100), textcolor = smtBearCol, size = size.tiny))
f_trimLabel(swLabs, maxSweepDraw * 2)
var pivotPt intHigh = pivotPt.new()
var pivotPt intLow = pivotPt.new()
var pivotPt swgHigh = pivotPt.new()
var pivotPt swgLow = pivotPt.new()
var trendState intTr = trendState.new()
var trendState swgTr = trendState.new()
f_updateStructure(intHigh, intLow, internalLen)
f_updateStructure(swgHigh, swgLow, swingLen)
[iBullCH, iBullBO, iBearCH, iBearBO, iBullLvl, iBearLvl, iBullIdx, iBearIdx] = f_breaks(intHigh, intLow, intTr)
[sBullCH, sBullBO, sBearCH, sBearBO, sBullLvl, sBearLvl, sBullIdx, sBearIdx] = f_breaks(swgHigh, swgLow, swgTr)
bool useInternal = structMode == 'Internal'
bool bullCHoCH = useInternal ? iBullCH : sBullCH
bool bullBOS = useInternal ? iBullBO : sBullBO
bool bearCHoCH = useInternal ? iBearCH : sBearCH
bool bearBOS = useInternal ? iBearBO : sBearBO
float bullBrkLvl = useInternal ? iBullLvl : sBullLvl
float bearBrkLvl = useInternal ? iBearLvl : sBearLvl
int bullBrkIdx = useInternal ? iBullIdx : sBullIdx
int bearBrkIdx = useInternal ? iBearIdx : sBearIdx
bool bullShift = chochOnly ? bullCHoCH : (bullCHoCH or bullBOS)
bool bearShift = chochOnly ? bearCHoCH : (bearCHoCH or bearBOS)
if alertShift and bullCHoCH
alQueue.push(f_alertLevel('choch', 'bullish', '', bullBrkLvl))
if alertShift and bearCHoCH
alQueue.push(f_alertLevel('choch', 'bearish', '', bearBrkLvl))
var array<line> strLines = array.new<line>()
var array<label> strLabs = array.new<label>()
if showStruct and (bullCHoCH or bullBOS)
strLines.push(line.new(bullBrkIdx, bullBrkLvl, bar_index, bullBrkLvl, xloc = xloc.bar_index, color = bullStrCol, style = useInternal ? line.style_dashed : line.style_solid))
strLabs.push(label.new(math.round(math.avg(bullBrkIdx, bar_index)), bullBrkLvl, bullCHoCH ? 'CHoCH' : 'BOS', xloc = xloc.bar_index, style = label.style_label_down, color = color.new(color.white, 100), textcolor = bullStrCol, size = size.tiny))
f_trimLine(strLines, maxStrDraw)
f_trimLabel(strLabs, maxStrDraw)
if showStruct and (bearCHoCH or bearBOS)
strLines.push(line.new(bearBrkIdx, bearBrkLvl, bar_index, bearBrkLvl, xloc = xloc.bar_index, color = bearStrCol, style = useInternal ? line.style_dashed : line.style_solid))
strLabs.push(label.new(math.round(math.avg(bearBrkIdx, bar_index)), bearBrkLvl, bearCHoCH ? 'CHoCH' : 'BOS', xloc = xloc.bar_index, style = label.style_label_up, color = color.new(color.white, 100), textcolor = bearStrCol, size = size.tiny))
f_trimLine(strLines, maxStrDraw)
f_trimLabel(strLabs, maxStrDraw)
float barDelta = (close[1] - open[1]) / (open[1] * 100)
float thrAccum = ta.cum(math.abs(nz(barDelta)))
float fvgThr = fvgAutoThr and bar_index > 0 ? thrAccum / bar_index * 2 : 0.0
float minGapAbs = fvgMinAtr > 0 and not na(atr14) ? atr14 * fvgMinAtr : 0.0
bool rawBullFvg = low > high[2] and close[1] > high[2] and barDelta > fvgThr and (low - high[2]) >= minGapAbs
bool rawBearFvg = high < low[2] and close[1] < low[2] and -barDelta > fvgThr and (low[2] - high) >= minGapAbs
var array<fvgZone> fvgs = array.new<fvgZone>()
if barstate.isconfirmed and (rawBullFvg or rawBearFvg)
float zTop = rawBullFvg ? low : low[2]
float zBot = rawBullFvg ? high[2] : high
box zBx = na
line zCe = na
if showFvg
zBx := box.new(bar_index - 2, zTop, bar_index + 1, zBot, xloc = xloc.bar_index, border_color = color.new(rawBullFvg ? fvgBullCol : fvgBearCol, 60), bgcolor = rawBullFvg ? fvgBullCol : fvgBearCol)
if showFvgEntry
float entryLvl = f_fvgEntry(zTop, zBot, rawBullFvg, fvgEntryPct)
zCe := line.new(bar_index - 2, entryLvl, bar_index + 1, entryLvl, xloc = xloc.bar_index, color = color.new(rawBullFvg ? fvgBullCol : fvgBearCol, 30), style = line.style_dotted)
fvgs.unshift(fvgZone.new(zTop, zBot, rawBullFvg ? 1 : -1, bar_index, false, zBx, zCe))
if fvgs.size() > 0
for i = 0 to fvgs.size() - 1
fvgZone z = fvgs.get(i)
if not z.mitigated
bool filled = barstate.isconfirmed and (z.dir == 1 ? low <= z.bot : high >= z.top)
if filled
z.mitigated := true
if not na(z.bx)
z.bx.set_right(bar_index)
z.bx.set_bgcolor(color.new(z.dir == 1 ? fvgBullCol : fvgBearCol, 94))
z.bx.set_border_color(color.new(z.dir == 1 ? fvgBullCol : fvgBearCol, 94))
if not na(z.ceLine)
z.ceLine.set_x2(bar_index)
z.ceLine.set_color(color.new(color.gray, 80))
else
if not na(z.bx)
z.bx.set_right(bar_index + 1)
if not na(z.ceLine)
z.ceLine.set_x2(bar_index + 1)
while fvgs.size() > maxFvgKeep
fvgZone old = fvgs.pop()
if not na(old.bx)
old.bx.delete()
if not na(old.ceLine)
old.ceLine.delete()
string autoTrendTf = timeframe.in_seconds(timeframe.period) <= 60 ? '60' : timeframe.in_seconds(timeframe.period) <= 300 ? '240' : timeframe.in_seconds(timeframe.period) <= 900 ? '240' : timeframe.in_seconds(timeframe.period) <= 1800 ? 'D' : timeframe.in_seconds(timeframe.period) <= 3600 ? 'D' : timeframe.in_seconds(timeframe.period) <= 14400 ? 'W' : timeframe.in_seconds(timeframe.period) <= 86400 ? 'W' : 'M'
string trendTf = trendAuto ? autoTrendTf : trendManual
if barstate.isfirst and filtTrendOn and timeframe.in_seconds(trendTf) <= timeframe.in_seconds()
runtime.error('Trend filter timeframe must be higher than chart timeframe.')
[trClose, trEma, trEmaPrev] = request.security(syminfo.tickerid, trendTf, [close[1], ta.ema(close, trendLen)[1], ta.ema(close, trendLen)[2]], lookahead = barmerge.lookahead_on)
string trendTxt = na(trClose) or na(trEma) or na(trEmaPrev) ? '-' : trClose > trEma and trEma > trEmaPrev ? 'Bullish' : trClose < trEma and trEma < trEmaPrev ? 'Bearish' : 'Ranging'
bool inKz1 = not na(time(timeframe.period, kzSession1, 'America/New_York'))
bool inKz2 = not na(time(timeframe.period, kzSession2, 'America/New_York'))
bool inKillzone = inKz1 or inKz2
float slBuffer = (na(atr14) ? 0.0 : atr14 * slAtrBuf) + slTickBuf * syminfo.mintick
f_nearestPool(bool isLong, float entry) =>
float nearest = na
int n = isLong ? pvHiP.size() : pvLoP.size()
if n > 0
for i = 0 to n - 1
bool live = isLong ? pvHiOn.get(i) : pvLoOn.get(i)
float level = isLong ? pvHiP.get(i) : pvLoP.get(i)
bool ahead = isLong ? level > entry : level < entry
if live and ahead
nearest := na(nearest) ? level : isLong ? math.min(nearest, level) : math.max(nearest, level)
nearest
f_resolveTp(bool isLong, float entry, float sl) =>
float risk = isLong ? entry - sl : sl - entry
float tp = isLong ? entry + rrTarget * risk : entry - rrTarget * risk
float tp2 = isLong ? entry + rrTarget2 * risk : entry - rrTarget2 * risk
float rMult = rrTarget
float rMul2 = rrTarget2
bool used = false
if tpMode == 'Percent Gain' and risk > 0
tp := isLong ? entry * (1.0 + tpPercent / 100.0) : entry * (1.0 - tpPercent / 100.0)
tp2 := isLong ? entry * (1.0 + tpPct2 / 100.0) : entry * (1.0 - tpPct2 / 100.0)
rMult := isLong ? (tp - entry) / risk : (entry - tp) / risk
rMul2 := isLong ? (tp2 - entry) / risk : (entry - tp2) / risk
if tpMode == 'Opposite Liquidity' and risk > 0
float pull = na(atr14) ? 0.0 : atr14 * tpLiqPullback
array<float> cands = array.new<float>()
int nP = isLong ? pvHiP.size() : pvLoP.size()
if nP > 0
int fromP = 0
for i = nP - 1 to fromP
bool live = isLong ? pvHiOn.get(i) : pvLoOn.get(i)
if live
float lvl = isLong ? pvHiP.get(i) : pvLoP.get(i)
float t = isLong ? lvl - pull : lvl + pull
float rr = isLong ? (t - entry) / risk : (entry - t) / risk
if isLong ? lvl > entry : lvl < entry
cands.push(t)
if cands.size() > 0
array.sort(cands, order.ascending)
float pick = isLong ? cands.get(0) : cands.get(cands.size() - 1)
tp := pick
rMult := isLong ? (pick - entry) / risk : (entry - pick) / risk
used := true
if cands.size() > 1
float pick2 = isLong ? cands.get(1) : cands.get(cands.size() - 2)
tp2 := pick2
rMul2 := isLong ? (pick2 - entry) / risk : (entry - pick2) / risk
if risk > 0
bool bad2 = isLong ? tp2 <= tp : tp2 >= tp
if bad2
tp2 := isLong ? tp + risk : tp - risk
rMul2 := isLong ? (tp2 - entry) / risk : (entry - tp2) / risk
[tp, rMult, used, tp2, rMul2]
f_setupTag(float r, bool usedLiq, bool ctRaid) =>
(ctRaid ? 'CT · ' : '') + (usedLiq ? 'LIQ ' : '') + str.tostring(r, '0.00') + 'R · ' + entryTag
f_filtersPass(bool isLong, float entry, float sl, bool hadSmt) =>
float risk = isLong ? entry - sl : sl - entry
bool ok = risk > 0
if ok and tpMode == 'Opposite Liquidity'
float nearest = f_nearestPool(isLong, entry)
float pull = na(atr14) ? 0.0 : atr14 * tpLiqPullback
float target = isLong ? nearest - pull : nearest + pull
float reward = isLong ? target - entry : entry - target
ok := not na(nearest) and reward >= tpMinR * risk
if ok and filtSmtOn
ok := smtLive and hadSmt
if ok and filtTrendOn
bool aligned = isLong ? trendTxt == 'Bullish' : trendTxt == 'Bearish'
bool ranging = trendTxt == 'Ranging'
ok := aligned or (ranging and filtAllowRanging)
if ok and filtPdOn
float rHi = swgHigh.currentLevel
float rLo = swgLow.currentLevel
ok := not na(rHi) and not na(rLo) and rHi > rLo
if ok
float eq = rLo + (rHi - rLo) * filtEqPct / 100.0
ok := isLong ? entry <= eq : entry >= eq
if ok and filtMaxRiskAtr > 0
ok := not na(atr14) and risk <= atr14 * filtMaxRiskAtr
if ok and filtKzOn
ok := inKillzone
ok
var int luSt = 0
var int luSwBar = 0
var float luSwLow0 = na // low of the raiding candle — invalidation reference
var float luRunLow = na // lowest low since the raid — where the SL sits
var int luChBar = 0
var float luEntry = na
var float luSL = na
var float luTP = na
var float luRR = na
var int luArmBar = 0
var int luEntryBar = 0 // bar the fill happened on — gates same-bar TP/SL resolution
var float luSL0 = na // original stop, kept for R maths after the stop is moved
var float luTP2 = na // runner target
var float luR2 = na
var bool luBe = false // stop has been moved to breakeven
var bool luP1 = false // first target already banked
var float luBanked = 0.0 // R already banked from the partial
var bool luSmt = false // the raid that started this setup carried an SMT divergence
var bool luCtRaid = false // the raid that started this setup was a CLOSE-THROUGH, not a wick.
var bool luLiq = false // the target came from a liquidity pool — kept so the label can be
var float luExitR = na // R the last long ended at — captured for the alert payload
var string luExitWhy = '' // why it ended: TP, SL, BE, trail, or a banked partial
var bool luTrailOn = false // the trail has activated and now governs the stop
var float luPeak = na // best price reached since the fill — what the trail follows
var box luRiskBx = na
var box luRewBx = na
var line luEntLn = na
var label luLbl = na
var int lsSt = 0
var int lsSwBar = 0
var float lsSwHigh0 = na
var float lsRunHigh = na
var int lsChBar = 0
var float lsEntry = na
var float lsSL = na
var float lsTP = na
var float lsRR = na
var int lsArmBar = 0
var int lsEntryBar = 0
var float lsSL0 = na
var float lsTP2 = na
var float lsR2 = na
var bool lsBe = false
var bool lsP1 = false
var float lsBanked = 0.0
var bool lsSmt = false
var bool lsCtRaid = false
var bool lsLiq = false
var float lsExitR = na
var string lsExitWhy = ''
var bool lsTrailOn = false
var float lsTrough = na
var box lsRiskBx = na
var box lsRewBx = na
var line lsEntLn = na
var label lsLbl = na
var int nWinL = 0
var int nLossL = 0
var int nWinS = 0
var int nLossS = 0
var float sumR = 0.0
var float grossWinR = 0.0
var float grossLossR = 0.0
var int nArmed = 0
var int nCancel = 0
var int nFiltered = 0
var int nBE = 0
var int streak = 0 // positive = consecutive wins, negative = consecutive losses
var array<box> setBoxes = array.new<box>()
var array<line> setLines = array.new<line>()
var array<label> setLabs = array.new<label>()
bool alArmLong = false
bool alArmShort = false
bool alEntLong = false
bool alEntShort = false
bool alTpHit = false
bool alSlHit = false
var float luShiftRef = na
var float lsShiftRef = na
float knownHigh = useInternal ? intHigh.currentLevel : swgHigh.currentLevel
float knownLow = useInternal ? intLow.currentLevel : swgLow.currentLevel
bool knownHighCrossed = useInternal ? intHigh.crossed : swgHigh.crossed
bool knownLowCrossed = useInternal ? intLow.crossed : swgLow.crossed
if barstate.isconfirmed and sweepSell and luSt == 0
luShiftRef := not knownHighCrossed[1] and knownHigh[1] > close[1] ? knownHigh[1] : na
luSt := 1
luSwBar := bar_index
luSwLow0 := low
luRunLow := low
luSmt := smtBull
luCtRaid := ctSell
if barstate.isconfirmed and (luSt == 1 or luSt == 2)
luRunLow := math.min(nz(luRunLow, low), low)
if barstate.isconfirmed and (luSt == 1)
if close < luSwLow0 - (luCtRaid ? ctInvAbs : 0.0)
luSt := 0
nCancel += 1
else if barstate.isconfirmed and bar_index > luSwBar and (shiftRule == 'Raid-bound structure' ? not na(luShiftRef) and close > luShiftRef and close[1] <= luShiftRef : bullShift)
if useFvgEntry
luSt := 2
luChBar := bar_index
else
float slClose = nz(luRunLow, low) - slBuffer
if close > slClose and not (oneAtATime and lsSt >= 3) and not f_filtersPass(true, close, slClose, luSmt)
luSt := 0
nFiltered += 1
else if close > slClose and not (oneAtATime and lsSt >= 3)
[tpv, rv, liqUsed, tp2v, r2v] = f_resolveTp(true, close, slClose)
luEntry := close
luSL := slClose
luRR := rv
luTP := tpv
luSL0 := slClose
luTP2 := tp2v
luR2 := r2v
luBe := false
luP1 := false
luBanked := 0.0
luTrailOn := false
luPeak := close
luSt := 4
luArmBar := bar_index
luEntryBar := bar_index
nArmed += 1
alArmLong := true
alEntLong := true
if alertArmed
alQueue.push(f_alertTrade('armed', 'long', luCtRaid ? 'close-through' : 'wick', luEntry, luSL, luTP, luRR))
if alertEntry
alQueue.push(f_alertTrade('entry', 'long', luCtRaid ? 'close-through' : 'wick', luEntry, luSL, luTP, luRR))
if showSetups
[rb, wb, el, lb] = f_drawSetup(true, luEntry, luSL, luTP, f_setupTag(rv, liqUsed, luCtRaid))
luRiskBx := rb
luRewBx := wb
luEntLn := el
luLbl := lb
setBoxes.push(rb)
setBoxes.push(wb)
setLines.push(el)
setLabs.push(lb)
f_trimBox(setBoxes, maxSetupDraw * 2)
f_trimLine(setLines, maxSetupDraw)
f_trimLabel(setLabs, maxSetupDraw)
else
luSt := 0
nCancel += 1
else if bar_index - luSwBar > maxBarsChoCH
luSt := 0
nCancel += 1
if barstate.isconfirmed and (luSt == 2)
if bar_index - luChBar > maxBarsFvg
luSt := 0
nCancel += 1
else if close < luSwLow0 - (luCtRaid ? ctInvAbs : 0.0)
luSt := 0
nCancel += 1
else
bool blocked = oneAtATime and lsSt >= 3
float ft = na
float fb = na
if not blocked and fvgs.size() > 0
for i = 0 to fvgs.size() - 1
fvgZone z = fvgs.get(i)
if z.dir == 1 and z.bIdx > luSwBar and z.bIdx >= luChBar - 1 and z.bIdx <= luChBar + 2 and not z.mitigated
ft := z.top
fb := z.bot
break
float cand = na(ft) ? na : f_fvgEntry(ft, fb, true, fvgEntryPct)
float candSL = nz(luRunLow, low) - slBuffer
if not na(cand) and cand > candSL and cand < close and not f_filtersPass(true, cand, candSL, luSmt)
luSt := 0
nFiltered += 1
else if not na(cand) and cand > candSL and cand < close
[tpv, rv, liqUsed, tp2v, r2v] = f_resolveTp(true, cand, candSL)
luEntry := cand
luSL := candSL
luRR := rv
luTP := tpv
luSL0 := candSL
luTP2 := tp2v
luR2 := r2v
luBe := false
luP1 := false
luBanked := 0.0
luTrailOn := false
luPeak := na
luLiq := liqUsed
luSt := 3
luArmBar := bar_index
nArmed += 1
alArmLong := true
if alertArmed
alQueue.push(f_alertTrade('armed', 'long', luCtRaid ? 'close-through' : 'wick', luEntry, luSL, luTP, luRR))
if showSetups and drawFilled
luRiskBx := na
luRewBx := na
luEntLn := na
luLbl := na
if showSetups and not drawFilled
[rb, wb, el, lb] = f_drawSetup(true, luEntry, luSL, luTP, f_setupTag(rv, liqUsed, luCtRaid))
luRiskBx := rb
luRewBx := wb
luEntLn := el
luLbl := lb
setBoxes.push(rb)
setBoxes.push(wb)
setLines.push(el)
setLabs.push(lb)
f_trimBox(setBoxes, maxSetupDraw * 2)
f_trimLine(setLines, maxSetupDraw)
f_trimLabel(setLabs, maxSetupDraw)
else if bar_index - luChBar > maxBarsFvg
luSt := 0
nCancel += 1
if barstate.isconfirmed and luSt == 3 and bar_index > luArmBar
if bar_index - luArmBar > maxBarsEntry
luSt := 0
nCancel += 1
if showSetups and not na(luRiskBx)
luRiskBx.set_bgcolor(color.new(color.gray, 90))
luRewBx.set_bgcolor(color.new(color.gray, 92))
luLbl.set_text('LONG expired')
luLbl.set_textcolor(color.new(color.gray, 20))
else if low <= luEntry
luSt := 4
luEntryBar := bar_index
luPeak := luEntry
alEntLong := true
if alertEntry
alQueue.push(f_alertTrade('entry', 'long', luCtRaid ? 'close-through' : 'wick', luEntry, luSL, luTP, luRR))
if showSetups and drawFilled
[rb, wb, el, lb] = f_drawSetup(true, luEntry, luSL, luTP, f_setupTag(luRR, luLiq, luCtRaid))
luRiskBx := rb
luRewBx := wb
luEntLn := el
luLbl := lb
setBoxes.push(rb)
setBoxes.push(wb)
setLines.push(el)
setLabs.push(lb)
f_trimBox(setBoxes, maxSetupDraw * 2)
f_trimLine(setLines, maxSetupDraw)
f_trimLabel(setLabs, maxSetupDraw)
else if bearShift or high >= luTP
luSt := 0
nCancel += 1
if showSetups and not na(luRiskBx)
luRiskBx.set_bgcolor(color.new(color.gray, 90))
luRewBx.set_bgcolor(color.new(color.gray, 92))
luRiskBx.set_border_color(color.new(color.gray, 80))
luRewBx.set_border_color(color.new(color.gray, 80))
luLbl.set_text('LONG cancelled')
luLbl.set_textcolor(color.new(color.gray, 20))
if barstate.isconfirmed and luSt == 4 and (useFvgEntry or bar_index > luEntryBar)
float risk0 = luEntry - nz(luSL0, luSL)
bool hitSL = low <= luSL
bool hitTP = high >= luTP and bar_index > luEntryBar
if hitSL
float rStop = risk0 > 0 ? (luSL - luEntry) / risk0 : 0.0
float rOut = luP1 ? luBanked + rStop * (1.0 - partialPct / 100.0) : rStop
sumR += rOut
if rOut > 0
nWinL += 1
grossWinR += rOut
streak := streak >= 0 ? streak + 1 : 1
else if rOut < 0
nLossL += 1
grossLossR += -rOut
streak := streak <= 0 ? streak - 1 : -1
else
nBE += 1
luSt := 0
alSlHit := true
luExitR := rOut
luExitWhy := luTrailOn and luSL > nz(luSL0, luSL) ? 'trail' : luBe ? 'BE' : 'SL'
if alertExit
alQueue.push(f_alertTrade('exit', 'long', luExitWhy, luEntry, luSL, luTP, luExitR))
if showSetups and not na(luLbl)
luRiskBx.set_right(bar_index)
luRewBx.set_right(bar_index)
luEntLn.set_x2(bar_index)
luLbl.set_x(bar_index)
string why = luTrailOn and luSL > nz(luSL0, luSL) ? 'trail' : luBe ? 'BE' : 'SL'
luLbl.set_text('LONG ' + why + ' ' + (rOut >= 0 ? '+' : '') + str.tostring(rOut, '0.00') + 'R')
luLbl.set_textcolor(rOut > 0 ? panelWin : rOut < 0 ? panelLoss : color.new(panelTxt, 20))
else if hitTP
if partialOn and not luP1
luP1 := true
luBanked := luRR * partialPct / 100.0
luBe := true
luSL := math.max(luSL, luEntry)
luTP := luTP2
alTpHit := true
luExitR := luBanked
luExitWhy := 'partial'
if alertExit
alQueue.push(f_alertTrade('exit', 'long', 'partial banked → runner', luEntry, luSL, luTP2, luExitR))
if showSetups and not na(luLbl)
luRewBx.set_top(luTP2)
luLbl.set_y(luTP2)
luLbl.set_text('LONG banked +' + str.tostring(luBanked, '0.00') + 'R → runner')
luLbl.set_textcolor(panelWin)
else
float rOut = luP1 ? luBanked + luR2 * (1.0 - partialPct / 100.0) : luRR
sumR += rOut
nWinL += 1
grossWinR += rOut
streak := streak >= 0 ? streak + 1 : 1
luSt := 0
alTpHit := true
luExitR := rOut
luExitWhy := 'TP'
if alertExit
alQueue.push(f_alertTrade('exit', 'long', 'TP', luEntry, luSL, luTP, luExitR))
if showSetups and not na(luLbl)
luRiskBx.set_right(bar_index)
luRewBx.set_right(bar_index)
luEntLn.set_x2(bar_index)
luLbl.set_x(bar_index)
luLbl.set_text('LONG TP +' + str.tostring(rOut, '0.00') + 'R')
luLbl.set_textcolor(panelWin)
else if bar_index > luEntryBar
if beOn and not luBe and risk0 > 0 and high >= luEntry + beTrigR * risk0
luBe := true
luSL := math.max(luSL, luEntry)
if trailOn and risk0 > 0
if not luTrailOn and high >= luEntry + trailTrigR * risk0
luTrailOn := true
if luTrailOn
float trailSL = luPeak * (1.0 - trailPct / 100.0)
luSL := math.max(luSL, trailSL)
if showSetups and not na(luRiskBx) and luSL > luEntry - risk0
luRiskBx.set_bottom(math.min(luSL, luEntry))
if barstate.isconfirmed and luSt == 4 and bar_index > luEntryBar
luPeak := math.max(nz(luPeak, high), high)
if showSetups and luSt >= 3 and not na(luRiskBx)
luRiskBx.set_right(bar_index + 1)
luRewBx.set_right(bar_index + 1)
luEntLn.set_x2(bar_index + 1)
luLbl.set_x(bar_index + 1)
if barstate.isconfirmed and sweepBuy and lsSt == 0
lsShiftRef := not knownLowCrossed[1] and knownLow[1] < close[1] ? knownLow[1] : na
lsSt := 1
lsSwBar := bar_index
lsSwHigh0 := high
lsRunHigh := high
lsSmt := smtBear
lsCtRaid := ctBuy
if barstate.isconfirmed and (lsSt == 1 or lsSt == 2)
lsRunHigh := math.max(nz(lsRunHigh, high), high)
if barstate.isconfirmed and (lsSt == 1)
if close > lsSwHigh0 + (lsCtRaid ? ctInvAbs : 0.0)
lsSt := 0
nCancel += 1
else if barstate.isconfirmed and bar_index > lsSwBar and (shiftRule == 'Raid-bound structure' ? not na(lsShiftRef) and close < lsShiftRef and close[1] >= lsShiftRef : bearShift)
if useFvgEntry
lsSt := 2
lsChBar := bar_index
else
float slCloseS = nz(lsRunHigh, high) + slBuffer
if close < slCloseS and not (oneAtATime and luSt >= 3) and not f_filtersPass(false, close, slCloseS, lsSmt)
lsSt := 0
nFiltered += 1
else if close < slCloseS and not (oneAtATime and luSt >= 3)
[tpv, rv, liqUsed, tp2v, r2v] = f_resolveTp(false, close, slCloseS)
lsEntry := close
lsSL := slCloseS
lsRR := rv
lsTP := tpv
lsSL0 := slCloseS
lsTP2 := tp2v
lsR2 := r2v
lsBe := false
lsP1 := false
lsBanked := 0.0
lsTrailOn := false
lsTrough := close
lsSt := 4
lsArmBar := bar_index
lsEntryBar := bar_index
nArmed += 1
alArmShort := true
alEntShort := true
if alertArmed
alQueue.push(f_alertTrade('armed', 'short', lsCtRaid ? 'close-through' : 'wick', lsEntry, lsSL, lsTP, lsRR))
if alertEntry
alQueue.push(f_alertTrade('entry', 'short', lsCtRaid ? 'close-through' : 'wick', lsEntry, lsSL, lsTP, lsRR))
if showSetups
[rb, wb, el, lb] = f_drawSetup(false, lsEntry, lsSL, lsTP, f_setupTag(rv, liqUsed, lsCtRaid))
lsRiskBx := rb
lsRewBx := wb
lsEntLn := el
lsLbl := lb
setBoxes.push(rb)
setBoxes.push(wb)
setLines.push(el)
setLabs.push(lb)
f_trimBox(setBoxes, maxSetupDraw * 2)
f_trimLine(setLines, maxSetupDraw)
f_trimLabel(setLabs, maxSetupDraw)
else
lsSt := 0
nCancel += 1
else if bar_index - lsSwBar > maxBarsChoCH
lsSt := 0
nCancel += 1
if barstate.isconfirmed and (lsSt == 2)
if bar_index - lsChBar > maxBarsFvg
lsSt := 0
nCancel += 1
else if close > lsSwHigh0 + (lsCtRaid ? ctInvAbs : 0.0)
lsSt := 0
nCancel += 1
else
bool blockedS = oneAtATime and luSt >= 3
float ftS = na
float fbS = na
if not blockedS and fvgs.size() > 0
for i = 0 to fvgs.size() - 1
fvgZone z = fvgs.get(i)
if z.dir == -1 and z.bIdx > lsSwBar and z.bIdx >= lsChBar - 1 and z.bIdx <= lsChBar + 2 and not z.mitigated
ftS := z.top
fbS := z.bot
break
float candS = na(ftS) ? na : f_fvgEntry(ftS, fbS, false, fvgEntryPct)
float candSLS = nz(lsRunHigh, high) + slBuffer
if not na(candS) and candS < candSLS and candS > close and not f_filtersPass(false, candS, candSLS, lsSmt)
lsSt := 0
nFiltered += 1
else if not na(candS) and candS < candSLS and candS > close
[tpv, rv, liqUsed, tp2v, r2v] = f_resolveTp(false, candS, candSLS)
lsEntry := candS
lsSL := candSLS
lsRR := rv
lsTP := tpv
lsSL0 := candSLS
lsTP2 := tp2v
lsR2 := r2v
lsBe := false
lsP1 := false
lsBanked := 0.0
lsTrailOn := false
lsTrough := na
lsLiq := liqUsed
lsSt := 3
lsArmBar := bar_index
nArmed += 1
alArmShort := true
if alertArmed
alQueue.push(f_alertTrade('armed', 'short', lsCtRaid ? 'close-through' : 'wick', lsEntry, lsSL, lsTP, lsRR))
if showSetups and drawFilled
lsRiskBx := na
lsRewBx := na
lsEntLn := na
lsLbl := na
if showSetups and not drawFilled
[rb, wb, el, lb] = f_drawSetup(false, lsEntry, lsSL, lsTP, f_setupTag(rv, liqUsed, lsCtRaid))
lsRiskBx := rb
lsRewBx := wb
lsEntLn := el
lsLbl := lb
setBoxes.push(rb)
setBoxes.push(wb)
setLines.push(el)
setLabs.push(lb)
f_trimBox(setBoxes, maxSetupDraw * 2)
f_trimLine(setLines, maxSetupDraw)
f_trimLabel(setLabs, maxSetupDraw)
else if bar_index - lsChBar > maxBarsFvg
lsSt := 0
nCancel += 1
if barstate.isconfirmed and lsSt == 3 and bar_index > lsArmBar
if bar_index - lsArmBar > maxBarsEntry
lsSt := 0
nCancel += 1
if showSetups and not na(lsRiskBx)
lsRiskBx.set_bgcolor(color.new(color.gray, 90))
lsRewBx.set_bgcolor(color.new(color.gray, 92))
lsLbl.set_text('SHORT expired')
lsLbl.set_textcolor(color.new(color.gray, 20))
else if high >= lsEntry
lsSt := 4
lsEntryBar := bar_index
lsTrough := lsEntry
alEntShort := true
if alertEntry
alQueue.push(f_alertTrade('entry', 'short', lsCtRaid ? 'close-through' : 'wick', lsEntry, lsSL, lsTP, lsRR))
if showSetups and drawFilled
[rb, wb, el, lb] = f_drawSetup(false, lsEntry, lsSL, lsTP, f_setupTag(lsRR, lsLiq, lsCtRaid))
lsRiskBx := rb
lsRewBx := wb
lsEntLn := el
lsLbl := lb
setBoxes.push(rb)
setBoxes.push(wb)
setLines.push(el)
setLabs.push(lb)
f_trimBox(setBoxes, maxSetupDraw * 2)
f_trimLine(setLines, maxSetupDraw)
f_trimLabel(setLabs, maxSetupDraw)
else if bullShift or low <= lsTP
lsSt := 0
nCancel += 1
if showSetups and not na(lsRiskBx)
lsRiskBx.set_bgcolor(color.new(color.gray, 90))
lsRewBx.set_bgcolor(color.new(color.gray, 92))
lsRiskBx.set_border_color(color.new(color.gray, 80))
lsRewBx.set_border_color(color.new(color.gray, 80))
lsLbl.set_text('SHORT cancelled')
lsLbl.set_textcolor(color.new(color.gray, 20))
if barstate.isconfirmed and lsSt == 4 and (useFvgEntry or bar_index > lsEntryBar)
float risk0s = nz(lsSL0, lsSL) - lsEntry
bool hitSLs = high >= lsSL
bool hitTPs = low <= lsTP and bar_index > lsEntryBar
if hitSLs
float rStop = risk0s > 0 ? (lsEntry - lsSL) / risk0s : 0.0
float rOut = lsP1 ? lsBanked + rStop * (1.0 - partialPct / 100.0) : rStop
sumR += rOut
if rOut > 0
nWinS += 1
grossWinR += rOut
streak := streak >= 0 ? streak + 1 : 1
else if rOut < 0
nLossS += 1
grossLossR += -rOut
streak := streak <= 0 ? streak - 1 : -1
else
nBE += 1
lsSt := 0
alSlHit := true
lsExitR := rOut
lsExitWhy := lsTrailOn and lsSL < nz(lsSL0, lsSL) ? 'trail' : lsBe ? 'BE' : 'SL'
if alertExit
alQueue.push(f_alertTrade('exit', 'short', lsExitWhy, lsEntry, lsSL, lsTP, lsExitR))
if showSetups and not na(lsLbl)
lsRiskBx.set_right(bar_index)
lsRewBx.set_right(bar_index)
lsEntLn.set_x2(bar_index)
lsLbl.set_x(bar_index)
string why = lsTrailOn and lsSL < nz(lsSL0, lsSL) ? 'trail' : lsBe ? 'BE' : 'SL'
lsLbl.set_text('SHORT ' + why + ' ' + (rOut >= 0 ? '+' : '') + str.tostring(rOut, '0.00') + 'R')
lsLbl.set_textcolor(rOut > 0 ? panelWin : rOut < 0 ? panelLoss : color.new(panelTxt, 20))
else if hitTPs
if partialOn and not lsP1
lsP1 := true
lsBanked := lsRR * partialPct / 100.0
lsBe := true
lsSL := math.min(lsSL, lsEntry)
lsTP := lsTP2
alTpHit := true
lsExitR := lsBanked
lsExitWhy := 'partial'
if alertExit
alQueue.push(f_alertTrade('exit', 'short', 'partial banked → runner', lsEntry, lsSL, lsTP2, lsExitR))
if showSetups and not na(lsLbl)
lsRewBx.set_bottom(lsTP2)
lsLbl.set_y(lsTP2)
lsLbl.set_text('SHORT banked +' + str.tostring(lsBanked, '0.00') + 'R → runner')
lsLbl.set_textcolor(panelWin)
else
float rOut = lsP1 ? lsBanked + lsR2 * (1.0 - partialPct / 100.0) : lsRR
sumR += rOut
nWinS += 1
grossWinR += rOut
streak := streak >= 0 ? streak + 1 : 1
lsSt := 0
alTpHit := true
lsExitR := rOut
lsExitWhy := 'TP'
if alertExit
alQueue.push(f_alertTrade('exit', 'short', 'TP', lsEntry, lsSL, lsTP, lsExitR))
if showSetups and not na(lsLbl)
lsRiskBx.set_right(bar_index)
lsRewBx.set_right(bar_index)
lsEntLn.set_x2(bar_index)
lsLbl.set_x(bar_index)
lsLbl.set_text('SHORT TP +' + str.tostring(rOut, '0.00') + 'R')
lsLbl.set_textcolor(panelWin)
else
if bar_index > lsEntryBar and beOn and not lsBe and risk0s > 0 and low <= lsEntry - beTrigR * risk0s
lsBe := true
lsSL := math.min(lsSL, lsEntry)
if bar_index > lsEntryBar and trailOn and risk0s > 0
if not lsTrailOn and low <= lsEntry - trailTrigR * risk0s
lsTrailOn := true
if lsTrailOn
float trailSL = lsTrough * (1.0 + trailPct / 100.0)
lsSL := math.min(lsSL, trailSL)
if showSetups and not na(lsRiskBx) and lsSL < lsEntry + risk0s
lsRiskBx.set_top(math.max(lsSL, lsEntry))
if barstate.isconfirmed and lsSt == 4 and bar_index > lsEntryBar
lsTrough := math.min(nz(lsTrough, low), low)
if showSetups and lsSt >= 3 and not na(lsRiskBx)
lsRiskBx.set_right(bar_index + 1)
lsRewBx.set_right(bar_index + 1)
lsEntLn.set_x2(bar_index + 1)
lsLbl.set_x(bar_index + 1)
[pdH, pdL, pdT] = request.security(syminfo.tickerid, 'D', [high[1], low[1], time_close[1]], lookahead = barmerge.lookahead_on)
float pdEq = not na(pdH) and not na(pdL) ? math.avg(pdH, pdL) : na
var bool pdHSwept = false
var bool pdLSwept = false
var int pdStartT = time
bool pdRolled = timeframe.change('D') or (not na(pdH) and not na(pdH[1]) and pdH != pdH[1]) or (not na(pdL) and not na(pdL[1]) and pdL != pdL[1])
if pdRolled
pdHSwept := false
pdLSwept := false
pdStartT := time
if not na(pdH) and high >= pdH
pdHSwept := true
if not na(pdL) and low <= pdL
pdLSwept := true
var line pdHLn = line.new(na, na, na, na, xloc = xloc.bar_time)
var line pdLLn = line.new(na, na, na, na, xloc = xloc.bar_time)
var line pdELn = line.new(na, na, na, na, xloc = xloc.bar_time)
var label pdHLb = label.new(na, na, '', xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.white, 100))
var label pdLLb = label.new(na, na, '', xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.white, 100))
var label pdELb = label.new(na, na, '', xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.white, 100))
if barstate.islast
bool pdOk = showPD and not na(pdH) and not na(pdL)
int rghT = time + pdExtend * timeframe.in_seconds(timeframe.period) * 1000
color cH = pdOk ? (pdHSwept ? color.new(pdCol, 60) : pdCol) : color.new(color.white, 100)
color cL = pdOk ? (pdLSwept ? color.new(pdCol, 60) : pdCol) : color.new(color.white, 100)
color cE = pdOk and showPdEq ? color.new(pdCol, 35) : color.new(color.white, 100)
int pdStampT = na(pdT) ? na : pdT - 1
string pdDay = f_dayName(pdStampT)
string pdDate = na(pdStampT) ? '' : str.format_time(pdStampT, 'dd/MM', syminfo.timezone)
string pdStamp = switch pdLabelMode
'Day' => pdDay == '' ? '' : ' ' + pdDay
'Date' => pdDate == '' ? '' : ' ' + pdDate
'Day + Date' => pdDay == '' and pdDate == '' ? '' : ' ' + pdDay + ' ' + pdDate
=> ''
pdHLn.set_xy1(pdStartT, pdOk ? pdH : na)
pdHLn.set_xy2(rghT, pdOk ? pdH : na)
pdHLn.set_color(cH)
pdHLn.set_width(pdWidth)
pdHLn.set_style(pdHSwept ? line.style_dotted : line.style_solid)
pdLLn.set_xy1(pdStartT, pdOk ? pdL : na)
pdLLn.set_xy2(rghT, pdOk ? pdL : na)
pdLLn.set_color(cL)
pdLLn.set_width(pdWidth)
pdLLn.set_style(pdLSwept ? line.style_dotted : line.style_solid)
pdELn.set_xy1(pdStartT, pdOk and showPdEq ? pdEq : na)
pdELn.set_xy2(rghT, pdOk and showPdEq ? pdEq : na)
pdELn.set_color(cE)
pdELn.set_width(pdWidth)
pdELn.set_style(line.style_dotted)
pdHLb.set_xy(rghT, pdOk ? pdH : na)
pdHLb.set_text(showPdLbl ? 'PDH' + pdStamp + (pdHSwept ? ' ✓' : '') : '')
pdHLb.set_textcolor(cH)
pdLLb.set_xy(rghT, pdOk ? pdL : na)
pdLLb.set_text(showPdLbl ? 'PDL' + (pdLSwept ? ' ✓' : '') : '')
pdLLb.set_textcolor(cL)
pdELb.set_xy(rghT, pdOk and showPdEq ? pdEq : na)
pdELb.set_text(showPdLbl and showPdEq ? 'PD EQ' : '')
pdELb.set_textcolor(cE)
string autoHtf = timeframe.in_seconds(timeframe.period) <= 60 ? '15' : timeframe.in_seconds(timeframe.period) <= 300 ? '60' : timeframe.in_seconds(timeframe.period) <= 900 ? '60' : timeframe.in_seconds(timeframe.period) <= 1800 ? '240' : timeframe.in_seconds(timeframe.period) <= 3600 ? '240' : timeframe.in_seconds(timeframe.period) <= 14400 ? 'D' : timeframe.in_seconds(timeframe.period) <= 86400 ? 'W' : 'M'
string htfTf = htfAuto ? autoHtf : htfManual
bool htfOk = timeframe.in_seconds(htfTf) > timeframe.in_seconds(timeframe.period)
bool newHtfBar = timeframe.change(htfTf)
var float ho0 = na
var float hh0 = na
var float hl0 = na
var float hc0 = na
var int ht0 = na
if newHtfBar or na(ho0)
ho0 := open
hh0 := high
hl0 := low
hc0 := close
ht0 := time(htfTf)
else
hh0 := math.max(hh0, high)
hl0 := math.min(hl0, low)
hc0 := close
[ho1,hh1,hl1,hc1, ho2,hh2,hl2,hc2, ho3,hh3,hl3,hc3, ho4,hh4,hl4,hc4, ho5,hh5,hl5,hc5, ho6,hh6,hl6,hc6,
ho7,hh7,hl7,hc7, ho8,hh8,hl8,hc8, ho9,hh9,hl9,hc9, ho10,hh10,hl10,hc10, ho11,hh11,hl11,hc11] =
request.security(syminfo.tickerid, htfTf,
[open[1],high[1],low[1],close[1], open[2],high[2],low[2],close[2], open[3],high[3],low[3],close[3],
open[4],high[4],low[4],close[4], open[5],high[5],low[5],close[5], open[6],high[6],low[6],close[6],
open[7],high[7],low[7],close[7], open[8],high[8],low[8],close[8], open[9],high[9],low[9],close[9],
open[10],high[10],low[10],close[10], open[11],high[11],low[11],close[11]],
lookahead = barmerge.lookahead_on)
var array<box> hbBoxes = array.new<box>()
var array<line> hbWicks = array.new<line>()
var array<line> hbEqs = array.new<line>()
var label hbTimer = na
var label hbWarn = na
if barstate.islast
for b in hbBoxes
b.delete()
hbBoxes.clear()
for w in hbWicks
w.delete()
hbWicks.clear()
for e in hbEqs
e.delete()
hbEqs.clear()
if not na(hbTimer)
hbTimer.delete()
hbTimer := na
if not na(hbWarn)
hbWarn.delete()
hbWarn := na
if showHtfBlock
if not htfOk
hbWarn := label.new(bar_index, high, 'HTF block: the higher timeframe must be above the chart timeframe', xloc = xloc.bar_index, style = label.style_label_down, color = color.new(#f23645, 20), textcolor = color.white, size = size.small)
else
array<float> aO = array.from(ho0,ho1,ho2,ho3,ho4,ho5,ho6,ho7,ho8,ho9,ho10,ho11)
array<float> aH = array.from(hh0,hh1,hh2,hh3,hh4,hh5,hh6,hh7,hh8,hh9,hh10,hh11)
array<float> aL = array.from(hl0,hl1,hl2,hl3,hl4,hl5,hl6,hl7,hl8,hl9,hl10,hl11)
array<float> aC = array.from(hc0,hc1,hc2,hc3,hc4,hc5,hc6,hc7,hc8,hc9,hc10,hc11)
int num = math.min(htfCount, 12)
int candleW = htfSize == 'Large' ? 5 : htfSize == 'Medium' ? 3 : 1
int step = candleW + htfGap
int baseX = bar_index + htfOffset
int half = math.max(1, math.round(candleW / 2.0))
float blockTop = na
for i = 0 to num - 1
float o = aO.get(i)
float h = aH.get(i)
float l = aL.get(i)
float c = aC.get(i)
if na(o) or na(h) or na(l) or na(c)
continue
bool bull = c >= o
int x = baseX + (num - 1 - i) * step
int xl = x - half
int xr = x + half
float bt = math.max(o, c)
float bb = math.min(o, c)
if bt == bb
bt := bt + syminfo.mintick
hbBoxes.push(box.new(xl, bt, xr, bb, xloc = xloc.bar_index, bgcolor = bull ? htfBullBody : htfBearBody, border_color = bull ? htfBullBorder : htfBearBorder, border_width = 1))
hbWicks.push(line.new(x, h, x, bt, xloc = xloc.bar_index, color = bull ? htfWickCol : htfBearWick, width = 1))
hbWicks.push(line.new(x, bb, x, l, xloc = xloc.bar_index, color = bull ? htfWickCol : htfBearWick, width = 1))
if htfShowEq and i >= 1
float eqp = math.avg(h, l)
hbEqs.push(line.new(xl, eqp, xr, eqp, xloc = xloc.bar_index, color = color.new(htfTxtCol, 30), style = line.style_dotted))
if na(blockTop) or h > blockTop
blockTop := h
if htfShowTimer and not na(blockTop)
int xC = baseX + math.round((num - 1) * step / 2.0)
hbTimer := label.new(xC, blockTop, f_tfLabel(htfTf) + '\n' + f_htfCountdown(ht0, htfTf), xloc = xloc.bar_index, style = label.style_label_down, color = color.new(color.white, 100), textcolor = htfTxtCol, size = size.small)
var table pnl = na
if barstate.islast
if not na(pnl)
pnl.delete()
pnl := na
if showPanel
string pPos = switch panelPos
'Top Left' => position.top_left
'Bottom Right' => position.bottom_right
'Bottom Left' => position.bottom_left
=> position.top_right
int wins = nWinL + nWinS
int losses = nLossL + nLossS
int closed = wins + losses + nBE
float winRate = closed > 0 ? 100.0 * wins / closed : na
float pf = grossLossR > 0 ? grossWinR / grossLossR : na
float avgR = closed > 0 ? sumR / closed : na
string strkTxt = streak == 0 ? '-' : streak > 0 ? str.tostring(streak) + ' wins' : str.tostring(math.abs(streak)) + ' losses'
string stTxt = luSt == 4 ? 'LONG in trade' : lsSt == 4 ? 'SHORT in trade' : luSt == 3 ? 'LONG armed — waiting for entry' : lsSt == 3 ? 'SHORT armed — waiting for entry' : luSt == 2 ? 'LONG — waiting for FVG' : lsSt == 2 ? 'SHORT — waiting for FVG' : luSt == 1 ? 'LONG — waiting for shift' : lsSt == 1 ? 'SHORT — waiting for shift' : 'Idle'
color stCol = luSt == 4 or luSt == 3 ? panelWin : lsSt == 4 or lsSt == 3 ? panelLoss : panelTxt
string bias = (useInternal ? intTr.bias : swgTr.bias) == 1 ? 'Bullish' : (useInternal ? intTr.bias : swgTr.bias) == -1 ? 'Bearish' : '-'
bool anyFilter = filtTrendOn or filtPdOn or filtMaxRiskAtr > 0 or filtKzOn or filtSmtOn
bool anyMgmt = beOn or partialOn or trailOn
bool anyRaidQ = raidMinPen > 0 or raidMinRej > 0
bool ctModeRow = raidMode != 'Wick rejection'
int tRow = showTrendRow ? 1 : 0
int fRow = anyFilter ? 1 : 0
int bRow = anyMgmt ? 1 : 0
int sRow = smtLive ? 1 : 0
int qRow = anyRaidQ ? 1 : 0
int mRow = ctModeRow ? 1 : 0
color trendCol = trendTxt == 'Bullish' ? panelWin : trendTxt == 'Bearish' ? panelLoss : panelTxt
string filtTxt = ''
if filtTrendOn
filtTxt := filtTxt + 'Trend '
if filtPdOn
filtTxt := filtTxt + 'P/D '
if filtMaxRiskAtr > 0
filtTxt := filtTxt + 'Risk '
if filtKzOn
filtTxt := filtTxt + 'KZ '
if filtSmtOn
filtTxt := filtTxt + 'SMT '
pnl := table.new(pPos, 2, 13 + tRow + fRow + bRow + sRow + qRow + mRow, bgcolor = panelBg, border_color = color.new(panelTxt, 70), frame_color = color.new(panelTxt, 55), frame_width = 1, border_width = 1)
int rw = 0
string pnlNote = 'HYPOTHETICAL RESULTS — no orders are placed and nothing here was traded.\n\nThe engine marks where a trade would have opened and closed under idealised assumptions: a limit order filling exactly at its level, no spread, no commission, no slippage, no funding, no partial fills, and a bar that touches both target and stop counted as a loss.\n\nReal execution is worse on every one of those counts. Past behaviour of a rule is not evidence of its future behaviour.'
table.cell(pnl, 0, rw, 'RaidShift · SIM', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace, tooltip = pnlNote)
table.cell(pnl, 1, rw, f_tfLabel(timeframe.period), text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace, tooltip = pnlNote)
rw += 1
if showTrendRow
table.cell(pnl, 0, rw, 'Main Trend', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, f_tfLabel(trendTf) + ' · ' + trendTxt, text_color = trendCol, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Structure / Bias', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, structMode + ' · ' + bias, text_color = bias == 'Bullish' ? panelWin : bias == 'Bearish' ? panelLoss : panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
string tgtTxt = switch tpMode
'Opposite Liquidity' => 'Liquidity'
'Percent Gain' => str.tostring(tpPercent, '0.00') + '%'
=> str.tostring(rrTarget, '0.00') + 'R'
table.cell(pnl, 0, rw, 'Entry / Target', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, entryTag + ' · ' + tgtTxt + (partialOn ? ' · partial' : '') + (trailOn ? ' · trail' : ''), text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
if ctModeRow
table.cell(pnl, 0, rw, 'Raid mode', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, raidMode == 'Both' ? 'Wick + Close-through' : 'Close-through only', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
if smtLive
table.cell(pnl, 0, rw, 'SMT vs ' + smtName, text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(nSmt, '0') + ' · last ' + lastSmtDir, text_color = lastSmtDir == 'Bullish' ? smtBullCol : lastSmtDir == 'Bearish' ? smtBearCol : panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
if anyRaidQ
table.cell(pnl, 0, rw, 'Raids skipped', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(nRaidSkip, '0') + ' (quality)', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
if anyFilter
table.cell(pnl, 0, rw, 'Filtered out', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(nFiltered, '0') + ' (' + filtTxt + ')', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Armed / Cancelled', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(nArmed, '0') + ' / ' + str.tostring(nCancel, '0'), text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Closed trades', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(closed, '0'), text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Wins', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(wins, '0'), text_color = panelWin, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Losses', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(losses, '0'), text_color = panelLoss, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
if anyMgmt
table.cell(pnl, 0, rw, 'Scratch exits', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(nBE, '0'), text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Win rate', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, na(winRate) ? '-' : str.tostring(winRate, '0.0') + '%', text_color = na(winRate) ? panelTxt : winRate >= 50 ? panelWin : panelLoss, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Net R', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, (sumR >= 0 ? '+' : '') + str.tostring(sumR, '0.00') + 'R', text_color = sumR >= 0 ? panelWin : panelLoss, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Profit Factor / Avg R', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, (na(pf) ? '-' : str.tostring(pf, '0.00')) + ' / ' + (na(avgR) ? '-' : str.tostring(avgR, '0.00') + 'R'), text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Long W/L · Short W/L', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, str.tostring(nWinL, '0') + '/' + str.tostring(nLossL, '0') + ' · ' + str.tostring(nWinS, '0') + '/' + str.tostring(nLossS, '0'), text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Streak', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, strkTxt, text_color = streak > 0 ? panelWin : streak < 0 ? panelLoss : panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
rw += 1
table.cell(pnl, 0, rw, 'Status', text_color = panelTxt, text_size = panelSize, text_font_family = font.family_monospace)
table.cell(pnl, 1, rw, stTxt, text_color = stCol, text_size = panelSize, text_font_family = font.family_monospace)
if alQueue.size() > 0
for m in alQueue
if alertOnClose
alert(m, alert.freq_once_per_bar_close)
else
alert(m, alert.freq_once_per_bar)
alertcondition(sweepSell, 'Sellside Liquidity Raided', 'Sellside liquidity raided — waiting for a bullish CHoCH')
alertcondition(sweepBuy, 'Buyside Liquidity Raided', 'Buyside liquidity raided — waiting for a bearish CHoCH')
alertcondition(bullCHoCH, 'Bullish CHoCH', 'Bullish CHoCH printed')
alertcondition(bearCHoCH, 'Bearish CHoCH', 'Bearish CHoCH printed')
alertcondition(alArmLong, 'LONG Setup Armed', 'LONG setup armed')
alertcondition(alArmShort, 'SHORT Setup Armed', 'SHORT setup armed')
alertcondition(alEntLong, 'LONG Entry Triggered', 'LONG entry filled')
alertcondition(alEntShort, 'SHORT Entry Triggered', 'SHORT entry filled')
alertcondition(alTpHit, 'Take Profit Hit', 'Take Profit hit')
alertcondition(alSlHit, 'Stop Loss Hit', 'Stop Loss hit')