Power of Three Entry Engine
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «indicator power of three entry engine for tradingview.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Индикатор «Power of Three Entry Engine» отображает на графике TradingView циклическую модель, в которой дневной диапазон цены проходит три фазы: накопление, манипуляцию и распределение. Основная задача — обнаружить момент, когда цена в фазе манипуляции пробивает один из краёв накопительного диапазона, а затем фиксирует закрытие обратно внутри него, формируя подтверждённую setup-зону. Для каждой такой зоны индикатор рассчитывает уровни входа, стоп-лосса (invalidation) и целевого движения (target).
Настройки программы
| Настройка | Описание |
|---|---|
| presetIn | Выбирает предустановку рыночных сессий: Auto (автоматическое определение по символу), Gold, Indices, Forex, Crypto или Custom (ручной ввод сессий). |
| confirmIn | Определяет условие подтверждения setup. «Close Inside» — достаточно закрытия обратно внутри диапазона. «Close Inside + CISD» дополнительно требует закрытия через открытие свечи, которая создала пробой (более строгий режим). |
| waitMin | Максимальное время ожидания подтверждения в минутах после пробоя диапазона. Если подтверждение не произошло за это время, движение считается продолжением тренда. Логика одинакова на всех таймфреймах. |
| targetIn | Множитель для расширения целевого уровня за пределы диапазона. 0 = противоположная сторона диапазона (классическая цель Power of Three). Более высокие значения увеличивают цель на соответствующее число высот диапазона. |
| roomIn | Минимальное соотношение расстояния до цели и расстояния до инвалидации. Если до цели недостаточно места относительно стоп-лосса, setup не отображается. |
| bufIn | Задаёт множитель ATR для отступа уровня стоп-лосса за пределы экстремума пробоя. Защита от случайных флуктуаций у фитильной свечи. Увеличение буфера делает систему более терпимой к шуму. |
| openIn | Отображает и использует в оценке открытие дня по Нью-Йоркскому времени (00:00). Вход на противоположной стороне от этого открытия добавляет балл к оценке setup. |
| minGrade | Минимальная оценка setup для отображения: A (не менее 4 из 5 баллов), B (3 балла), C (2 или менее). Без учёта True Day Open: A — 3 из 4, B — 2. C показывает все setup, B и A — только более сильные. |
| dirIn | Ограничивает отображение и оповещения: только бычьи setup, только медвежьи или оба направления одновременно. |
| htfIn | Выбирает старший таймфрейм для сравнения закрытия его свечей с 50 EMA. Совпадение направления добавляет балл к оценке setup. |
| sAccIn | Временной интервал сессии накопления (Accumulation) в формате ЧЧММ-ЧЧММ по Нью-Йоркскому времени. Используется при выбранной предустановке Custom. |
| sManIn | Временной интервал сессии манипуляции (Manipulation) в формате ЧЧММ-ЧЧММ по Нью-Йоркскому времени. Используется при выбранной предустановке Custom. |
| sDisIn | Временной интервал сессии распределения (Distribution) в формате ЧЧММ-ЧЧММ по Нью-Йоркскому времени. Используется при выбранной предустановке Custom. |
| themeIn | Выбор цветовой схемы: Auto (следует фону графика), Dark или Light. |
| phaseIn | Заливает фон графика цветом текущей фазы: голубой для накопления, янтарный для манипуляции, цветом setup для распределения. |
| ribbonIn | Отображает цветные полосы накопления, манипуляции и распределения над каждым циклом на графике. |
| focusIn | При активации приглушает свечи вне активной setup-зоны, чтобы текущая setup была более заметна. Автоматически включается в Reels Mode. |
| reachIn | Рисует линию типичного достижения цели после подтверждённой setup на данном символе (медиана по прошлым циклам), до инвалидации или конца сессии. Это измерение прошлого поведения, не прогноз. |
| profIn | Отображает панель профиля символа, показывающую статистику поведения инструмента по загруженным циклам (доля пробоев, подтверждений, типичное достижение цели). Скрыта в Reels Mode. |
| profPos | Задаёт положение панели профиля символа на графике: верхний левый, верхний центр, верхний правый, нижний левый, нижний центр или нижний правый угол. |
| railIn | Отображает столбец ценовых уровней (Target, Entry, Invalidation) справа от цены с короткими метками; точная цена доступна при наведении. |
| sizeIn | Размер текста меток и панелей на графике: Small, Normal или Large. |
| colorIn | Включает ручной выбор цветов для бычьих и медвежьих setup-зон вместо использования автоматической цветовой схемы в зависимости от темы графика. |
| longIn | Цвет для бычьих (bullish) setup-зон и меток на графике. |
| shortIn | Цвет для медвежьих (bearish) setup-зон и меток на графике. |
| reelsIn | Включает компактный режим с увеличенным текстом и упрощённой статус-карточкой, оптимизированный для вертикальных записей и мобильных устройств. |
| keepIn | Задаёт количество недавних циклов, которые отрисовываются на графике в полном объёме. Более старые циклы без setup удаляются. |
| histIn | Сохраняет завершённые setup на графике (до 50 штук) вместе с их уровнями и информацией о том, как завершился каждый цикл, для последующего анализа. |
| pillIn | Задаёт расположение информационной панели (статус-карточки) с текущим состоянием индикатора на графике. |
| jsonIn | Включает отправку всех событий индикатора в виде JSON-сообщений через единственный alert() с любой функцией оповещения TradingView. |
Поиск по коду файла
indicator("Power of Three Entry Engine", shorttitle = "Po3 Entry Engine", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, behind_chart = false)
string G_SETUP = "🎯 Setup"
string G_SESS = "🕒 Custom Sessions"
string G_VIS = "🎨 Visuals"
string G_ALERT = "🔔 Alerts"
string presetIn = input.string("Auto", "🧭 Market Preset", options = ["Auto", "Gold", "Indices", "Forex", "Crypto", "Custom"], group = G_SETUP, tooltip = "Auto reads the symbol and selects session hours for it. Custom uses the session inputs below.", display = display.none)
string confirmIn = input.string("Close Inside", "✅ Confirmation", options = ["Close Inside", "Close Inside + CISD"], group = G_SETUP, tooltip = "Close Inside confirms on the first strong close back in the range. Close Inside + CISD also requires a close through the open of the move that made the sweep, which is slower and stricter. With Close Inside, a CISD close still adds one grade point.", display = display.none)
int waitMin = input.int(120, "⏳ Max Wait To Confirm (min)", minval = 1, maxval = 600, group = G_SETUP, tooltip = "If price does not confirm within this many minutes after the sweep, the move is treated as continuation. Minutes keep the rule the same on every timeframe.", display = display.none)
float targetIn = input.float(0.0, "🏁 Target Projection", minval = 0, maxval = 3, step = 0.25, group = G_SETUP, tooltip = "0 = the opposite side of the range, the classic Power of Three objective. Higher values extend the target beyond it by that multiple of the range height.", display = display.none)
float roomIn = input.float(1.0, "📏 Minimum Room", minval = 0.25, maxval = 5, step = 0.25, group = G_SETUP, tooltip = "Distance to target must be at least this multiple of the distance to invalidation.", display = display.none)
float bufIn = input.float(1.0, "🛡️ Invalidation Buffer (ATR)", minval = 0, maxval = 2, step = 0.05, group = G_SETUP, tooltip = "Invalidation sits beyond the sweep extreme by this multiple of the ATR, so ordinary noise around the wick does not end the setup.", display = display.none)
bool openIn = input.bool(true, "🕛 True Day Open", group = G_SETUP, tooltip = "Draws the 00:00 New York open. In Power of Three the move is usually entered on the far side of this open: below it before a bullish distribution, above it before a bearish one. An entry on that side adds one grade point.", display = display.none)
string minGrade = input.string("C", "🏅 Minimum Grade", options = ["A", "B", "C"], group = G_SETUP, tooltip = "One point each for clean sweep depth, fast confirmation, higher timeframe agreement, a CISD close and an entry on the far side of the True Day Open. A = at least four of five, B = three, C = two or fewer. Without the True Day Open: A = three of four, B = two. C shows every setup; B or A keeps only the stronger ones.", display = display.none)
string dirIn = input.string("Both", "↕️ Direction", options = ["Both", "Bullish Only", "Bearish Only"], group = G_SETUP, tooltip = "Limits which setups are drawn and alerted.", display = display.none)
string htfIn = input.timeframe("240", "🧠 Higher Timeframe Bias", group = G_SETUP, tooltip = "Closed higher timeframe candles compared with their 50 EMA. Agreement adds one grade point.", display = display.none)
string sAccIn = input.session("2000-0200", "🌙 Accumulation", group = G_SESS, display = display.none)
string sManIn = input.session("0200-0830", "⚡ Manipulation", group = G_SESS, display = display.none)
string sDisIn = input.session("0830-1600", "🚀 Distribution", group = G_SESS, display = display.none)
string themeIn = input.string("Auto", "🌗 Theme", options = ["Auto", "Dark", "Light"], group = G_VIS, tooltip = "Auto follows the chart background.", display = display.none)
bool phaseIn = input.bool(true, "🌈 Phase Shading", group = G_VIS, tooltip = "Tints the chart background through each phase: blue for accumulation, amber for manipulation, and the setup color for distribution.", display = display.none)
bool ribbonIn = input.bool(true, "🎞️ Phase Ribbon", group = G_VIS, tooltip = "Shows the accumulation, manipulation and distribution strip above each cycle.", display = display.none)
bool focusIn = input.bool(false, "🔦 Focus Mode", group = G_VIS, tooltip = "Softens candles outside the active setup so the setup stands out. Always on in Reels Mode.", display = display.none)
bool reachIn = input.bool(true, "📐 Typical Reach", group = G_VIS, tooltip = "Draws how far price has typically traveled after a confirmed setup on this symbol, before invalidation or the session end. It is a measurement of past behavior, not a forecast.", display = display.none)
bool profIn = input.bool(true, "📊 Profile Panel", group = G_VIS, tooltip = "Shows how this symbol has behaved across the loaded cycles. Hidden in Reels Mode.", display = display.none)
string profPos = input.string("Top Right", "📍 Profile Position", options = ["Top Left", "Top Center", "Top Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = G_VIS, display = display.none)
bool railIn = input.bool(true, "🏷️ Price Rail", group = G_VIS, tooltip = "Shows the active levels with their prices in a clean column to the right of price. Level badges on the chart stay short; hover them for the price.", display = display.none)
string sizeIn = input.string("Normal", "🔠 Text Size", options = ["Small", "Normal", "Large"], group = G_VIS, display = display.none)
bool colorIn = input.bool(false, "🎨 Use Custom Colors", group = G_VIS, display = display.none)
color longIn = input.color(#2be4a7, "Bullish Color", group = G_VIS, display = display.none)
color shortIn = input.color(#ff4d6a, "Bearish Color", group = G_VIS, display = display.none)
bool reelsIn = input.bool(false, "📱 Reels Mode", group = G_VIS, tooltip = "Larger text and a compact status card for vertical recordings and phones.", display = display.none)
int keepIn = input.int(5, "🗂️ Cycles To Keep", minval = 1, maxval = 20, group = G_VIS, tooltip = "Recent cycles drawn in full. Older cycles without a setup are cleared.", display = display.none)
bool histIn = input.bool(true, "🗃️ Keep Past Setups", group = G_VIS, tooltip = "Keeps past setups on the chart (up to 50) with their levels and how each one ended, so you can review them.", display = display.none)
string pillIn = input.string("Bottom Left", "📍 Status Position", options = ["Top Left", "Top Center", "Top Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = G_VIS, display = display.none)
bool jsonIn = input.bool(true, "🛰️ Send Event Alerts", group = G_ALERT, tooltip = "Create one alert with Any alert() function call to receive every event as a JSON message.", display = display.none)
f_autoPreset() =>
string s = str.upper(syminfo.ticker)
bool metal = str.contains(s, "XAU") or str.contains(s, "XAG") or str.startswith(s, "GC1") or str.startswith(s, "MGC") or str.startswith(s, "GOLD")
bool index = str.contains(s, "NAS") or str.contains(s, "SPX") or str.contains(s, "US30") or str.contains(s, "US100") or str.contains(s, "US500") or str.contains(s, "DJI") or str.startswith(s, "NQ") or str.startswith(s, "ES1") or str.startswith(s, "MNQ") or str.startswith(s, "MES")
metal ? "Gold" : index ? "Indices" : syminfo.type == "crypto" ? "Crypto" : syminfo.type == "forex" ? "Forex" : syminfo.type == "cfd" ? "Forex" : "Indices"
string preset = presetIn == "Auto" ? f_autoPreset() : presetIn
string sessAcc = preset == "Custom" ? sAccIn : preset == "Indices" ? "1800-0830" : "2000-0200"
string sessMan = preset == "Custom" ? sManIn : preset == "Indices" ? "0830-1030" : "0200-0830"
string sessDis = preset == "Custom" ? sDisIn : preset == "Indices" ? "1030-1600" : "0830-1600"
string TZ = "America/New_York"
bool tfOk = timeframe.isintraday and timeframe.in_seconds() <= 1800
bool inAcc = not na(time(timeframe.period, sessAcc + ":1234567", TZ))
bool inMan = not na(time(timeframe.period, sessMan + ":1234567", TZ))
bool inDis = not na(time(timeframe.period, sessDis + ":1234567", TZ))
int maxWait = math.max(1, int(math.ceil(waitMin * 60.0 / timeframe.in_seconds())))
int nyDay = dayofmonth(time, TZ)
bool newDay = nyDay != nyDay[1]
f_luma(color c) => (0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) / 255
color bgC = themeIn == "Auto" ? chart.bg_color : themeIn == "Dark" ? #0b0e14 : #ffffff
bool isDark = f_luma(bgC) < 0.5
color cLong = colorIn ? longIn : isDark ? #2be4a7 : #00875f
color cShort = colorIn ? shortIn : isDark ? #ff4d6a : #d92d4a
color cAmber = isDark ? #f5b83d : #b26a00
color cIce = isDark ? #6fb7ff : #1f6fd1
color cText = isDark ? #e9eef6 : #131722
color cMuted = isDark ? #8a97ab : #5d6778
color cCard = isDark ? #121826 : #f3f6fb
color cCard2 = isDark ? #1a2232 : #e6ebf3
color cLine = isDark ? #26314a : #d3dae6
string txtN = sizeIn == "Small" ? size.small : sizeIn == "Large" ? size.large : size.normal
string txtS = reelsIn ? size.normal : sizeIn == "Small" ? size.tiny : sizeIn == "Large" ? size.normal : size.small
string txtT = reelsIn ? size.small : sizeIn == "Large" ? size.small : size.tiny
float atr14 = ta.atr(14)
float atr200 = nz(ta.atr(200), atr14)
float dayAtr = request.security(syminfo.tickerid, "D", ta.atr(14)[1], lookahead = barmerge.lookahead_on)
float swing = ta.highest(high, 100) - ta.lowest(low, 100)
float htfClose = request.security(syminfo.tickerid, htfIn, close[1], lookahead = barmerge.lookahead_on)
float htfEma = request.security(syminfo.tickerid, htfIn, ta.ema(close, 50)[1], lookahead = barmerge.lookahead_on)
int htfBias = na(htfClose) or na(htfEma) ? 0 : htfClose > htfEma ? 1 : -1
f_cisd(int side) =>
float lvl = na
for i = 0 to 20
bool against = side == -1 ? close[i] > open[i] : close[i] < open[i]
if against
lvl := open[i]
else if not na(lvl)
break
lvl
f_num(float x) => na(x) ? "null" : str.tostring(x)
f_json(string ev, int side, float lvl, float e, float inv, float t, string g) =>
'{"schema":"tws.v1","engine":"po3","event":"' + ev + '","side":"' + (side == 1 ? "bullish" : side == -1 ? "bearish" : "none") + '","symbol":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","level":' + f_num(lvl) + ',"entry":' + f_num(e) + ',"invalidation":' + f_num(inv) + ',"target":' + f_num(t) + ',"grade":"' + g + '"}'
type Cycle
array<box> boxes
array<line> lines
array<label> labels
array<box> ribbons
bool setup = false
f_newCycle() => Cycle.new(array.new<box>(), array.new<line>(), array.new<label>(), array.new<box>())
method wipe(Cycle c) =>
for b in c.boxes
box.delete(b)
for l in c.lines
line.delete(l)
for t in c.labels
label.delete(t)
for b in c.ribbons
box.delete(b)
method addBox(Cycle c, box b) =>
c.boxes.push(b)
b
method addLine(Cycle c, line l) =>
c.lines.push(l)
l
method addLabel(Cycle c, label t) =>
c.labels.push(t)
t
f_ribbon(Cycle c, int x, float top, float bottom, color col, string txt) =>
box rb = box.new(x, top, x, bottom, border_color = color.new(col, 100), bgcolor = color.new(col, ribbonIn ? 76 : 100), text = ribbonIn ? txt : "", text_color = col, text_size = size.large, text_halign = text.align_center, text_valign = text.align_center, text_formatting = text.format_bold)
c.ribbons.push(rb)
rb
f_level(Cycle c, array<line> store, int x1, int x2, float y, color col, string st, int w) =>
store.push(c.addLine(line.new(x1, y, x2, y, color = col, style = st, width = w)))
f_tag(int x, float y, string txt, float price, color col) =>
label.new(x, y, txt, color = color.new(col, 82), textcolor = col, style = label.style_label_left, size = txtS, text_formatting = text.format_bold, tooltip = txt + " " + str.tostring(price, format.mintick))
int WAIT = 0, int BUILD = 1, int ARMED = 2, int SWEPT = 3, int ACTIVE = 4, int DONE = 5
var int state = WAIT
var string note = "Waiting for the next session"
var string tag = "WAITING"
var color tagC = cMuted
var array<Cycle> cycles = array.new<Cycle>()
var Cycle cur = f_newCycle()
var array<Cycle> hist = array.new<Cycle>() // past setups kept for review
var float rHi = na, var float rLo = na, var float cyHi = na
var int accX = na, var int swX = na, var int entryX = na
var int side = 0
var float swExt = na, var float cisd = na
var float entry = na, var float invalid = na, var float target = na, var float exitPx = na
var int resKind = 0 // 1 invalidated, 2 target reached, 3 session close
var bool hasSetup = false
var color disC = cMuted // distribution color follows the setup side
var box rangeBox = na, var box rbAcc = na, var box rbMan = na, var box rbDis = na
var box zoneT = na, var box zoneI = na
var line lnHi = na, var line lnLo = na, var line lnTdo = na
var label swDot = na, var label swTxt = na
var array<line> levels = array.new<line>()
var line lnReach = na
var label tgT = na, var label tgE = na, var label tgI = na
var string grade = ""
var int gradeRank = 0
var int gradePts = 0
var int gradeFull = 0
var string gradeTip = ""
var bool stepRange = false, var bool stepSweep = false, var bool stepConfirm = false
var float dayOpen = na
var bool tdoOk = false
var int nCycles = 0, var int nSwept = 0, var int nHigh = 0, var int nConfirmed = 0, var int nSet = 0
var int nOpenChk = 0, var int nOpenFar = 0
var array<float> confirmBars = array.new<float>()
var array<float> reaches = array.new<float>()
var bool trkOn = false
var int trkSide = 0
var float trkEntry = na, var float trkBest = na, var float trkH = na, var float trkInv = na
bool evRange = false, bool evSweep = false, bool evConfirm = false, bool evInvalid = false, bool evTarget = false, bool evEnd = false, bool resolved = false
if barstate.isconfirmed and tfOk
bool accStart = inAcc and not inAcc[1]
bool accEnd = inAcc[1] and not inAcc
bool disEnd = inDis[1] and not inDis
if trkOn
bool trkStop = trkSide == 1 ? low <= trkInv : high >= trkInv
if not trkStop
trkBest := trkSide == 1 ? math.max(trkBest, high) : math.min(trkBest, low)
if trkStop or disEnd or accStart
reaches.push(math.max(0.0, (trkBest - trkEntry) * trkSide / trkH))
if reaches.size() > 200
reaches.shift()
trkOn := false
if (disEnd or accStart) and state >= ARMED and state < DONE
bool wasActive = state == ACTIVE
state := DONE
tag := wasActive ? "SESSION CLOSE" : "NO SETUP"
tagC := cMuted
note := wasActive ? "Levels not reached before the session closed" : "No confirmed sweep this session"
resolved := wasActive
if wasActive
exitPx := close[1], resKind := 3, evEnd := true
if accStart
cycles.push(cur)
if cycles.size() > keepIn
Cycle old = cycles.shift()
if histIn and old.setup
hist.push(old)
if hist.size() > 50
hist.shift().wipe()
else
old.wipe()
cur := f_newCycle()
levels := array.new<line>()
state := BUILD
rHi := high, rLo := low, cyHi := high, accX := bar_index, side := 0, hasSetup := false, disC := cMuted
entry := na, invalid := na, target := na, exitPx := na, resKind := 0, tdoOk := false
rbMan := na, rbDis := na, zoneT := na, zoneI := na, lnHi := na, lnLo := na, lnTdo := na, lnReach := na, tgT := na, tgE := na, tgI := na
grade := "", gradeRank := 0, gradePts := 0, gradeFull := 0, gradeTip := "", stepRange := false, stepSweep := false, stepConfirm := false
tag := "BUILDING RANGE", tagC := cIce, note := "Accumulation range is forming"
rangeBox := cur.addBox(box.new(bar_index, rHi, bar_index, rLo, border_color = color.new(cIce, 70), bgcolor = color.new(cIce, 90)))
rbAcc := f_ribbon(cur, bar_index, high + atr200 * 2.3, high + atr200 * 1.25, cIce, "ACCUMULATION")
if state != WAIT
cyHi := math.max(cyHi, high)
if newDay and state != WAIT
dayOpen := open, tdoOk := true
if openIn
lnTdo := cur.addLine(line.new(bar_index, open, bar_index + 1, open, color = color.new(cText, 40), style = line.style_dotted, width = 1))
cur.addLabel(label.new(bar_index, open, "TRUE OPEN", color = color.new(cText, 100), textcolor = color.new(cText, 30), style = label.style_label_right, size = size.tiny, tooltip = "00:00 New York open " + str.tostring(open, format.mintick)))
if not na(lnTdo) and (inAcc or inMan or inDis)
line.set_x2(lnTdo, bar_index)
if state == BUILD and inAcc and not accStart
rHi := math.max(rHi, high), rLo := math.min(rLo, low)
box.set_top(rangeBox, rHi), box.set_bottom(rangeBox, rLo), box.set_right(rangeBox, bar_index)
if state == BUILD and accEnd
float h = rHi - rLo
box.set_right(rangeBox, bar_index - 1)
lnHi := cur.addLine(line.new(accX, rHi, bar_index, rHi, color = color.new(cIce, 25), width = 1))
lnLo := cur.addLine(line.new(accX, rLo, bar_index, rLo, color = color.new(cIce, 25), width = 1))
if not na(dayAtr) and (h > dayAtr * 0.9 or h < dayAtr * 0.06)
state := DONE, tag := "NO SETUP", tagC := cMuted
note := h > dayAtr * 0.9 ? "Range is too wide for a clean sweep" : "Range is too narrow to measure"
else
state := ARMED, tag := "ARMED", tagC := cAmber
note := "Watching " + str.tostring(rHi, format.mintick) + " and " + str.tostring(rLo, format.mintick)
evRange := true, stepRange := true, nCycles += 1
if inMan and na(rbMan) and state != WAIT
rbMan := f_ribbon(cur, bar_index, cyHi + atr200 * 2.3, cyHi + atr200 * 1.25, cAmber, "MANIPULATION")
if inDis and na(rbDis) and state != WAIT
rbDis := f_ribbon(cur, bar_index, cyHi + atr200 * 2.3, cyHi + atr200 * 1.25, disC, "DISTRIBUTION")
float depth = atr14 * 0.05
if state == ARMED and inMan
bool up = high > rHi + depth
bool dn = low < rLo - depth
if up and dn
state := DONE, tag := "NO SETUP", tagC := cMuted, note := "Both sides of the range were taken"
else if up or dn
state := SWEPT, side := up ? -1 : 1, swX := bar_index, swExt := up ? high : low, cisd := f_cisd(side)
tag := "SWEEP DETECTED", tagC := cAmber, note := "Waiting for a close back inside the range"
evSweep := true, stepSweep := true, nSwept += 1, nHigh += up ? 1 : 0
line.set_color(up ? lnHi : lnLo, cAmber), line.set_width(up ? lnHi : lnLo, 2)
swDot := cur.addLabel(label.new(bar_index, swExt, "", color = color.new(cAmber, 15), style = label.style_circle, size = size.tiny))
swTxt := cur.addLabel(label.new(bar_index, swExt + side * -1 * atr200 * 0.7, "SWEEP", color = color.new(cAmber, 100), textcolor = cAmber, style = label.style_none, size = txtS, text_formatting = text.format_bold))
if state == SWEPT
if side == -1 ? high > swExt : low < swExt
swExt := side == -1 ? high : low
label.set_xy(swDot, bar_index, swExt), label.set_xy(swTxt, bar_index, swExt + side * -1 * atr200 * 0.7)
bool otherSide = side == -1 ? low < rLo - depth : high > rHi + depth
bool inside = side == -1 ? close < rHi : close > rLo
bool cisdPass = not na(cisd) and (side == -1 ? close < cisd : close > cisd)
bool cisdOk = confirmIn == "Close Inside" or na(cisd) or cisdPass
bool bodyOk = math.abs(close - open) >= (high - low) * 0.3
if otherSide
state := DONE, tag := "NO SETUP", tagC := cMuted, note := "Both sides of the range were taken"
else if inside and cisdOk and bodyOk
float h = rHi - rLo
float e = close
float i = swExt - side * atr14 * bufIn
float t = side == 1 ? rHi + h * targetIn : rLo - h * targetIn
float room = (t - e) * side / math.max(syminfo.mintick, (e - i) * side)
nConfirmed += 1
confirmBars.push(bar_index - swX)
if confirmBars.size() > 200
confirmBars.shift()
trkOn := true, trkSide := side, trkEntry := e, trkBest := e, trkH := math.max(syminfo.mintick, h), trkInv := i
float sweepDepth = math.abs(swExt - (side == -1 ? rHi : rLo)) / atr14
bool gDepth = sweepDepth >= 0.15 and sweepDepth <= 1.5
bool gFast = bar_index - swX <= math.ceil(maxWait / 2.0)
bool gHtf = htfBias == side
bool gCisd = cisdPass
bool useOpen = oПоказано первые 50% кода (символов: 31930)