ICT Order Blocks + Alerts

Flatty25 · study · 268 行 · 点赞 66 · 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/
// © Flatty25
 
//@version=6
//=============================================================================
//    OB Identify + Verify v1.9
//
//    Purpose:
//      Educational Order Block indicator that detects ICT-style OBs with clean
//      visual markers. Icons on chart, explanations in this description.
//
//    ━━━ CHART LEGEND ━━━
//    ▲ / ▼  = Order Block candle (last opposite-direction candle before displacement)
//    ✓      = Displacement confirmed (candle closed beyond OB open)
//    ───    = OB level line (price may return here as support/resistance)
//    - - -  = Invalidated OB level (only when "Stop Line at Mitigation" is OFF)
//    OB+    = Bullish Order Block (expect price to find support)
//    OB-    = Bearish Order Block (expect price to find resistance)
//
//    ━━━ INVALIDATION ━━━
//    An OB is invalidated when price CLOSES through the OB level:
//    • OB+ invalid if price closes BELOW the line
//    • OB- invalid if price closes ABOVE the line
//
//    ━━━ ALERTS ━━━
//    Create an alert on this indicator and pick either:
//    • "Any alert() function call" — one alert for every event you enabled in
//      the Alerts inputs, with the OB level in the message, or
//    • a single condition (New OB+, OB+ Tapped, OB+ Invalidated, ...). Use
//      "Once Per Bar Close" for New OB and Invalidated so they only fire on
//      confirmed closes.
//
//    Detection Logic:
//      - OB+ (Bullish): Last down-close candle before a bullish displacement
//        candle (up-close, closes above the OB candle's open) whose body > ATR filter
//      - OB- (Bearish): Last up-close candle before a bearish displacement
//        candle (down-close, closes below the OB candle's open) whose body > ATR filter
//
//    Changelog:
//      v1.9  - Added alerts: new OB, price taps OB level, OB invalidated
//            - Displacement candle must now close in the direction of the move
//            - Fixed: "Max OBs" limit could be exceeded because mitigated OBs
//              were removed instead of the oldest active one
//            - Fixed: mitigated OBs piled up forever in memory; now capped by
//              "Keep Mitigated OBs"
//            - With "Stop Line at Mitigation" OFF, invalidated lines turn dashed
//            - Rewritten with one OrderBlock type instead of 9 parallel arrays
//      v1.8  - Replaced text callouts with clean icons (▲▼✓)
//            - Added green checkmark for displacement confirmation
//            - Removed invalidation text callout (line shows level)
//            - Added icon size toggle (tiny/small)
//      v1.7  - Added vertical padding for callout labels
//      v1.6  - OB+/OB- label above/below line, triangle marker
//      v1.5  - Large font, force_overlay on labels
//      v1.4  - Added callout offset, centered line label
//      v1.3  - Mitigation requires CLOSE through level, skips displacement candle
//            - Added ATR-based displacement filter
//      v1.2  - Moved labels to right end of line
//      v1.1  - Fixed array bounds error
//      v1.0  - Initial release
//=============================================================================
indicator("ICT Order Blocks + Alerts", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
//=============================================================================
// Inputs
//=============================================================================
const string groupOB     = "Order Blocks"
const string groupFilter = "Filters"
const string groupViz    = "Visuals"
const string groupMit    = "Mitigation"
const string groupAlert  = "Alerts"
 
// OB Settings
int    maxBullOB   = input.int(5, "Max Bullish OBs", minval = 1, maxval = 15, group = groupOB,
                     tooltip = "Maximum number of active (not yet invalidated) bullish Order Blocks to display.\n\nWhat is an Order Block?\nThe last opposite-direction candle before a strong displacement move. Price often returns to this level as support/resistance.")
int    maxBearOB   = input.int(5, "Max Bearish OBs", minval = 1, maxval = 15, group = groupOB,
                     tooltip = "Maximum number of active (not yet invalidated) bearish Order Blocks to display.")
 
// Filter Settings
string atrTooltip  = "How strong must the displacement candle be?\n\n" +
                     "ATR (Average True Range) measures typical price movement.\n" +
                     "The multiplier sets the minimum displacement body size:\n\n" +
                     "• 0.5 = body must be ≥ half the ATR (more OBs, some weak)\n" +
                     "• 1.0 = body must be ≥ full ATR (balanced)\n" +
                     "• 1.5+ = only strong displacements (fewer OBs, higher quality)\n\n" +
                     "━━━ Timeframe Guidance ━━━\n" +
                     "ATR automatically adapts to your chart timeframe.\n" +
                     "However, lower timeframes have more noise:\n\n" +
                     "• 1m charts: Use 0.8 – 1.2 (filter noise)\n" +
                     "• 5m charts: Use 0.5 – 1.0 (balanced)\n" +
                     "• 15m charts: Use 0.5 – 0.8 (cleaner)\n" +
                     "• 4H charts: Use 0.3 – 0.7 (moves are meaningful)\n\n" +
                     "━━━ Warning ━━━\n" +
                     "⚠ Below 0.3 = too much noise, many false OBs\n" +
                     "⚠ Above 2.0 = may miss valid OBs"
 
float  minDispATR  = input.float(1.0, "Min Displacement (ATR multiplier)", minval = 0.1, maxval = 3.0, step = 0.1, group = groupFilter,
                     tooltip = atrTooltip)
int    atrLength   = input.int(14, "ATR Length", minval = 1, group = groupFilter,
                     tooltip = "Number of bars used to calculate ATR.\n\nDefault 14 works well for most timeframes.\nLower values (7-10) = more responsive to recent volatility.\nHigher values (20-30) = smoother, less reactive.")
 
// Visual Settings
color  colorOBplus = input.color(#2962ff, "OB+ Color (Bullish)", group = groupViz)
color  colorOBminus= input.color(#e91e63, "OB- Color (Bearish)", group = groupViz)
int    lineWidth   = input.int(2, "Line Width", minval = 1, maxval = 4, group = groupViz)
bool   showMarkers = input.bool(true, "Show OB Markers (▲▼✓)", group = groupViz,
                     tooltip = "Display triangle on OB candle and checkmark on displacement candle.\n\n▲▼ = Order Block candle\n✓ = Displacement confirmed")
string iconSize    = input.string("Small", "Icon Size", options = ["Tiny", "Small", "Normal"], group = groupViz,
                     tooltip = "Size of the marker icons on the chart.")
 
// Mitigation Settings
bool   stopAtMit   = input.bool(true, "Stop Line at Mitigation", group = groupMit,
                     tooltip = "End the OB line when price closes through the level.\nIf OFF, the line keeps extending as a dashed line.")
int    keepMitig   = input.int(3, "Keep Mitigated OBs (per side)", minval = 0, maxval = 15, group = groupMit,
                     tooltip = "How many invalidated OBs stay on the chart for reference. Older ones are removed.\n0 = remove an OB as soon as it is invalidated.")
 
// Alert Settings
bool   alertNew    = input.bool(true, "New OB formed", group = groupAlert,
                     tooltip = "Fires at the close of the displacement candle.")
bool   alertTap    = input.bool(true, "Price taps OB level", group = groupAlert,
                     tooltip = "Fires the first time price trades back to an active OB level (wick touch) after the displacement candle.")
bool   alertInval  = input.bool(true, "OB invalidated", group = groupAlert,
                     tooltip = "Fires when a candle closes through an active OB level.")
 
//=============================================================================
// Order Block type & storage
//=============================================================================
type OrderBlock
    float level
    int   obBar
    int   dispBar
    bool  mitigated = false
    bool  tapped    = false
    line  ln
    label lbl
    label mkOB
    label mkDisp
 
var array<OrderBlock> bullOBs = array.new<OrderBlock>()
var array<OrderBlock> bearOBs = array.new<OrderBlock>()
 
//=============================================================================
// Calculations
//=============================================================================
float  atrValue    = ta.atr(atrLength)
float  dispBody    = math.abs(close - open)
string iconSizeVal = iconSize == "Tiny" ? size.tiny : iconSize == "Small" ? size.small : size.normal
color  noBg        = color.new(color.white, 100)
 
//=============================================================================
// Helper Functions
//=============================================================================
// Delete all drawings that belong to an OB
destroyOB(OrderBlock ob) =>
    line.delete(ob.ln)
    label.delete(ob.lbl)
    label.delete(ob.mkOB)
    label.delete(ob.mkDisp)
 
// Keep at most maxActive active OBs and maxMitigated invalidated OBs (newest are kept)
pruneOBs(array<OrderBlock> obs, int maxActive, int maxMitigated) =>
    int active = 0
    int mitig  = 0
    if obs.size() > 0
        for i = obs.size() - 1 to 0
            OrderBlock ob = obs.get(i)
            if ob.mitigated
                mitig += 1
            else
                active += 1
            if (ob.mitigated and mitig > maxMitigated) or (not ob.mitigated and active > maxActive)
                destroyOB(ob)
                obs.remove(i)
 
// Draw a new OB and return it
newOB(bool bull, float level, int obBar, float obY, float dispY, color c) =>
    line  ln  = line.new(obBar, level, bar_index, level, color = c, width = lineWidth, style = line.style_solid)
    label lbl = label.new(bar_index, level, bull ? "OB+" : "OB-",
                          style = bull ? label.style_label_down : label.style_label_up,
                          color = noBg, textcolor = c, size = size.small, force_overlay = true)
    label mkOB   = na
    label mkDisp = na
    if showMarkers
        // Triangle on the OB candle, checkmark on the displacement candle
        mkOB   := label.new(obBar, obY, bull ? "▲" : "▼",
                            style = bull ? label.style_label_up : label.style_label_down,
                            color = noBg, textcolor = c, size = iconSizeVal, force_overlay = true)
        mkDisp := label.new(bar_index, dispY, "✓",
                            style = bull ? label.style_label_down : label.style_label_up,
                            color = noBg, textcolor = c, size = iconSizeVal, force_overlay = true)
    OrderBlock.new(level, obBar, bar_index, false, false, ln, lbl, mkOB, mkDisp)
 
// Extend lines and check taps / invalidation. Returns [tapped, invalidated, tapLevel, invalidLevel].
updateOBs(array<OrderBlock> obs, bool bull) =>
    bool  tap      = false
    bool  inval    = false
    float tapLvl   = na
    float invalLvl = na
    for ob in obs
        if not ob.mitigated or not stopAtMit
            ob.ln.set_x2(bar_index)
            ob.lbl.set_x(math.round((ob.obBar + bar_index) / 2.0))
        // Only check AFTER the displacement bar
        if not ob.mitigated and bar_index > ob.dispBar
            bool closedThrough = bull ? close < ob.level : close > ob.level
            bool touched       = bull ? low <= ob.level : high >= ob.level
            if closedThrough
                ob.mitigated := true
                inval        := true
                invalLvl     := ob.level
                if not stopAtMit
                    ob.ln.set_style(line.style_dashed)
            else if touched and not ob.tapped
                ob.tapped := true
                tap       := true
                tapLvl    := ob.level
    [tap, inval, tapLvl, invalLvl]
 
//=============================================================================
// OB Detection
//=============================================================================
// Displacement filter: current candle body must be significant
bool strongDisplacement = dispBody > atrValue * minDispATR
 
// Bullish OB: down-close candle [1] followed by a strong up-close candle [0] closing above open [1]
bool newOBplus  = close[1] < open[1] and close > open and close > open[1] and strongDisplacement
 
// Bearish OB: up-close candle [1] followed by a strong down-close candle [0] closing below open [1]
bool newOBminus = close[1] > open[1] and close < open and close < open[1] and strongDisplacement
 
//=============================================================================
// Update existing OBs, then add new ones
//=============================================================================
[bullTap, bullInval, bullTapLvl, bullInvalLvl] = updateOBs(bullOBs, true)
[bearTap, bearInval, bearTapLvl, bearInvalLvl] = updateOBs(bearOBs, false)
 
if newOBplus
    bullOBs.push(newOB(true, open[1], bar_index - 1, low[1], high, colorOBplus))
if newOBminus
    bearOBs.push(newOB(false, open[1], bar_index - 1, high[1], low, colorOBminus))
 
pruneOBs(bullOBs, maxBullOB, keepMitig)
pruneOBs(bearOBs, maxBearOB, keepMitig)
 
//=============================================================================
// Alerts
//=============================================================================
alertcondition(newOBplus,  "New OB+ (Bullish)", "New bullish Order Block (OB+) on {{ticker}} ({{interval}})")
alertcondition(newOBminus, "New OB- (Bearish)", "New bearish Order Block (OB-) on {{ticker}} ({{interval}})")
alertcondition(bullTap,    "OB+ Tapped",        "Price tapped a bullish Order Block (OB+) on {{ticker}} ({{interval}})")
alertcondition(bearTap,    "OB- Tapped",        "Price tapped a bearish Order Block (OB-) on {{ticker}} ({{interval}})")
alertcondition(bullInval,  "OB+ Invalidated",   "Bullish Order Block (OB+) invalidated on {{ticker}} ({{interval}})")
alertcondition(bearInval,  "OB- Invalidated",   "Bearish Order Block (OB-) invalidated on {{ticker}} ({{interval}})")
 
string alertAt = " on " + syminfo.ticker + " (" + timeframe.period + ") at "
 
if alertNew and newOBplus
    alert("New OB+" + alertAt + str.tostring(open[1], format.mintick), alert.freq_once_per_bar_close)
if alertNew and newOBminus
    alert("New OB-" + alertAt + str.tostring(open[1], format.mintick), alert.freq_once_per_bar_close)
if alertTap and bullTap
    alert("OB+ tapped" + alertAt + str.tostring(bullTapLvl, format.mintick), alert.freq_once_per_bar)
if alertTap and bearTap
    alert("OB- tapped" + alertAt + str.tostring(bearTapLvl, format.mintick), alert.freq_once_per_bar)
if alertInval and bullInval
    alert("OB+ invalidated" + alertAt + str.tostring(bullInvalLvl, format.mintick), alert.freq_once_per_bar_close)
if alertInval and bearInval
    alert("OB- invalidated" + alertAt + str.tostring(bearInvalLvl, format.mintick), alert.freq_once_per_bar_close)

← 返回列表