MarketStructure

613
MarketStructure

Overview

MarketStructure is a Pine Script v6 library of smart money concepts building blocks: alternating swing points, market structure with Break of Structure (BOS) and Change of Character (CHoCH), the dealing range, order blocks and fair value gaps, plus the drawing helpers an indicator needs to show them.

It is written so that one indicator can run several structures side by side (for example a 50-bar swing structure and a 5-bar internal structure) and so that order flow or other confirmations can be plugged into breaks, gap entries and gap inversions through optional parameters.

What's inside

  • swings(len): confirms swing highs and lows that alternate. A swing high is the highest high of len bars on each side and is confirmed len bars later. A second high in a row only counts if it is higher, and then replaces the first.
  • Structure, newStructure() and update(len, bullOk, bearOk): tracks the latest swing high and low, tags each new swing as HH, LH, HL or LL, follows the dealing range (the highest high and lowest low since the latest swings) and detects breaks: a close beyond the latest unbroken swing. A break against the previous bias is a CHoCH, a break with it is a BOS. bullOk and bearOk let the calling script add its own confirmation.
  • drawBreak(), drawSwingLabel(), drawStrongWeak(), drawZones(): draw breaks, swing labels, strong / weak highs and lows, and premium / discount zones (range extremes, 79-100% extreme zones, 62-79% optimal trade entry zones with their 70.5% lines, and the 50% equilibrium).
  • OrderBlock, findOrderBlock(fromBar, bias, maxRange), mitigate(), nearAny(), drawOrderBlocks(): at a bullish break, the order block is the down-close candle with the lowest low between the broken swing and the break (the mirror for bearish breaks). Candles larger than maxRange are never chosen. Blocks are removed when price closes (or wicks) through them.
  • Gap, GapStyle, newGap(), addGap(), updateGaps(): fair value gaps drawn as two halves split at the 50% line. updateGaps() extends untested gaps, fires one entry signal when price pulls back into a gap and a candle closes back out of it in its direction, inverts a gap that is closed through on high volume, and deletes a gap whose 50% line fails on a body close. Gaps against the swing trend can be treated as targets that never signal.


Quick start

Pine Script®


Notes

  • Swings are confirmed len bars after they print, so structure always lags by the swing length. Breaks use closes only.
  • Call update() and swings() once per bar, unconditionally; each call site keeps its own state.
  • Fair value gaps should be detected from closed candles (the indicators that use this library request offsets 3, 2 and 1 with lookahead), so they never repaint.
  • The concepts (market structure, order blocks, fair value gaps, premium / discount) are widely taught smart money concepts. This library is an independent implementation.


Demo

Add the library to a chart on its own to see a demo that uses every exported function.

Library "MarketStructure"
Smart-money market structure toolkit. `swings()` confirms alternating swing highs and lows; `Structure`
tracks them with Higher High / Lower High / Higher Low / Lower Low tags, breaks of structure (BOS) and
changes of character (CHoCH), and the dealing range between them. Order blocks are found at each break
and retired when price mitigates them. Fair value gaps are drawn as two halves split at their 50% line
and managed through their life: pullback entries, inversion when a candle closes through them on high
volume, and failure when a body closes past the 50% line. Drawing helpers cover breaks, swing labels,
order blocks, strong / weak highs and lows, and premium / discount zones.

swings(len)
  Confirms swing highs and lows that alternate. A swing high is the highest high of `len` bars on each side,
confirmed `len` bars after it prints (likewise for lows). After a swing high, another swing high only
counts if it is higher (it replaces the first); the same for lows. Call it once per bar, unconditionally.
  Parameters:
    len (simple int): (simple int) Bars on each side of the swing.
  Returns: ([bool, bool]) A new swing high / a new swing low was confirmed on this bar. Its price is `high[len]` /
`low[len]`.

newStructure()
  Creates an empty Structure. Declare it with `var`.
  Returns: (Structure) The structure.

method update(s, len, bullOk, bearOk)
  Advances the structure by one bar: confirms swings, tracks the dealing range and detects breaks (a close
beyond the latest unbroken swing). Call it once per bar, unconditionally.
  Namespace types: Structure
  Parameters:
    s (Structure): (Structure) The structure.
    len (simple int): (simple int) Swing length (bars on each side).
    bullOk (bool): (series bool) Allow a bullish break on this bar, for extra confirmation filters. Optional. Default is
`true`.
    bearOk (bool): (series bool) Allow a bearish break on this bar. Optional. Default is `true`.
  Returns: (Event) What changed on this bar.

drawBreak(sw, tag, c, lineStyle, above, textSize, keepHistory)
  Draws a break: a line from the broken swing to this bar and the tag at its middle. With `keepHistory` off,
each call site keeps only its latest drawing.
  Parameters:
    sw (Swing): (Swing) The broken swing.
    tag (string): (series string) Label text, e.g. "Break of Structure".
    c (color): (series color) Colour.
    lineStyle (string): (series string) A `line.style_*` value.
    above (bool): (series bool) Label above the line (bullish breaks) or below it.
    textSize (int): (series int) Label text size, in points.
    keepHistory (bool): (series bool) Keep previous drawings of this call site.
  Returns: (void)

drawSwingLabel(sw, tag, c, above, textSize, keepHistory, replaces)
  Labels a swing point. A swing that replaced the previous one of its side takes over that label.
  Parameters:
    sw (Swing): (Swing) The swing.
    tag (string): (series string) Label text, e.g. "Higher High".
    c (color): (series color) Colour.
    above (bool): (series bool) Label above the swing (highs) or below it (lows).
    textSize (int): (series int) Text size, in points.
    keepHistory (bool): (series bool) Keep previous labels of this call site.
    replaces (bool): (series bool) Delete this call site's previous label first (it marked a swing that was replaced).
  Returns: (void)

method drawStrongWeak(s, bullCol, bearCol, textSize)
  Draws the dealing range's extremes, extended right: the high is Strong in a bearish structure (it must
hold) and Weak otherwise; the low is Strong in a bullish structure. Call it on every bar; it draws on the last.
  Namespace types: Structure
  Parameters:
    s (Structure): (Structure) The (swing) structure.
    bullCol (color): (series color) Colour of the low.
    bearCol (color): (series color) Colour of the high.
    textSize (int): (series int) Text size, in points.
  Returns: (void)

method drawZones(s, premiumCol, eqCol, discountCol, textSize)
  Draws premium / discount zones of the dealing range: the range high and low (stops for shorts / longs),
the extreme zones (79-100%), the optimal trade entry zones (62-79%) with their 70.5% lines, and the 50%
equilibrium. Call it on every bar; it draws on the last.
  Namespace types: Structure
  Parameters:
    s (Structure): (Structure) The (swing) structure.
    premiumCol (color): (series color) Premium colour.
    eqCol (color): (series color) Equilibrium colour.
    discountCol (color): (series color) Discount colour.
    textSize (int): (series int) Text size, in points.
  Returns: (void)

findOrderBlock(fromBar, bias, maxRange)
  Finds the order block of a break. For a bullish break it is the down-close candle with the lowest low
between the broken swing and this bar (a bearish break: the up-close candle with the highest high). Candles
whose range exceeds `maxRange` are skipped; if no opposite-colour candle remains, the lowest-low
(highest-high) candle is used. Scans at most 500 bars back.
  Parameters:
    fromBar (int): (series int) Bar index of the broken swing.
    bias (int): (series int) 1 for a bullish break, -1 for a bearish break.
    maxRange (float): (series float) Largest candle range considered.
  Returns: (OrderBlock) The block, or `na` when no candle qualifies.

method mitigate(obs, useClose)
  Removes the order blocks price has mitigated: a bullish block when the source goes below its bottom, a
bearish block when it goes above its top.
  Namespace types: array<OrderBlock>
  Parameters:
    obs (array<OrderBlock>): (array<OrderBlock>) Order blocks.
    useClose (bool): (series bool) Mitigate on a close beyond the block (`true`) or on a wick (`false`).
  Returns: ([bool, bool]) A bullish / a bearish block was mitigated on this bar.

method nearAny(obs, count, top, bottom, bias, dist)
  Whether one of the newest `count` order blocks of a bias lies within `dist` of a price range.
  Namespace types: array<OrderBlock>
  Parameters:
    obs (array<OrderBlock>): (array<OrderBlock>) Order blocks, newest first.
    count (int): (series int) Blocks considered.
    top (float): (series float) Range top.
    bottom (float): (series float) Range bottom.
    bias (int): (series int) Block bias to look for.
    dist (float): (series float) Allowed distance.
  Returns: (bool) A block is near.

drawOrderBlocks(obs, count, boxes, labels, bullCol, bearCol, kind, textSize, border)
  Draws the newest `count` order blocks, extended right, into a pool of boxes and labels that is created on
first use. Call it on the last bar.
  Parameters:
    obs (array<OrderBlock>): (array<OrderBlock>) Order blocks, newest first.
    count (int): (series int) Blocks to show.
    boxes (array<box>): (array<box>) Box pool for this set of blocks (start with an empty `var` array).
    labels (array<label>): (array<label>) Label pool for this set of blocks (start with an empty `var` array).
    bullCol (color): (series color) Bullish block colour.
    bearCol (color): (series color) Bearish block colour.
    kind (string): (series string) Name prefix, e.g. "Internal" or "Swing".
    textSize (int): (series int) Label text size, in points.
    border (bool): (series bool) Draw a border.
  Returns: (void)

newGap(top, bottom, bias, leftTime, rightTime, sweep, nearOb, target, st)
  Creates and draws a gap.
  Parameters:
    top (float): (series float) Gap top.
    bottom (float): (series float) Gap bottom.
    bias (int): (series int) 1 bullish, -1 bearish.
    leftTime (int): (series int) Time of the gap's middle candle (left edge).
    rightTime (int): (series int) Time of the gap's last candle (right edge until it is touched).
    sweep (bool): (series bool) Formed right after a liquidity sweep.
    nearOb (bool): (series bool) An order block of the same bias is near.
    target (bool): (series bool) Against the swing trend.
    st (GapStyle): (GapStyle) Settings.
  Returns: (Gap) The gap.

method addGap(gaps, g, maxCount)
  Adds a gap as the newest, keeping at most `maxCount` (older ones stay drawn but stop updating).
  Namespace types: array<Gap>
  Parameters:
    gaps (array<Gap>): (array<Gap>) Gaps, newest first.
    g (Gap): (Gap) The new gap.
    maxCount (int): (series int) Gaps tracked. Optional. Default is 50.
  Returns: (void)

method updateGaps(gaps, st, swingBias, atr, highVolume, entryBuyOk, entrySellOk, invertDownOk, invertUpOk)
  Updates every tracked gap on this bar. Untouched gaps extend to the current bar. A candle that closes
through a gap against it on high volume inverts the gap (when allowed); otherwise a body close past the 50%
line fails the gap and deletes it. After a pullback into a gap, a candle closing back out of it in its
direction (within `atr` of its edge) gives one entry signal, unless the gap is a target.
  Namespace types: array<Gap>
  Parameters:
    gaps (array<Gap>): (array<Gap>) Gaps, newest first.
    st (GapStyle): (GapStyle) Settings.
    swingBias (int): (series int) Swing structure bias, for targets.
    atr (float): (series float) Largest distance between the signal close and the gap edge.
    highVolume (bool): (series bool) This bar's volume is high enough to invert a gap.
    entryBuyOk (bool): (series bool) Extra confirmation for buy signals. Optional. Default is `true`.
    entrySellOk (bool): (series bool) Extra confirmation for sell signals. Optional. Default is `true`.
    invertDownOk (bool): (series bool) Extra confirmation for a bullish gap to invert into a bearish one. Optional.
Default is `true`.
    invertUpOk (bool): (series bool) Extra confirmation for a bearish gap to invert into a bullish one. Optional. Default
is `true`.
  Returns: (GapEvents) What happened on this bar.

Swing
  A confirmed swing point.
  Fields:
    price (series float): Swing price.
    barIndex (series int): Bar index of the swing candle.
    barTime (series int): Opening time of the swing candle.
    broken (series bool): A close has already gone through it.

Structure
  Market structure for one swing length. Create it with `var Structure s = newStructure()`.
  Fields:
    high (Swing): Latest swing high.
    low (Swing): Latest swing low.
    prevHigh (series float): Price of the swing high before `high` (for Higher / Lower High).
    prevLow (series float): Price of the swing low before `low` (for Higher / Lower Low).
    bias (series int): 1 after a bullish break, -1 after a bearish break, 0 before the first break.
    lastSide (series int): 1 if the latest swing was a high, -1 if it was a low.
    rangeTop (series float): Highest price since the latest swing high: the top of the dealing range.
    rangeBottom (series float): Lowest price since the latest swing low: the bottom of the dealing range.
    rangeTopTime (series int): Time of the bar that set `rangeTop`.
    rangeBottomTime (series int): Time of the bar that set `rangeBottom`.

Event
  What changed in a Structure on this bar, returned by `update()`.
  Fields:
    newHigh (series bool): A swing high was confirmed (it is now `Structure.high`).
    newLow (series bool): A swing low was confirmed (it is now `Structure.low`).
    highReplaced (series bool): The new swing high replaced a swing high that had no swing low after it.
    lowReplaced (series bool): The new swing low replaced a swing low that had no swing high after it.
    highTag (series string): "HH" or "LH" for a new swing high (`na` for the first one).
    lowTag (series string): "HL" or "LL" for a new swing low (`na` for the first one).
    breakDir (series int): 1 when a close broke the swing high, -1 when it broke the swing low, 0 otherwise.
    choch (series bool): The break went against the previous bias: a change of character (otherwise a break of structure).
    broken (Swing): The swing that was broken.

OrderBlock
  An order block: the candle the move that broke structure started from.
  Fields:
    top (series float): Candle high.
    bottom (series float): Candle low.
    barTime (series int): Candle time.
    barIndex (series int): Candle bar index.
    bias (series int): 1 for a bullish (demand) block, -1 for a bearish (supply) block.
    note (series string): Optional extra tag shown after the block's name.

Gap
  A fair value gap, drawn as two boxes split at its 50% line (consequent encroachment).
  Fields:
    top (series float): Gap top.
    bottom (series float): Gap bottom.
    bias (series int): 1 bullish (support), -1 bearish (resistance). Flips when the gap inverts.
    upper (series box): Box of the upper half.
    lower (series box): Box of the lower half.
    tag (series label): Label with the gap's name and tags.
    sweep (series bool): The gap formed right after a liquidity sweep.
    nearOb (series bool): An order block of the same bias is near.
    target (series bool): The gap opposes the swing trend: a liquidity target, not an entry.
    touched (series bool): Price has pulled back into the gap.
    deep (series bool): The pullback reached the 50% line.
    signaled (series bool): An entry signal has fired for this gap.
    inverted (series bool): The gap was closed through and flipped direction.

GapStyle
  Display and behaviour settings for fair value gaps.
  Fields:
    bullColor (series color): Bullish gap colour (its transparency is the fill).
    bearColor (series color): Bearish gap colour.
    buyColor (series color): Buy signal label colour.
    sellColor (series color): Sell signal label colour.
    textSize (series int): Text size, in points.
    showSignals (series bool): Draw entry signal labels.
    useTargets (series bool): Gaps against the swing trend become targets (faded, no signals).
    allowInversion (series bool): Gaps that fail on a high-volume opposing candle invert instead of being deleted.

GapEvents
  Gap events on one bar, returned by `updateGaps()`.
  Fields:
    bullEntry (series bool): A bullish gap gave a buy signal.
    bearEntry (series bool): A bearish gap gave a sell signal.
    bullInverse (series bool): A bearish gap inverted into a bullish one.
    bearInverse (series bool): A bullish gap inverted into a bearish one.
    bullFailed (series bool): A bullish gap failed (body close below its 50% line).
    bearFailed (series bool): A bearish gap failed (body close above its 50% line).

Wyłączenie odpowiedzialności

Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.