Liquidity Trap Detector
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «liquidity trap detector.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Данный продукт представляет собой индикатор для TradingView, который анализирует график и отображает информацию о так называемых ликвидностных ловушках — ситуациях, когда цена пробивает ключевой уровень, но затем возвращается обратно. Индикатор работает поверх графика и визуализирует зоны ловушек градиентными заливками, линии и текстовые метки.
В основе работы лежат несколько модулей. Движок тренда рассчитывает DEMA-линию со сглаживанием и определяет направление рынка по порогам, вычисленным через ATR. Модуль уровней находит свечные максимумы и минимумы с помощью пивотов и отслеживает их как потенциальные точки пробоя. При подтверждении возврата цены через уровень индикатор фиксирует ловушку и строит зону.
Визуализация включает градиентную облачную область тренда, окрашивание свечей по направлению, треугольники при смене тренда, зоны ловушек с градиентными слоями и метки с информацией о захваченном объёме. Индикатор поддерживает условия оповещений TradingView для сигналов о смене тренда и подтверждённых ловушках. Также на графике отображается информационная панель.
Все параметры настраиваются пользователем через панель входных данных: длины расчётов, пороговые значения, количество отображаемых уровней и зон, цвета и режимы отображения. Индикатор не является автоматическим советником и не выполняет симуляцию торговых операций.
Настройки программы
| Настройка | Описание |
|---|---|
| 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 | Включает или отключает видимость градиентной области тренда. |
| 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Показано первые 50% кода (символов: 12104)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.