Liquidity Trap Detector
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «indicator liquidity trap detector for tradingview.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Liquidity Trap Detector — индикатор для TradingView, написанный на Pine Script v6. Он накладывается на график и предназначен для выявления бычьих и медвежьих ловушек (liquidity traps) на основе анализа свечных уровней и тренда.
В основе работы — движок тренда на базе DEMA с порогами разворота, рассчитанными через средний истинный диапазон (ATR). Индикатор определяет свечные максимумы и минимумы с помощью встроенных функций pivot high/low, отслеживает их пробой с заданным буфером и проверяет возврат цены через уровень в пределах trap window для подтверждения ловушки.
Визуализация включает градиентные зоны ловушки с настраиваемым количеством слоёв, линии триггеров, раскраску свечей по тренду и треугольные маркеры разворотов. Доступны пять условий оповещения: разворот тренда вверх/вниз, подтверждение бычьей/медвежьей ловушки и повторное тестирование зоны ловушки.
Настройки программы
| Настройка | Описание |
|---|---|
| trendLen | Количество баров для расчёта базовой линии тренда DEMA. Большее значение даёт более сглаженную и медленную базовую линию. |
| trendSmooth | Дополнительное сглаживание EMA, применяемое к базовой линии DEMA. Значение 1 отключает дополнительное сглаживание. |
| trendAtrLen | Количество баров для расчёта среднего истинного диапазона (ATR) для порогов разворота тренда и ширины градиента. |
| trendBand | Расстояние от базовой линии DEMA в кратных ATR, которое цена должна закрыть для разворота тренда. Базовая линия также должна наклоняться в новом направлении. Более высокие значения требуют более сильного отклонения. |
| cloudWidth | Ширина градиента тренда, отрисованного от базовой линии DEMA, в кратных ATR. |
| swingLen | Количество баров с каждой стороны, необходимое для подтверждения свечного максимума или минимума, используемого как уровень пробоя. |
| maxLevels | Максимальное количество отслеживаемых свечных уровней с каждой стороны. Самый старый уровень удаляется при формировании нового. |
| maxAge | Максимальное количество баров, в течение которых непробитый свечной уровень отслеживается после формирования, прежде чем быть удалённым. |
| atrLen | Количество баров для расчёта среднего истинного диапазона (ATR) для буфера пробоя. |
| breakBuf | Расстояние за уровнем в кратных ATR, которое цена должна закрыть для регистрации пробоя. Более высокие значения требуют более решительного пробоя. |
| trapWindow | Максимальное количество баров после пробоя, в течение которых цена должна закрыться обратно через уровень. Если да — ловушка подтверждена и зона создаётся. Если нет — пробой принимается и уровень удаляется. |
| maxZones | Максимальное количество активных зон ловушки, отображаемых с каждой стороны. Самая старая зона удаляется при формировании новой. |
| mitigation | Определяет момент, когда зона ловушки аннулируется и удаляется. Absolute требует закрытия за крайней точкой ловушки, Middle — за средней точкой зоны. |
| hideOverlap | При включении новая зона ловушки заменяет существующую зону на той же стороне, с которой она перекрывается. |
| extendBars | Количество баров, на которые зоны ловушки и уровни проецируются вперёд от текущего бара. |
| showTrend | Включает или отключает видимость градиента тренда DEMA. |
| paintBars | Включает или отключает раскраску свечей в зависимости от текущего направления тренда. |
| showSignals | Включает или отключает треугольные маркеры на бычьих и медвежьих разворотах тренда. |
| showLabel | Включает или отключает текст BULL TRAP и BEAR TRAP внутри каждой зоны. |
| showMetric | Включает или отключает отображение объёма, загнанного в ловушку. Требуется включённый показ текста ловушки и наличие данных об объёме. |
| bullCol | Цвет, используемый для зон медвежьих ловушек, элементов бычьего тренда и бычьих маркеров повторного тестирования. |
| bearCol | Цвет, используемый для зон бычьих ловушек, элементов медвежьего тренда и медвежьих маркеров повторного тестирования. |
| gradRows | Количество градиентных слоёв внутри каждой зоны ловушки. Слои наиболее непрозрачны у пробитого уровня и постепенно становятся прозрачнее к крайней точке ловушки. |
Поиск по коду файла
indicator("Liquidity Trap Detector", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)
const string g1 = "Trend Engine"
const string g2 = "Level Detection"
const string g3 = "Trap Logic"
const string g4 = "Zone Construction"
const string g5 = "Visualization"
color BULL = #00FF00
color BEAR = #FF0066
int trendLen = input.int(26, "DEMA Length", minval = 5, group = g1,
tooltip = "Number of bars used to calculate the DEMA trend baseline. Higher values produce a smoother, slower baseline.")
int trendSmooth = input.int(2, "DEMA Smoothing", minval = 1, maxval = 10, group = g1,
tooltip = "Additional EMA smoothing applied to the DEMA baseline. A value of 1 disables the extra smoothing.")
int trendAtrLen = input.int(78, "ATR Length", minval = 5, group = g1,
tooltip = "Number of bars used to calculate the Average True Range for the trend flip thresholds and gradient width.")
float trendBand = input.float(2.55, "Flip Threshold ATR", minval = 0.25, maxval = 3.0, step = 0.05, group = g1,
tooltip = "Distance from the DEMA baseline, as a multiple of ATR, that price must close beyond to flip the trend. The baseline must also be sloping in the new direction. Higher values require stronger displacement.")
float cloudWidth = input.float(0.8, "Gradient Width ATR", minval = 0.20, maxval = 2.0, step = 0.05, group = g1,
tooltip = "Width of the trend gradient drawn from the DEMA baseline, as a multiple of ATR.")
int swingLen = input.int(5, "Swing Length", minval = 2, maxval = 30, group = g2,
tooltip = "Number of bars on each side required to confirm a swing high or low used as a breakout level.")
int maxLevels = input.int(6, "Levels Per Side", minval = 1, maxval = 20, group = g2,
tooltip = "Maximum number of swing levels tracked on each side. The oldest level is discarded when a new one forms.")
int maxAge = input.int(300, "Level Max Age (bars)", minval = 20, maxval = 2000, group = g2,
tooltip = "Maximum number of bars an unbroken swing level is tracked after it forms before it is discarded.")
int atrLen = input.int(14, "ATR Length", minval = 1, group = g3,
tooltip = "Number of bars used to calculate the Average True Range for the breakout buffer.")
float breakBuf = input.float(0.1, "Break Buffer (ATR)", minval = 0.0, step = 0.05, group = g3,
tooltip = "Distance beyond the level, as a multiple of ATR, that price must close to register a breakout. Higher values require a more decisive break.")
int trapWindow = input.int(5, "Trap Window (bars)", minval = 1, maxval = 30, group = g3,
tooltip = "Maximum number of bars after a breakout for price to close back through the level. If it does, a trap is confirmed. If it doesn't, the breakout is accepted and the level is discarded.")
int maxZones = input.int(4, "Zones Per Side", minval = 1, maxval = 10, group = g4,
tooltip = "Maximum number of active trap zones displayed on each side. The oldest zone is removed when a new one forms.")
string mitigation = input.string("Absolute", "Mitigation", options = ["Absolute", "Middle"], group = g4,
tooltip = "Defines when a trap zone is invalidated and removed. Absolute requires a close beyond the trap extreme. Middle requires a close beyond the zone midpoint.")
bool hideOverlap = input.bool(true, "Hide Overlap", group = g4,
tooltip = "When enabled, a new trap zone replaces an existing zone on the same side that it overlaps.")
int extendBars = input.int(40, "Zone Extension", minval = 10, maxval = 500, step = 10, group = g4,
tooltip = "Number of bars the trap zones and level lines are projected forward from the current bar.")
bool showTrend = input.bool(true, "Show Trend Gradient", group = g5,
tooltip = "Toggles visibility of the DEMA trend gradient.")
bool paintBars = input.bool(true, "Color Candles", group = g5,
tooltip = "Toggles coloring of candles based on the current trend direction.")
bool showSignals = input.bool(true, "Show Trend Flips", group = g5,
tooltip = "Toggles triangle markers on bullish and bearish trend flips.")
bool showLabel = input.bool(true, "Show Trap Text", group = g5,
tooltip = "Toggles the BULL TRAP and BEAR TRAP text inside each zone.")
bool showMetric = input.bool(true, "Show Trapped Volume", group = g5,
tooltip = "Toggles the trapped volume reading beneath the trap text. Requires Show Trap Text to be enabled and volume data on the instrument.")
color bullCol = input.color(BULL, "Bear Trap / Bull Trend", inline = "col", group = g5,
tooltip = "Color used for bear trap zones, bullish trend elements, and bullish retest markers.")
color bearCol = input.color(BEAR, "Bull Trap / Bear Trend", inline = "col", group = g5,
tooltip = "Color used for bull trap zones, bearish trend elements, and bearish retest markers.")
int gradRows = input.int(4, "Trap Gradient Layers", minval = 2, maxval = 6, group = g5,
tooltip = "Number of gradient layers inside each trap zone. Layers are most opaque at the broken level and fade toward the trap extreme.")
float src = hlc3
float ema1 = ta.ema(src, trendLen)
float ema2 = ta.ema(ema1, trendLen)
float demaRaw = 2.0 * ema1 - ema2
float basis = trendSmooth > 1 ? ta.ema(demaRaw, trendSmooth) : demaRaw
float tAtr = ta.atr(trendAtrLen)
float upperFlip = basis + tAtr * trendBand
float lowerFlip = basis - tAtr * trendBand
var int trend = 0
if trend == 0
trend := close >= basis ? 1 : -1
else if trend == -1 and close > upperFlip and basis > basis[1]
trend := 1
else if trend == 1 and close < lowerFlip and basis < basis[1]
trend := -1
bool switchUp = trend == 1 and trend[1] == -1
bool switchDown = trend == -1 and trend[1] == 1
color trendCol = trend == 1 ? bullCol : bearCol
float cloud = tAtr * cloudWidth
float c0 = basis
float c1 = trend == 1 ? basis - cloud * 0.20 : basis + cloud * 0.20
float c2 = trend == 1 ? basis - cloud * 0.40 : basis + cloud * 0.40
float c3 = trend == 1 ? basis - cloud * 0.60 : basis + cloud * 0.60
float c4 = trend == 1 ? basis - cloud * 0.80 : basis + cloud * 0.80
float c5 = trend == 1 ? basis - cloud : basis + cloud
p0 = plot(showTrend ? c0 : na, color=color.new(trendCol, 100))
p1 = plot(showTrend ? c1 : na, color=color.new(trendCol, 100))
p2 = plot(showTrend ? c2 : na, color=color.new(trendCol, 100))
p3 = plot(showTrend ? c3 : na, color=color.new(trendCol, 100))
p4 = plot(showTrend ? c4 : na, color=color.new(trendCol, 100))
p5 = plot(showTrend ? c5 : na, color=color.new(trendCol, 100))
fill(p0, p1, color=color.new(trendCol, 22))
fill(p1, p2, color=color.new(trendCol, 32))
fill(p2, p3, color=color.new(trendCol, 44))
fill(p3, p4, color=color.new(trendCol, 57))
fill(p4, p5, color=color.new(trendCol, 72))
barcolor(paintBars ? trendCol : na)
plotshape(showSignals and switchUp, title="Bull Trend", style=shape.triangleup, location=location.belowbar, color=bullCol, size=size.tiny)
plotshape(showSignals and switchDown, title="Bear Trend", style=shape.triangledown, location=location.abovebar, color=bearCol, size=size.tiny)
type Level
float price
int pivBi
bool isHigh
bool broken
int breakBi
int breakT
float extreme
float trapVol
type TrapZone
float top
float btm
float trig
float total_vol
int left_time
bool bearish
bool armed
type TrapDraw
box ob
box eOB
array<box> gradBoxes
line trigLn
line trigExt
line farLn
line farExt
var Level[] highLevels = array.new<Level>()
var Level[] lowLevels = array.new<Level>()
var TrapZone[] bullTraps = array.new<TrapZone>()
var TrapZone[] bearTraps = array.new<TrapZone>()
var TrapDraw[] bullDraws = array.new<TrapDraw>()
var TrapDraw[] bearDraws = array.new<TrapDraw>()
float atr = ta.atr(atrLen)
float ph = ta.pivothigh(high, swingLen, swingLen)
float pl = ta.pivotlow(low, swingLen, swingLen)
var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
table.cell(wm, Показано первые 50% кода (символов: 12114)