本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jabez4jc
//@version=6
// @description 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.
library("MarketStructure", overlay = true)
//#region ———————————————————— Swings and structure
// @function 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.
// @param len (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]`.
export swings(simple int len) =>
var int side = 0
var float lastHigh = na
var float lastLow = na
float ph = ta.pivothigh(high, len, len)
float pl = ta.pivotlow(low, len, len)
bool newHigh = not na(ph) and (side != 1 or ph > lastHigh)
if newHigh
side := 1
lastHigh := ph
bool newLow = not na(pl) and (side != -1 or pl < lastLow)
if newLow
side := -1
lastLow := pl
[newHigh, newLow]
// @type A confirmed swing point.
// @field price Swing price.
// @field barIndex Bar index of the swing candle.
// @field barTime Opening time of the swing candle.
// @field broken A close has already gone through it.
export type Swing
float price
int barIndex
int barTime
bool broken = false
// @type Market structure for one swing length. Create it with `var Structure s = newStructure()`.
// @field high Latest swing high.
// @field low Latest swing low.
// @field prevHigh Price of the swing high before `high` (for Higher / Lower High).
// @field prevLow Price of the swing low before `low` (for Higher / Lower Low).
// @field bias 1 after a bullish break, -1 after a bearish break, 0 before the first break.
// @field lastSide 1 if the latest swing was a high, -1 if it was a low.
// @field rangeTop Highest price since the latest swing high: the top of the dealing range.
// @field rangeBottom Lowest price since the latest swing low: the bottom of the dealing range.
// @field rangeTopTime Time of the bar that set `rangeTop`.
// @field rangeBottomTime Time of the bar that set `rangeBottom`.
export type Structure
Swing high
Swing low
float prevHigh
float prevLow
int bias = 0
int lastSide = 0
float rangeTop
float rangeBottom
int rangeTopTime
int rangeBottomTime
// @type What changed in a Structure on this bar, returned by `update()`.
// @field newHigh A swing high was confirmed (it is now `Structure.high`).
// @field newLow A swing low was confirmed (it is now `Structure.low`).
// @field highReplaced The new swing high replaced a swing high that had no swing low after it.
// @field lowReplaced The new swing low replaced a swing low that had no swing high after it.
// @field highTag "HH" or "LH" for a new swing high (`na` for the first one).
// @field lowTag "HL" or "LL" for a new swing low (`na` for the first one).
// @field breakDir 1 when a close broke the swing high, -1 when it broke the swing low, 0 otherwise.
// @field choch The break went against the previous bias: a change of character (otherwise a break of structure).
// @field broken The swing that was broken.
export type Event
bool newHigh = false
bool newLow = false
bool highReplaced = false
bool lowReplaced = false
string highTag
string lowTag
int breakDir = 0
bool choch = false
Swing broken
// @function Creates an empty Structure. Declare it with `var`.
// @returns (Structure) The structure.
export newStructure() =>
Structure.new(Swing.new(), Swing.new())
// @function 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.
// @param s (Structure) The structure.
// @param len (simple int) Swing length (bars on each side).
// @param bullOk (series bool) Allow a bullish break on this bar, for extra confirmation filters. Optional. Default is
// `true`.
// @param bearOk (series bool) Allow a bearish break on this bar. Optional. Default is `true`.
// @returns (Event) What changed on this bar.
export method update(Structure s, simple int len, bool bullOk = true, bool bearOk = true) =>
Event e = Event.new()
[newHigh, newLow] = swings(len)
if newHigh
e.highReplaced := s.lastSide == 1
if not e.highReplaced
s.prevHigh := s.high.price
s.high := Swing.new(high[len], bar_index - len, time[len])
s.lastSide := 1
s.rangeTop := high[len]
s.rangeTopTime := time[len]
e.newHigh := true
e.highTag := na(s.prevHigh) ? na : s.high.price > s.prevHigh ? "HH" : "LH"
if newLow
e.lowReplaced := s.lastSide == -1
if not e.lowReplaced
s.prevLow := s.low.price
s.low := Swing.new(low[len], bar_index - len, time[len])
s.lastSide := -1
s.rangeBottom := low[len]
s.rangeBottomTime := time[len]
e.newLow := true
e.lowTag := na(s.prevLow) ? na : s.low.price < s.prevLow ? "LL" : "HL"
if not na(s.rangeTop) and high > s.rangeTop
s.rangeTop := high
s.rangeTopTime := time
if not na(s.rangeBottom) and low < s.rangeBottom
s.rangeBottom := low
s.rangeBottomTime := time
if not na(s.high.price) and not s.high.broken and close > s.high.price and bullOk
s.high.broken := true
e.breakDir := 1
e.choch := s.bias == -1
e.broken := s.high
s.bias := 1
if not na(s.low.price) and not s.low.broken and close < s.low.price and bearOk
s.low.broken := true
e.breakDir := -1
e.choch := s.bias == 1
e.broken := s.low
s.bias := -1
e
// @function 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.
// @param sw (Swing) The broken swing.
// @param tag (series string) Label text, e.g. "Break of Structure".
// @param c (series color) Colour.
// @param lineStyle (series string) A `line.style_*` value.
// @param above (series bool) Label above the line (bullish breaks) or below it.
// @param textSize (series int) Label text size, in points.
// @param keepHistory (series bool) Keep previous drawings of this call site.
// @returns (void)
export drawBreak(Swing sw, string tag, color c, string lineStyle, bool above, int textSize, bool keepHistory) =>
var line ln = na
var label lb = na
if not keepHistory
ln.delete()
lb.delete()
ln := line.new(sw.barTime, sw.price, time, sw.price, xloc = xloc.bar_time, color = c, style = lineStyle)
lb := label.new(math.round(0.5 * (sw.barIndex + bar_index)), sw.price, tag, color = color(na), textcolor = c, style = above ? label.style_label_down : label.style_label_up, size = textSize)
// @function Labels a swing point. A swing that replaced the previous one of its side takes over that label.
// @param sw (Swing) The swing.
// @param tag (series string) Label text, e.g. "Higher High".
// @param c (series color) Colour.
// @param above (series bool) Label above the swing (highs) or below it (lows).
// @param textSize (series int) Text size, in points.
// @param keepHistory (series bool) Keep previous labels of this call site.
// @param replaces (series bool) Delete this call site's previous label first (it marked a swing that was replaced).
// @returns (void)
export drawSwingLabel(Swing sw, string tag, color c, bool above, int textSize, bool keepHistory, bool replaces = false) =>
var label lb = na
if not keepHistory or replaces
lb.delete()
lb := label.new(sw.barTime, sw.price, tag, xloc = xloc.bar_time, color = color(na), textcolor = c, style = above ? label.style_label_down : label.style_label_up, size = textSize)
// @function 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.
// @param s (Structure) The (swing) structure.
// @param bullCol (series color) Colour of the low.
// @param bearCol (series color) Colour of the high.
// @param textSize (series int) Text size, in points.
// @returns (void)
export method drawStrongWeak(Structure s, color bullCol, color bearCol, int textSize) =>
var line topLine = line.new(na, na, na, na, xloc = xloc.bar_time)
var line botLine = line.new(na, na, na, na, xloc = xloc.bar_time)
var label topLbl = label.new(na, na, xloc = xloc.bar_time, color = color(na), style = label.style_label_down)
var label botLbl = label.new(na, na, xloc = xloc.bar_time, color = color(na), style = label.style_label_up)
if barstate.islast and not na(s.rangeTop) and not na(s.rangeBottom)
int right = time + 20 * (time - time[1])
topLine.set_xy1(s.rangeTopTime, s.rangeTop)
topLine.set_xy2(right, s.rangeTop)
topLine.set_color(bearCol)
topLbl.set_xy(right, s.rangeTop)
topLbl.set_text(s.bias == -1 ? "Strong High" : "Weak High")
topLbl.set_textcolor(bearCol)
topLbl.set_size(textSize)
botLine.set_xy1(s.rangeBottomTime, s.rangeBottom)
botLine.set_xy2(right, s.rangeBottom)
botLine.set_color(bullCol)
botLbl.set_xy(right, s.rangeBottom)
botLbl.set_text(s.bias == 1 ? "Strong Low" : "Weak Low")
botLbl.set_textcolor(bullCol)
botLbl.set_size(textSize)
zoneBox(int left, float top, float bottom, string tag, string tip, color c, int transp, int textSize) =>
var box bx = box.new(na, na, na, na, xloc = xloc.bar_time, border_color = color(na))
var label lb = label.new(na, na, xloc = xloc.bar_time, color = color(na), style = label.style_label_left)
bx.set_lefttop(left, top)
bx.set_rightbottom(time, bottom)
bx.set_bgcolor(color.new(c, transp))
lb.set_xy(time, math.avg(top, bottom))
lb.set_text(tag)
lb.set_textcolor(c)
lb.set_size(textSize)
lb.set_tooltip(tip + "\n" + str.tostring(bottom, format.mintick) + " - " + str.tostring(top, format.mintick))
zoneLevel(int left, float level, string tag, string tip, color c, string style, int textSize) =>
var line ln = line.new(na, na, na, na, xloc = xloc.bar_time)
var label lb = label.new(na, na, xloc = xloc.bar_time, color = color(na), style = label.style_label_left)
ln.set_xy1(left, level)
ln.set_xy2(time, level)
ln.set_color(c)
ln.set_style(style)
lb.set_xy(time, level)
lb.set_text(tag)
lb.set_textcolor(c)
lb.set_size(textSize)
lb.set_tooltip(tip == "" ? str.tostring(level, format.mintick) : tip + "\n" + str.tostring(level, format.mintick))
// @function 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.
// @param s (Structure) The (swing) structure.
// @param premiumCol (series color) Premium colour.
// @param eqCol (series color) Equilibrium colour.
// @param discountCol (series color) Discount colour.
// @param textSize (series int) Text size, in points.
// @returns (void)
export method drawZones(Structure s, color premiumCol, color eqCol, color discountCol, int textSize) =>
if barstate.islast and not na(s.rangeTop) and not na(s.rangeBottom)
int left = math.min(s.rangeTopTime, s.rangeBottomTime)
float top = s.rangeTop
float bot = s.rangeBottom
float r = top - bot
zoneLevel(left, top, "Range High · Stop for Shorts", "100% of the dealing range: stop level for shorts", premiumCol, line.style_dashed, textSize)
zoneBox(left, top, bot + 0.79 * r, "Extreme Premium 79-100%", "Extreme premium (79% - 100%): wait for a rejection", premiumCol, 70, textSize)
zoneBox(left, bot + 0.79 * r, bot + 0.62 * r, "Premium · Short Entry 62-79%", "Premium optimal trade entry zone (62% - 79%)", premiumCol, 80, textSize)
zoneLevel(left, bot + 0.705 * r, "", "", premiumCol, line.style_dotted, textSize)
zoneLevel(left, math.avg(top, bot), "Equilibrium 50%", "50% of the dealing range", eqCol, line.style_dashed, textSize)
zoneLevel(left, top - 0.705 * r, "", "", discountCol, line.style_dotted, textSize)
zoneBox(left, top - 0.62 * r, top - 0.79 * r, "Discount · Long Entry 62-79%", "Discount optimal trade entry zone (62% - 79%)", discountCol, 80, textSize)
zoneBox(left, top - 0.79 * r, bot, "Extreme Discount 79-100%", "Extreme discount (79% - 100%): wait for a rejection", discountCol, 70, textSize)
zoneLevel(left, bot, "Range Low · Stop for Longs", "100% of the dealing range: stop level for longs", discountCol, line.style_dashed, textSize)
//#endregion
//#region ———————————————————— Order blocks
// @type An order block: the candle the move that broke structure started from.
// @field top Candle high.
// @field bottom Candle low.
// @field barTime Candle time.
// @field barIndex Candle bar index.
// @field bias 1 for a bullish (demand) block, -1 for a bearish (supply) block.
// @field note Optional extra tag shown after the block's name.
export type OrderBlock
float top
float bottom
int barTime
int barIndex
int bias
string note = ""
// @function 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.
// @param fromBar (series int) Bar index of the broken swing.
// @param bias (series int) 1 for a bullish break, -1 for a bearish break.
// @param maxRange (series float) Largest candle range considered.
// @returns (OrderBlock) The block, or `na` when no candle qualifies.
export findOrderBlock(int fromBar, int bias, float maxRange) =>
OrderBlock ob = na
if not na(fromBar) and fromBar <= bar_index
int span = math.min(bar_index - fromBar, 500)
int best = -1
int backup = -1
for i = 0 to span
if high[i] - low[i] <= maxRange
bool opposite = bias == 1 ? close[i] < open[i] : close[i] > open[i]
bool better = bias == 1 ? (backup < 0 or low[i] < low[backup]) : (backup < 0 or high[i] > high[backup])
if better
backup := i
if opposite and (best < 0 or (bias == 1 ? low[i] < low[best] : high[i] > high[best]))
best := i
int k = best >= 0 ? best : backup
if k >= 0
ob := OrderBlock.new(high[k], low[k], time[k], bar_index - k, bias)
ob
// @function 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.
// @param obs (array<OrderBlock>) Order blocks.
// @param useClose (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.
export method mitigate(array<OrderBlock> obs, bool useClose) =>
bool bullHit = false
bool bearHit = false
if obs.size() > 0
for i = obs.size() - 1 to 0
OrderBlock ob = obs.get(i)
bool gone = ob.bias == 1 ? (useClose ? close : low) < ob.bottom : (useClose ? close : high) > ob.top
if gone
bullHit := bullHit or ob.bias == 1
bearHit := bearHit or ob.bias == -1
obs.remove(i)
[bullHit, bearHit]
// @function Whether one of the newest `count` order blocks of a bias lies within `dist` of a price range.
// @param obs (array<OrderBlock>) Order blocks, newest first.
// @param count (series int) Blocks considered.
// @param top (series float) Range top.
// @param bottom (series float) Range bottom.
// @param bias (series int) Block bias to look for.
// @param dist (series float) Allowed distance.
// @returns (bool) A block is near.
export method nearAny(array<OrderBlock> obs, int count, float top, float bottom, int bias, float dist) =>
bool near = false
for [i, ob] in obs
if i >= count
break
if ob.bias == bias and ob.bottom - dist <= top and ob.top + dist >= bottom
near := true
break
near
// @function 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.
// @param obs (array<OrderBlock>) Order blocks, newest first.
// @param count (series int) Blocks to show.
// @param boxes (array<box>) Box pool for this set of blocks (start with an empty `var` array).
// @param labels (array<label>) Label pool for this set of blocks (start with an empty `var` array).
// @param bullCol (series color) Bullish block colour.
// @param bearCol (series color) Bearish block colour.
// @param kind (series string) Name prefix, e.g. "Internal" or "Swing".
// @param textSize (series int) Label text size, in points.
// @param border (series bool) Draw a border.
// @returns (void)
export drawOrderBlocks(array<OrderBlock> obs, int count, array<box> boxes, array<label> labels, color bullCol, color bearCol, string kind, int textSize, bool border) =>
while boxes.size() < count
boxes.push(box.new(na, na, na, na, xloc = xloc.bar_time, extend = extend.right))
labels.push(label.new(na, na, xloc = xloc.bar_time, color = color(na), style = label.style_label_left))
for i = 0 to count - 1
box bx = boxes.get(i)
label lb = labels.get(i)
if i < obs.size()
OrderBlock ob = obs.get(i)
color c = ob.bias == 1 ? bullCol : bearCol
string name = kind + (ob.bias == 1 ? " Bullish" : " Bearish") + " Order Block" + (ob.note == "" ? "" : " · " + ob.note)
bx.set_lefttop(ob.barTime, ob.top)
bx.set_rightbottom(time, ob.bottom)
bx.set_bgcolor(c)
bx.set_border_color(border ? c : color(na))
lb.set_xy(time, math.avg(ob.top, ob.bottom))
lb.set_text(name)
lb.set_textcolor(color.new(c, 0))
lb.set_size(textSize)
lb.set_tooltip(name + ": " + str.tostring(ob.bottom, format.mintick) + " - " + str.tostring(ob.top, format.mintick))
else
bx.set_lefttop(na, na)
bx.set_rightbottom(na, na)
lb.set_text("")
//#endregion
//#region ———————————————————— Fair value gaps
// @type A fair value gap, drawn as two boxes split at its 50% line (consequent encroachment).
// @field top Gap top.
// @field bottom Gap bottom.
// @field bias 1 bullish (support), -1 bearish (resistance). Flips when the gap inverts.
// @field upper Box of the upper half.
// @field lower Box of the lower half.
// @field tag Label with the gap's name and tags.
// @field sweep The gap formed right after a liquidity sweep.
// @field nearOb An order block of the same bias is near.
// @field target The gap opposes the swing trend: a liquidity target, not an entry.
// @field touched Price has pulled back into the gap.
// @field deep The pullback reached the 50% line.
// @field signaled An entry signal has fired for this gap.
// @field inverted The gap was closed through and flipped direction.
export type Gap
float top
float bottom
int bias
box upper
box lower
label tag
bool sweep = false
bool nearOb = false
bool target = false
bool touched = false
bool deep = false
bool signaled = false
bool inverted = false
// @type Display and behaviour settings for fair value gaps.
// @field bullColor Bullish gap colour (its transparency is the fill).
// @field bearColor Bearish gap colour.
// @field buyColor Buy signal label colour.
// @field sellColor Sell signal label colour.
// @field textSize Text size, in points.
// @field showSignals Draw entry signal labels.
// @field useTargets Gaps against the swing trend become targets (faded, no signals).
// @field allowInversion Gaps that fail on a high-volume opposing candle invert instead of being deleted.
export type GapStyle
color bullColor
color bearColor
color buyColor
color sellColor
int textSize
bool showSignals
bool useTargets
bool allowInversion
// @type Gap events on one bar, returned by `updateGaps()`.
// @field bullEntry A bullish gap gave a buy signal.
// @field bearEntry A bearish gap gave a sell signal.
// @field bullInverse A bearish gap inverted into a bullish one.
// @field bearInverse A bullish gap inverted into a bearish one.
// @field bullFailed A bullish gap failed (body close below its 50% line).
// @field bearFailed A bearish gap failed (body close above its 50% line).
export type GapEvents
bool bullEntry = false
bool bearEntry = false
bool bullInverse = false
bool bearInverse = false
bool bullFailed = false
bool bearFailed = false
restyle(Gap g, GapStyle st) =>
color base = g.bias == 1 ? st.bullColor : st.bearColor
array<string> tags = array.new<string>()
if g.sweep
tags.push("Liquidity Sweep")
if g.nearOb
tags.push("Near Order Block")
if g.target
tags.push("Target")
string extra = tags.join(" + ")
string dir = g.bias == 1 ? "Bullish" : "Bearish"
color fill = g.target ? color.new(base, 90) : base
for bx in array.from(g.upper, g.lower)
bx.set_bgcolor(fill)
bx.set_border_color(extra == "" and not g.inverted ? fill : color.new(base, 0))
bx.set_border_style(g.target ? line.style_dotted : line.style_solid)
g.tag.set_text(dir + (g.inverted ? " Inverse Fair Value Gap" : " Fair Value Gap") + (extra == "" ? "" : " · " + extra))
g.tag.set_textcolor(color.new(base, 0))
g.tag.set_tooltip(dir + (g.inverted ? " inverse fair value gap" : " fair value gap") + ": " + str.tostring(g.bottom, format.mintick) + " - " + str.tostring(g.top, format.mintick) + "\n50% line: " + str.tostring(math.avg(g.top, g.bottom), format.mintick) + (g.target ? "\nAgainst the swing trend: a target, not an entry" : ""))
// @function Creates and draws a gap.
// @param top (series float) Gap top.
// @param bottom (series float) Gap bottom.
// @param bias (series int) 1 bullish, -1 bearish.
// @param leftTime (series int) Time of the gap's middle candle (left edge).
// @param rightTime (series int) Time of the gap's last candle (right edge until it is touched).
// @param sweep (series bool) Formed right after a liquidity sweep.
// @param nearOb (series bool) An order block of the same bias is near.
// @param target (series bool) Against the swing trend.
// @param st (GapStyle) Settings.
// @returns (Gap) The gap.
export newGap(float top, float bottom, int bias, int leftTime, int rightTime, bool sweep, bool nearOb, bool target, GapStyle st) =>
float mid = math.avg(top, bottom)
color c = bias == 1 ? st.bullColor : st.bearColor
Gap g = Gap.new(top, bottom, bias,
box.new(leftTime, top, rightTime, mid, xloc = xloc.bar_time, bgcolor = c, border_color = c),
box.new(leftTime, mid, rightTime, bottom, xloc = xloc.bar_time, bgcolor = c, border_color = c),
label.new(rightTime, mid, "", xloc = xloc.bar_time, color = color(na), style = label.style_label_left, size = st.textSize),
sweep, nearOb, target)
restyle(g, st)
g
// @function Adds a gap as the newest, keeping at most `maxCount` (older ones stay drawn but stop updating).
// @param gaps (array<Gap>) Gaps, newest first.
// @param g (Gap) The new gap.
// @param maxCount (series int) Gaps tracked. Optional. Default is 50.
// @returns (void)
export method addGap(array<Gap> gaps, Gap g, int maxCount = 50) =>
if gaps.size() >= maxCount
Gap old = gaps.pop()
old.tag.delete()
gaps.unshift(g)
// @function 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.
// @param gaps (array<Gap>) Gaps, newest first.
// @param st (GapStyle) Settings.
// @param swingBias (series int) Swing structure bias, for targets.
// @param atr (series float) Largest distance between the signal close and the gap edge.
// @param highVolume (series bool) This bar's volume is high enough to invert a gap.
// @param entryBuyOk (series bool) Extra confirmation for buy signals. Optional. Default is `true`.
// @param entrySellOk (series bool) Extra confirmation for sell signals. Optional. Default is `true`.
// @param invertDownOk (series bool) Extra confirmation for a bullish gap to invert into a bearish one. Optional.
// Default is `true`.
// @param invertUpOk (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.
export method updateGaps(array<Gap> gaps, GapStyle st, int swingBias, float atr, bool highVolume, bool entryBuyOk = true, bool entrySellOk = true, bool invertDownOk = true, bool invertUpOk = true) =>
GapEvents ev = GapEvents.new()
if gaps.size() > 0
for i = gaps.size() - 1 to 0
Gap g = gaps.get(i)
if barstate.islast
g.tag.set_x(time)
bool bull = g.bias == 1
float mid = math.avg(g.top, g.bottom)
bool pastMid = bull ? close < mid : close > mid
bool through = bull ? close < g.bottom : close > g.top
bool against = bull ? close < open : close > open
if st.allowInversion and not g.inverted and through and against and highVolume and (bull ? invertDownOk : invertUpOk)
g.inverted := true
g.bias := -g.bias
g.sweep := false
g.nearOb := false
g.touched := false
g.deep := false
g.signaled := false
g.target := st.useTargets and swingBias != 0 and g.bias != swingBias
restyle(g, st)
ev.bearInverse := ev.bearInverse or bull
ev.bullInverse := ev.bullInverse or not bull
else if pastMid
ev.bullFailed := ev.bullFailed or bull
ev.bearFailed := ev.bearFailed or not bull
g.upper.delete()
g.lower.delete()
g.tag.delete()
gaps.remove(i)
else
if not g.touched
g.upper.set_right(time)
g.lower.set_right(time)
g.touched := bull ? low <= g.top : high >= g.bottom
g.deep := g.deep or (bull ? low <= mid : high >= mid)
bool target = st.useTargets and swingBias != 0 and g.bias != swingBias
if target != g.target
g.target := target
restyle(g, st)
bool rejected = bull ? close > open and close > g.top and close - g.top <= atr : close < open and close < g.bottom and g.bottom - close <= atr
if g.touched and rejected and not g.signaled and not g.target and (bull ? entryBuyOk : entrySellOk)
g.signaled := true
ev.bullEntry := ev.bullEntry or bull
ev.bearEntry := ev.bearEntry or not bull
if st.showSignals
string txt = (bull ? "Buy" : "Sell") + (g.inverted ? " · Inverse Gap" : "") + (g.deep ? "\nDeep Pullback" : "") + (g.sweep ? "\nAfter Liquidity Sweep" : "") + (g.nearOb ? "\nNear Order Block" : "")
label.new(bar_index, close, txt, yloc = bull ? yloc.belowbar : yloc.abovebar, color = bull ? st.buyColor : st.sellColor, style = bull ? label.style_label_up : label.style_label_down, textcolor = color.white, size = st.textSize, tooltip = g.deep ? "The pullback reached the gap's 50% line before price closed back out of the gap" : "The pullback only touched the gap's edge before price closed back out of the gap")
ev
//#endregion
//#region ———————————————————— Demo
var Structure demo = newStructure()
Event demoEvent = demo.update(10)
if demoEvent.breakDir != 0
drawBreak(demoEvent.broken, demoEvent.choch ? "CHoCH" : "BOS", demoEvent.breakDir == 1 ? color.teal : color.red, line.style_solid, demoEvent.breakDir == 1, 10, true)
if demoEvent.newHigh and not na(demoEvent.highTag)
drawSwingLabel(demo.high, demoEvent.highTag, color.red, true, 10, true, demoEvent.highReplaced)
if demoEvent.newLow and not na(demoEvent.lowTag)
drawSwingLabel(demo.low, demoEvent.lowTag, color.teal, false, 10, true, demoEvent.lowReplaced)
demo.drawStrongWeak(color.teal, color.red, 10)
demo.drawZones(color.new(color.red, 85), color.gray, color.new(color.teal, 85), 10)
// Swings on their own, without structure: confirmed `len` bars after the swing candle
[demoSwingHigh, demoSwingLow] = swings(5)
plotshape(demoSwingHigh, "swings() high", shape.circle, location.abovebar, color.red, offset = -5, size = size.tiny)
plotshape(demoSwingLow, "swings() low", shape.circle, location.belowbar, color.teal, offset = -5, size = size.tiny)
// Order blocks: one per structure break, removed once a close goes through them
float demoAtr = ta.atr(200)
var array<OrderBlock> demoObs = array.new<OrderBlock>()
var array<box> demoObBoxes = array.new<box>()
var array<label> demoObLabels = array.new<label>()
if demoEvent.breakDir != 0
OrderBlock ob = findOrderBlock(demoEvent.broken.barIndex, demoEvent.breakDir, 2 * demoAtr)
if not na(ob)
demoObs.unshift(ob)
[demoBullMitigated, demoBearMitigated] = demoObs.mitigate(true)
plotshape(demoBullMitigated, "Bullish block mitigated", shape.xcross, location.belowbar, color.teal, size = size.tiny)
plotshape(demoBearMitigated, "Bearish block mitigated", shape.xcross, location.abovebar, color.red, size = size.tiny)
if barstate.islast
drawOrderBlocks(demoObs, 3, demoObBoxes, demoObLabels, color.new(color.teal, 80), color.new(color.red, 80), "Demo", 10, true)
// Fair value gaps from three candles, tagged when an order block is near and faded when against the swing trend
var GapStyle demoGapStyle = GapStyle.new(color.new(color.teal, 70), color.new(color.red, 70), color.teal, color.red, 10, true, true, true)
var array<Gap> demoGaps = array.new<Gap>()
GapEvents demoGapEvents = demoGaps.updateGaps(demoGapStyle, demo.bias, demoAtr, volume > 1.5 * ta.sma(volume, 20))
if low > high[2] and close[1] > high[2]
demoGaps.addGap(newGap(low, high[2], 1, time[1], time, false, demoObs.nearAny(3, low, high[2], 1, demoAtr), demo.bias == -1, demoGapStyle), 20)
if high < low[2] and close[1] < low[2]
demoGaps.addGap(newGap(low[2], high, -1, time[1], time, false, demoObs.nearAny(3, low[2], high, -1, demoAtr), demo.bias == 1, demoGapStyle), 20)
plotshape(demoGapEvents.bullInverse or demoGapEvents.bearInverse, "Gap inverted", shape.diamond, location.top, color.orange, size = size.tiny)
//#endregion