Indicator · Pine Script v6 · On the chart

Capital41 Order Block Detector v2

by damianpitt· code credited to Capital41 | MIT License

Capital41 Order Block Detector v2 identifies institutional supply and demand zones on the price chart.

View on GitHub

GitHub stars6on the repository
Pine versionv6current
Lines of code255
Settings10inputs
LicenceMIT
Last update8 weeks ago31 Aug 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

255 lines of Pine Script v6 from Capital41_Order_Block/Capital41_Order_Block_v2.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

Capital41_Order_Block_v2.pine
// Copyright (c) 2026 Capital41 | MIT License
// CAPITAL41 ORDER BLOCK DETECTOR v2

// What it does:
// - Detects bullish and bearish order blocks (OBs) based on impulse candles.
// - Bullish OB: the last bearish candle before a strong bullish impulse move.
//   Marks an institutional demand zone where buyers stepped in.
// - Bearish OB: the last bullish candle before a strong bearish impulse move.
//   Marks an institutional supply zone where sellers stepped in.
// - Tracks mitigation: when price returns to the OB zone it is considered tested.
// - Draws color-coded boxes that fade with age and turn gray on mitigation.
// - Completes the ICT/SMC toolkit alongside Liquidity Sweep, Liquidity Void Map,
//   and Structure Swings.
//
// TradingView setup:
// 1) Open TradingView -> Pine Editor.
// 2) Paste this script, Save, and Add to chart.
// 3) Use 30m or 4h on BTC or US stocks.
// 4) Adjust impulse multiplier for sensitivity (lower = more OBs, more noise).
//
// Usage guide (30m/4h):
// - Bullish OBs (green boxes) act as demand / support zones on pullbacks.
// - Bearish OBs (red boxes) act as supply / resistance zones on rallies.
// - Fresh (unmitigated) OBs are higher probability than stale/mitigated ones.
// - OBs that align with BOS levels from Structure Swings are highest quality.
// - Combine with Liquidity Sweep for stop-hunt confirmation at OB zones.
// - Combine with Liquidity Void Map to find OBs that sit inside FVGs.



//@version=6
indicator("Capital41 Order Block Detector v2", overlay = true,
         max_boxes_count = 300, max_labels_count = 200)


// Inputs
atrLen         = input.int(14, "ATR length", minval = 1)
impulseMult    = input.float(1.5, "Impulse ATR multiplier", minval = 0.5, maxval = 5.0, step = 0.1)
obLookback     = input.int(10, "OB scan lookback (bars)", minval = 1, maxval = 30)
maxActive      = input.int(25, "Max active order blocks", minval = 5, maxval = 100)
freshnessLen   = input.int(80, "Freshness bars", minval = 10, maxval = 500)
minMitAge      = input.int(2, "Min bars before mitigation", minval = 1, maxval = 20)

useBody        = input.bool(false, "Use candle body only (vs full range)")
removeMitigated = input.bool(false, "Remove mitigated OBs")
showLabels     = input.bool(true, "Show OB labels")
showBadge      = input.bool(true, "Show status badge")

colorBull      = color.new(color.lime, 0)
colorBear      = color.new(color.red, 0)
colorMitigated = color.new(color.gray, 0)
colorNeutral   = color.new(color.gray, 80)


// ATR for impulse detection
atr = ta.atr(atrLen)

// Impulse detection (non-repainting)
bullImpulse = barstate.isconfirmed and close > open and (close - open) > atr * impulseMult
bearImpulse = barstate.isconfirmed and close < open and (open - close) > atr * impulseMult

// OB zone management via parallel arrays
var array<box>   obBox  = array.new<box>()
var array<float>  obTop  = array.new<float>()
var array<float>  obBot  = array.new<float>()
var array<int>    obDir  = array.new<int>()                      // 1 = bull, -1 = bear
var array<int>    obBorn = array.new<int>()
var array<bool>   obMit  = array.new<bool>()


// Helper: check if a new OB zone overlaps with an existing active OB of same direction
f_hasNearby(_top, _bot, _dir) =>
    found = false
    if array.size(obTop) > 0
        for i = 0 to array.size(obTop) - 1
            if array.get(obDir, i) == _dir
                eTop = array.get(obTop, i)
                eBot = array.get(obBot, i)
                if _top >= eBot and _bot <= eTop
                    found := true
                    break
    found

// Update existing OBs (run BEFORE creating new ones)
bullMitNow = false
bearMitNow = false

if array.size(obBox) > 0
    for i = array.size(obBox) - 1 to 0
        bx   = array.get(obBox, i)
        oTop = array.get(obTop, i)
        oBot = array.get(obBot, i)
        oDir = array.get(obDir, i)
        oBorn = array.get(obBorn, i)
        oMit = array.get(obMit, i)
        age  = bar_index - oBorn


        // Check mitigation (price returns to the OB zone)
        if not oMit and age >= minMitAge
            if oDir == 1 and low <= oTop
                array.set(obMit, i, true)
                oMit := true
                bullMitNow := true
            if oDir == -1 and high >= oBot
                array.set(obMit, i, true)
                oMit := true
                bearMitNow := true


        // Remove mitigated if configured
        if oMit and removeMitigated
            box.delete(bx)
            array.remove(obBox, i)
            array.remove(obTop, i)
            array.remove(obBot, i)
            array.remove(obDir, i)
            array.remove(obBorn, i)
            array.remove(obMit, i)
            continue


        // Remove very old OBs (3x freshness length)
        if age > freshnessLen * 3
            box.delete(bx)
            array.remove(obBox, i)
            array.remove(obTop, i)
            array.remove(obBot, i)
            array.remove(obDir, i)
            array.remove(obBorn, i)
            array.remove(obMit, i)
            continue


        // Extend box right edge
        box.set_right(bx, bar_index)


        // Age-fade transparency: fresh = 75, stale = 92, mitigated = 92
        freshPct = math.max(0.0, 1.0 - float(age) / float(freshnessLen))
        trans    = oMit ? 92 : int(75.0 + (1.0 - freshPct) * 17.0)
        bgCol    = oMit ? color.new(colorMitigated, trans) : oDir == 1 ? color.new(colorBull, trans) : color.new(colorBear, trans)
        bdCol    = oMit ? color.new(colorMitigated, 50) : oDir == 1 ? colorBull : colorBear
        box.set_bgcolor(bx, bgCol)
        box.set_border_color(bx, bdCol)

// Detect new order blocks
bullOBCreated = false
bearOBCreated = false

if bullImpulse
    for i = 1 to obLookback
        if close[i] < open[i]  // last bearish candle = bullish OB
            obT = useBody ? open[i] : high[i]
            obB = useBody ? close[i] : low[i]
            if not f_hasNearby(obT, obB, 1)
                bx = box.new(bar_index - i, obT, bar_index, obB,
                     bgcolor = color.new(colorBull, 75), border_color = colorBull, border_width = 1)
                array.push(obBox, bx)
                array.push(obTop, obT)
                array.push(obBot, obB)
                array.push(obDir, 1)
                array.push(obBorn, bar_index)
                array.push(obMit, false)
                bullOBCreated := true
                if showLabels
                    label.new(bar_index - i, obB, "OB",
                              style = label.style_label_up, color = color.new(colorBull, 60),
                              textcolor = color.white, size = size.tiny)
            break

if bearImpulse
    for i = 1 to obLookback
        if close[i] > open[i]  // last bullish candle = bearish OB
            obT = useBody ? close[i] : high[i]
            obB = useBody ? open[i] : low[i]
            if not f_hasNearby(obT, obB, -1)
                bx = box.new(bar_index - i, obT, bar_index, obB,
                     bgcolor = color.new(colorBear, 75), border_color = colorBear, border_width = 1)
                array.push(obBox, bx)
                array.push(obTop, obT)
                array.push(obBot, obB)
                array.push(obDir, -1)
                array.push(obBorn, bar_index)
                array.push(obMit, false)
                bearOBCreated := true
                if showLabels
                    label.new(bar_index - i, obT, "OB",
                              style = label.style_label_down, color = color.new(colorBear, 60),
                              textcolor = color.white, size = size.tiny)
            break


// Enforce max active: remove oldest when over limit
while array.size(obBox) > maxActive
    box.delete(array.shift(obBox))
    array.shift(obTop)
    array.shift(obBot)
    array.shift(obDir)
    array.shift(obBorn)
    array.shift(obMit)

// === Counts for badge ===
bullActive = 0, bearActive = 0, bullMit = 0, bearMit = 0
if array.size(obDir) > 0
    for i = 0 to array.size(obDir) - 1
        d = array.get(obDir, i)
        m = array.get(obMit, i)
        if d == 1
            if m
                bullMit += 1
            else
                bullActive += 1
        else
            if m
                bearMit += 1
            else
                bearActive += 1
                

// Status badge
var table status = table.new(position.bottom_center, 4, 1, border_width = 1)
if barstate.islast
    if showBadge
        bText = " B " + str.tostring(bullActive) + " "
        sText = " S " + str.tostring(bearActive) + " "
        mText = " MIT " + str.tostring(bullMit + bearMit) + " "
        tText = " TOT " + str.tostring(array.size(obBox)) + " "

        table.cell(status, 0, 0, bText, bgcolor = bullActive > 0 ? color.new(colorBull, 65) : colorNeutral,
                   text_color = color.white, text_size = size.tiny)
        table.cell(status, 1, 0, sText, bgcolor = bearActive > 0 ? color.new(colorBear, 65) : colorNeutral,
                   text_color = color.white, text_size = size.tiny)
        table.cell(status, 2, 0, mText, bgcolor = (bullMit + bearMit) > 0 ? color.new(colorMitigated, 70) : colorNeutral,
                   text_color = color.white, text_size = size.tiny)
        table.cell(status, 3, 0, tText, bgcolor = color.new(color.gray, 75),
                   text_color = color.white, text_size = size.tiny)
    else
        for i = 0 to 3
            table.cell(status, i, 0, "", bgcolor = color.new(color.black, 100), text_color = color.new(color.black, 100))


// Alerts
alertcondition(bullOBCreated, title = "Bullish OB Created",
               message = "Order Block: new bullish OB (demand zone) on {{ticker}} ({{interval}})")

alertcondition(bearOBCreated, title = "Bearish OB Created",
               message = "Order Block: new bearish OB (supply zone) on {{ticker}} ({{interval}})")

// Mitigation alerts: fire when any OB was just mitigated this bar
alertcondition(bullMitNow, title = "Bullish OB Mitigated",
               message = "Order Block: bullish OB (demand) mitigated on {{ticker}} ({{interval}})")

alertcondition(bearMitNow, title = "Bearish OB Mitigated",
               message = "Order Block: bearish OB (supply) mitigated on {{ticker}} ({{interval}})")

Overview

Capital41 Order Block Detector v2 defines bullish order blocks as the last bearish candle prior to a strong upward impulse move and bearish order blocks as the last bullish candle before a downward impulse, measured using an ATR multiplier. It plots color-coded boxes for active order blocks, changing box appearance as zones age or become mitigated when price returns to them. User inputs adjust ATR settings, impulse multiplier thresholds, lookback depth, zone limits, body versus wick range, and label visibility.

Details

Published by

damianpitt on GitHub

Code credit

Capital41 | MIT License, as written in the script's header

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

SMC / ICT / price action, Support & resistance

Markets

Crypto, Stocks

Timeframes

M15-H1, H4 and above

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

cryptoindicatorsmarket-structureorder-blockspinescriptsmart-moneytechnical-analysistechnical-analysis-indicatorstradingtradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
ATR lengthint14atrLen
Impulse ATR multiplierfloat1.5impulseMult
OB scan lookback (bars)int10obLookback
Max active order blocksint25maxActive
Freshness barsint80freshnessLen
Min bars before mitigationint2minMitAge
Use candle body only (vs full range)boolfalseuseBody
Remove mitigated OBsboolfalseremoveMitigated
Show OB labelsbooltrueshowLabels
Show status badgebooltrueshowBadge
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

ICT Equal Highs and Lows

by ArunKBhaskar
575 stars

This overlay indicator finds pivot highs and lows on the price chart and compares the last two highs and the last two lows. When the percentage difference between a pair is below the Equal HL threshold, it treats them as equal levels and draws a box. Left and

Indicator v5 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows

DE-tracker

by Allen1212
303 stars

This indicator plots labels on the TradingView price chart to mark ARK Invest's buy and sell trades for the DE stock. Buy transactions appear in green with X1 or X2 multipliers showing the number of ARK ETFs involved on the same day; sells appear in red. The m

Indicator v4 Support & resistanceSMC / ICT / price action
Updated 2 years ago · None stated GitHub repository of DE-tracker

This Pine Script indicator plots a ZigZag on the price chart. It identifies reversal points when price moves more than a set percentage from the last pivot. The script calculates forecasts using zigzag data and labels detected geometric patterns including harm

Indicator v4 TrendSupport & resistance

Golden Bullet Strategy

by TradersPost
218 stars

The Golden Bullet Strategy is an overlay signal indicator based on Smart Money Concepts and time-based liquidity models. It identifies liquidity sweeps of a designated reference session range during a specified hunt window. It then confirms Market Structure Sh

Indicator v6 SMC / ICT / price actionSessions & time
Updated 3 months ago · None stated GitHub repository of Golden Bullet Strategy

Open Source Fractal

by cantolab
183 stars

This indicator implements the Fractal Model concept to plot market structure shifts, liquidity sweeps, and Change in State of Delivery (CISD) levels. It overlays custom higher-timeframe candle previews, open prices, and time markers directly on the price chart

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 2 months ago · MIT GitHub repository of Open Source Fractal

Swing Failure Signals

by Ganador1
154 stars

This indicator calculates pivot highs and pivot lows to detect liquidity sweeps and Swing Failure Patterns. It identifies when price breaks past recent key swing highs or lows within a configurable historical window, then looks for a quick reversal or change i

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 2 months ago · Apache-2.0 GitHub repository of Swing Failure Signals

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers