ICT 2022 Model - Liquidity Sweep, MSS & FVG Entry

IvanSetuper · study · 1100 行 · 点赞 87 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © IvanSetuper
 
//@version=6
indicator("ICT 2022 Mentorship Entry Model", "ICT 2022 Model", overlay = true, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500, max_bars_back = 500)
 
// ————— Constants
 
const int    BULL       = 1
const int    BEAR       = -1
const int    EXTEND     = 15      // bars that level lines and higher timeframe gaps run past the newest bar
const int    TRADE_BARS = 4       // length of the entry and target lines
const int    SMT_LEN    = 3       // bars on each side of an SMT pivot
const int    SMT_KEEP   = 100     // bars an SMT pivot stays usable
const int    PAUSE      = 30      // minutes without a bar that count as a break in trading
const int    MAX_RUN    = 400     // furthest a breaker's candle run may reach behind its sweep; has to stay inside max_bars_back
const int    MAX_BACK   = 5000    // furthest a drawing may start behind the newest bar; the most max_bars_back() takes
const string YES        = "✔"
const string NO         = "✖"
const color  GREEN      = #089981
const color  RED        = #F23645
 
const string G_MODEL  = "Model"
const string G_RISK   = "Risk"
const string G_LIQ    = "Liquidity"
const string G_LEVELS = "Levels"
const string G_ZONES  = "FVGs and breakers"
const string G_PAIR   = "Paired symbol"
const string G_TABLES = "Tables"
const string G_STYLE  = "Style"
 
const string TT_WINDOW  = "A setup is taken only when its bar opens inside this window, in the time zone below. A setup that is already on the chart stays after the window ends."
const string TT_FLAT    = "Every setup ends at this time of day. A trade still open is closed at the close of the bar that contains this time, with whatever it has made or lost by then. An order that has not filled is cancelled. When the market is closed at this time, the last price before the break counts. Write 16:00 or 1600."
const string TT_ZONE    = "Day change, sessions and the two times above use this zone. Any IANA name works, for example America/New_York or Europe/London."
const string TT_STOP    = "Gap candles: the far end of the three candles that form the entry FVG, or the swing behind the shift when that lies further out. Sweep extreme: the furthest price has gone since the sweep, when that lies further out still, so this stop is never the tighter of the two. A wider stop means a smaller position, and costs weigh less on it."
const string TT_TARGET  = "Auto: 3R on days that have already traded outside the previous day's range, 2R on days that have not. A day runs from midnight to midnight in the time zone above. The Sunday evening session of futures and FX belongs to Monday, so Monday's previous day is Friday."
const string TT_EXPIRY  = "A market structure shift (MSS) waits this many bars for a fair value gap (FVG). The first one to complete, on the shift candle or after it, gives the entry. Without one the shift is dropped."
const string TT_GRADE   = "Two extra checks grade a setup. Session sweep: on the bar of the sweep or later, price took the high or low of a finished session or of the previous day. Alignment: the paired symbol's structure points the same way. A+ misses neither, A- one, B+ both. Without a paired symbol only the session sweep counts, and a paired symbol that has no data fails the alignment. A breaker block is listed when the setup has one and does not change the grade."
const string TT_CANCEL  = "On: a setup is dropped as soon as price reaches 1R without first trading back to the entry. Off: its drawing stays until a bar closes beyond the last target or the stop, or until the time set under Close trades at, and no new setup appears until then. Either way its label says missed."
const string TT_HIDE    = "Removes a trade from the chart once it has lost. Winners and setups that never filled stay, so the chart looks better than the model is."
const string TT_RISK    = "What you are willing to lose when the stop is hit, costs included, in the symbol's currency. The entry label shows the largest position that fits and what it loses at the stop. When even the smallest position loses more, the label shows that larger amount. 0 leaves the size off the label."
const string TT_HTF     = "Higher timeframe FVGs and swings come from these two timeframes. Left on Chart, they are picked by the script: 5 and 15 minutes up to a 1 minute chart, 15 minutes and 1 hour up to 5 minutes, 1 and 4 hours up to 15 minutes, 4 hours and 1 day above that. Your own choice has to be two different timeframes above the chart's."
const string TT_KEEP    = "Bars a swing high or low stays in the liquidity pool once it is confirmed. First value: swings of the chart. Second: swings of the higher timeframes."
const string TT_SWEEP   = "Draws the latest sweep the model counts and keeps the one behind every setup. A sweep counts when price takes a swing while it trades inside a higher timeframe FVG, or trades into such an FVG for the first time. Only these sweeps can lead to a setup, whether they are drawn or not."
const string TT_SESSION = "Start and end in the time zone of the Model group. A level is removed once price trades through it after its session. The boxes of this group only show or hide lines: every session and the previous day count for the session sweep check either way."
const string TT_OPENS   = "The open of the bar that starts at this time in the time zone of the Model group. A chart without such a bar gets no line: a stock chart before the market opens, or a 1 hour chart for 8:30."
const string TT_SMT     = "SMT divergence: the paired symbol trades through a swing high or low while the chart's symbol holds its own. The line joins that swing to the tip of the move back toward it and stays until the chart's symbol breaks the swing too. It does not change the grade."
const string TT_PAIR    = "Compared with the chart for SMT and for the alignment check. Empty: NQ, YM and RTY are paired with ES, ES with NQ, gold with silver, BTC with ETH, EUR with GBP, and index CFDs with their S&P or Nasdaq twin at the same broker."
const string TT_COSTS   = "Spread, commission and slippage of a whole trade, entry plus exit, as a percentage of price. First value: every market except crypto. Second: crypto. For scale, 0.008% of 25,000 is 2 points. The position size allows for them, and the tooltip of the entry label gives them in R."
 
enum Direction
    both   = "Long and short"
    longs  = "Long only"
    shorts = "Short only"
 
enum Stop
    gap   = "Gap candles"
    sweep = "Sweep extreme"
 
enum Target
    auto  = "Auto"
    two   = "2R"
    three = "3R"
 
enum Grade
    any    = "Any"
    aMinus = "A- or better"
    aPlus  = "A+ only"
 
// ————— Inputs
 
Direction directionInput    = input.enum(Direction.both, "Direction", group = G_MODEL)
string    windowInput       = input.session("0930-1400", "Setups between", group = G_MODEL, tooltip = TT_WINDOW)
string    flatInput         = input.string("16:00", "Close trades at", group = G_MODEL, tooltip = TT_FLAT)
string    zoneInput         = input.string("America/New_York", "Time zone", group = G_MODEL, tooltip = TT_ZONE)
Stop      stopInput         = input.enum(Stop.gap, "Stop", group = G_MODEL, tooltip = TT_STOP)
Target    targetInput       = input.enum(Target.auto, "Final target", group = G_MODEL, tooltip = TT_TARGET)
int       expiryInput       = input.int(5, "Bars from MSS to FVG", minval = 1, maxval = 50, group = G_MODEL, tooltip = TT_EXPIRY)
Grade     gradeInput        = input.enum(Grade.any, "Minimum grade", group = G_MODEL, tooltip = TT_GRADE)
bool      cancelMissedInput = input.bool(false, "Cancel missed setups", group = G_MODEL, tooltip = TT_CANCEL)
bool      hideLosersInput   = input.bool(false, "Hide losing trades", group = G_MODEL, tooltip = TT_HIDE)
 
float     riskInput         = input.float(500, "Risk per trade", minval = 0, group = G_RISK, tooltip = TT_RISK)
float     costInput         = input.float(0.008, "Costs per trade, % of price", minval = 0, step = 0.001, inline = "cost", group = G_RISK, tooltip = TT_COSTS)
float     cryptoCostInput   = input.float(0.07, "", minval = 0, step = 0.01, inline = "cost", group = G_RISK)
 
string    htf1Input         = input.timeframe("", "Higher timeframes", inline = "htf", group = G_LIQ, tooltip = TT_HTF)
string    htf2Input         = input.timeframe("", "", inline = "htf", group = G_LIQ)
int       keepInput         = input.int(100, "Swing memory", minval = 10, inline = "keep", group = G_LIQ, tooltip = TT_KEEP)
int       keepHtfInput      = input.int(1000, "", minval = 10, inline = "keep", group = G_LIQ)
bool      sweepsInput       = input.bool(true, "Sweeps", inline = "sweep", group = G_LIQ, tooltip = TT_SWEEP)
string    sweepTextInput    = input.string("$$$", "", inline = "sweep", group = G_LIQ)
 
bool      dayInput          = input.bool(true, "Day high and low", group = G_LEVELS)
bool      prevDayInput      = input.bool(true, "Previous day", group = G_LEVELS)
bool      asiaInput         = input.bool(true, "Asia", inline = "asia", group = G_LEVELS, tooltip = TT_SESSION)
string    asiaTimeInput     = input.session("2000-0000", "", inline = "asia", group = G_LEVELS)
bool      londonInput       = input.bool(true, "London", inline = "london", group = G_LEVELS)
string    londonTimeInput   = input.session("0200-0500", "", inline = "london", group = G_LEVELS)
bool      nyInput           = input.bool(true, "New York AM", inline = "ny", group = G_LEVELS)
string    nyTimeInput       = input.session("0900-1130", "", inline = "ny", group = G_LEVELS)
bool      midnightInput     = input.bool(true, "Midnight open", group = G_LEVELS, tooltip = TT_OPENS)
bool      open830Input      = input.bool(false, "8:30 open", group = G_LEVELS, tooltip = TT_OPENS)
 
bool      htfGapsInput      = input.bool(true, "Higher timeframe FVGs", group = G_ZONES)
bool      gapInput          = input.bool(true, "Entry FVG", group = G_ZONES)
bool      breakerInput      = input.bool(true, "Breaker block", group = G_ZONES)
color     gapColorInput     = input.color(color.new(#787B86, 77), "FVGs", group = G_ZONES)
color     bullBlockInput    = input.color(color.new(GREEN, 82), "Breakers", inline = "block", group = G_ZONES)
color     bearBlockInput    = input.color(color.new(RED, 82), "", inline = "block", group = G_ZONES)
 
bool      smtInput          = input.bool(true, "SMT", group = G_PAIR, tooltip = TT_SMT)
string    pairInput         = input.symbol("", "Symbol", group = G_PAIR, tooltip = TT_PAIR)
 
bool      checklistInput    = input.bool(true, "Checklist", group = G_TABLES)
bool      watermarkInput    = input.bool(true, "Watermark", group = G_TABLES)
 
color     longColorInput    = input.color(#2962FF, "Long and short", inline = "side", group = G_STYLE)
color     shortColorInput   = input.color(#DC143C, "", inline = "side", group = G_STYLE)
color     lineColorInput    = input.color(#787B86, "Lines and text", group = G_STYLE)
bool      targetsInput      = input.bool(true, "Stop and target lines", group = G_STYLE)
bool      pricesInput       = input.bool(false, "Prices on the labels", group = G_STYLE)
 
// ————— Types
 
// Resting orders behind a swing high or low.
type Liquidity
    float price
    int   bar
    int   until    // last bar on which it can be taken
 
// A sweep the model counts, with the candle run in front of it that may become the breaker.
type Sweep
    int   bar
    float level    // the swing or gap edge price took
    int   origin   // bar that level comes from
    float top      // the candle run
    float bot
    int   left
    bool  cleared  // a bar has closed beyond the run, which makes it a breaker
    float far      // furthest price has gone against the trade since the sweep, the sweep bar included
    int   farBar
 
// A fair value gap: of a higher timeframe, or the chart's own three-candle gap.
type Gap
    int    dir
    float  top
    float  bot
    int    left      // chart bar where its first candle opened
    int    born      // chart bar on which its third candle closed
    int    edgeBar   // chart bar that printed the near edge
    string tf        // short name of its timeframe
    bool   touched
 
type Shift
    int   dir
    int   bar
    float level
    int   refBar
    float swing    // stop candidate: the fractal behind the shift
    int   swingBar
    Sweep sweep
    Gap   gap      // the entry gap, once one has completed
 
// Everything the model tracks per direction. For longs the stop side is below price, for shorts above.
type Side
    int              dir
    array<Liquidity> pool      // liquidity resting on the stop side
    float            swing     // latest fractal on the stop side
    int              swingBar
    bool             held      // no bar has closed beyond that fractal yet
    Sweep            pending   // last counted sweep of the stop side that no setup has used
    Gap              gap       // chart gap in this direction that the current bar completed
    int              tookBar   // bar that last took a session high or low on the stop side
 
type Candle
    int   left
    float hi
    float lo
    float cl
    int   hiBar
    int   loBar
 
type Htf
    string name
    Candle cur
    Candle prev
    Candle prev2
 
// High and low of a session or a day.
type Range
    float hi
    float lo
    int   hiBar
    int   loBar
    bool  hiTaken
    bool  loTaken
    bool  live
 
// A price that gets a level line.
type Tag
    float  price
    int    bar
    string caption
 
// A pivot both symbols printed on the same bar.
type Anchor
    int   bar
    float price
    float pairPrice
    bool  pairTook   // the paired symbol has traded beyond its pivot
    float pull       // deepest pullback since the pivot
    float tip        // furthest point of the leg back toward the pivot
    int   tipBar
 
type Smt
    int           dir
    array<Anchor> anchors
    Anchor        active
    int           since
 
type Setup
    int    dir
    int    bar
    float  entry
    float  stop
    int    stopBar
    int    rr
    float  cost      // of the whole trade, in R
    string grade
    string checks
    Shift  shift     // the shift it came from, with its sweep and its gap
    int    fillBar
    int    exitBar
    float  result
    bool   missed
    bool   hidden    // taken off the chart as a losing trade
    line   entryLine
    line   stopLine
    line   firstLine
    line   finalLine
    line   shiftLine
    line   sweepLine
    label  entryLabel
    label  stopLabel
    label  firstLabel
    label  finalLabel
    label  shiftLabel
    label  sweepLabel
    box    gapBox
    box    blockBox
 
// What this bar did to a setup, in words. One alert at the end of the script carries them all.
array<string> notices = array.new<string>()
 
// ————— Functions
//
// Pine may drop a call whose value is not used, along with what the function does to its arguments. It did
// that here to calls on an object the script reads nowhere else. seal() and feed() end in a statement that
// returns nothing, and such a call is always kept.
 
// @function True when `a` lies beyond `b` in direction `dir`: above it for 1, below it for -1.
past(int dir, float a, float b) => dir * (a - b) > 0
 
// @function Same as past(), with touching allowed.
reached(int dir, float a, float b) => dir * (a - b) >= 0
 
// @function The bar's extreme in direction `dir`: its high for 1, its low for -1.
lead(int dir, int back = 0) => dir == BULL ? high[back] : low[back]
 
// @function The bar a drawing can start from: `bar`, or the furthest bar a drawing may reach when `bar` is older.
reachable(int bar) => math.max(bar, bar_index - MAX_BACK)
 
method near(Gap g) => g.dir == BULL ? g.top : g.bot
method far(Gap g)  => g.dir == BULL ? g.bot : g.top
method risk(Setup s) => math.abs(s.entry - s.stop)
method target(Setup s, float k) => s.entry + s.dir * k * s.risk()
 
// @function Minutes after midnight for a clock time written as 16:00, 1600 or 9:30, na for any other text.
clock(string hhmm) =>
    bool  valid = str.match(hhmm, "[0-2]?[0-9]:?[0-5][0-9]") == hhmm
    float n     = valid ? str.tonumber(str.replace(hhmm, ":", "")) : na
    n < 2400 ? int(n / 100) * 60 + int(n % 100) : na
 
// @function True when minute `now` of the day lies inside a session written as HHMM-HHMM. The session may run
//           past midnight. Read off the wall clock, so it stays right in the weeks when clocks change.
// @param session Has to be the same text on every bar: it is read once.
within(string session, int now) =>
    var int start = clock(str.substring(session, 0, 4))
    var int end   = clock(str.substring(session, 5, 9))
    start < end ? now >= start and now < end : now >= start or now < end
 
// @function The moment the clock in the model's time zone shows minute `minuteOfDay` on the date of `t`, moved
//           by `days` days.
moment(int t, int minuteOfDay, int days = 0) =>
    timestamp(zoneInput, year(t, zoneInput), month(t, zoneInput), dayofmonth(t, zoneInput) + days, int(minuteOfDay / 60), minuteOfDay % 60, 0)
 
// @function Short name of a timeframe for labels: M5, H1, D.
tfName(string tf) =>
    int s = timeframe.in_seconds(tf)
    switch
        s < 60    => "S" + str.tostring(s)
        s < 3600  => "M" + str.tostring(s / 60)
        s < 86400 => "H" + str.tostring(s / 3600)
        =>           str.length(tf) == 2 and str.startswith(tf, "1") ? str.substring(tf, 1) : tf
 
// @function The two higher timeframes that go with the chart's timeframe.
autoHtf() =>
    int s = timeframe.in_seconds()
    switch
        s <= 60  => ["5", "15"]
        s <= 300 => ["15", "60"]
        s <= 900 => ["60", "240"]
        =>          ["240", "1D"]
 
// @function The symbol to compare with when the user names none, or "" when the chart has no usual twin.
autoPair() =>
    string result = ""
    if syminfo.type == "futures"
        result := switch syminfo.root
            "ES"  => "CME_MINI:NQ1!"
            "MES" => "CME_MINI:NQ1!"
            "NQ"  => "CME_MINI:ES1!"
            "MNQ" => "CME_MINI:ES1!"
            "YM"  => "CME_MINI:ES1!"
            "MYM" => "CME_MINI:ES1!"
            "RTY" => "CME_MINI:ES1!"
            "M2K" => "CME_MINI:ES1!"
            "GC"  => "COMEX:SI1!"
            "MGC" => "COMEX:SI1!"
            "SI"  => "COMEX:GC1!"
            =>       ""
    else if array.from("forex", "cfd", "crypto").includes(syminfo.type)
        array<string> twins = array.from("BTC", "ETH", "EUR", "GBP", "XAU", "XAG", "NAS100", "SPX500", "US100", "US500", "NSXUSD", "SPXUSD")
        for [k, name] in twins
            string twin = twins.get(k % 2 == 0 ? k + 1 : k - 1)
            // a cross of the two, such as ETHBTC, has no twin
            if str.contains(syminfo.ticker, name) and not str.contains(syminfo.ticker, twin)
                result := syminfo.prefix + ":" + str.replace(syminfo.ticker, name, twin)
                break
    result
 
// @function Direction of the latest structure shift in a price series: 1, -1, or 0 before the first one.
//           Same rule as on the chart: a close beyond the latest unbroken three-bar fractal.
structure(float hi, float lo, float cl) =>
    var float top = na
    var float bot = na
    var int   dir = 0
    if cl > top
        dir := BULL
        top := na
    else if cl < bot
        dir := BEAR
        bot := na
    if hi[1] > hi[2] and hi[1] > hi
        top := hi[1]
    if lo[1] < lo[2] and lo[1] < lo
        bot := lo[1]
    dir
 
// @function Adds a swing to a liquidity pool. The pool is kept in bar order, oldest first, which also keeps
//           it ordered by price: any bar that traded through an older swing removed it.
// @param until Last bar on which the swing can be taken. A swing two timeframes share keeps the later one.
rest(array<Liquidity> pool, float price, int bar, int until) =>
    int k = pool.size()
    while k > 0 and pool.get(k - 1).bar > bar
        k -= 1
    if k > 0 and pool.get(k - 1).bar == bar
        pool.set(k - 1, Liquidity.new(price, bar, math.max(until, pool.get(k - 1).until)))
    else
        pool.insert(k, Liquidity.new(price, bar, until))
 
// @function Drops the swings whose time in the pool is up.
forget(array<Liquidity> pool) =>
    int k = pool.size()
    while k > 0
        k -= 1
        if bar_index >= pool.get(k).until
            pool.remove(k)
 
// @function Follows a sweep bar by bar: whether a bar has closed beyond its candle run, which makes the run a
//           breaker, and the furthest price has gone against the trade since.
method watch(Sweep sweep, int dir) =>
    if not na(sweep)
        if past(dir, close, dir == BULL ? sweep.top : sweep.bot)
            sweep.cleared := true
        if past(-dir, lead(-dir), sweep.far)
            sweep.far    := lead(-dir)
            sweep.farBar := bar_index
 
// @function A sweep on this bar that feeds direction `dir`, with its breaker candidate: the run of candles
//           closing in that direction which ends at the last swing in front of the sweep, or one bar earlier
//           when that bar closed the other way.
// @param level    The swing or gap edge price took.
// @param origin   Bar that level comes from.
// @param swingBar Bar of the last swing in front of the sweep, na when the session has none yet.
newSweep(int dir, float level, int origin, int swingBar) =>
    Sweep sweep = Sweep.new(bar_index, level, origin, far = lead(-dir), farBar = bar_index)
    int   k     = bar_index - swingBar
    if k < MAX_RUN
        if not past(dir, close[k], open[k])
            k += 1
        if past(dir, close[k], open[k])
            sweep.top := high[k]
            sweep.bot := low[k]
            while k < MAX_RUN and past(dir, close[k + 1], open[k + 1])
                k += 1
                sweep.top := math.max(sweep.top, high[k])
                sweep.bot := math.min(sweep.bot, low[k])
            sweep.left := bar_index - k
    sweep.watch(dir)
    sweep
 
// @function Runs the bar against the liquidity behind side `s`. Swings it traded through leave the pool. The
//           sweep counts, and becomes the side's pending sweep, when it happens inside a higher timeframe gap
//           of that direction or is the first time price trades into one.
// @param quiet The bar shifted structure through these swings. That is a break, not a sweep: nothing counts.
// @returns The sweep that counted on this bar, or na.
scan(Side s, Side opp, array<Gap> gaps, bool quiet) =>
    int       dir  = s.dir
    float     wick = lead(-dir)
    Liquidity deep = na
    Liquidity last = na
    while s.pool.size() > 0 and past(-dir, wick, s.pool.last().price)
        deep := s.pool.pop()
        last := na(last) ? deep : last
    bool inGap  = false
    Gap  tapped = na
    for gap in gaps
        if gap.dir == dir and gap.born < bar_index
            bool inside = low <= gap.top and high >= gap.bot
            inGap := inGap or inside
            if not gap.touched and reached(-dir, wick, gap.near())
                gap.touched := true
                // a bar that jumped over the whole gap did not trade in it
                if inside
                    tapped := gap
    float level  = na
    int   origin = na
    if not quiet
        if not na(tapped)
            level  := tapped.near()
            origin := tapped.edgeBar
        else if not na(deep) and inGap
            // a wick through the deepest swing points at it, a close beyond it at the nearest one
            Liquidity pick = past(dir, close, deep.price) ? deep : last
            level  := pick.price
            origin := pick.bar
    Sweep sweep = na(level) ? na : newSweep(dir, level, origin, opp.swingBar)
    if not na(sweep)
        s.pending := sweep
    sweep
 
// @function The three-candle gap in direction `dir` that this bar completes, or na. The middle candle has to
//           close beyond the first one, so a gap left by wicks alone does not count.
newGap(int dir) =>
    float wick = lead(-dir)
    float edge = lead(dir, 2)
    past(dir, wick, edge) and past(dir, close[1], edge) ? Gap.new(dir, math.max(wick, edge), math.min(wick, edge), bar_index - 2, bar_index) : na
 
// @function Registers a three-bar fractal at the previous bar on the stop side of `s`: the stop candidate of
//           `s`, the swing a close has to clear for a shift the other way, and liquidity resting beyond it.
//           Uses the swing memory input.
findFractal(Side s) =>
    int   dir = s.dir
    float tip = lead(-dir, 1)
    if past(-dir, tip, lead(-dir, 2)) and past(-dir, tip, lead(-dir))
        s.swing    := tip
        s.swingBar := bar_index - 1
        s.held     := true
        rest(s.pool, tip, bar_index - 1, bar_index + keepInput)
 
// @function Closes the candle a higher timeframe was building. Gaps it closed through die; the last three
//           candles are checked for a new gap and for a swing in the middle one. Uses the swing memory input.
// @param at Chart bar on which the candle ended.
method seal(Htf t, int at, array<Gap> gaps, Side bull, Side bear) =>
    Candle d = t.cur
    t.cur := na
    int k = gaps.size()
    while k > 0
        k -= 1
        Gap gap = gaps.get(k)
        if gap.tf == t.name and past(-gap.dir, d.cl, gap.far())
            gaps.remove(k)
    Candle a = t.prev2
    Candle b = t.prev
    t.prev2 := b
    t.prev  := d
    if not na(a)
        if d.lo > a.hi and b.cl > a.hi
            gaps.push(Gap.new(BULL, d.lo, a.hi, a.left, at, d.loBar, t.name))
        else if d.hi < a.lo and b.cl < a.lo
            gaps.push(Gap.new(BEAR, a.lo, d.hi, a.left, at, d.hiBar, t.name))
        if b.hi > a.hi and b.hi > d.hi
            rest(bear.pool, b.hi, b.hiBar, at + keepHtfInput)
        if b.lo < a.lo and b.lo < d.lo
            rest(bull.pool, b.lo, b.loBar, at + keepHtfInput)
 
// @function Adds the chart bar to the candle a higher timeframe is building.
// @param closes The bar is the last of its higher timeframe candle.
method feed(Htf t, bool closes, array<Gap> gaps, Side bull, Side bear) =>
    Candle c = t.cur
    if na(c)
        t.cur := Candle.new(bar_index, high, low, close, bar_index, bar_index)
    else
        if high > c.hi
            c.hi    := high
            c.hiBar := bar_index
        if low < c.lo
            c.lo    := low
            c.loBar := bar_index
        c.cl := close
    if closes
        t.seal(bar_index, gaps, bull, bear)
 
// @function Follows the high and low of a session. They move with price while the session runs. Afterwards
//           the first trade through one of them takes it and counts as a session sweep on that side.
method track(Range r, bool inside, Side bull, Side bear) =>
    if inside and not r.live
        r.hi      := high
        r.lo      := low
        r.hiBar   := bar_index
        r.loBar   := bar_index
        r.hiTaken := false
        r.loTaken := false
    else if inside
        if high > r.hi
            r.hi    := high
            r.hiBar := bar_index
        if low < r.lo
            r.lo    := low
            r.loBar := bar_index
    else
        if not r.hiTaken and high > r.hi
            r.hiTaken    := true
            bear.tookBar := bar_index
        if not r.loTaken and low < r.lo
            r.loTaken    := true
            bull.tookBar := bar_index
    r.live := inside
 
// @function Adds a level to the list of level lines. Levels at one price share a label.
method note(array<Tag> tags, float price, int bar, string caption) =>
    if not na(price)
        bool merged = false
        for tag in tags
            if tag.price == price
                tag.caption := tag.caption + " + " + caption
                merged := true
                break
        if not merged
            tags.push(Tag.new(price, bar, caption))
 
// @function Adds the untaken ends of a range to the list of level lines.
method note(array<Tag> tags, Range r, string hiCaption, string loCaption) =>
    if not r.hiTaken
        tags.note(r.hi, r.hiBar, hiCaption)
    if not r.loTaken
        tags.note(r.lo, r.loBar, loCaption)
 
// @function The live gap of one direction whose middle is closest to the last price.
nearest(array<Gap> gaps, int dir) =>
    Gap   best = na
    float room = na
    for gap in gaps
        float away = math.abs(close - (gap.top + gap.bot) / 2)
        if gap.dir == dir and (na(best) or away < room)
            best := gap
            room := away
    best
 
// @function Amount of money as text: a dollar sign for US dollars, the currency code otherwise, and the bare
//           number for a symbol that has no currency.
money(float amount) =>
    string digits = str.tostring(amount, "#,##0.##")
    switch syminfo.currency
        "USD"  => "$" + digits
        "NONE" => digits
        =>        digits + " " + syminfo.currency
 
// @function The largest position that loses no more than the risk input at the stop, never below the smallest
//           position the symbol trades in, and what that position loses there.
// @param loss What one unit of price loses at the stop: the distance to it plus the costs.
sizing(float loss) =>
    float  perUnit = loss * syminfo.pointvalue
    // futures trade in whole contracts whatever the data feed reports
    float  step    = syminfo.type == "futures" or not (syminfo.mincontract > 0) ? 1 : syminfo.mincontract
    // a hair above the quotient, so that one that should be whole is not lost to rounding: 1.9999999999999982 is two contracts
    float  qty     = math.max(step, math.floor(riskInput / perUnit / step * (1 + 1e-9)) * step)
    string unit    = switch
        syminfo.type == "futures"                                => qty == 1 ? " contract" : " contracts"
        array.from("stock", "fund", "dr").includes(syminfo.type) => qty == 1 ? " share" : " shares"
        =>                                                          " units"
    str.tostring(qty, "#,##0.########") + unit + ", risk " + money(qty * perUnit)
 
// @function R multiple as text: +2R, -1R, +0.37R.
inR(float r) =>
    float shown = math.round(r, 2)
    shown == 0 ? "0R" : (shown > 0 ? "+" : "") + str.tostring(shown, "0.##") + "R"
 
// @function Closes a trade with its result in R, before costs.
method settle(Setup s, float r) =>
    s.exitBar := bar_index
    s.result  := r
    notices.push("trade closed, " + inR(r))
 
// @function One bar of the order and of the trade. A bar that opens at the entry or beyond it fills the order at
//           once. Otherwise price has to trade back to the entry before it reaches 1R: when 1R comes first, or
//           in the same bar, the setup is missed. Inside one bar the stop is checked before the target.
method trade(Setup s) =>
    int dir = s.dir
    if na(s.fillBar) and not s.missed
        bool atOpen = reached(-dir, open, s.entry)
        if not atOpen and reached(dir, lead(dir), s.target(1))
            s.missed := true
            notices.push("1R reached before the entry, cancel the order")
        else if atOpen or reached(-dir, lead(-dir), s.entry)
            s.fillBar := bar_index
            notices.push("entry filled at " + str.tostring(s.entry, format.mintick))
    if not na(s.fillBar) and na(s.exitBar)
        if reached(-dir, lead(-dir), s.stop)
            s.settle(-1.0)
        else if reached(dir, lead(dir), s.target(s.rr))
            s.settle(s.rr)
 
// @function Ends a setup at the flat time: a trade still open is closed at `price`, an order that neither
//           filled nor was missed is cancelled.
method flatten(Setup s, float price) =>
    if na(s.fillBar)
        if not s.missed
            notices.push("no fill by " + flatInput + ", cancel the order")
    else if na(s.exitBar)
        s.settle(s.dir * (price - s.entry) / s.risk())
 
// @function Text of the entry label once the setup has an outcome: its side and what became of it.
method outcome(Setup s) =>
    (s.dir == BULL ? "LONG " : "SHORT ") + (not na(s.result) ? inR(s.result) : s.missed ? "missed" : "no fill")
 
// @function Takes a finished setup off the active drawing: stop and target lines go, the label keeps the side
//           and the outcome. A losing trade disappears completely when the user asked for that.
method retire(Setup s) =>
    line.delete(s.stopLine)
    line.delete(s.firstLine)
    line.delete(s.finalLine)
    label.delete(s.stopLabel)
    label.delete(s.firstLabel)
    label.delete(s.finalLabel)
    s.entryLabel.set_text(s.outcome())
    if hideLosersInput and s.result < 0
        s.hidden := true
        line.delete(s.entryLine)
        line.delete(s.shiftLine)
        line.delete(s.sweepLine)
        label.delete(s.entryLabel)
        label.delete(s.shiftLabel)
        label.delete(s.sweepLabel)
        box.delete(s.gapBox)
        box.delete(s.blockBox)
 
// @function A text label without a body, anchored at its left edge.
textAt(int x, float y, string caption, color tint, string scale = size.tiny) =>
    label.new(x, y, caption, style = label.style_label_left, color = color(na), textcolor = tint, size = scale)
 
// @function The dotted line of a sweep, from the bar its level comes from to the bar that took it.
method mark(Sweep sweep) =>
    line.new(reachable(sweep.origin), sweep.level, reachable(sweep.bar), sweep.level, color = lineColorInput, style = line.style_dotted)
 
// @function Draws a new setup: shift line, breaker, entry gap, entry, stop and targets, in the colours and with
//           the parts the style inputs ask for.
method draw(Setup s) =>
    int    dir   = s.dir
    Shift  shift = s.shift
    Sweep  sweep = shift.sweep
    Gap    gap   = shift.gap
    int    left  = reachable(shift.refBar)
    int    right = bar_index + TRADE_BARS
    color  tint  = dir == BULL ? longColorInput : shortColorInput
    string stop  = str.tostring(s.stop, format.mintick)
    string first = str.tostring(s.target(1), format.mintick)
    string final = str.tostring(s.target(s.rr), format.mintick)
    string runs  = str.tostring(s.rr) + "R"
    if sweepsInput
        s.sweepLine  := sweep.mark()
        s.sweepLabel := textAt(reachable(sweep.bar), sweep.level, sweepTextInput, lineColorInput)
    if sweep.cleared and breakerInput
        s.blockBox := box.new(reachable(sweep.left), sweep.top, bar_index, sweep.bot, border_color = color(na), bgcolor = dir == BULL ? bullBlockInput : bearBlockInput)
    if gapInput
        s.gapBox := box.new(gap.left, gap.top, right, gap.bot, border_color = color(na), bgcolor = gapColorInput)
    s.shiftLine  := line.new(left, shift.level, shift.bar, shift.level, color = lineColorInput)
    s.shiftLabel := label.new(math.round((left + shift.bar) / 2), shift.level, "MSS", style = dir == BULL ? label.style_label_down : label.style_label_up, color = color(na), textcolor = lineColorInput, size = size.tiny)
    s.entryLine  := line.new(bar_index, s.entry, right, s.entry, color = tint, width = 2)
    s.entryLabel := textAt(right, s.entry, (dir == BULL ? "LONG" : "SHORT") + (riskInput > 0 ? "  " + sizing(s.risk() * (1 + s.cost)) : ""), tint)
    s.entryLabel.set_tooltip(s.checks + "\n\nEntry " + str.tostring(s.entry, format.mintick) + "\nStop " + stop + "\n1R " + first + "\n" + runs + " " + final + "\nCosts " + inR(-s.cost))
    if targetsInput
        s.stopLine   := line.new(reachable(s.stopBar), s.stop, right, s.stop, color = lineColorInput, style = line.style_dotted)
        s.firstLine  := line.new(bar_index, s.target(1), right, s.target(1), color = lineColorInput, style = line.style_dotted)
        s.finalLine  := line.new(bar_index, s.target(s.rr), right, s.target(s.rr), color = lineColorInput, style = line.style_dotted)
        s.stopLabel  := textAt(right, s.stop, pricesInput ? "SL  " + stop : "SL", lineColorInput, size.small)
        s.firstLabel := textAt(right, s.target(1), pricesInput ? "1R  " + first : "1R", lineColorInput, size.small)
        s.finalLabel := textAt(right, s.target(s.rr), pricesInput ? runs + "  " + final : runs, lineColorInput, size.small)
 
// @function Moves an SMT leg on with the bar `back` bars ago: a deeper pullback restarts the leg there,
//           otherwise the leg's tip follows price back toward the pivot.
method follow(Anchor a, int dir, int back = 0) =>
    if na(a.pull) or past(dir, lead(dir, back), a.pull)
        a.pull   := lead(dir, back)
        a.tip    := lead(-dir, back)
        a.tipBar := bar_index - back
    else if past(-dir, lead(-dir, back), a.tip)
        a.tip    := lead(-dir, back)
        a.tipBar := bar_index - back
 
// @function One step of SMT tracking on one side. Pivots this symbol has broken are dropped. A divergence
//           starts at the most recent pivot whose twin the paired symbol has broken, and holds until this
//           symbol breaks its own. The line ends at the tip of the leg that runs back toward the pivot.
// @param pivot     This symbol's pivot confirmed on this bar, or na.
// @param pairPivot The paired symbol's pivot confirmed on this bar, or na.
// @param pairLead  The paired symbol's extreme on this bar.
method step(Smt m, float pivot, float pairPivot, float pairLead) =>
    int dir = m.dir
    int k   = m.anchors.size()
    while k > 0
        k -= 1
        Anchor a = m.anchors.get(k)
        if past(-dir, lead(-dir), a.price) or bar_index - a.bar > SMT_KEEP
            m.anchors.remove(k)
            if not na(m.active) and m.active.bar == a.bar
                m.active := na
        else
            a.pairTook := a.pairTook or past(-dir, pairLead, a.pairPrice)
            a.follow(dir)
    if not na(pivot) and not na(pairPivot)
        Anchor fresh = Anchor.new(bar_index - SMT_LEN, pivot, pairPivot)
        for back = SMT_LEN - 1 to 0
            fresh.follow(dir, back)
        m.anchors.push(fresh)
    if na(m.active)
        k := m.anchors.size() - 1
        while k >= 0
            if m.anchors.get(k).pairTook
                m.active := m.anchors.get(k)
                m.since  := bar_index
                break
            k -= 1
    m.active
 
// ————— Calculations
 
if timeframe.in_seconds() > 3600
    runtime.error("This is an intraday model. Use a chart of 1 hour or lower.")
if not chart.is_standard
    runtime.error("Use standard candles. On Heikin Ashi, Renko and similar charts the entry and stop prices do not exist in the market.")
if syminfo.mintick * 1e10 < 2
    runtime.error("Prices on this symbol are too small: Pine Script treats numbers 0.0000000001 apart or closer as equal. Use a pair quoted per thousand or per million coins.")
 
var int flatMinute = clock(flatInput)
if na(flatMinute)
    runtime.error("Close trades at: write the time as 16:00 or 1600.")
 
[autoTf1, autoTf2] = autoHtf()
string tf1 = htf1Input == "" ? autoTf1 : htf1Input
string tf2 = htf2Input == "" ? autoTf2 : htf2Input
if math.min(timeframe.in_seconds(tf1), timeframe.in_seconds(tf2)) <= timeframe.in_seconds() or timeframe.in_seconds(tf1) == timeframe.in_seconds(tf2)
    runtime.error("Higher timeframes: pick two different timeframes above the chart's, or leave both on Chart.")
 
int  dayNow    = dayofmonth(time, zoneInput)
bool newDate   = bar_index == 0 or dayNow != dayNow[1]
bool reopened  = bar_index == 0 or time - time_close[1] >= PAUSE * 60000
int  minuteNow = hour(time, zoneInput) * 60 + minute(time, zoneInput)
 
// Days change with the date, except that a date which opens after noon and trades through midnight is the
// evening session of the next day: futures and FX on Sunday. Monday's previous day is then Friday.
var bool evening = false
bool newDay = newDate and (reopened or not evening)
if newDate
    evening := bar_index > 0 and minuteNow >= 720
 
bool inWindow  = within(windowInput, minuteNow)
bool inAsia    = within(asiaTimeInput, minuteNow)
bool inLondon  = within(londonTimeInput, minuteNow)
bool inNy      = within(nyTimeInput, minuteNow)
bool opens1    = timeframe.change(tf1)
bool opens2    = timeframe.change(tf2)
bool closes1   = time_close == time_close(tf1)
bool closes2   = time_close == time_close(tf2)
 
// The last moment up to this bar's close at which the clock showed the flat time. Inside the bar: setups end
// at its close. In the break before the bar: they ended while the market was closed.
int  flatToday = moment(time_close, flatMinute)
int  flatLast  = flatToday <= time_close ? flatToday : moment(time_close, flatMinute, -1)
bool flatNow   = flatLast > time
bool flatGone  = not flatNow and flatLast > time_close[1]
 
// The paired symbol's structure is read off its previous bar. Its current bar is not always final when the
// chart's bar closes, and a grade must not change when the chart reloads.
var string pair     = pairInput == "" ? autoPair() : pairInput
var string pairName = str.replace(syminfo.ticker(pair), "1!", "")
[pairHigh, pairLow, pairHighPrev, pairLowPrev, pairClosePrev] = request.security(pair == "" ? syminfo.tickerid : pair, timeframe.period, [high, low, high[1], low[1], close[1]], ignore_invalid_symbol = true)
bool hasPair = pair != "" and not na(pairClosePrev)
int  pairDir = structure(pairHighPrev, pairLowPrev, pairClosePrev)
 
var Side       bull    = Side.new(BULL, array.new<Liquidity>())
var Side       bear    = Side.new(BEAR, array.new<Liquidity>())
var array<Gap> gaps    = array.new<Gap>()
var Htf        htf1    = Htf.new(tfName(tf1))
var Htf        htf2    = Htf.new(tfName(tf2))
var Shift      shift   = na
var Setup      live    = na
var Setup      shown   = na     // the setup the checklist describes
var int        openBar = 0      // first bar after the latest break in trading
 
var Range today    = Range.new()
var Range prevDay  = Range.new()
var Range asia     = Range.new()
var Range london   = Range.new()
var Range ny       = Range.new()
var Tag   midnight = Tag.new(na, na, "0:00 AM")
var Tag   open830  = Tag.new(na, na, "8:30 AM")
 
// What this bar did, for the drawings and the alerts further down.
Setup born    = na    // setup that appeared
Setup gone    = na    // setup that left the chart
Sweep counted = na    // sweep that counted
 
// The model runs on closed bars only, so no setup or level depends on a bar that is still forming.
if barstate.isconfirmed
    if newDay
        prevDay := today.copy()
        today.live := false
    if newDate
        midnight.price := minuteNow == 0 ? open : na    // no line on a date whose first bar opens later
        midnight.bar   := bar_index
        open830.price  := na
    if minuteNow == 510 and na(open830.price)
        open830.price := open
        open830.bar   := bar_index
    today.track(true, bull, bear)
    prevDay.track(false, bull, bear)
    asia.track(inAsia, bull, bear)
    london.track(inLondon, bull, bear)
    ny.track(inNy, bull, bear)
 
    // A sweep counts until midnight. And nothing is built across a break in trading: after one, the swings
    // and a waiting shift start afresh as well, and no gap or fractal uses bars from both sides of it.
    if newDate or reopened
        bull.pending := na
        bear.pending := na
    if reopened
        openBar       := bar_index
        shift         := na
        bull.swing    := na
        bull.swingBar := na
        bear.swing    := na
        bear.swingBar := na
    bool joined = bar_index - openBar >= 2
 
    // A higher timeframe candle can end without a chart bar of its own: the data skips its last minutes, or
    // the chart's timeframe does not divide it. It is closed here, before this bar is read, because its gap
    // and its swing were already in place when the bar traded.
    if opens1 and not na(htf1.cur)
        htf1.seal(bar_index - 1, gaps, bull, bear)
    if opens2 and not na(htf2.cur)
        htf2.seal(bar_index - 1, gaps, bull, bear)
 
    // Sweeps on record are followed through this bar before it can count a new one in their place.
    bull.pending.watch(BULL)
    bear.pending.watch(BEAR)
    if not na(shift)
        shift.sweep.watch(shift.dir)
 
    bull.gap := joined ? newGap(BULL) : na
    bear.gap := joined ? newGap(BEAR) : na
 
    // Market structure shift: the first close beyond the latest fractal of the other side. It counts for a
    // setup only when a sweep of the stop side is waiting from an earlier bar.
    Side  moved = bear.held and past(BULL, close, bear.swing) ? bull : bull.held and past(BEAR, close, bull.swing) ? bear : na
    Shift fresh = na
    if not na(moved)
        Side other = moved.dir == BULL ? bear : bull
        if not na(moved.pending)
            fresh := Shift.new(moved.dir, bar_index, other.swing, other.swingBar, moved.swing, moved.swingBar, moved.pending, moved.gap)
        other.held := false
 
    Sweep lowSweep  = scan(bull, bear, gaps, not na(fresh) and moved.dir == BEAR)
    Sweep highSweep = scan(bear, bull, gaps, not na(fresh) and moved.dir == BULL)
    counted := na(highSweep) ? lowSweep : highSweep
 
    // The open setup. Its drawing follows closes, its order and trade follow highs and lows, and the flat time
    // ends both.
    bool busy = not na(live)
    if busy
        if flatGone
            live.flatten(close[1])
        else
            live.trade()
            if flatNow
                live.flatten(close)
        if flatGone or flatNow or past(live.dir, close, live.target(live.rr)) or past(-live.dir, close, live.stop) or (live.missed and cancelMissedInput)
            gone := live
            live := na
 
    // A waiting shift takes the first gap that completes on its own candle or later. The setup appears one bar
    // after the shift when the shift candle left the gap, and on the gap's bar otherwise, if that bar is
    // inside the window, nothing else is open, and price has neither run to 1R nor broken the gap or the stop
    // meanwhile.
    if not na(shift)
        Side side = shift.dir == BULL ? bull : bear
        if na(shift.gap)
            shift.gap := side.gap
        if bar_index - shift.bar > expiryInput
            shift := na
        else if not na(shift.gap)
            int   dir   = shift.dir
            Gap   gap   = shift.gap
            Sweep sweep = shift.sweep
            int   third = bar_index - gap.born
            float entry = gap.near()
            // Stop: the far extreme of the gap's three candles, or the swing behind the shift when it lies
            // further out. The wide setting also takes in everything since the sweep.
            float stop    = lead(-dir, third)
            int   stopBar = gap.born
            for back = third + 1 to third + 2
                if past(-dir, lead(-dir, back), stop)
                    stop    := lead(-dir, back)
                    stopBar := bar_index - back
            if reached(-dir, shift.swing, stop)
                stop    := shift.swing
                stopBar := shift.swingBar
            if stopInput == Stop.sweep and past(-dir, sweep.far, stop)
                stop    := sweep.far
                stopBar := sweep.farBar
            float span   = math.abs(entry - stop)
            bool  ran    = false
            bool  broken = past(-dir, close, gap.far())
            for back = 0 to third
                ran := ran or reached(dir, lead(dir, back), entry + dir * span)
                if back < third
                    broken := broken or reached(-dir, lead(-dir, back), stop)
 
            bool   took    = side.tookBar >= sweep.bar
            bool   aligned = pairDir == dir
            int    misses  = (took ? 0 : 1) + (pair != "" and not aligned ? 1 : 0)
            string grade   = misses == 0 ? "A+" : misses == 1 ? "A-" : "B+"
            bool   sideOk  = directionInput == Direction.both or (directionInput == Direction.longs ? dir == BULL : dir == BEAR)
            bool   gradeOk = gradeInput == Grade.any or misses == 0 or (gradeInput == Grade.aMinus and misses == 1)
 
            // a setup on the bar that ends at the flat time would be over before it could trade
            if inWindow and not flatNow and not ran and not broken and not busy and sideOk and gradeOk
                int    rr     = targetInput == Target.two ? 2 : targetInput == Target.three ? 3 : prevDay.hiTaken or prevDay.loTaken ? 3 : 2
                string checks = (YES + " Liquidity sweep\n" + YES + " Structure shift\n" + YES + " Fair value gap\n"
                     + (sweep.cleared ? YES + " Breaker block\n" : "")
                     + (took ? YES : NO) + " Session sweep"
                     + (pair != "" ? "\n" + (aligned ? YES : NO) + " " + pairName + " alignment" + (hasPair ? "" : ", no data") : ""))
                float cost = entry * (syminfo.type == "crypto" ? cryptoCostInput : costInput) / 100 / span
                live  := Setup.new(dir, bar_index, entry, stop, stopBar, rr, cost, grade, checks, shift)
                born  := live
                shown := live
                // A sweep feeds one setup: it stops waiting, and a shift that formed on this bar loses it too.
                if not na(side.pending) and side.pending.bar == sweep.bar
                    side.pending := na
                if not na(fresh) and fresh.dir == dir and fresh.sweep.bar == sweep.bar
                    fresh := na
                notices.push(str.format("{0} setup, entry {1}, stop {2}, 1R {3}, {4}R {5}", dir == BULL ? "long" : "short", str.tostring(entry, format.mintick), str.tostring(stop, format.mintick), str.tostring(live.target(1), format.mintick), rr, str.tostring(live.target(rr), format.mintick)))
            shift := na
    if not na(fresh)
        shift := fresh
 
    if joined
        findFractal(bull)
        findFractal(bear)
    forget(bull.pool)
    forget(bear.pool)
    htf1.feed(closes1, gaps, bull, bear)
    htf2.feed(closes2, gaps, bull, bear)
 
// SMT is checked on every tick: a divergence exists the moment one symbol trades through its pivot.
var Smt smtBear = Smt.new(BEAR, array.new<Anchor>())
var Smt smtBull = Smt.new(BULL, array.new<Anchor>())
Anchor divBear = smtBear.step(ta.pivothigh(high, SMT_LEN, SMT_LEN), ta.pivothigh(pairHigh, SMT_LEN, SMT_LEN), pairHigh)
Anchor divBull = smtBull.step(ta.pivotlow(low, SMT_LEN, SMT_LEN), ta.pivotlow(pairLow, SMT_LEN, SMT_LEN), pairLow)
 
// ————— Visuals
 
// A drawing placed by bar number looks up that bar's time, and Pine settles how much history of `time` it keeps
// while the chart loads. On a live bar that buffer no longer grows, so a line reaching further back than any
// line did in history would stop the script. Reserving the full depth here rules that out.
max_bars_back(time, MAX_BACK)
 
// A new setup is drawn, a finished one keeps its entry and its outcome, a missed one that stays says so.
if not na(born)
    born.draw()
if not na(gone)
    gone.retire()
else if not na(live) and live.missed
    live.entryLabel.set_text(live.outcome())
 
// The latest sweep that counted: a dotted line from the swing or the gap edge to the bar that took it.
var line  sweepLine  = na
var label sweepLabel = na
if sweepsInput and not na(counted)
    line.delete(sweepLine)
    label.delete(sweepLabel)
    sweepLine  := counted.mark()
    sweepLabel := textAt(counted.bar, counted.level, sweepTextInput, lineColorInput)
 
var line  smtLine  = na
var label smtLabel = na
if barstate.islast
    line.delete(smtLine)
    label.delete(smtLabel)
    Anchor div = na(divBull) ? divBear : na(divBear) ? divBull : smtBull.since > smtBear.since ? divBull : divBear
    if smtInput and hasPair and not na(div)
        smtLine  := line.new(reachable(div.bar), div.price, div.tipBar, div.tip, color = lineColorInput)
        smtLabel := textAt(div.tipBar, div.tip, "SMT", lineColorInput)
 
// Level lines run from the bar that printed the level to a little past the newest bar.
// A session's high and low are drawn once the session is over.
var array<line>  levelLines  = array.new<line>()
var array<label> levelLabels = array.new<label>()
if barstate.islast
    array<Tag> tags = array.new<Tag>()
    if dayInput
        tags.note(today, "HOD", "LOD")
    if londonInput and not london.live
        tags.note(london, "LON.H", "LON.L")
    if asiaInput and not asia.live
        tags.note(asia, "ASIA.H", "ASIA.L")
    if nyInput and not ny.live
        tags.note(ny, "NYAM.H", "NYAM.L")
    if prevDayInput
        tags.note(prevDay, "PDH", "PDL")
    if midnightInput
        tags.note(midnight.price, midnight.bar, midnight.caption)
    if open830Input
        tags.note(open830.price, open830.bar, open830.caption)
    int right = bar_index + EXTEND
    for [k, tag] in tags
        int left = reachable(tag.bar)
        if k < levelLines.size()
            levelLines.get(k).set_xy1(left, tag.price)
            levelLines.get(k).set_xy2(right, tag.price)
            levelLabels.get(k).set_xy(right, tag.price)
            levelLabels.get(k).set_text(tag.caption)
        else
            levelLines.push(line.new(left, tag.price, right, tag.price, color = lineColorInput, style = line.style_dotted))
            levelLabels.push(textAt(right, tag.price, tag.caption, lineColorInput))
    while levelLines.size() > tags.size()
        line.delete(levelLines.pop())
        label.delete(levelLabels.pop())
 
// Of all live higher timeframe gaps only the nearest bullish and the nearest bearish one are shown. The choice
// follows the last price, so it can change while a bar forms.
var array<box> gapBoxes = array.new<box>(2, na)
if barstate.islast and htfGapsInput
    for [k, dir] in array.from(BULL, BEAR)
        Gap gap  = nearest(gaps, dir)
        box slot = gapBoxes.get(k)
        if na(gap)
            box.delete(slot)
            gapBoxes.set(k, na)
        else
            if na(slot)
                slot := box.new(bar_index, gap.top, bar_index, gap.bot, border_color = color(na), bgcolor = gapColorInput, text_color = lineColorInput, text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_bottom)
                gapBoxes.set(k, slot)
            slot.set_lefttop(reachable(gap.left), gap.top)
            slot.set_rightbottom(bar_index + EXTEND, gap.bot)
            slot.set_text(gap.tf + " FVG" + (gap.touched ? "" : " ●"))
 
// The tables take their colours from the chart, so they read on a light background and on a dark one.
color tableText = chart.fg_color
color headColor = color.new(chart.fg_color, 80)
color cellColor = color.new(chart.fg_color, 92)
bool  darkChart = color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color) < 382
 
var table checkTable = table.new(position.bottom_right, 2, 8)
if barstate.islast and checklistInput
    checkTable.clear(0, 0, 1, 7)
    if not na(shown) and not shown.hidden
        array<string> rows = str.split(shown.checks, "\n")
        checkTable.cell(0, 0, "Setup grade", text_color = tableText, bgcolor = headColor, text_size = size.tiny, text_halign = text.align_left, text_formatting = text.format_bold)
        checkTable.cell(1, 0, shown.grade, text_color = darkChart ? color.yellow : tableText, bgcolor = headColor, text_size = size.tiny, text_formatting = text.format_bold)
        checkTable.cell(0, 1, "Checklist", text_color = tableText, bgcolor = headColor, text_size = size.tiny, text_halign = text.align_left, text_formatting = text.format_bold)
        checkTable.cell(1, 1, "Status", text_color = tableText, bgcolor = headColor, text_size = size.tiny, text_formatting = text.format_bold)
        for [k, row] in rows
            bool pass = str.startswith(row, YES)
            checkTable.cell(0, k + 2, str.substring(row, 2), text_color = tableText, bgcolor = cellColor, text_size = size.tiny, text_halign = text.align_left, text_formatting = text.format_bold)
            checkTable.cell(1, k + 2, pass ? YES : NO, text_color = pass ? GREEN : RED, bgcolor = cellColor, text_size = size.tiny)
 
var table watermark = table.new(position.bottom_center, 1, 1)
if barstate.islast and watermarkInput
    string frame = timeframe.isseconds ? str.tostring(timeframe.multiplier) + "s" : timeframe.multiplier % 60 == 0 ? str.tostring(timeframe.multiplier / 60) + "h" : str.tostring(timeframe.multiplier) + "m"
    watermark.cell(0, 0, "ICT 2022(" + frame + ")\n" + syminfo.ticker + "\n" + str.format_time(time, "dd MMM yyyy", zoneInput), text_color = color.new(chart.fg_color, 45), text_size = size.normal, text_font_family = font.family_monospace)
 
// ————— Alerts
 
if notices.size() > 0
    alert(syminfo.ticker + ": " + notices.join("; "), alert.freq_once_per_bar_close)
 
alertcondition(not na(born) and born.dir == BULL, "Long setup", "{{ticker}}: long setup, entry at the top of the gap")
alertcondition(not na(born) and born.dir == BEAR, "Short setup", "{{ticker}}: short setup, entry at the bottom of the gap")

← 返回列表