本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// @version=6
// LE Breaker v1.9.2
// (c) CoryM76 - All Rights Reserved
// Part of the LiquidityEdge suite.
//
// v1.9.2 - CLEAN-UP. Removed: Unicorn (yellow highlight, HTF FVG pull), the whole
// BUY / SELL trigger engine (retest triggers, trade ladders, stops, targets, 50%
// lines, trade log) for breakers and mitigations, and their alerts. The chart now
// shows only zones: breakers, mitigations and order blocks, with plain names.
// Defaults: Reaper FVG bar ON and PURPLE, hover info dots OFF. Dashboard trimmed to live
// counts, bias and nearest zones. One less request.security call.
//
// v1.8.3 - fix compile error CE10235 in the hover info label code.
//
// v1.8.2 - HOVER INFO. Every zone gets a small i; hover it for what the zone
// is, how to use it, test count, unicorn and Reaper meaning. The purple bar
// is the Reaper FVG and is now named on the chart. Toggle in Cleanup.
//
// v1.8.1 - stacked zones no longer print their names on top of each other.
// When zone texts would land at about the same price (within "Stack
// distance" x ATR), the first stays at the far right, the next shifts to
// the middle of the box, the next to the left. Toggle in Cleanup.
//
// v1.8.0 - CLEAN CHART. All BUY / SELL triggers (breaker and mitigation) now
// default OFF, so no trade ladders (entry / stop / TP lines) are drawn
// unless you turn them on. Zone labels are gone: each zone now prints its
// name as plain text inside the box at the far right (Bullish Breaker,
// Bearish Breaker, Bullish Mitigation, Bearish Mitigation, Bullish Order
// Block, Bearish Order Block) - no label box, no stars. Stars are an
// option (Show test / grade stars, off by default) and the fade-on-test
// is off by default. Text position Bottom / Middle / Top in Cleanup.
//
// v1.7.5 - order block labels (name + test stars) now sit INSIDE the box in
// its bottom-right corner and move with the box. Setting: "Label
// position" in Order Blocks (Inside right / Left edge).
//
// v1.7.4 - order block boxes now use a dashed border by default (setting:
// "Box border style" in Order Blocks) so they read differently from the
// solid breaker and mitigation boxes.
//
// v1.7.3 fix - zone labels were unreadable: the label box was filled with the
// zone's own border color and the text was the same color, so the stars
// and name disappeared. Labels now sit on a dark backing (own setting,
// "Zone label background") with the direction-colored text on top.
//
// v1.7.2 - safety build: grade symbols are plain ASCII (* solid, - hollow)
// so the file contains no special characters at all. The "Grade symbols"
// setting was removed. Added after a 'script could not be translated'
// error on v1.7.1.
//
// v1.7.1 fix - compile error CE10123: color.t() returns a decimal (float) but
// the zone's stored base transparency was declared as a whole number
// (int). Field is now float.
//
// v1.7.0 - CLEANUP + GRADED ORDER BLOCKS.
// NEW Order Blocks: the last opposite candle before a displacement move
// that breaks swing structure. Tracked per direction, faded and
// removed on a close through the zone. Visual + alerts (no trades).
// NEW Grading stars on every zone (order blocks, breakers, mitigations):
// "Test count" (default) = a star turns solid each time price
// returns to the zone; "Quality grade" = solid stars for each
// confluence the zone formed with (FVG in the leg, liquidity sweep,
// HTF aligned, discount/premium for order blocks; unicorn / HTF /
// Reaper for breakers). Stars are drawn in plain ASCII: * = solid, - = hollow.
// NEW Cleanup group: breaker on/off toggle, compact labels (default),
// zones auto-removed after N bars (default 400), zones fade a little
// with every test, zone label size.
// CHG Lower clutter defaults: breakers kept 8 -> 5, mitigations 12 -> 6,
// targets 5 -> 3, trades kept 6 -> 3, finished trades cleared after
// 90 bars (was never). All still adjustable. Saved settings stay
// until the indicator is removed and re-added.
//
// v1.6.3 fix - HTF Confluence "Structure" mode was checking the wrong
// thing: bullish alignment was "not htfStructBear" (absence of opposing
// structure) rather than "htfStructBull" (actual confirming structure) -
// the loosER test, when the tooltip describes Structure as the stricter,
// "purer but choppier" alternative to EMA mode. Now requires genuine
// confirming structure on the correct side, matching what the tooltip
// already promised.
//
// v1.6.2 fix - Unicorn's default detection mode ("HTF FVG") never applied
// the "Min FVG size" filter (i_fvgMin). The other two modes ("Chart-TF
// displacement", "Any overlap") correctly check (hi - lo) >= i_fvgMin
// before accepting a gap as valid - the HTF FVG branch skipped that check
// entirely, so on the default setting a genuinely tiny, insignificant
// 1-tick HTF gap counted as a full unicorn confluence the same as a
// meaningful one. Now applies the same size filter there too, so all
// three unicorn modes respect the same minimum-size setting consistently.
//
// v1.6.1 fix - "Show take profit lines" OFF hid the lines but the label
// boxes could still reappear. Root cause: two OTHER places in the trade
// lifecycle recolor TP lines/labels to the grey "done" color (i_doneCol,
// which is only 45% transparent - clearly visible) whenever a TP level
// gets hit, or whenever a trade fully completes - and neither of those
// recolors checked i_showTP, so they'd override the fully-transparent
// styling set at creation the moment either of those happened. Both spots
// (the TP-hit detection loop, and f_greyLockTrade's TP loop) now skip
// that recolor entirely when i_showTP is off, so a hidden TP stays hidden
// through its whole lifecycle instead of just at creation.
//
// v1.6 add - TP VISIBILITY + AGE-BASED CLEANUP. Two additions to cut down
// completed-trade clutter (up to "Trades kept on chart" completed trades'
// full TP ladders could sit on the chart simultaneously before):
// - "Show take profit lines" toggle (Stop / Targets group) - OFF hides
// all TP lines/labels while leaving entry/stop visible. Implemented by
// always creating the TP line/label objects (so array lengths stay in
// lockstep with the price-target array everywhere else in the file
// indexes them) but rendering them fully transparent when off, rather
// than skipping their creation - the latter would have desynced the
// arrays and thrown index errors in the hit-detection and lifecycle
// code.
// - "Auto-clear a completed trade after N bars" (0 = never) - once a
// trade is done (won or stopped), its entry/stop/TP drawings and its
// array slot are removed entirely after this many bars, independent
// of "Trades kept on chart" (which caps by COUNT, not age). New
// doneBar field on Trade tracks completion time for this.
//
// v1.5 add - REAPER INVERSION FVG. The ICT Reaper PD Array: a fair value
// gap sitting within the breaker's own impulsive leg (the sweep-to-MSS
// move), located in discount (bullish breaker) or premium (bearish
// breaker) relative to that leg's range - the idea being to enter when
// price returns to that gap, catching the reversal against traders who
// got stopped out. Distinct from Unicorn (which checks for FVG overlap
// generally, HTF or chart-TF) - Reaper specifically requires the gap to
// be inside THIS breaker's own leg AND on the cheap/expensive side of it.
// Runs on both Breaker and Mitigation (shares the same underlying
// mechanics). New "Reaper Inversion FVG" input group: on/off, a minimum-
// distance-beyond-equilibrium buffer (0 = just past 50%), a toggle to use
// the Reaper zone as the entry pocket when present (on by default -
// overrides the Unicorn pocket, since it's the more specific zone), and
// its own fill/border colors. Tags "REAPER" onto the zone label and the
// BUY/SELL signal string when a trade fires off a Reaper zone. Reaper's
// own drawing box is tracked and cleaned up the same way the existing
// zone/CE/label already are - no orphaned drawings left behind on
// invalidation or array eviction.
//
// Standalone ICT breaker-block engine. Detects failed order blocks that
// flip polarity after a liquidity sweep and a market-structure shift
// (body close required), marks the breaker zone, flags it as a "unicorn"
// when it overlaps a fair value gap, and fires BUY / SELL triggers on the
// retest with an SL + TP ladder.
//
// v1.4 changes:
// - Breaker zone anchor default flipped from "Candle range" to "Candle
// body" - the ICT material is explicit that the breaker zone itself
// (not just which candle gets picked) should use the candle body, not
// the full wick-to-wick range. Both options remain available.
// - ADDED: Mitigation Block engine (Ch 4.3.2). Same underlying sweep ->
// structure-shift -> anchor-candle -> retest mechanics as Breaker
// (this is the same "M pattern / swing failure" construction, ICT
// just treats it as repeatable rather than a one-time structural
// event). Runs as an independent, more sensitive detection track:
// its own (tighter, default 3/3) pivot strength so it catches the
// minor intraday swing failures that a 5/5 major-structure pivot
// would miss, its own zone cap/extension, its own colors and "Mit"
// tag, and its own BUY/SELL toggles - all layered on the SAME
// unicorn (FVG overlap), HTF confluence, retest, and SL/TP-ladder
// engine Breaker already uses, so a Mitigation trade is built and
// tracked identically once triggered. Zones still invalidate and
// retire individually like a Breaker zone; the "constant, both
// directions, all day" behavior you're after comes from how often a
// *new* minor M-pattern forms at the tighter pivot setting, not from
// one zone re-firing forever - that matches how the material
// describes it recurring throughout the session rather than being a
// single re-tradeable level.
//
// v1.3 - corrected to the textbook ICT model, with toggles:
// - Breaker box now anchors at the order-block candle (fixes placement).
// - Unicorn rebuilt: by default the breaker must overlap a HIGHER-TF FVG
// (default 15m, detected internally - not drawn; run the LE FVG/IFVG
// Engine for the visual). Switchable to chart-TF displacement FVG
// (classic same-TF unicorn) or loose any-overlap.
// - Unicorn entry uses the OVERLAP POCKET (breaker FVG intersection) by
// default, with SL beyond the pocket; switchable to full zone.
// - HTF confluence: tag (default) / filter / off; EMA or structure read,
// timeframe selectable (default 15m).
//
// Set your own colors in the inputs - nothing is pre-tuned here.
indicator("LE Breaker v1.9.2", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
string TZ = "America/New_York"
// =====================================================================
// INPUTS
// =====================================================================
g_det = "🧱 Detection"
g_uni = "Confluence (Unicorn)"
g_reap = "💀 Reaper Inversion FVG"
g_trig = "Triggers"
g_risk = "Stop / Targets"
g_sess = "🕘 Session Filter"
g_htf = "🧭 HTF Confluence"
g_vis = "🎨 Visuals"
g_dash = "🖥 Dashboard"
g_alert = "🔔 Alerts"
g_cln = "🧹 Cleanup"
g_ob = "📦 Order Blocks"
i_pivLeft = input.int(5, "Pivot strength (left)", minval = 1, group = g_det)
i_pivRight = input.int(5, "Pivot strength (right)", minval = 1, group = g_det)
i_sweepOn = input.bool(true, "Require liquidity sweep", group = g_det, tooltip = "Bullish: price must take out a prior swing low before the up-shift. Bearish: take out a prior swing high.")
i_mssClose = input.bool(true, "Require body close for MSS", group = g_det, tooltip = "Market structure shift must close through the level, not just wick. Strongly recommended ON.")
i_anchor = input.string("Candle body", "Breaker zone anchor", options = ["Candle range", "Candle body"], group = g_det, tooltip = "Range = high-to-low of the failed candle. Body = open-to-close. Body is the ICT-textbook default - the material is explicit that the zone itself uses the body, even though the candle SELECTION looks at the full range.")
i_dedupe = input.bool(true, "Avoid duplicate zones", group = g_det, tooltip = "Do not draw a new breaker on top of an existing valid one of the same direction. Cuts stacked near-identical zones.")
i_maxBrk = input.int(5, "Max breakers to track", minval = 1, maxval = 60, group = g_det)
i_zoneExt = input.int(40, "Zone extension (bars)", minval = 0, group = g_det)
i_lookMax = input.int(50, "Detection lookback (bars)", minval = 10, maxval = 200, group = g_det)
i_sizeOn = input.bool(false, "Filter by zone size", group = g_det, tooltip = "Only keep breaker zones within the min/max point range below.")
i_minSize = input.float(0.0, "Min zone size (points)", minval = 0.0, group = g_det, tooltip = "Drop zones smaller than this. Cuts tiny noise zones.")
i_maxSize = input.float(0.0, "Max zone size (points)", minval = 0.0, group = g_det, tooltip = "Drop zones larger than this. 0 = no maximum.")
i_invMode = input.string("Zone edge", "Invalidation", options = ["Zone edge", "Swing extreme"], group = g_det, tooltip = "Zone edge = kill the breaker when price closes back through the zone. Swing extreme = keep it alive until price closes beyond the swing made between the sweep and the activation (deeper).")
g_mit = "🔁 Mitigation Block"
i_mitOn = input.bool(true, "Enable Mitigation detection", group = g_mit, tooltip = "Same sweep -> structure-shift -> anchor-candle -> retest mechanics as Breaker, but tuned to catch the minor, constantly-repeating intraday swing failures (ICT's 'M pattern') instead of major one-time structure. Runs independently of Breaker above; both can fire on the same chart.")
i_mitPivLeft = input.int(3, "Pivot strength (left)", minval = 1, group = g_mit, tooltip = "Deliberately tighter than Breaker's default (5/5) so it reacts to minor swing highs/lows - that's what makes it catch the repeating intraday pattern instead of only major structure.")
i_mitPivRight = input.int(3, "Pivot strength (right)", minval = 1, group = g_mit)
i_mitSweepOn = input.bool(true, "Require liquidity sweep", group = g_mit)
i_mitMssClose = input.bool(true, "Require body close for MSS", group = g_mit)
i_mitAnchor = input.string("Candle body", "Zone anchor", options = ["Candle range", "Candle body"], group = g_mit)
i_mitDedupe = input.bool(true, "Avoid duplicate zones", group = g_mit)
i_mitMaxZones = input.int(6, "Max mitigation zones to track", minval = 1, maxval = 60, group = g_mit, tooltip = "Higher than Breaker's default since these form more often.")
i_mitZoneExt = input.int(25, "Zone extension (bars)", minval = 0, group = g_mit)
i_mitLookMax = input.int(30, "Detection lookback (bars)", minval = 5, maxval = 200, group = g_mit)
i_mitRearm = input.bool(true, "Allow zone re-entry", group = g_mit)
i_mitMaxFires = input.int(1, "Max entries per zone", minval = 1, maxval = 5, group = g_mit, tooltip = "Default 1 (single-shot per zone, same discipline as a breaker) - the frequent, both-directions feel comes from how often a NEW minor M-pattern forms with tighter pivots, not from replaying the same zone.")
bool i_mitBuyOn = false
bool i_mitSellOn = false
i_mitBullFill = input.color(color.new(#29B6F6, 86), "Mit bull fill", group = g_mit, inline = "m1")
i_mitBullBrd = input.color(color.new(#29B6F6, 25), "border", group = g_mit, inline = "m1")
i_mitBearFill = input.color(color.new(#EC407A, 86), "Mit bear fill", group = g_mit, inline = "m2")
i_mitBearBrd = input.color(color.new(#EC407A, 25), "border", group = g_mit, inline = "m2")
i_mitLblOn = input.bool(true, "Show zone labels", group = g_mit)
i_mitLblBull = input.color(#29B6F6, "Mit bull label text", group = g_mit, inline = "mlt")
i_mitLblBear = input.color(#EC407A, "Mit bear label text", group = g_mit, inline = "mlt")
bool i_uniOn = false
string i_uniMode = "HTF FVG"
string i_uniHtfTF = "15"
string i_uniEntry = "Overlap pocket"
int i_fvgWin = 30
i_reaperOn = input.bool(true, "Detect Reaper Inversion FVG", group = g_reap, tooltip = "The ICT Reaper PD Array: a fair value gap sitting within the breaker's own impulsive leg (the sweep-to-MSS move), located in discount (bullish breaker) or premium (bearish breaker) relative to that leg's range. The gap must be inside the leg AND on the cheap / expensive side of it.")
i_reapMinDist = input.float(0.0, "Min distance beyond equilibrium (0-0.5, x leg range)", minval = 0.0, maxval = 0.5, step = 0.05, group = g_reap, tooltip = "0 = the FVG just needs to be on the correct side of the leg's 50%. Higher = require it further into discount/premium (e.g. 0.2 = at least 20% of the leg's range beyond eq).")
bool i_reapPriority = false
i_reapCol = input.color(color.new(#7C4DFF, 70), "Reaper fill", inline = "rp", group = g_reap)
i_reapBrd = input.color(color.new(#7C4DFF, 15), "border", inline = "rp", group = g_reap)
float i_fvgMin = 0.0
string i_filter = "Show all"
bool i_buyOn = false
bool i_sellOn = false
string i_retest = "Close inside"
bool i_rearm = true
int i_maxFires = 2
bool i_cdOn = true
int i_cd = 5
float i_slBuf = 2.0
string i_tpMode = "R multiple"
int i_numTP = 3
float i_rrStep = 1.0
int i_atrLen = 14
float i_atrMult = 1.5
float i_ptStep = 20.0
int i_maxTrades = 3
bool i_showTP = false
int i_tpMaxAge = 90
bool i_ceOn = false
i_sessOn = input.bool(false, "Restrict to sessions", group = g_sess, tooltip = "When ON, a breaker is only plotted if it confirms inside one of the enabled killzones below. All times New York (ET).")
i_kzLDN = input.bool(true, "London killzone", group = g_sess, inline = "ldn")
i_ldnSess = input.session("0200-0500", "", group = g_sess, inline = "ldn")
i_kzAM = input.bool(true, "NY AM killzone", group = g_sess, inline = "am")
i_amSess = input.session("0700-1000", "", group = g_sess, inline = "am")
i_kzPM = input.bool(true, "NY PM killzone", group = g_sess, inline = "pm")
i_pmSess = input.session("1330-1600", "", group = g_sess, inline = "pm")
i_confMode = input.string("Tag", "HTF confluence", options = ["Off", "Tag", "Filter"], group = g_htf, tooltip = "Tag = mark which breakers align with the higher timeframe (hides nothing). Filter = only show/trade aligned breakers. Off = ignore.")
i_confTF = input.timeframe("15", "HTF confluence timeframe", group = g_htf)
i_confWay = input.string("EMA", "Alignment method", options = ["EMA", "Structure"], group = g_htf, tooltip = "EMA = price on the correct side of the HTF EMA (clean, steady). Structure = HTF making higher highs/lows (bull) or lower highs/lows (bear); purer but choppier.")
i_confEma = input.int(50, "HTF EMA length", minval = 1, group = g_htf)
i_bullFill = input.color(color.new(#1FA85A, 86), "Bull breaker fill", group = g_vis, inline = "b1")
i_bullBrd = input.color(color.new(#1FA85A, 25), "border", group = g_vis, inline = "b1")
i_bearFill = input.color(color.new(#E24B4A, 86), "Bear breaker fill", group = g_vis, inline = "b2")
i_bearBrd = input.color(color.new(#E24B4A, 25), "border", group = g_vis, inline = "b2")
color i_uniBrd = color.new(#FFD600, 0)
color i_doneCol = color.new(color.gray, 45)
i_borderW = input.int(1, "Zone border thickness", minval = 1, maxval = 5, group = g_vis)
i_lblOn = input.bool(true, "Show zone labels", group = g_vis)
i_lblBull = input.color(#1FA85A, "Bull label text", group = g_vis, inline = "lt")
i_lblBear = input.color(#E24B4A, "Bear label text", group = g_vis, inline = "lt")
i_dashOn = input.bool(true, "Show dashboard", group = g_dash)
i_dashPos = input.string("Middle Right", "Position", options = ["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"], group = g_dash)
i_dashSz = input.string("Small", "Size", options = ["Tiny", "Small", "Normal"], group = g_dash)
i_brkOn = input.bool(true, "Enable Breaker detection", group = g_cln, tooltip = "OFF = no new breakers (existing ones finish their life). Use it to look at only order blocks and mitigations.")
i_starMode = input.string("Test count", "Stars show", options = ["Test count", "Quality grade"], group = g_cln, tooltip = "Test count = every star starts hollow and turns solid each time price comes back to test the zone (5 max). Quality grade = solid stars for the confluences the zone formed with: Order Block 0-4 (FVG in the leg, liquidity sweep, HTF aligned, in discount/premium), Breaker/Mitigation 0-3 (unicorn, HTF aligned, Reaper). Note: in ICT terms a fresh, untested zone is usually the strongest - a zone with many tests has had its orders used up.")
i_lblMode = input.string("Compact", "Zone label detail", options = ["Compact", "Full"], group = g_cln, tooltip = "Compact = name and stars only. Full also adds * (unicorn), REAPER and HTF tags.")
i_lblSz = input.string("Small", "Zone label size", options = ["Tiny", "Small", "Normal"], group = g_cln)
i_starsOn = input.bool(false, "Show test / grade stars in zone text", group = g_cln, tooltip = "OFF (default) = the zone text is just the name, e.g. Bullish Breaker. ON = adds the star row set by 'Stars show' (printed as * and -).")
i_txtPos = input.string("Bottom", "Zone text position (far right of box)", options = ["Bottom", "Middle", "Top"], group = g_cln)
i_tipOn = input.bool(false, "Hover info dots on zones", group = g_cln, tooltip = "Puts a small i on every zone (and on the purple Reaper bar). Hover it to read what the zone is, how many times it was tested and how to use it.")
i_txtStack = input.bool(true, "Offset zone text when zones stack", group = g_cln, tooltip = "When two or more zones sit at about the same price, their names would print on top of each other. ON = the first keeps the far right, the next moves to the middle of the box, the next to the left side.")
i_txtGap = input.float(2.0, "Stack distance (x ATR)", minval = 0.0, step = 0.5, group = g_cln, tooltip = "Zone texts closer than this many ATRs in price count as stacked. Raise it if names still touch, lower it if they offset too eagerly.")
i_dimTested = input.bool(false, "Fade a zone a little with each test", group = g_cln)
i_zoneMaxAge = input.int(400, "Remove zones older than N bars (0 = never)", minval = 0, maxval = 5000, group = g_cln, tooltip = "Zones that never got invalidated still disappear after this many bars so old levels do not pile up.")
i_obOn = input.bool(true, "Enable Order Blocks", group = g_ob)
i_obDisp = input.float(1.0, "Displacement (x ATR body)", minval = 0.0, step = 0.1, group = g_ob, tooltip = "The move that breaks structure must contain a candle body at least this many ATRs (looks at the break candle and the two before it). 0 = no displacement needed. Raise it for fewer, stronger blocks.")
i_obLook = input.int(30, "Detection lookback (bars)", minval = 5, maxval = 200, group = g_ob)
i_obAnchor = input.string("Candle body", "Zone anchor", options = ["Candle range", "Candle body"], group = g_ob)
i_obMax = input.int(5, "Max order blocks to track", minval = 1, maxval = 40, group = g_ob)
i_obExt = input.int(40, "Zone extension (bars)", minval = 0, group = g_ob)
i_obDedupe = input.bool(true, "Avoid duplicate zones", group = g_ob)
i_obStyle = input.string("Dashed", "Box border style", options = ["Dashed", "Dotted", "Solid"], group = g_ob, tooltip = "Dashed keeps order blocks visually different from the solid breaker and mitigation boxes.")
i_obLblOn = input.bool(true, "Show zone labels", group = g_ob)
i_obBullFill = input.color(color.new(#00BFA5, 86), "Bull OB fill", group = g_ob, inline = "o1")
i_obBullBrd = input.color(color.new(#00BFA5, 25), "border", group = g_ob, inline = "o1")
i_obBearFill = input.color(color.new(#FF7043, 86), "Bear OB fill", group = g_ob, inline = "o2")
i_obBearBrd = input.color(color.new(#FF7043, 25), "border", group = g_ob, inline = "o2")
i_obLblBull = input.color(#00BFA5, "Bull OB label text", group = g_ob, inline = "olt")
i_obLblBear = input.color(#FF7043, "Bear OB label text", group = g_ob, inline = "olt")
// =====================================================================
// TYPES
// =====================================================================
type Breaker
box bx
line ce
label lb
float top
float bot
bool bull
bool uni
bool trig
bool valid
bool armed
int fires
float swing
float pkTop
float pkBot
int bornBar
bool reaper
float reapTop
float reapBot
box reapBx
int kind
int grade
int gmax
bool aligned
int tests
bool inside
color fillC
float baseTr
type Trade
bool bull
float entry
float sl
array<float> tps
line eLn
line sLn
label eLb
label sLb
array<line> tpLn
array<label> tpLb
int hits
bool done
bool won
int bornBar
int doneBar
var array<Breaker> brks = array.new<Breaker>()
var array<Breaker> mits = array.new<Breaker>()
var array<Breaker> obs = array.new<Breaker>()
var array<Trade> trades = array.new<Trade>()
// =====================================================================
// HELPERS
// =====================================================================
f_dpos() =>
i_dashPos == "Top Right" ? position.top_right : i_dashPos == "Top Center" ? position.top_center : i_dashPos == "Top Left" ? position.top_left : i_dashPos == "Middle Right" ? position.middle_right : i_dashPos == "Middle Center" ? position.middle_center : i_dashPos == "Middle Left" ? position.middle_left : i_dashPos == "Bottom Right" ? position.bottom_right : i_dashPos == "Bottom Center" ? position.bottom_center : position.bottom_left
f_dsz() => i_dashSz == "Tiny" ? size.tiny : i_dashSz == "Normal" ? size.normal : size.small
f_bstyle() => i_obStyle == "Dashed" ? line.style_dashed : i_obStyle == "Dotted" ? line.style_dotted : line.style_solid
f_zsz() => i_lblSz == "Tiny" ? size.tiny : i_lblSz == "Normal" ? size.normal : size.small
f_stars(int filled, int total) =>
int f = math.max(0, math.min(filled, total))
string onS = "*"
string offS = "-"
str.repeat(onS, f) + str.repeat(offS, total - f)
f_zoneLbl(Breaker b) =>
string nm = b.kind == 2 ? (b.bull ? "Bullish Order Block" : "Bearish Order Block") : b.kind == 1 ? (b.bull ? "Bullish Mitigation" : "Bearish Mitigation") : (b.bull ? "Bullish Breaker" : "Bearish Breaker")
bool tm = i_starMode == "Test count"
string s = nm
if i_starsOn
s := s + " " + f_stars(tm ? b.tests : b.grade, tm ? 5 : b.gmax)
if i_lblMode == "Full"
s := s + (b.uni ? " *" : "") + (b.reaper ? " REAPER" : "") + (i_confMode == "Tag" and b.aligned ? " HTF" : "")
if i_starsOn and not tm and b.tests > 0
s := s + " - tested " + str.tostring(b.tests) + "x"
s
f_tip(Breaker b) =>
string nm = b.kind == 2 ? (b.bull ? "Bullish Order Block" : "Bearish Order Block") : b.kind == 1 ? (b.bull ? "Bullish Mitigation Block" : "Bearish Mitigation Block") : (b.bull ? "Bullish Breaker" : "Bearish Breaker")
string how = b.bull ? "Look for LONGS on a retest into it." : "Look for SHORTS on a retest into it."
string what = ""
if b.kind == 2
what := "Last opposite candle before a strong displacement that broke structure. Institutions left orders there. Fresh = strongest, every retest weakens it, and a close through it kills it. Grade counts: FVG left behind, liquidity sweep first, HTF trend aligned, discount (bull) or premium (bear) location."
else if b.kind == 1
what := "A tighter, smaller-pivot version of a breaker: price failed to make a new extreme, broke structure the other way, and the last opposing candle flips its role. Earlier but weaker than a full breaker."
else
what := "A failed order block: price swept liquidity, broke structure the other way (MSS) and closed through the old block, so it flips role. Old " + (b.bull ? "resistance now acts as support." : "support now acts as resistance.")
string t = nm + "\n" + what + "\n" + how + " Confirm with your levels, skip it if price already ran through the middle."
t := t + "\nTests so far: " + str.tostring(b.tests) + " (fewer = stronger)"
if b.uni
t := t + "\nYellow border = UNICORN: overlaps a higher-timeframe FVG, the highest quality tier."
if b.reaper
t := t + "\nPURPLE BAR = REAPER FVG: a fair value gap inside the sweep-to-MSS leg, on the cheap side (discount for bulls, premium for bears). It is the tightest entry pocket in the zone."
t
f_zval() => i_txtPos == "Top" ? text.align_top : i_txtPos == "Middle" ? text.align_center : text.align_bottom
// writes the zone name as plain text inside the box, far right (no label object)
f_setZoneText(Breaker b) =>
bool on = b.kind == 2 ? i_obLblOn : b.kind == 1 ? i_mitLblOn : i_lblOn
color tc = b.kind == 2 ? (b.bull ? i_obLblBull : i_obLblBear) : b.kind == 1 ? (b.bull ? i_mitLblBull : i_mitLblBear) : (b.bull ? i_lblBull : i_lblBear)
if not na(b.bx)
box.set_text(b.bx, on ? f_zoneLbl(b) : "")
box.set_text_color(b.bx, tc)
box.set_text_size(b.bx, f_zsz())
box.set_text_halign(b.bx, text.align_right)
box.set_text_valign(b.bx, f_zval())
if i_tipOn
float ty = b.reaper and not na(b.reapTop) and not na(b.reapBot) ? (b.reapTop + b.reapBot) / 2.0 : (b.top + b.bot) / 2.0
if na(b.lb)
b.lb := label.new(box.get_left(b.bx), ty, "i", xloc = xloc.bar_index, style = label.style_label_center, color = color.new(#38B6FF, 35), textcolor = color.white, size = size.tiny, tooltip = f_tip(b))
if not na(b.lb)
label.set_tooltip(b.lb, f_tip(b))
f_anchor(Breaker z) => i_txtPos == "Top" ? z.top : i_txtPos == "Middle" ? (z.top + z.bot) / 2.0 : z.bot
f_collect(array<Breaker> src, array<Breaker> dst) =>
int n = array.size(src)
if n > 0
for i = 0 to n - 1
Breaker z = array.get(src, i)
if z.valid and not na(z.bx)
array.push(dst, z)
// counts a new test each time price comes back into the zone from outside
f_testZone(Breaker b) =>
bool hit = false
if bar_index > b.bornBar
bool ov = b.bull ? low <= b.top : high >= b.bot
if ov and not b.inside
b.tests += 1
hit := true
b.inside := ov
hit
f_applyTests(Breaker b) =>
if i_starsOn
f_setZoneText(b)
if i_dimTested and not na(b.bx)
box.set_bgcolor(b.bx, color.new(b.fillC, math.min(97, b.baseTr + b.tests * 5)))
f_bullBreaker(int win) =>
int lowOff = 0
float lo = low[0]
for k = 1 to win
if k < bar_index and low[k] < lo
lo := low[k]
lowOff := k
int idx = -1
for k = lowOff to win
if idx == -1 and k < bar_index and close[k] > open[k]
idx := k
idx
f_bearBreaker(int win) =>
int hiOff = 0
float hi = high[0]
for k = 1 to win
if k < bar_index and high[k] > hi
hi := high[k]
hiOff := k
int idx = -1
for k = hiOff to win
if idx == -1 and k < bar_index and close[k] < open[k]
idx := k
idx
f_fvgOverlap(bool bull, float zt, float zb) =>
bool found = false
for k = 0 to i_fvgWin
if not found and (k + 2) < bar_index
if bull
float lo = high[k + 2]
float hi = low[k]
if hi > lo and (hi - lo) >= i_fvgMin and not (hi < zb or lo > zt)
found := true
else
float lo = high[k]
float hi = low[k + 2]
if hi > lo and (hi - lo) >= i_fvgMin and not (hi < zb or lo > zt)
found := true
found
f_dupZone(array<Breaker> arr, bool bull, float zt, float zb) =>
bool dup = false
int n = array.size(arr)
if n > 0
for i = 0 to n - 1
Breaker b = array.get(arr, i)
if b.valid and b.bull == bull and not (zt < b.bot or zb > b.top)
dup := true
dup
f_inSess(string s) => not na(time(timeframe.period, s, TZ))
f_inAnySession() => not i_sessOn or (i_kzLDN and f_inSess(i_ldnSess)) or (i_kzAM and f_inSess(i_amSess)) or (i_kzPM and f_inSess(i_pmSess))
float atrVal = ta.atr(i_atrLen)
// =====================================================================
// HTF FVG (internal, for unicorn HTF mode - not drawn)
// Tracks the most-recent unfilled higher-TF bull and bear FVG.
// =====================================================================
float htfH1 = na
float htfL1 = na
float htfH3 = na
float htfL3 = na
bool newHtfFvg = false
var float htfBullTop = na
var float htfBullBot = na
var float htfBearTop = na
var float htfBearBot = na
if newHtfFvg and not na(htfH3) and not na(htfL1)
// bull FVG: prev htf low above the htf high 3 bars back - now also
// checks i_fvgMin, same as the other two unicorn modes already did.
// Previously this was the only one of the three that skipped the size
// filter entirely, so a 1-tick HTF gap counted the same as a real one.
if htfL1 > htfH3 and (htfL1 - htfH3) >= i_fvgMin
htfBullTop := htfL1
htfBullBot := htfH3
// bear FVG: prev htf high below the htf low 3 bars back
if htfH1 < htfL3 and (htfL3 - htfH1) >= i_fvgMin
htfBearTop := htfL3
htfBearBot := htfH1
// mitigate (clear) once price fully trades through
if not na(htfBullBot) and low < htfBullBot
htfBullTop := na
htfBullBot := na
if not na(htfBearTop) and high > htfBearTop
htfBearTop := na
htfBearBot := na
// =====================================================================
// HTF CONFLUENCE (alignment read on the HTF)
// =====================================================================
float htfEma = request.security(syminfo.tickerid, i_confTF, ta.ema(close, i_confEma), lookahead = barmerge.lookahead_off)
[cH, cL] = request.security(syminfo.tickerid, i_confTF, [high, low], lookahead = barmerge.lookahead_off)
bool htfStructBull = not na(cH) and not na(cH[1]) and cH > cH[1] and cL > cL[1]
bool htfStructBear = not na(cH) and not na(cH[1]) and cH < cH[1] and cL < cL[1]
f_confOk(bool bull) =>
bool ok = true
if i_confMode != "Off"
if i_confWay == "EMA"
ok := na(htfEma) ? true : (bull ? close > htfEma : close < htfEma)
else
ok := bull ? htfStructBull : htfStructBear
ok
// =====================================================================
// UNICORN (3 modes) -> returns [isUnicorn, pocketTop, pocketBot]
// =====================================================================
f_unicorn(bool bull, float zt, float zb, int win) =>
bool isU = false
float pt = na
float pb = na
if i_uniOn
if i_uniMode == "HTF FVG"
float ft = bull ? htfBullTop : htfBearTop
float fb = bull ? htfBullBot : htfBearBot
if not na(ft) and not na(fb) and not (zt < fb or zb > ft)
isU := true
pt := math.min(zt, ft)
pb := math.max(zb, fb)
else
int w = i_uniMode == "Chart-TF displacement" ? math.max(3, win) : i_fvgWin
for k = 0 to w
if not isU and (k + 2) < bar_index
float lo = bull ? high[k + 2] : high[k]
float hi = bull ? low[k] : low[k + 2]
if hi > lo and (hi - lo) >= i_fvgMin and not (hi < zb or lo > zt)
isU := true
pt := math.min(zt, hi)
pb := math.max(zb, lo)
[isU, pt, pb]
f_reaperFvg(bool bull, int legBars, float sweepLvl) =>
bool found = false
float rTop = na
float rBot = na
float legOpp = bull ? high[legBars] : low[legBars]
for i = 0 to legBars
if bull
legOpp := math.max(legOpp, high[i])
else
legOpp := math.min(legOpp, low[i])
if i_reaperOn and legBars >= 3
for i = 1 to legBars - 2
if not found
if bull and low[i] > high[i + 2]
found := true
rTop := low[i]
rBot := high[i + 2]
else if not bull and high[i] < low[i + 2]
found := true
rTop := low[i + 2]
rBot := high[i]
bool okZone = false
if found
float legHi = bull ? legOpp : sweepLvl
float legLo = bull ? sweepLvl : legOpp
float rng = legHi - legLo
float eq = (legHi + legLo) / 2.0
float fvgMid = (rTop + rBot) / 2.0
okZone := rng > 0 and (bull ? fvgMid < eq - i_reapMinDist * rng : fvgMid > eq + i_reapMinDist * rng)
bool ok = found and okZone
[ok, ok ? rTop : na, ok ? rBot : na]
// =====================================================================
// PIVOT + SWEEP STATE
// =====================================================================
float ph = ta.pivothigh(i_pivLeft, i_pivRight)
float pl = ta.pivotlow(i_pivLeft, i_pivRight)
var float lastPH = na
var float lastPL = na
if not na(ph)
lastPH := ph
if not na(pl)
lastPL := pl
var bool sweptLow = false
var bool sweptHigh = false
var float sweepLoLvl = na
var float sweepHiLvl = na
if not na(lastPL) and low < lastPL
sweepLoLvl := sweptLow ? math.min(sweepLoLvl, low) : low
sweptLow := true
if not na(lastPH) and high > lastPH
sweepHiLvl := sweptHigh ? math.max(sweepHiLvl, high) : high
sweptHigh := true
bool sweepOkBull = not i_sweepOn or sweptLow
bool sweepOkBear = not i_sweepOn or sweptHigh
bool snapSweptLow = sweptLow
bool snapSweptHigh = sweptHigh
// =====================================================================
// BREAKER DETECTION
// =====================================================================
var int lastTrigBar = na
f_addBreaker(bool bull, float zt, float zb, float swing, int obOff) =>
bool sizeBad = i_sizeOn and ((zt - zb) < i_minSize or (i_maxSize > 0 and (zt - zb) > i_maxSize))
bool confBad = i_confMode == "Filter" and not f_confOk(bull)
bool skip = (i_dedupe and f_dupZone(brks, bull, zt, zb)) or not f_inAnySession() or sizeBad or confBad
if not skip
int leftX = bar_index - obOff
int rt = bar_index + i_zoneExt
color fill = bull ? i_bullFill : i_bearFill
color brd = bull ? i_bullBrd : i_bearBrd
[uni, pkT, pkB] = f_unicorn(bull, zt, zb, obOff)
[rp, rTop, rBot] = f_reaperFvg(bull, obOff, swing)
bool aligned = f_confOk(bull)
bool show = i_filter == "Show all" or uni
box nb = na
line nc = na
label nl = na
box rb = na
if show
nb := box.new(leftX, zt, rt, zb, border_color = uni ? i_uniBrd : brd, border_width = uni ? i_borderW + 1 : i_borderW, bgcolor = fill)
if i_ceOn
float mid = (zt + zb) / 2.0
nc := line.new(leftX, mid, rt, mid, color = color.new(color.gray, 35), style = line.style_dotted, width = 1)
if rp
rb := box.new(bar_index - obOff, rTop, rt, rBot, xloc = xloc.bar_index, bgcolor = i_reapCol, border_color = i_reapBrd, border_width = 1, text = "Reaper FVG", text_size = size.tiny, text_color = color.white, text_halign = text.align_left)
Breaker b = Breaker.new(nb, nc, nl, zt, zb, bull, uni, false, true, true, 0, swing, pkT, pkB, bar_index, rp, rTop, rBot, rb, 0, (uni ? 1 : 0) + ((i_confMode != "Off" and aligned) ? 1 : 0) + (rp ? 1 : 0), 3, i_confMode != "Off" and aligned, 0, false, fill, color.t(fill))
f_setZoneText(b)
array.push(brks, b)
while array.size(brks) > i_maxBrk
Breaker old = array.shift(brks)
if not na(old.bx)
box.delete(old.bx)
if not na(old.ce)
line.delete(old.ce)
if not na(old.lb)
label.delete(old.lb)
if not na(old.reapBx)
box.delete(old.reapBx)
f_addMitigation(bool bull, float zt, float zb, float swing, int obOff) =>
bool sizeBad = i_sizeOn and ((zt - zb) < i_minSize or (i_maxSize > 0 and (zt - zb) > i_maxSize))
bool confBad = i_confMode == "Filter" and not f_confOk(bull)
bool skip = (i_mitDedupe and f_dupZone(mits, bull, zt, zb)) or not f_inAnySession() or sizeBad or confBad
if not skip
int leftX = bar_index - obOff
int rt = bar_index + i_mitZoneExt
color fill = bull ? i_mitBullFill : i_mitBearFill
color brd = bull ? i_mitBullBrd : i_mitBearBrd
[uni, pkT, pkB] = f_unicorn(bull, zt, zb, obOff)
[rp, rTop, rBot] = f_reaperFvg(bull, obOff, swing)
bool aligned = f_confOk(bull)
bool show = i_filter == "Show all" or uni
box nb = na
line nc = na
label nl = na
box rb = na
if show
nb := box.new(leftX, zt, rt, zb, border_color = uni ? i_uniBrd : brd, border_width = uni ? i_borderW + 1 : i_borderW, bgcolor = fill)
if i_ceOn
float mid = (zt + zb) / 2.0
nc := line.new(leftX, mid, rt, mid, color = color.new(color.gray, 35), style = line.style_dotted, width = 1)
if rp
rb := box.new(bar_index - obOff, rTop, rt, rBot, xloc = xloc.bar_index, bgcolor = i_reapCol, border_color = i_reapBrd, border_width = 1, text = "Reaper FVG", text_size = size.tiny, text_color = color.white, text_halign = text.align_left)
Breaker b = Breaker.new(nb, nc, nl, zt, zb, bull, uni, false, true, true, 0, swing, pkT, pkB, bar_index, rp, rTop, rBot, rb, 1, (uni ? 1 : 0) + ((i_confMode != "Off" and aligned) ? 1 : 0) + (rp ? 1 : 0), 3, i_confMode != "Off" and aligned, 0, false, fill, color.t(fill))
f_setZoneText(b)
array.push(mits, b)
while array.size(mits) > i_mitMaxZones
Breaker old = array.shift(mits)
if not na(old.bx)
box.delete(old.bx)
if not na(old.ce)
line.delete(old.ce)
if not na(old.lb)
label.delete(old.lb)
if not na(old.reapBx)
box.delete(old.reapBx)
// =====================================================================
// ORDER BLOCKS
// =====================================================================
f_bullOB(int win) =>
int lowOff = 0
float lo = low[0]
for k = 1 to win
if k < bar_index and low[k] < lo
lo := low[k]
lowOff := k
int idx = -1
for k = lowOff to win
if idx == -1 and k < bar_index and close[k] < open[k]
idx := k
[idx, lowOff]
f_bearOB(int win) =>
int hiOff = 0
float hi = high[0]
for k = 1 to win
if k < bar_index and high[k] > hi
hi := high[k]
hiOff := k
int idx = -1
for k = hiOff to win
if idx == -1 and k < bar_index and close[k] > open[k]
idx := k
[idx, hiOff]
f_obFvg(bool bull, int span) =>
bool found = false
for k = 0 to math.max(span - 2, 0)
if not found and (k + 2) < bar_index
if bull
found := low[k] > high[k + 2]
else
found := high[k] < low[k + 2]
found
f_addOB(bool bull, float zt, float zb, int obOff, int extOff, bool swept) =>
bool sizeBad = i_sizeOn and ((zt - zb) < i_minSize or (i_maxSize > 0 and (zt - zb) > i_maxSize))
bool confBad = i_confMode == "Filter" and not f_confOk(bull)
bool skip = (i_obDedupe and f_dupZone(obs, bull, zt, zb)) or not f_inAnySession() or sizeBad or confBad
if not skip
float hiLeg = high[0]
float loLeg = low[0]
for k = 0 to extOff
hiLeg := math.max(hiLeg, high[k])
loLeg := math.min(loLeg, low[k])
float mid = (zt + zb) / 2.0
float eq = (hiLeg + loLeg) / 2.0
bool htfOk = i_confMode != "Off" and f_confOk(bull)
bool fvgOk = f_obFvg(bull, obOff)
bool inDisc = bull ? mid < eq : mid > eq
int grade = (fvgOk ? 1 : 0) + (swept ? 1 : 0) + (htfOk ? 1 : 0) + (inDisc ? 1 : 0)
int leftX = bar_index - obOff
int rt = bar_index + i_obExt
color fill = bull ? i_obBullFill : i_obBearFill
color brd = bull ? i_obBullBrd : i_obBearBrd
box nb = box.new(leftX, zt, rt, zb, border_color = brd, border_width = i_borderW, border_style = f_bstyle(), bgcolor = fill)
line nc = na
label nl = na
box rb = na
float nf = na
Breaker b = Breaker.new(nb, nc, nl, zt, zb, bull, false, false, true, true, 0, nf, nf, nf, bar_index, false, nf, nf, rb, 2, grade, 4, htfOk, 0, false, fill, color.t(fill))
f_setZoneText(b)
array.push(obs, b)
while array.size(obs) > i_obMax
Breaker old = array.shift(obs)
if not na(old.bx)
box.delete(old.bx)
if not na(old.lb)
label.delete(old.lb)
// =====================================================================
// MITIGATION DETECTION
// =====================================================================
float mph = ta.pivothigh(i_mitPivLeft, i_mitPivRight)
float mpl = ta.pivotlow(i_mitPivLeft, i_mitPivRight)
var float lastMPH = na
var float lastMPL = na
if not na(mph)
lastMPH := mph
if not na(mpl)
lastMPL := mpl
var bool sweptLowM = false
var bool sweptHighM = false
var float sweepLoLvlM = na
var float sweepHiLvlM = na
if not na(lastMPL) and low < lastMPL
sweepLoLvlM := sweptLowM ? math.min(sweepLoLvlM, low) : low
sweptLowM := true
if not na(lastMPH) and high > lastMPH
sweepHiLvlM := sweptHighM ? math.max(sweepHiLvlM, high) : high
sweptHighM := true
bool sweepOkBullM = not i_mitSweepOn or sweptLowM
bool sweepOkBearM = not i_mitSweepOn or sweptHighM
bool mitCloseUpEdge = close > lastMPH and not (close[1] > lastMPH)
bool mitWickUpEdge = high > lastMPH and not (high[1] > lastMPH)
bool mssBullMit = i_mitOn and sweepOkBullM and not na(lastMPH) and (i_mitMssClose ? mitCloseUpEdge : mitWickUpEdge)
if mssBullMit and barstate.isconfirmed
int mdi = f_bullBreaker(i_mitLookMax)
if mdi >= 0
float mct = i_mitAnchor == "Candle body" ? math.max(open[mdi], close[mdi]) : high[mdi]
float mcb = i_mitAnchor == "Candle body" ? math.min(open[mdi], close[mdi]) : low[mdi]
if mct > mcb
f_addMitigation(true, mct, mcb, sweepLoLvlM, mdi)
sweptLowM := false
bool mitCloseDnEdge = close < lastMPL and not (close[1] < lastMPL)
bool mitWickDnEdge = low < lastMPL and not (low[1] < lastMPL)
bool mssBearMit = i_mitOn and sweepOkBearM and not na(lastMPL) and (i_mitMssClose ? mitCloseDnEdge : mitWickDnEdge)
if mssBearMit and barstate.isconfirmed
int mui = f_bearBreaker(i_mitLookMax)
if mui >= 0
float mct = i_mitAnchor == "Candle body" ? math.max(open[mui], close[mui]) : high[mui]
float mcb = i_mitAnchor == "Candle body" ? math.min(open[mui], close[mui]) : low[mui]
if mct > mcb
f_addMitigation(false, mct, mcb, sweepHiLvlM, mui)
sweptHighM := false
bool closeUpEdge = close > lastPH and not (close[1] > lastPH)
bool wickUpEdge = high > lastPH and not (high[1] > lastPH)
bool mssBull = i_brkOn and sweepOkBull and not na(lastPH) and (i_mssClose ? closeUpEdge : wickUpEdge)
if mssBull and barstate.isconfirmed
int di = f_bullBreaker(i_lookMax)
if di >= 0
float ct = i_anchor == "Candle body" ? math.max(open[di], close[di]) : high[di]
float cb = i_anchor == "Candle body" ? math.min(open[di], close[di]) : low[di]
if ct > cb
f_addBreaker(true, ct, cb, sweepLoLvl, di)
sweptLow := false
bool closeDnEdge = close < lastPL and not (close[1] < lastPL)
bool wickDnEdge = low < lastPL and not (low[1] < lastPL)
bool mssBear = i_brkOn and sweepOkBear and not na(lastPL) and (i_mssClose ? closeDnEdge : wickDnEdge)
if mssBear and barstate.isconfirmed
int ui = f_bearBreaker(i_lookMax)
if ui >= 0
float ct = i_anchor == "Candle body" ? math.max(open[ui], close[ui]) : high[ui]
float cb = i_anchor == "Candle body" ? math.min(open[ui], close[ui]) : low[ui]
if ct > cb
f_addBreaker(false, ct, cb, sweepHiLvl, ui)
sweptHigh := false
// ---- order block detection: structure break + displacement
bool obBosBull = i_obOn and not na(lastPH) and close > lastPH and not (close[1] > lastPH)
bool obBosBear = i_obOn and not na(lastPL) and close < lastPL and not (close[1] < lastPL)
float obBody = math.max(math.abs(close - open), math.max(math.abs(close[1] - open[1]), math.abs(close[2] - open[2])))
bool obDispOk = i_obDisp <= 0 or (not na(obBody) and not na(atrVal) and obBody >= i_obDisp * atrVal)
if obBosBull and obDispOk and barstate.isconfirmed
[obi, obx] = f_bullOB(i_obLook)
if obi >= 0
float oct = i_obAnchor == "Candle body" ? math.max(open[obi], close[obi]) : high[obi]
float ocb = i_obAnchor == "Candle body" ? math.min(open[obi], close[obi]) : low[obi]
if oct > ocb
f_addOB(true, oct, ocb, obi, obx, snapSweptLow)
if obBosBear and obDispOk and barstate.isconfirmed
[obj, obw] = f_bearOB(i_obLook)
if obj >= 0
float oct2 = i_obAnchor == "Candle body" ? math.max(open[obj], close[obj]) : high[obj]
float ocb2 = i_obAnchor == "Candle body" ? math.min(open[obj], close[obj]) : low[obj]
if oct2 > ocb2
f_addOB(false, oct2, ocb2, obj, obw, snapSweptHigh)
// =====================================================================
// TRADE CREATION
// =====================================================================
f_newTrade(bool bull, float entry, float sl) =>
int x1 = bar_index
int x2 = bar_index + i_zoneExt
float risk = math.abs(entry - sl)
line eLn = line.new(x1, entry, x2, entry, color = color.new(color.white, 0), style = line.style_solid, width = 1)
label eLb = label.new(x2, entry, (bull ? "LONG " : "SHORT ") + str.tostring(math.round_to_mintick(entry)), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(bull ? i_bullBrd : i_bearBrd, 0), textcolor = color.white, size = size.tiny)
line sLn = line.new(x1, sl, x2, sl, color = color.new(#E24B4A, 0), style = line.style_dashed, width = 1)
label sLb = label.new(x2, sl, "SL " + str.tostring(math.round_to_mintick(sl)), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(#E24B4A, 20), textcolor = color.white, size = size.tiny)
array<float> tps = array.new<float>()
array<line> tpLn = array.new<line>()
array<label> tpLb = array.new<label>()
for n = 1 to i_numTP
float tp = i_tpMode == "ATR" ? (bull ? entry + atrVal * i_atrMult * n : entry - atrVal * i_atrMult * n) : i_tpMode == "Points" ? (bull ? entry + i_ptStep * n : entry - i_ptStep * n) : (bull ? entry + risk * i_rrStep * n : entry - risk * i_rrStep * n)
array.push(tps, tp)
color tpLnCol = i_showTP ? color.new(#1FA85A, 20) : color.new(#1FA85A, 100)
color tpLbBg = i_showTP ? color.new(#1FA85A, 30) : color.new(#1FA85A, 100)
color tpLbTxt = i_showTP ? color.white : color.new(color.white, 100)
array.push(tpLn, line.new(x1, tp, x2, tp, color = tpLnCol, style = line.style_dashed, width = 1))
array.push(tpLb, label.new(x2, tp, "TP" + str.tostring(n) + " " + str.tostring(math.round_to_mintick(tp)), xloc = xloc.bar_index, style = label.style_label_left, color = tpLbBg, textcolor = tpLbTxt, size = size.tiny))
Trade t = Trade.new(bull, entry, sl, tps, eLn, sLn, eLb, sLb, tpLn, tpLb, 0, false, false, bar_index, na)
array.push(trades, t)
while array.size(trades) > i_maxTrades
Trade old = array.shift(trades)
line.delete(old.eLn)
line.delete(old.sLn)
label.delete(old.eLb)
label.delete(old.sLb)
int m = array.size(old.tpLn)
if m > 0
for q = 0 to m - 1
line.delete(array.get(old.tpLn, q))
label.delete(array.get(old.tpLb, q))
// =====================================================================
// TRADE LIFECYCLE
// =====================================================================
f_greyLockTrade(Trade t) =>
line.set_color(t.eLn, i_doneCol)
line.set_color(t.sLn, i_doneCol)
label.set_color(t.eLb, i_doneCol)
label.set_color(t.sLb, i_doneCol)
line.set_x2(t.eLn, bar_index)
line.set_x2(t.sLn, bar_index)
label.set_x(t.eLb, bar_index)
label.set_x(t.sLb, bar_index)
int m = array.size(t.tpLn)
if m > 0
for q = 0 to m - 1
if i_showTP
line.set_color(array.get(t.tpLn, q), i_doneCol)
label.set_color(array.get(t.tpLb, q), i_doneCol)
line.set_x2(array.get(t.tpLn, q), bar_index)
label.set_x(array.get(t.tpLb, q), bar_index)
int tradeRightX = bar_index + i_zoneExt
int nT = array.size(trades)
if nT > 0
for i = 0 to nT - 1
Trade t = array.get(trades, i)
if not t.done
line.set_x2(t.eLn, tradeRightX)
line.set_x2(t.sLn, tradeRightX)
label.set_x(t.eLb, tradeRightX)
label.set_x(t.sLb, tradeRightX)
int mt = array.size(t.tpLn)
if mt > 0
for q = 0 to mt - 1
line.set_x2(array.get(t.tpLn, q), tradeRightX)
label.set_x(array.get(t.tpLb, q), tradeRightX)
int nh = t.hits
int ntp = array.size(t.tps)
if ntp > 0
for q = 0 to ntp - 1
if nh == q
float tpq = array.get(t.tps, q)
bool reached = t.bull ? high >= tpq : low <= tpq
if reached
nh := q + 1
if i_showTP
line.set_color(array.get(t.tpLn, q), i_doneCol)
label.set_color(array.get(t.tpLb, q), i_doneCol)
t.hits := nh
bool stopped = t.bull ? low <= t.sl : high >= t.sl
bool won = t.hits >= array.size(t.tps)
if won
t.done := true
t.won := true
t.doneBar := bar_index
f_greyLockTrade(t)
else if stopped
t.done := true
t.won := false
t.doneBar := bar_index
f_greyLockTrade(t)
array.set(trades, i, t)
if i_tpMaxAge > 0
int nT2 = array.size(trades)
if nT2 > 0
for i = nT2 - 1 to 0
Trade t = array.get(trades, i)
if t.done and not na(t.doneBar) and (bar_index - t.doneBar) > i_tpMaxAge
line.delete(t.eLn)
line.delete(t.sLn)
label.delete(t.eLb)
label.delete(t.sLb)
int m2 = array.size(t.tpLn)
if m2 > 0
for q = 0 to m2 - 1
line.delete(array.get(t.tpLn, q))
label.delete(array.get(t.tpLb, q))
array.remove(trades, i)
// =====================================================================
// ZONE UPDATE
// =====================================================================
var string lastSig = ""
var bool buyNow = false
var bool sellNow = false
var bool uniBuy = false
var bool uniSell = false
buyNow := false
sellNow := false
uniBuy := false
uniSell := false
int rightX = bar_index + i_zoneExt
bool cdOk = not i_cdOn or na(lastTrigBar) or (bar_index - lastTrigBar) >= i_cd
int nB = array.size(brks)
if nB > 0
for i = 0 to nB - 1
Breaker b = array.get(brks, i)
if b.valid
if not na(b.bx)
box.set_right(b.bx, rightX)
if not na(b.ce)
line.set_x2(b.ce, rightX)
if not na(b.reapBx)
box.set_right(b.reapBx, rightX)
bool invBull = i_invMode == "Swing extreme" and not na(b.swing) ? close < b.swing : close < b.bot
bool invBear = i_invMode == "Swing extreme" and not na(b.swing) ? close > b.swing : close > b.top
bool aged = i_zoneMaxAge > 0 and (bar_index - b.bornBar) > i_zoneMaxAge
if (b.bull and invBull) or aged
b.valid := false
if not na(b.bx)
box.delete(b.bx)
if not na(b.ce)
line.delete(b.ce)
if not na(b.lb)
label.delete(b.lb)
if not na(b.reapBx)
box.delete(b.reapBx)
else if not b.bull and invBear
b.valid := false
if not na(b.bx)
box.delete(b.bx)
if not na(b.ce)
line.delete(b.ce)
if not na(b.lb)
label.delete(b.lb)
if not na(b.reapBx)
box.delete(b.reapBx)
else
if f_testZone(b)
f_applyTests(b)
if not b.armed and i_rearm
if (b.bull and close > b.top) or (not b.bull and close < b.bot)
b.armed := true
int maxFires = i_rearm ? i_maxFires : 1
bool canFire = b.armed and b.fires < maxFires
bool useReaper = i_reapPriority and b.reaper and not na(b.reapTop) and not na(b.reapBot)
bool usePocket = not useReaper and b.uni and i_uniEntry == "Overlap pocket" and not na(b.pkTop) and not na(b.pkBot)
float useTop = useReaper ? b.reapTop : usePocket ? b.pkTop : b.top
float useBot = useReaper ? b.reapBot : usePocket ? b.pkBot : b.bot
bool inZone = i_retest == "Wick touch" ? (low <= useTop and high >= useBot) : (close <= useTop and close >= useBot)
bool passFilter = i_filter == "Show all" or b.uni
if canFire and inZone and passFilter and cdOk
if b.bull and i_buyOn
b.trig := true
b.armed := false
b.fires := b.fires + 1
float entry = close
float sl = useBot - i_slBuf
f_newTrade(true, entry, sl)
buyNow := true
uniBuy := b.uni
lastTrigBar := bar_index
lastSig := (useReaper ? "BUY * REAPER @ " : b.uni ? "BUY * UNICORN @ " : "BUY @ ") + str.tostring(math.round_to_mintick(entry))
else if not b.bull and i_sellOn
b.trig := true
b.armed := false
b.fires := b.fires + 1
float entry = close
float sl = useTop + i_slBuf
f_newTrade(false, entry, sl)
sellNow := true
uniSell := b.uni
lastTrigBar := bar_index
lastSig := (useReaper ? "SELL * REAPER @ " : b.uni ? "SELL * UNICORN @ " : "SELL @ ") + str.tostring(math.round_to_mintick(entry))
array.set(brks, i, b)
// =====================================================================
// MITIGATION ZONE UPDATE
// =====================================================================
var string lastSigMit = ""
var bool mitBuyNow = false
var bool mitSellNow = false
var bool mitUniBuy = false
var bool mitUniSell = false
mitBuyNow := false
mitSellNow := false
mitUniBuy := false
mitUniSell := false
var int mitLastTrigBar = na
bool mitCdOk = not i_cdOn or na(mitLastTrigBar) or (bar_index - mitLastTrigBar) >= i_cd
int nM = array.size(mits)
if nM > 0
for i = 0 to nM - 1
Breaker b = array.get(mits, i)
if b.valid
if not na(b.bx)
box.set_right(b.bx, rightX)
if not na(b.ce)
line.set_x2(b.ce, rightX)
if not na(b.reapBx)
box.set_right(b.reapBx, rightX)
bool invBull = i_invMode == "Swing extreme" and not na(b.swing) ? close < b.swing : close < b.bot
bool invBear = i_invMode == "Swing extreme" and not na(b.swing) ? close > b.swing : close > b.top
bool aged = i_zoneMaxAge > 0 and (bar_index - b.bornBar) > i_zoneMaxAge
if (b.bull and invBull) or aged
b.valid := false
if not na(b.bx)
box.delete(b.bx)
if not na(b.ce)
line.delete(b.ce)
if not na(b.lb)
label.delete(b.lb)
if not na(b.reapBx)
box.delete(b.reapBx)
else if not b.bull and invBear
b.valid := false
if not na(b.bx)
box.delete(b.bx)
if not na(b.ce)
line.delete(b.ce)
if not na(b.lb)
label.delete(b.lb)
if not na(b.reapBx)
box.delete(b.reapBx)
else
if f_testZone(b)
f_applyTests(b)
if not b.armed and i_mitRearm
if (b.bull and close > b.top) or (not b.bull and close < b.bot)
b.armed := true
int mitMaxFires = i_mitRearm ? i_mitMaxFires : 1
bool canFire = b.armed and b.fires < mitMaxFires
bool useReaper = i_reapPriority and b.reaper and not na(b.reapTop) and not na(b.reapBot)
bool usePocket = not useReaper and b.uni and i_uniEntry == "Overlap pocket" and not na(b.pkTop) and not na(b.pkBot)
float useTop = useReaper ? b.reapTop : usePocket ? b.pkTop : b.top
float useBot = useReaper ? b.reapBot : usePocket ? b.pkBot : b.bot
bool inZone = i_retest == "Wick touch" ? (low <= useTop and high >= useBot) : (close <= useTop and close >= useBot)
bool passFilter = i_filter == "Show all" or b.uni
if canFire and inZone and passFilter and mitCdOk
if b.bull and i_mitBuyOn
b.trig := true
b.armed := false
b.fires := b.fires + 1
float entry = close
float sl = useBot - i_slBuf
f_newTrade(true, entry, sl)
mitBuyNow := true
mitUniBuy := b.uni
mitLastTrigBar := bar_index
lastSigMit := (b.uni ? "MIT BUY * UNICORN @ " : "MIT BUY @ ") + str.tostring(math.round_to_mintick(entry))
else if not b.bull and i_mitSellOn
b.trig := true
b.armed := false
b.fires := b.fires + 1
float entry = close
float sl = useTop + i_slBuf
f_newTrade(false, entry, sl)
mitSellNow := true
mitUniSell := b.uni
mitLastTrigBar := bar_index
lastSigMit := (b.uni ? "MIT SELL * UNICORN @ " : "MIT SELL @ ") + str.tostring(math.round_to_mintick(entry))
array.set(mits, i, b)
// =====================================================================
// ORDER BLOCK UPDATE
// =====================================================================
bool obTestBull = false
bool obTestBear = false
int nO = array.size(obs)
if nO > 0
for i = nO - 1 to 0
Breaker b = array.get(obs, i)
bool kill = (b.bull ? close < b.bot : close > b.top) or (i_zoneMaxAge > 0 and (bar_index - b.bornBar) > i_zoneMaxAge)
if kill
if not na(b.bx)
box.delete(b.bx)
if not na(b.lb)
label.delete(b.lb)
array.remove(obs, i)
else
if not na(b.bx)
box.set_right(b.bx, bar_index + i_obExt)
if f_testZone(b)
f_applyTests(b)
if b.bull
obTestBull := true
else
obTestBear := true
array.set(obs, i, b)
// ---- stacked zone text: offset sideways so names never print on top of each other
if barstate.islast and i_txtStack
array<Breaker> allZ = array.new<Breaker>()
f_collect(brks, allZ)
f_collect(mits, allZ)
f_collect(obs, allZ)
int nZ = array.size(allZ)
if nZ > 0
for i = 0 to nZ - 1
Breaker zi = array.get(allZ, i)
int slot = 0
if i > 0
for j = 0 to i - 1
Breaker zj = array.get(allZ, j)
if math.abs(f_anchor(zi) - f_anchor(zj)) <= i_txtGap * nz(atrVal, 0.0)
slot += 1
if i_tipOn and not na(zi.lb)
label.set_tooltip(zi.lb, f_tip(zi))
box.set_text_halign(zi.bx, slot == 0 ? text.align_right : slot == 1 ? text.align_center : text.align_left)
// =====================================================================
// TRADE STATUS STRING
// =====================================================================
f_tradeStatus() =>
int n = array.size(trades)
string s = "None yet"
if n > 0
Trade t = array.get(trades, n - 1)
string dir = t.bull ? "LONG" : "SHORT"
if not t.done
s := dir + " live: " + (t.hits > 0 ? "TP" + str.tostring(t.hits) + " hit" : "open")
else if t.won
s := dir + " WON (TP" + str.tostring(array.size(t.tps)) + ")"
else
s := dir + " stopped" + (t.hits > 0 ? " (after TP" + str.tostring(t.hits) + ")" : "")
s
f_tradeStatusCol() =>
int n = array.size(trades)
color c = color.new(#555555, 40)
if n > 0
Trade t = array.get(trades, n - 1)
c := not t.done ? color.new(#FFD600, 15) : t.won ? color.new(#1FA85A, 15) : color.new(#E24B4A, 15)
c
// =====================================================================
// DASHBOARD
// =====================================================================
var table dash = na
if i_dashOn and barstate.islast
table.delete(dash)
dash := table.new(f_dpos(), 2, 7, bgcolor = color.new(#0B1E3B, 0), frame_color = color.new(#38b6ff, 30), frame_width = 1, border_color = color.new(#2E5C8A, 60), border_width = 1)
int liveN = 0
int bullN = 0
int bearN = 0
int uniN = 0
float nearAbove = na
float nearBelow = na
int mB = array.size(brks)
if mB > 0
for i = 0 to mB - 1
Breaker b = array.get(brks, i)
if b.valid
liveN += 1
if b.bull
bullN += 1
else
bearN += 1
if b.uni
uniN += 1
if b.bot > close and (na(nearAbove) or b.bot < nearAbove)
nearAbove := b.bot
if b.top < close and (na(nearBelow) or b.top > nearBelow)
nearBelow := b.top
int mitLiveN = 0
int mitBullN = 0
int mitBearN = 0
int mM = array.size(mits)
if mM > 0
for i = 0 to mM - 1
Breaker mb = array.get(mits, i)
if mb.valid
mitLiveN += 1
if mb.bull
mitBullN += 1
else
mitBearN += 1
int obLive = array.size(obs)
int obBullN = 0
if obLive > 0
for i = 0 to obLive - 1
Breaker ob = array.get(obs, i)
if ob.bull
obBullN += 1
sz = f_dsz()
color hdr = color.new(#1C3A5E, 0)
table.cell(dash, 0, 0, "LE Breaker", text_color = #CFE3F5, text_size = sz, bgcolor = hdr, text_halign = text.align_center)
table.cell(dash, 1, 0, "v1.9.2", text_color = #CFE3F5, text_size = sz, bgcolor = hdr, text_halign = text.align_center)
table.cell(dash, 0, 1, "Live breakers", text_color = #7FB0D8, text_size = sz, text_halign = text.align_left)
table.cell(dash, 1, 1, str.tostring(liveN) + " (" + str.tostring(bullN) + "B / " + str.tostring(bearN) + "S)", text_color = color.white, text_size = sz)
string bias = "None"
color biasC = color.new(#555555, 40)
if liveN > 0
if na(nearAbove) and not na(nearBelow)
bias := "Bullish (above zones)"
biasC := color.new(#1FA85A, 22)
else if na(nearBelow) and not na(nearAbove)
bias := "Bearish (below zones)"
biasC := color.new(#E24B4A, 22)
else if not na(nearAbove) and not na(nearBelow)
float distUp = nearAbove - close
float distDn = close - nearBelow
if distDn < distUp
bias := "Bullish lean (near support)"
biasC := color.new(#1FA85A, 22)
else if distUp < distDn
bias := "Bearish lean (near resistance)"
biasC := color.new(#E24B4A, 22)
else
bias := "Balanced"
biasC := color.new(#555555, 40)
table.cell(dash, 0, 2, "Bias", text_color = #7FB0D8, text_size = sz, text_halign = text.align_left)
table.cell(dash, 1, 2, bias, text_color = color.white, text_size = sz, bgcolor = biasC)
table.cell(dash, 0, 3, "Breaker above", text_color = #7FB0D8, text_size = sz, text_halign = text.align_left)
table.cell(dash, 1, 3, na(nearAbove) ? "None" : str.tostring(math.round_to_mintick(nearAbove)) + " (" + str.tostring(math.round(nearAbove - close)) + "p)", text_color = #00bcd4, text_size = sz)
table.cell(dash, 0, 4, "Breaker below", text_color = #7FB0D8, text_size = sz, text_halign = text.align_left)
table.cell(dash, 1, 4, na(nearBelow) ? "None" : str.tostring(math.round_to_mintick(nearBelow)) + " (" + str.tostring(math.round(close - nearBelow)) + "p)", text_color = #ef5350, text_size = sz)
table.cell(dash, 0, 5, "Live mitigations", text_color = #7FB0D8, text_size = sz, text_halign = text.align_left)
table.cell(dash, 1, 5, str.tostring(mitLiveN) + " (" + str.tostring(mitBullN) + "B / " + str.tostring(mitBearN) + "S)", text_color = color.white, text_size = sz)
table.cell(dash, 0, 6, "Live order blocks", text_color = #7FB0D8, text_size = sz, text_halign = text.align_left)
table.cell(dash, 1, 6, str.tostring(obLive) + " (" + str.tostring(obBullN) + "B / " + str.tostring(obLive - obBullN) + "S)", text_color = color.white, text_size = sz)
// =====================================================================
// ALERTS
// =====================================================================
alertcondition(obTestBull, title = "Bull Order Block tested", message = "LE Bull Order Block tested on {{ticker}} {{interval}}")
alertcondition(obTestBear, title = "Bear Order Block tested", message = "LE Bear Order Block tested on {{ticker}} {{interval}}")
// END OF SCRIPT