本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// v2 (24/10/2026):
// - an equal high / equal low breaks the structure, when the point between the two levels is a real point;
// - structure exceptions fixed (option "Fix structure exceptions"): a point that is not the extreme between its
// neighbours is moved (exception 1), a missing point with no candle to validate it is removed with the point before it (exception 2);
// - "Point style" option: Circle is drawn exactly on the high / low.
// TradingView version (29/10/2026): the "Timeframe" option is removed. The structure is always calculated on the chart
// timeframe (as with an empty "Timeframe" before), so request.security() never reads a higher timeframe.
indicator('Algo Market Structure', overlay=true, max_bars_back=800, max_labels_count=300, max_lines_count=300)
// -----------------------------------------
// --------------- INPUTS ------------------
// -----------------------------------------
var GRP_TF1 = "•••••••• Market Structure ••••••••"
tf1_useStructure = input.bool(true, "Show Structure Points", group=GRP_TF1)
tf1_timeframe = "" // chart timeframe
tf1_min = input.timeframe("", "Min", group=GRP_TF1)
tf1_structureTopColor = input.color(color.green, "Top point", group=GRP_TF1)
tf1_structureBottomColor = input.color(color.green, "Bottom point", group=GRP_TF1)
tf1_structurelabelSize = input.int(6, "Point size", minval=1, maxval=40, group=GRP_TF1, tooltip="Size in typographic points. Lower = smaller dot.")
tf1_pointStyle = input.string("Circle", "Point style", options=["Circle", "Text dot"], group=GRP_TF1, tooltip="Circle: a shape drawn exactly on the high / low. Text dot: the previous look, drawn with a font character, which can sit slightly off the wick.")
var GRP_OTHER_STRUCTURE = "•••••••• Other Settings ••••••••"
indicator_start_time = input.time(timestamp("02 Jan 2015 00:00 +0300"), title="Indicator Start Date", group=GRP_OTHER_STRUCTURE)
tf1_fixExceptions = input.bool(true, "Fix structure exceptions", group=GRP_OTHER_STRUCTURE, tooltip="Exception 1: a point that is not the extreme between its two neighbours is moved onto the extreme. Exception 2: when no candle validates the move from a missing point to the new point, that missing point and the point before it are removed.")
// -----------------------------------------
// --- CONSTANTS ---
TRANSPARENT = color.new(color.white, 100)
LABEL_SPACE = " "
MIN = -9999999999999999999.0
MAX = 9999999999999999999.0
// Maintain array of time values for all bars.
var array<int> timesArray = array.new<int>()
array.push(timesArray, time)
// --- CONSTANTS ---
// -----------------------------------------
// --------------- FUNCTIONS ---------------
// Candles
isNeutral(i=0) =>
open[i] == close[i]
isBearish(i=0) =>
_n = isNeutral(i)
_temp = _n ? close[i+1] < open[i+1] : close[i] < open[i]
_temp
isBullish(i=0) =>
_n = isNeutral(i)
_temp = _n ? close[i+1] > open[i+1] : close[i] > open[i]
_temp
// Styles
getLineStyle(_style) =>
_linestyle = _style == "Solid" ? line.style_solid : _style == "Dashed" ? line.style_dashed : line.style_dotted
_linestyle
getlabelSize(_labelSize) =>
_size = _labelSize == "auto" ? size.auto : _labelSize == "Tiny" ? size.tiny : _labelSize == "Small" ? size.small : _labelSize == "Normal" ? size.normal : _labelSize == "Large" ? size.large : size.huge
_size
// Arrays
addToArray(_array, _val) => array.unshift(_array, _val)
removeFromArray(_array, _index) => array.remove(_array, _index)
updateArrayElement(_array, _index, _val) => array.set(_array, _index, _val)
getLastElementInArray(_arr) =>
_size = array.size(_arr)
_el = _size > 0 ? array.get(_arr, _size-1) : na
_el
_get(_array, _i=0) =>
_temp = array.get(_array, _i)
_temp
get5ArrayValues(_array) =>
_0 = array.get(_array, 0)
_1 = array.get(_array, 1)
_2 = array.get(_array, 2)
_3 = array.get(_array, 3)
_4 = array.get(_array, 4)
[_0, _1, _2, _3, _4]
// Box
_bottom(_id) => box.get_bottom(_id)
_top(_id) => box.get_top(_id)
_left(_id) => box.get_left(_id)
_right(_id) => box.get_right(_id)
// Fractals
isRegularFractal(mode, n) =>
ret = mode == 'Buy' ? high[n - 1] < high[n] and high[n + 1] < high[n] : mode == 'Sell' ? low[n - 1] > low[n] and low[n + 1] > low[n] : false
ret
isBWFractal(mode, n) =>
ret = mode == 'Buy' ? high[n - 2] < high[n] and high[n - 1] < high[n] and high[n + 1] < high[n] and high[n + 2] < high[n] : mode == 'Sell' ? low[n - 2] > low[n] and low[n - 1] > low[n] and low[n + 1] > low[n] and low[n + 2] > low[n] : false
ret
isFractalHigh(i, _filter) =>
_filter == '3' ? isRegularFractal('Buy', i) : isBWFractal('Buy', i + 1)
isFractalLow(i, _filter) =>
_filter == '3' ? isRegularFractal('Sell', i) : isBWFractal('Sell', i + 1)
// Helpers
delete_label(_l) =>
if not na(_l)
label.delete(_l)
delete_line(_l) =>
if not na(_l)
line.delete(_l)
delete_box(_l) =>
if not na(_l)
box.delete(_l)
// Structure point: a circle shape centred on the price, or a text dot whose size can go below size.tiny
newStructurePoint(_time, _price, _color) =>
label _l = na
if tf1_pointStyle == "Circle"
_l := label.new(_time, _price, "", xloc=xloc.bar_time, style=label.style_circle, color=_color, textcolor=_color, size=tf1_structurelabelSize)
else
_l := label.new(_time, _price, "●", xloc=xloc.bar_time, style=label.style_none, textcolor=_color, size=tf1_structurelabelSize)
_l
resolutionInMinutes(tf = "") =>
chartTf = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
float result = tf == "" ? chartTf : request.security(syminfo.tickerid, tf, chartTf)
f_timeFrom(length, _tf = timeframe.period) =>
int _timeFrom = na
_timeFrom := int(time + resolutionInMinutes(_tf) * 60 * 1000 * length)
_timeFrom
isHigherTimeframe(tf, eq = false) =>
_cond = eq ? resolutionInMinutes() >= resolutionInMinutes(tf) : resolutionInMinutes() > resolutionInMinutes(tf)
_cond
isLowerTimeframe(tf, eq = false) =>
_cond = eq ? resolutionInMinutes() <= resolutionInMinutes(tf) : resolutionInMinutes() < resolutionInMinutes(tf)
_cond
timeToBarIndex(_from) =>
__cond = math.round((time - _from) / (1000 * timeframe.in_seconds(timeframe.period)))
_cond = __cond <= 5000 ? math.abs(math.round(__cond)) : 5000
_cond
barIndexAtTime(_arr, series int timeToFind) =>
int barOfTime = array.indexof(_arr, timeToFind)
int _result = na
if barOfTime == -1
_timetobars = timeToBarIndex(timeToFind)
_result := _timetobars
else
_result := bar_index - barOfTime
result = _result <= 5000 ? math.abs(math.round(_result)) : 5000
result
findHtfTimeInLtf(_src, _pivotPrice, _maxBack) =>
int _time = na
int _bar_index = na
float _delta = 10e10
if not na(_pivotPrice)
for _i = _maxBack to 0
_thisDelta = _src == "high" ? math.abs(high[_i] - _pivotPrice) : math.abs(low[_i] - _pivotPrice)
if _thisDelta < _delta
_delta := _thisDelta
_time := time[_i]
_bar_index := bar_index[_i]
[_time, _bar_index]
getExactTime(_time, _price, _timeframe, _direction) =>
_pivotTime = _time
if isLowerTimeframe(_timeframe)
_barsback = barIndexAtTime(timesArray, _time)
[__hTime, __hBi] = findHtfTimeInLtf(_direction, _price, _barsback)
_pivotTime := __hTime
_pivotTime
// _after = true: start after the candle of _time2 (search for a new high beyond the last one)
findHighestBetweenTimes(_time1, _time2, _defaultH, _after = false) =>
_highest = _defaultH
_highestTime = _time1
sBi0 = barIndexAtTime(timesArray, _time1)
sBi1 = barIndexAtTime(timesArray, _time2)
if _time1 > _time2
_startFrom = _after ? sBi1-1 : isBullish(sBi1) ? sBi1 : sBi1-1
_endTo = isBearish(sBi0) ? sBi0 : sBi0+1
for i = _startFrom to _endTo
if high[i] > _highest
_highest := high[i]
_highestTime := time[i]
[_highest, _highestTime]
findLowestBetweenTimes(_time1, _time2, _defaultL, _after = false) =>
_lowest = _defaultL
_lowestTime = _time1
sBi0 = barIndexAtTime(timesArray, _time1)
sBi1 = barIndexAtTime(timesArray, _time2)
if _time1 > _time2
_startFrom = _after ? sBi1-1 : isBearish(sBi1) ? sBi1 : sBi1-1
_endTo = isBullish(sBi0) ? sBi0 : sBi0+1
for i = _startFrom to _endTo
if low[i] < _lowest
_lowest := low[i]
_lowestTime := time[i]
[_lowest, _lowestTime]
// Is there a bullish (or bearish) candle between two times, both included? A neutral doji takes the previous colour.
hasCandleBetween(_time1, _time2, _bullish) =>
_b1 = barIndexAtTime(timesArray, _time1)
_b2 = barIndexAtTime(timesArray, _time2)
_found = false
for i = math.min(_b1, _b2) to math.max(_b1, _b2)
if _bullish ? isBullish(i) : isBearish(i)
_found := true
break
_found
isSamePrice(_a, _b) =>
math.abs(_a - _b) < syminfo.mintick / 2
// An equal high breaks the structure only if the low between the two highs is a real point:
// a bearish candle between the first high and that low, a bullish one between that low and the equal high.
// Otherwise it is the same top (two candles side by side with the same high).
equalHighBreaks(_equalTime, _pivotTime) =>
_ok = false
if _equalTime != _pivotTime
[_m, _mTime] = findLowestBetweenTimes(_equalTime, _pivotTime, MAX)
_bm = barIndexAtTime(timesArray, _mTime)
_bp = barIndexAtTime(timesArray, _pivotTime)
_ok := _mTime >= _pivotTime and _mTime <= _equalTime and hasCandleBetween(_pivotTime, _mTime, false) and hasCandleBetween(_mTime, _equalTime, true) and not (_mTime == _equalTime and not isBullish(_bm)) and not (_mTime == _pivotTime and isBullish(_bp))
_ok
equalLowBreaks(_equalTime, _pivotTime) =>
_ok = false
if _equalTime != _pivotTime
[_m, _mTime] = findHighestBetweenTimes(_equalTime, _pivotTime, MIN)
_bm = barIndexAtTime(timesArray, _mTime)
_bp = barIndexAtTime(timesArray, _pivotTime)
_ok := _mTime >= _pivotTime and _mTime <= _equalTime and hasCandleBetween(_pivotTime, _mTime, true) and hasCandleBetween(_mTime, _equalTime, false) and not (_mTime == _equalTime and not isBearish(_bm)) and not (_mTime == _pivotTime and isBearish(_bp))
_ok
// Exceptions, checked right after a missing point M is added between the previous point P and the new point N.
// New low: P = low[1], M = high[0], N = low[0]. New high: P = high[1], M = low[0], N = high[0].
fixAfterNewLow(_pH, _pHt, _labH, _pL, _pLt, _labL) =>
if array.size(_pH) > 6 and array.size(_pL) > 6
if array.get(_pH, 0) <= array.get(_pH, 1) and not hasCandleBetween(array.get(_pHt, 0), array.get(_pLt, 0), false)
// Exception 2: no bearish candle between M and N, so M and P cannot exist
delete_label(array.get(_labL, 1))
delete_label(array.get(_labH, 0))
array.remove(_pL, 1)
array.remove(_pLt, 1)
array.remove(_labL, 1)
array.remove(_pH, 0)
array.remove(_pHt, 0)
array.remove(_labH, 0)
else
// Exception 1: P must be the lowest point between the high before it and M
[_lst, _lstTime] = findLowestBetweenTimes(array.get(_pHt, 0), array.get(_pHt, 1), MAX)
if _lst < array.get(_pL, 1) and _lstTime != array.get(_pLt, 1)
array.set(_pL, 1, _lst)
array.set(_pLt, 1, _lstTime)
_lab = array.get(_labL, 1)
if not na(_lab)
label.set_xy(_lab, _lstTime, _lst)
true
fixAfterNewHigh(_pH, _pHt, _labH, _pL, _pLt, _labL) =>
if array.size(_pH) > 6 and array.size(_pL) > 6
if array.get(_pL, 0) >= array.get(_pL, 1) and not hasCandleBetween(array.get(_pLt, 0), array.get(_pHt, 0), true)
// Exception 2: no bullish candle between M and N, so M and P cannot exist
delete_label(array.get(_labH, 1))
delete_label(array.get(_labL, 0))
array.remove(_pH, 1)
array.remove(_pHt, 1)
array.remove(_labH, 1)
array.remove(_pL, 0)
array.remove(_pLt, 0)
array.remove(_labL, 0)
else
// Exception 1: P must be the highest point between the low before it and M
[_hst, _hstTime] = findHighestBetweenTimes(array.get(_pLt, 0), array.get(_pLt, 1), MIN)
if _hst > array.get(_pH, 1) and _hstTime != array.get(_pHt, 1)
array.set(_pH, 1, _hst)
array.set(_pHt, 1, _hstTime)
_lab = array.get(_labH, 1)
if not na(_lab)
label.set_xy(_lab, _hstTime, _hst)
true
get_pivot_ohlc(i=0) =>
[open, high, low, close, time, open[1], high[1], low[1], close[1], time[1], open[2], high[2], low[2], close[2], time[2]]
get_phpl(countSinceBullCandle, countSinceBearCandle) =>
_highest = countSinceBullCandle >= 0 ? ta.highest(countSinceBullCandle + 1) : -1
_highestBi = ta.valuewhen(high == _highest, bar_index, 0)
_highestTime = ta.valuewhen(high == _highest, time, 0)
_lowest = countSinceBearCandle >= 0 ? ta.lowest(countSinceBearCandle + 1) : -1
_lowestBi = ta.valuewhen(low == _lowest, bar_index, 0)
_lowestTime = ta.valuewhen(low == _lowest, time, 0)
[_highest, _highestTime, _lowest, _lowestTime]
_TimeTo = f_timeFrom(7)
GetPipSize() =>
syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)
// --------------- FUNCTIONS ---------------
// -----------------------------------------
// ------------------------------------------------------
// --------------- TIMEFRAME1 STRUCTURE ----------------
[tf1_open, tf1_high, tf1_low, tf1_close, tf1_time, tf1_open1, tf1_high1, tf1_low1, tf1_close1, tf1_time1, tf1_open2, tf1_high2, tf1_low2, tf1_close2, tf1_time2] = request.security(syminfo.tickerid, tf1_timeframe, get_pivot_ohlc())
isUseTimeframe1 = not isHigherTimeframe(tf1_timeframe) and isHigherTimeframe(tf1_min, true) and tf1_useStructure and time > indicator_start_time
var tf1_lastBullCandle = false
var tf1_lastBearCandle = false
if tf1_close1 > tf1_open1
tf1_lastBullCandle := true
tf1_lastBearCandle := false
if tf1_close1 < tf1_open1
tf1_lastBullCandle := false
tf1_lastBearCandle := true
_tf1_countBull = ta.barssince(tf1_lastBullCandle)
tf1_countSinceBullCandle = request.security(syminfo.tickerid, tf1_timeframe, _tf1_countBull)
_tf1_countBear = ta.barssince(tf1_lastBearCandle)
tf1_countSinceBearCandle = request.security(syminfo.tickerid, tf1_timeframe, _tf1_countBear)
tf1_newbar = ta.change(time(tf1_timeframe)) > 0
// Initialize arrays
var tf1_pivotHighs = array.new_float(5, MIN)
var tf1_pivotHighsTime = array.new_int(5)
var tf1_pivotLows = array.new_float(5, MAX)
var tf1_pivotLowsTime = array.new_int(5)
// Label of each point, in the same order as the arrays above
var tf1_highLabels = array.new<label>(5)
var tf1_lowLabels = array.new<label>(5)
tf1_isStructureHigh = false
tf1_isStructureLow = false
tf1_canPlot = tf1_newbar and isUseTimeframe1
var tf1_mostRecentBullCount1 = time
var tf1_mostRecentBearCount1 = time
var tf1_initialised = false
if tf1_canPlot and not tf1_initialised
addToArray(tf1_pivotHighsTime, tf1_time)
addToArray(tf1_pivotHighs, tf1_high)
addToArray(tf1_highLabels, label(na))
addToArray(tf1_pivotLowsTime, tf1_time)
addToArray(tf1_pivotLows, tf1_low)
addToArray(tf1_lowLabels, label(na))
tf1_initialised := true
if tf1_canPlot
// --- STRUCTURE HIGH ---
if tf1_countSinceBullCandle >= 1
__time = tf1_close1 > tf1_open1 ? tf1_time1 : tf1_time
[tf1_highest, tf1_highestTime] = findHighestBetweenTimes(__time, _get(tf1_pivotHighsTime), MIN, true)
if tf1_countSinceBullCandle == 1
tf1_mostRecentBullCount1 := __time
// An equal high is a break too (equal high = break of structure)
_equalH = isSamePrice(tf1_highest, _get(tf1_pivotHighs))
_higherH = tf1_highest > _get(tf1_pivotHighs) and not _equalH
if _higherH or (_equalH and equalHighBreaks(tf1_highestTime, _get(tf1_pivotHighsTime)))
if (tf1_countSinceBullCandle == 1 and tf1_close1 != tf1_open1) or (tf1_countSinceBullCandle > 1 and tf1_highestTime >= tf1_mostRecentBullCount1 and tf1_close < tf1_open)
tf1_isStructureHigh := true
// Update H structure label and array
addToArray(tf1_pivotHighsTime, tf1_highestTime)
addToArray(tf1_pivotHighs, tf1_highest)
addToArray(tf1_highLabels, newStructurePoint(tf1_highestTime, tf1_highest, tf1_structureTopColor))
// Update L structure label and array
[tf1_lowest, tf1_lowestTime] = findLowestBetweenTimes(_get(tf1_pivotHighsTime), _get(tf1_pivotHighsTime, 1), MAX)
if tf1_lowestTime != _get(tf1_pivotLowsTime)
addToArray(tf1_pivotLowsTime, tf1_lowestTime)
addToArray(tf1_pivotLows, tf1_lowest)
addToArray(tf1_lowLabels, newStructurePoint(tf1_lowestTime, tf1_lowest, tf1_structureBottomColor))
if tf1_fixExceptions
fixAfterNewHigh(tf1_pivotHighs, tf1_pivotHighsTime, tf1_highLabels, tf1_pivotLows, tf1_pivotLowsTime, tf1_lowLabels)
else if _higherH and tf1_countSinceBullCandle > 1 and _get(tf1_pivotHighsTime) >= tf1_mostRecentBullCount1 and tf1_close < tf1_open
// Update H structure label and array
updateArrayElement(tf1_pivotHighsTime, 0, tf1_highestTime)
updateArrayElement(tf1_pivotHighs, 0, tf1_highest)
delete_label(_get(tf1_highLabels))
updateArrayElement(tf1_highLabels, 0, newStructurePoint(tf1_highestTime, tf1_highest, tf1_structureTopColor))
// --- STRUCTURE LOW ---
if tf1_countSinceBearCandle >= 1
__time = tf1_close1 < tf1_open1 ? tf1_time1 : tf1_time
[tf1_lowest, tf1_lowestTime] = findLowestBetweenTimes(__time, _get(tf1_pivotLowsTime), MAX, true)
if tf1_countSinceBearCandle == 1
tf1_mostRecentBearCount1 := __time
// An equal low is a break too (equal low = break of structure)
_equalL = isSamePrice(tf1_lowest, _get(tf1_pivotLows))
_lowerL = tf1_lowest < _get(tf1_pivotLows) and not _equalL
if _lowerL or (_equalL and equalLowBreaks(tf1_lowestTime, _get(tf1_pivotLowsTime)))
if (tf1_countSinceBearCandle == 1 and tf1_close1 != tf1_open1) or (tf1_countSinceBearCandle > 1 and tf1_lowestTime >= tf1_mostRecentBearCount1 and tf1_close > tf1_open)
tf1_isStructureLow := true
// Update L structure label and array
addToArray(tf1_pivotLowsTime, tf1_lowestTime)
addToArray(tf1_pivotLows, tf1_lowest)
addToArray(tf1_lowLabels, newStructurePoint(tf1_lowestTime, tf1_lowest, tf1_structureBottomColor))
// Update H structure label and array
[tf1_highest, tf1_highestTime] = findHighestBetweenTimes(_get(tf1_pivotLowsTime), _get(tf1_pivotLowsTime, 1), MIN)
if tf1_highestTime != _get(tf1_pivotHighsTime)
addToArray(tf1_pivotHighsTime, tf1_highestTime)
addToArray(tf1_pivotHighs, tf1_highest)
addToArray(tf1_highLabels, newStructurePoint(tf1_highestTime, tf1_highest, tf1_structureTopColor))
if tf1_fixExceptions
fixAfterNewLow(tf1_pivotHighs, tf1_pivotHighsTime, tf1_highLabels, tf1_pivotLows, tf1_pivotLowsTime, tf1_lowLabels)
else if _lowerL and tf1_countSinceBearCandle > 1 and _get(tf1_pivotLowsTime) >= tf1_mostRecentBearCount1 and tf1_close > tf1_open
// Update L structure label and array
updateArrayElement(tf1_pivotLowsTime, 0, tf1_lowestTime)
updateArrayElement(tf1_pivotLows, 0, tf1_lowest)
delete_label(_get(tf1_lowLabels))
updateArrayElement(tf1_lowLabels, 0, newStructurePoint(tf1_lowestTime, tf1_lowest, tf1_structureBottomColor))
// --------------- GET STRUCTURE DATA ---------------
[tf1_ph0, tf1_ph1, tf1_ph2, tf1_ph3, tf1_ph4] = get5ArrayValues(tf1_pivotHighs)
[tf1_pl0, tf1_pl1, tf1_pl2, tf1_pl3, tf1_pl4] = get5ArrayValues(tf1_pivotLows)
[tf1_ph0Time, tf1_ph1Time, tf1_ph2Time, tf1_ph3Time, tf1_ph4Time] = get5ArrayValues(tf1_pivotHighsTime)
[tf1_pl0Time, tf1_pl1Time, tf1_pl2Time, tf1_pl3Time, tf1_pl4Time] = get5ArrayValues(tf1_pivotLowsTime)
// --------------- GET STRUCTURE DATA ---------------
// --------------- TIMEFRAME1 STATS ---------------
var tf1_isPriceEfficient = false
var tf1_structureDirection = "bullish"
var tf1_isMSU = false
tf1_isBullishMsu = false
tf1_isBearishMsu = false
tf1_isBullishVta = false
tf1_isBearishVta = false
var float tf1_bottomTlqPrice = na
var float tf1_topTlqPrice = na
tf1_isValidHH = tf1_structureDirection == "bullish" ? tf1_isStructureHigh and tf1_ph0 > tf1_ph1 and tf1_ph0 > tf1_ph2 : tf1_isStructureHigh and tf1_ph0 > nz(tf1_topTlqPrice)
tf1_isValidLL = tf1_structureDirection == "bearish" ? tf1_isStructureLow and tf1_pl0 < tf1_pl1 and tf1_pl0 < tf1_pl2 : tf1_isStructureLow and tf1_pl0 < nz(tf1_bottomTlqPrice)
// label.new(bar_index, high, str.tostring(tf1_structureDirection))
// --------------- TIMEFRAME1 STATS ---------------