Day Type Radar
Похожие материалы по тегам
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «day type radar for tradingview.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Day Type Radar — индикатор для интрадей-анализа на TradingView, написанный на Pine Script v6. Он определяет тип торговой сессии на основе поведения цены внутри Initial Balance и автоматически масштабируемого диапазона открытия. Индикатор классифицирует сессию как развивающуюся, Drive, Balance, Trend или Churn, отслеживая шесть классов событий: Drive, Probe-Reject, Accepted Break, Trap, Rotation и Late Expansion.
Все расстояния нормализуются по ATR, что позволяет применять одни и те же правила к разным инструментам и режимам волатильности. Временные окна масштабируются относительно длины сессии и таймфрейма графика. События фиксируются только на подтверждённых барах, метки не перемещаются и не перезаписываются после регистрации.
Индикатор отображает зону IB, линию открытия сессии, фазовую ленту и карточку с текущим типом дня, цепочкой событий и исторической статистикой. Поддерживаются настраиваемые режимы сессий, несколько таймзон, переключатели отображения событий и форматы оповещений. Это образовательный инструмент анализа рынка, не являющийся торговой рекомендацией.
Настройки программы
| Настройка | Описание |
|---|---|
| sessMode | Режим сессии — Определяет способ определения границ торговой сессии: автоматически по типу актива, по биржевой сессии, по фиксированному дневному якорю или по пользовательскому окну. |
| anchor24 | Якорь дня (рынки 24ч) — Выбор точки начала торгового дня для рынков без чёткой биржевой сессии: автоматически по типу актива или вручную выбранный часовой якорь. |
| customSess | Пользовательское окно сессии — Время начала и окончания пользовательской торговой сессии в формате ЧЧММ-ЧЧММ. Используется только при выборе режима пользовательского окна. |
| customTz | Часовой пояс пользовательского окна — Часовой пояс, в котором читается пользовательское окно сессии: по часовому поясу биржи или UTC. |
| dispTzIn | Часовой пояс отображения — Часовой пояс, в котором показываются время на карточке и под блоком сессии. Логика сигнализации от этого не меняется. |
| ibOverride | Длительность Initial Balance в минутах — Фиксированная длительность фазы формирования Initial Balance в минутах. Ноль означает автоматический расчёт. |
| sens | Чувствительность — Общий множитель чувствительности: Calm сужает пороги, Balanced — базовые значения, Active — расширяет пороги для срабатывания событий. |
| onDrive | Drive — Включает или выключает отображение и учёт событий класса Drive на графике и в статистике. |
| onProbe | Probe-Reject — Включает или выключает отображение и учёт событий класса Probe-Reject на графике и в статистике. |
| onAccept | Accepted Break — Включает или выключает отображение и учёт событий класса Accepted Break на графике и в статистике. |
| onTrap | Trap — Включает или выключает отображение и учёт событий класса Trap на графике и в статистике. |
| onRot | Rotation — Включает или выключает отображение и учёт событий класса Rotation на графике и в статистике. |
| onLate | Late Expansion — Включает или выключает отображение и учёт событий класса Late Expansion на графике и в статистике. |
| acceptMin | Accepted Break: минимум минут вне IB — Минимальное время, в течение которого цена должна закрываться за пределами Initial Balance с учётом буфера, чтобы пробой считался принятым. |
| trapMin | Окно ловушки в минутах — Максимальное время от первого закрытия за пределами IB, в течение которого возврат внутрь классифицируется как Trap. |
| pokeATR | Минимальный выход Probe (ATR) — Минимальное расстояние за край IB, которое цена должна достичь без закрытия за пределами, чтобы считаться зондированием. |
| bufATR | Буфер пробоя за край IB (ATR) — Минимальное расстояние за край IB, на которое закрытие должно выйти, чтобы считаться находящимся за пределами Initial Balance. |
| driveATR | Минимальный диапазон Drive (ATR) — Минимальная ширина диапазона сессии на контрольной точке Drive, необходимая для признания сильного открытия. |
| driveEdge | Допуск края Drive (доля) — Доля диапазона, в которой должен находиться открытие на одном конце и закрытие на другом конце для признания Drive. |
| edgePct | Зона края Rotation (доля IB) — Ширина зон у краёв Initial Balance, в которых определяется ребро-to-ребро Rotation. |
| minIBATR | Rotation: минимальный диапазон IB (ATR) — Минимальная ширина Initial Balance в единицах ATR, ниже которой Rotation игнорируется. |
| compFrac | Late Exp: максимальная компрессия (доля IB) — Максимальная доля диапазона IB, до которой должен сужаться базовый диапазон перед баром расширения. |
| expATR | Late Exp: минимальный расширяющий бар (ATR) — Минимальная высота бара расширения в единицах ATR, необходимая для классификации как Late Expansion. |
| atrLen | Длина ATR — Период расчёта Average True Range, используемый для нормализации всех расстояний. |
| maxFails | Churn lock: неудачных пробоев до блокировки — Количество неудачных пробоев, после которых сессия блокируется как Churn. Повторный неудачный пробой после принятого удваивает счёт. |
| unlockATR | Churn release: закрытие за край (ATR) — Расстояние за край IB, на которое должно закрыться цена, чтобы разблокировать состояние Churn. |
| endCut | Новых событий в конце сессии (%) — Процент сессии от конца, в пределах которого новые события не регистрируются. Ноль отключает ограничение. |
| lateExtreme | Late Exp: должен закрыться за высок/низ сессии — Требование, чтобы Late Expansion закрывался за максимум или минимум сессии, зафиксированные до бара пробоя. |
| oneAndDone | Одно событие на класс за сессию — Каждый класс событий регистрируется не более одного раза за сессию. Тип дня продолжает обновляться при каждом изменении состояния. |
| outcomeMeasure | Измеряемый результат (R) — Выбор метрики для последнего столбца карточки: доля событий, достигших 1R, 2R, 3R или средний результат в R. |
Поиск по коду файла
indicator("Day Type Radar", "DTR", overlay = true, max_labels_count = 500, max_boxes_count = 500, max_lines_count = 500, max_bars_back = 5000)
enum Phase
closed = "Closed"
ib = "Initial Balance"
balance = "Balance"
trend = "Trend"
enum SigClass
drive = "Drive"
probe = "Probe-Reject"
accepted = "Accepted Break"
trap = "Trap"
rotation = "Rotation"
lateExp = "Late Expansion"
type Signal
SigClass cls
int dir
int bi
float entry
float stop
float target
float risk
float mfe = 0.0
type Day
int startT = na
float sOpen = na
float sHi = na
float sLo = na
float ibHi = na
float ibLo = na
bool ibDone = false
bool driveChecked = false
int driveSide = 0
int acceptedSide = 0
int exSide = 0
int exStartT = na
float exExt = na
bool exAcc = false
int lastZone = 0
bool lateFired = false
int nSig = 0
int fails = 0
bool churn = false
int probeT = na
string fired = ""
Phase phase
type Ledger
array<int> observed
array<int> resolved
array<int> reached1
array<int> reached
array<float> sumR
array<Signal> live
type ReadRec
int kind
int dir
float px
float atr
float ibHi
float ibLo
float hi
float lo
type Stats
array<int> n
array<float> sumRem
array<int> beyond
array<int> dirN
array<int> follow
array<float> sumExt
array<ReadRec> live
const string G_SES = "1 - Session and timing"
const string G_SEN = "2 - Sensitivity"
const string G_TOG = "2b - Event toggles"
const string G_CLS = "3 - Event rules (advanced)"
const string G_LED = "4 - Event ledger"
const string G_RL = "5 - Reference levels"
const string G_DB = "6 - Dashboards"
const string G_VIS = "7 - Visuals"
const string G_AL = "8 - Alerts"
sessMode = input.string("Auto", "Session mode", options = ["Auto", "Exchange session", "Day anchor", "Custom window"], group = G_SES, tooltip = "Auto: stocks, funds and indices use the exchange session. Crypto, forex, CFDs, futures and commodities (near 24h markets) use a fixed day anchor, so the 'day' is identical on every chart load. The other options force that choice. Exchange session needs a market with a daily break. It is blocked on crypto and spot forex. On other 24h markets it follows the exchange's own session breaks.", display = display.data_window)
anchor24 = input.string("Auto", "Day anchor (24h markets)", options = ["Auto", "UTC 00:00", "Tokyo 09:00", "London 08:00", "New York 09:30"], group = G_SES, tooltip = "Used only when the day anchor is active. Auto: crypto = UTC full day. Forex and EUREX / ICE Europe products (e.g. Brent) = London 08:00. Everything else (US index futures, WTI, gold, other commodities and CFDs) = New York 09:30. Pick manually to use another open.", display = display.data_window)
customSess = input.session("0930-1600", "Custom session window", group = G_SES, tooltip = "Used only in Custom window mode.", display = display.data_window)
customTz = input.string("Exchange", "Custom window timezone", options = ["Exchange", "UTC"], group = G_SES, tooltip = "Timezone used to read the custom window.", display = display.data_window)
dispTzIn = input.string("Exchange", "Display time zone", options = ["Exchange", "UTC", "America/New_York", "America/Chicago", "Europe/London", "Europe/Berlin", "Asia/Kolkata", "Asia/Dubai", "Asia/Singapore", "Asia/Hong_Kong", "Asia/Tokyo", "Australia/Sydney"], group = G_SES, tooltip = "Changes only the times shown on the card and under the box. Signal logic never changes.", display = display.data_window)
ibOverride = input.int(0, "Initial Balance minutes (0 = automatic)", minval = 0, group = G_SES, tooltip = "0 = automatic, nominally about 16% of the session and capped at 120 min before chart-bar constraints. Manual values are raised to at least one chart bar and at least the Drive window plus one chart bar.", display = display.data_window)
sens = input.string("Balanced", "Sensitivity", options = ["Calm", "Balanced", "Active"], group = G_SEN, tooltip = "Calm = tighter ATR-based Drive, Probe, Break-buffer and Late-Expansion size thresholds. Active = looser. Time windows and other structural limits are unchanged.", display = display.data_window)
onDrive = input.bool(true, "Drive", group = G_TOG, tooltip = "Each toggle mutes that event's chart label, reference levels, ledger counts and alerts. The event is still evaluated inside the engine, so the day type, chain and Churn lock can remain consistent. The ledger row is shown as off.")
onProbe = input.bool(true, "Probe-Reject", group = G_TOG)
onAccept = input.bool(true, "Accepted Break", group = G_TOG)
onTrap = input.bool(true, "Trap", group = G_TOG)
onRot = input.bool(true, "Rotation", group = G_TOG)
onLate = input.bool(true, "Late Expansion", group = G_TOG)
acceptMin = input.int(15, "Accepted Break: minutes outside IB", minval = 5, group = G_CLS, tooltip = "How long price must keep closing outside the IB (beyond the buffer) before the break counts as accepted.", display = display.data_window)
trapMin = input.int(40, "Trap window (minutes)", minval = 10, group = G_CLS, tooltip = "A break that closes back inside the IB within this time from its first close outside is called a Trap.", display = display.data_window)
pokeATR = input.float(0.25, "Probe minimum poke (ATR)", minval = 0.0, step = 0.05, group = G_CLS, tooltip = "How far beyond an IB edge price must poke, without closing outside, to count as a probe.", display = display.data_window)
bufATR = input.float(0.25, "Break buffer beyond IB edge (ATR)", minval = 0.0, step = 0.05, group = G_CLS, tooltip = "A close must be this far beyond the IB edge to count as outside. Filters noise at the edge.", display = display.data_window)
driveATR = input.float(1.0, "Drive minimum range (ATR)", minval = 0.1, step = 0.1, group = G_CLS, tooltip = "Minimum session range at the Drive checkpoint.", display = display.data_window)
driveEdge = input.float(0.20, "Drive edge tolerance (fraction)", minval = 0.05, maxval = 0.4, step = 0.05, group = G_CLS, tooltip = "The open must sit in this outer fraction of the range at one end, and the close in the same fraction at the other end.", display = display.data_window)
edgePct = input.float(0.25, "Rotation edge zone (fraction of IB)", minval = 0.1, maxval = 0.4, step = 0.05, group = G_CLS, tooltip = "Width of the IB edge zones used to detect an edge-to-edge rotation.", display = display.data_window)
minIBATR = input.float(1.5, "Rotation: minimum IB range (ATR)", minval = 0.5, step = 0.25, group = G_CLS, tooltip = "Rotation is ignored when the IB is narrower than this.", display = display.data_window)
compFrac = input.float(0.5, "Late Exp: max compression (fraction of IB)", minval = 0.1, step = 0.05, group = G_CLS, tooltip = "The range just before the breakout bar must be tighter than this fraction of the IB.", display = display.data_window)
expATR = input.float(1.5, "Late Exp: min expansion bar (ATR)", minval = 0.5, step = 0.25, group = G_CLS, tooltip = "The breakout bar must be at least this many ATR tall.", display = display.data_window)
atrLen = input.int(14, "ATR length", minval = 2, group = G_CLS, tooltip = "ATR length used to normalise every distance.", display = display.data_window)
maxFails = input.int(2, "Churn lock: failed breaks before lock", minval = 1, group = G_CLS, tooltip = "This many failed breaks lock the day as Churn. A failure after an accepted break counts double.", display = display.data_window)
unlockATR = input.float(1.0, "Churn release: close beyond edge (ATR)", minval = 0.5, step = 0.25, group = G_CLS, tooltip = "A close this far beyond an IB edge releases the Churn lock.", display = display.data_window)
endCut = input.int(8, "No new events in last (% of session)", minval = 0, maxval = 30, group = G_CLS, tooltip = "Stops new events near the session end. 0 = off.", display = display.data_window)
lateExtreme = input.bool(true, "Late Exp: must close beyond session high / low", group = G_CLS, tooltip = "Late Expansion must close beyond the session high or low set before the breakout bar.")
oneAndDone = input.bool(true, "One event per class per session", group = G_CLS, tooltip = "Each class prints once per session. The day type still updates on every state change. The event chain lists printed events plus state markers (IB, Lock, Free).")
outcomeMeasure = input.string("2R", "Outcome to measure (R)", options = ["1R", "2R", "3R", "Average R"], group = G_LED, tooltip = "Changes the last Radar Card outcome column. 1R, 2R or 3R show the percentage of resolved events that reached that target before the reference boundary. Average R shows the average resolved outcome using the 2R reference target. The first Reached 1R column is always 1R. This setting changes only the measurement shown in the last Radar Card column; it does not change event detection.", display = display.data_window)
int finalR = outcomeMeasure == "1R" ? 1 : outcomeMeasure == "3R" ? 3 : 2
float targetR = finalR
bool measureAverage = outcomeMeasure == "Average R"
minRiskATR = input.float(0.5, "Minimum reference distance (ATR)", minval = 0.1, step = 0.1, group = G_LED, tooltip = "The reference boundary distance is never smaller than this ATR multiple and never smaller than 2 ticks.", display = display.data_window)
minSample = input.int(20, "Low-sample notice below N", minval = 1, group = G_LED, tooltip = "Rows with fewer resolved events are dimmed and marked with an asterisk.", display = display.data_window)
showOutcome = input.bool(false, "Show outcome markers", group = G_LED, tooltip = "Marks where a completed event reached its reference target or reference boundary first.")
showLadder = input.bool(true, "Show R levels for live events", group = G_RL, tooltip = "Draws event price, reference boundary and R reference levels for unresolved events. Informational only.")
ladderMode = input.string("Latest only", "Levels shown for", options = ["Latest only", "All live"], group = G_RL, tooltip = "Latest only keeps the chart clean.", display = display.data_window)
labelOffset = input.int(6, "Label distance from last bar (bars)", minval = 2, maxval = 30, group = G_RL, tooltip = "How far right of the last bar the level labels sit.", display = display.data_window)
layout = input.string("Desktop", "Layout", options = ["Desktop", "Mobile"], group = G_DB, tooltip = "Mobile uses a compact five-column historical outcome table.", display = display.data_window)
showDash1 = input.bool(true, "Radar card", group = G_DB, tooltip = "Day type, event chain, observed events and historical reference-level outcomes.")
d1Pos = input.string("Top Right", "Radar card position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = G_DB, display = display.data_window)
d1Size = input.string("Auto", "Radar card text size", options = ["Auto", "Tiny", "Small", "Normal", "Large"], group = G_DB, display = display.data_window)
showDash2 = input.bool(false, "Day-Type Stats", group = G_DB, tooltip = "Historical observations from each read to the session close. Off by default to keep the chart clean.")
d2Pos = input.string("Bottom Left", "Day-Type Stats position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = G_DB, tooltip = "Do not use the same position as the Radar card, or the tables overlap.", display = display.data_window)
d2Size = input.string("Auto", "Day-Type Stats text size", options = ["Auto", "Tiny", "Small", "Normal", "Large"], group = G_DB, display = display.data_window)
showLabels = input.bool(true, "Event labels", group = G_VIS)
lblSize = input.string(size.small, "Label size", options = [size.tiny, size.small, size.normal], group = G_VIS, display = display.data_window)
minorMode = input.string("Dots", "Probe and Rotation labels", options = ["Dots", "Text"], group = G_VIS, tooltip = "Dots keep minor events quiet.", display = display.data_window)
showBox = input.bool(true, "Session box + text under it", group = G_VIS)
narrStyle = input.string("Story + stats", "Text under the box", options = ["Story + stats", "Tag only", "Off"], group = G_VIS, display = display.data_window)
showIB = input.bool(true, "Initial Balance zone", group = G_VIS)
showOpen = input.bool(true, "Session open line", group = G_VIS)
showExt = input.bool(false, "IB +/-1x extensions", group = G_VIS, tooltip = "Projects the IB range one IB-width above and below.")
showRibbon = input.bool(true, "Phase ribbon (bottom)", group = G_VIS, tooltip = "Colour strip: IB, Balance, Trend up/down, Churn.")
showChurnMarks = input.bool(false, "Churn lock / free markers", group = G_VIS)
showSessLines = input.bool(true, "Session start / end lines", group = G_VIS, tooltip = "Thin dotted vertical lines at the session open and close. 24h markets on the UTC full-day anchor show start lines only (one day ends where the next begins). The first loaded session is skipped.")
cSessLine = input.color(color.new(#9E9E9E, 55), "Session line colour", group = G_VIS)
cDrive = input.color(#FB8C00, "Drive", group = G_VIS, inline = "c1")
cProbe = input.color(#8E24AA, "Probe-Reject", group = G_VIS, inline = "c1")
cAccept = input.color(#00897B, "Accepted Break", group = G_VIS, inline = "c2")
cTrap = input.color(#E53935, "Trap", group = G_VIS, inline = "c2")
cRot = input.color(#1E88E5, "Rotation", group = G_VIS, inline = "c3")
cLate = input.color(#FDD835, "Late Expansion", group = G_VIS, inline = "c3")
cIB = input.color(#FFB300, "Phase: IB", group = G_VIS, inline = "p1")
cBal = input.color(#78909C, "Balance", group = G_VIS, inline = "p1")
cUp = input.color(#26A69A, "Trend up", group = G_VIS, inline = "p2")
cDn = input.color(#EF5350, "Trend down", group = G_VIS, inline = "p2")
cChurn = input.color(#E040FB, "Churn", group = G_VIS, inline = "p3")
alertFilter = input.string("All events", "Alert on", options = ["All events", "Major only"], group = G_AL, tooltip = "Major only skips Probe-Reject and Rotation. Create one alert using Day Type Radar > Any alert() function call. Events are emitted on confirmed bar closes.", display = display.data_window)
alertFmt = input.string("Text", "Alert message format", options = ["Text", "JSON"], group = G_AL, tooltip = "Text for notifications. JSON for webhooks. Both contain symbol, timeframe, event, direction, event price, reference boundary and R reference level.", display = display.data_window)
const int N_CLS = 6
const int MIN_TF_SEC = 60
const int MAX_TF_SEC = 14400
var array<string> NAMES = array.from("Drive", "Probe-Reject", "Accepted Break", "Trap", "Rotation", "Late Expansion")
var array<string> SHORT = array.from("Drive", "Probe", "Accept", "Trap", "Rotate", "Late")
var array<color> COLS = array.from(cDrive, cProbe, cAccept, cTrap, cRot, cLate)
var array<bool> ON = array.from(onDrive, onProbe, onAccept, onTrap, onRot, onLate)
var array<string> RNAMES = array.from("Balance read", "Drive read", "Trend read", "Churn read")
var array<color> RCOLS = array.from(cBal, cDrive, cAccept, cChurn)
float sMul = sens == "Calm" ? 1.5 : sens == "Active" ? 0.7 : 1.0
bool mobile = layout == "Mobile"
classIdx(SigClass c) =>
switch c
SigClass.drive => 0
SigClass.probe => 1
SigClass.accepted => 2
SigClass.trap => 3
SigClass.rotation => 4
SigClass.lateExp => 5
=> -1
txtCol(color c) =>
(color.r(c) * 0.299 + color.g(c) * 0.587 + color.b(c) * 0.114) > 150 ? color.black : color.white
getPos(string s) =>
switch s
"Top Left" => position.top_left
"Top Center" => position.top_center
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
=> position.top_right
szOf(string s, bool mob) =>
switch s
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
=> mob ? size.normal : size.small
pct(int a, int b) =>
b > 0 ? str.tostring(a * 100.0 / b, "0") + "%" : "-"
fmtR(float v) =>
na(v) ? "-" : (v > 0 ? "+" : "") + str.tostring(v, "0.00")
mk(SigClass c, int dir, float stopRaw, float px, float a) =>
Signal out = na
float minRisk = math.max(minRiskATR * a, 2 * syminfo.mintick)
float rawRisk = math.max(math.abs(px - stopRaw), minRisk)
float stopP = math.round_to_mintick(px - dir * rawRisk)
float risk = math.abs(px - stopP)
float tgtP = math.round_to_mintick(px + dir * risk * targetR)
bool ok = not na(risk) and risk >= syminfo.mintick and stopP != px and tgtP != px and tgtP != stopP
if ok
out := Signal.new(cls = c, dir = dir, bi = bar_index, entry = px, stop = stopP, target = tgtP, risk = risk)
out
dayName(Day x) =>
string out = "Developing"
if x.ibDone
if x.churn
out := "Churn"
else if x.acceptedSide != 0
out := "Trend day " + (x.acceptedSide == 1 ? "up" : "down")
else if x.driveSide != 0
out := "Drive day " + (x.driveSide == 1 ? "up" : "down")
else
out := "Balance day"
else if x.driveSide != 0
out := "Open drive " + (x.driveSide == 1 ? "up" : "down")
out
dayRead(Day x, float ibPct) =>
string out = "Initial Balance forming | " + str.tostring(ibPct, "0") + "% done"
if x.ibDone
if x.churn
out := "Breakouts failed repeatedly | IB edges are not holding"
else if x.acceptedSide != 0
out := "Closes held outside the IB | break accepted"
else if x.driveSide != 0
out := "Strong open drive | no active accepted break"
else
out := "Price rotating inside the IB | no accepted break"
else if x.driveSide != 0
out := "Open drive seen | IB forming | " + str.tostring(ibPct, "0") + "% done"
out
dayTag(Day x) =>
string out = "Developing"
if x.ibDone
if x.churn
out := "Churn"
else if x.acceptedSide != 0
out := "Trend " + (x.acceptedSide == 1 ? "up" : "down")
else if x.driveSide != 0
out := "Drive " + (x.driveSide == 1 ? "up" : "down")
else
out := "Balance"
else if x.driveSide != 0
out := "Open drive " + (x.driveSide == 1 ? "up" : "down")
out
phaseCol(Day x) =>
not x.ibDone ? cIB : x.churn ? cChurn : x.phase == Phase.trend ? (x.acceptedSide == 1 ? cUp : cDn) : cBal
cel(table t, int c, int r, string txt, color tc, color bgc, string ha, string sz) =>
table.cell(t, c, r, txt, text_color = tc, bgcolor = bgc, text_halign = ha, text_size = sz)
var table wmTg = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
table.cell(wmTg, 0, 0, "Telegram @VipForexCloud", text_color = color.new(color.gray, 70), text_size = size.large)
method reset(Day this, int t, float o, float h, float l) =>
this.startT := t
this.sOpen := o
this.sHi := h
this.sLo := l
this.ibHi := h
this.ibLo := l
this.ibDone := false
this.driveChecked := false
this.driveSide := 0
this.acceptedSide := 0
this.exSide := 0
this.exStartT := na
this.exExt := na
this.exAcc := false
this.lastZone := 0
this.lateFired := false
this.nSig := 0
this.fails := 0
this.churn := false
this.probeT := na
this.fired := ""
this.phase := Phase.ib
method begin(Day this, int side, float h, float l, int t) =>
this.exSide := side
this.exStartT := t
this.exExt := side == 1 ? h : l
this.exAcc := false
this.lastZone := 0
method finish(Day this) =>
this.exSide := 0
this.exStartT := na
this.exAcc := false
this.acceptedSide := 0
this.lastZone := 0
if this.phase == Phase.trend
this.phase := Phase.balance
method settle(Ledger this, Signal s, bool isResolved, bool didReach1, bool didReach, float resultR) =>
int k = classIdx(s.cls)
this.observed.set(k, this.observed.get(k) + 1)
if isResolved
this.resolved.set(k, this.resolved.get(k) + 1)
if didReach1
this.reached1.set(k, this.reached1.get(k) + 1)
if didReach
this.reached.set(k, this.reached.get(k) + 1)
this.sumR.set(k, this.sumR.get(k) + resultR)
method advance(Ledger this, float h, float l, bool markers, int bi) =>
int i = this.live.size() - 1
while i >= 0
Signal s = this.live.get(i)
bool alreadyR1 = s.mfe >= 1.0
float fav = (s.dir == 1 ? h - s.entry : s.entry - l) / s.risk
s.mfe := math.max(s.mfe, fav)
bool hitS = s.dir == 1 ? l <= s.stop : h >= s.stop
bool hitR1 = s.dir == 1 ? h >= s.entry + s.risk : l <= s.entry - s.risk
bool hitT = s.dir == 1 ? h >= s.target : l <= s.target
if hitS or hitT
bool didReach1 = alreadyR1 or (hitR1 and not hitS)
bool didReach = hitT and not hitS
float resultR = didReach ? math.abs(s.target - s.entry) / s.risk : -1.0
this.settle(s, true, didReach1, didReach, resultR)
if markers
label.new(bi, didReach ? s.target : s.stop, didReach ? "Target reached" : "Reference boundary", style = label.style_none, textcolor = didReach ? color.teal : color.red, size = size.small)
this.live.remove(i)
i -= 1
method expire(Ledger this, float px) =>
while this.live.size() > 0
Signal s = this.live.pop()
this.settle(s, false, false, false, 0.0)
method startRead(Stats this, int kind, int dir, float px, float a, float ibHi, float ibLo) =>
this.live.push(ReadRec.new(kind = kind, dir = dir, px = px, atr = a, ibHi = ibHi, ibLo = ibLo, hi = px, lo = px))
method track(Stats this, float h, float l) =>
for r in this.live
r.hi := math.max(r.hi, h)
r.lo := math.min(r.lo, l)
method settleAll(Stats this, float fc) =>
while this.live.size() > 0
ReadRec r = this.live.pop()
int k = r.kind
float ibR = math.max(r.ibHi - r.ibLo, syminfo.mintick)
this.n.set(k, this.n.get(k) + 1)
this.sumRem.set(k, this.sumRem.get(k) + (r.hi - r.lo) / math.max(r.atr, syminfo.mintick))
if fc > r.ibHi or fc < r.ibLo
this.beyond.set(k, this.beyond.get(k) + 1)
if r.dir != 0
this.dirN.set(k, this.dirN.get(k) + 1)
if r.dir * (fc - r.px) > 0
this.follow.set(k, this.follow.get(k) + 1)
float ext = r.dir == 1 ? r.hi - r.ibHi : r.dir == -1 ? r.ibLo - r.lo : math.max(r.hi - r.ibHi, r.ibLo - r.lo)
this.sumExt.set(k, this.sumExt.get(k) + math.max(ext, 0.0) / ibR)
var Day d = Day.new(phase = Phase.closed)
var Ledger led = Ledger.new(observed = array.new<int>(N_CLS, 0), resolved = array.new<int>(N_CLS, 0), reached1 = array.new<int>(N_CLS, 0), reached = array.new<int>(N_CLS, 0), sumR = array.new<float>(N_CLS, 0.0), live = array.new<Signal>())
var Stats stats = Stats.new(n = array.new<int>(4, 0), sumRem = array.new<float>(4, 0.0), beyond = array.new<int>(4, 0), dirN = array.new<int>(4, 0), follow = array.new<int>(4, 0), sumExt = array.new<float>(4, 0.0), live = array.new<ReadRec>())
var array<string> story = array.new<string>()
var array<string> beats = array.new<string>()
var color ribbonCol = na
var box sBox = na
var label sLbl = na
var float lastSessMin = na
var bool armed = false
var int lastConfT = na
var float sessAtr = na
bool badChart = not chart.is_standard
bool badTf = not timeframe.isintraday or timeframe.in_seconds() < MIN_TF_SEC or timeframe.in_seconds() > MAX_TF_SEC
bool blocked = badChart or badTf
string blockMsg = badChart ? "Day Type Radar needs a standard chart type (Candles, Bars, Line, Area).\nHeikin Ashi, Renko, Kagi, Line Break, Range and Point & Figure change the prices." : "Day Type Radar supports intraday charts from 1 minute to 4 hours."
var table warnT = table.new(position.bottom_center, 1, 1)
if barstate.islast and blocked
table.cell(warnT, 0, 0, blockMsg, text_color = color.white, bgcolor = color.new(color.red, 15), text_size = size.normal)
int tfSec = timeframe.in_seconds()
float tfMin = tfSec / 60.0
string exTz = syminfo.timezone
string stype = syminfo.type
string assetName = switch stype
"stock" => "Stock"
"fund" => "Fund / ETF"
"dr" => "Depositary receipt"
"index" => "Index"
"futures" => "Futures"
"forex" => "Forex"
"crypto" => "Crypto"
"cfd" => "CFD"
"commodity" => "Commodity"
=> "Other"
bool isMarket24 = stype == "crypto" or stype == "forex" or stype == "cfd" or stype == "futures" or stype == "commodity"
bool euro = syminfo.prefix == "EUREX" or syminfo.prefix == "ICEEUR"
string anchorKey = anchor24 != "Auto" ? anchor24 : stype == "crypto" ? "UTC 00:00" : (stype == "forex" or euro) ? "London 08:00" : "New York 09:30"
string aSess = switch anchorKey
"UTC 00:00" => "0000-2359"
"Tokyo 09:00" => "0900-1700"
"London 08:00" => "0800-1630"
=> "0930-1600"
string aTz = switch anchorKey
"UTC 00:00" => "UTC"
"Tokyo 09:00" => "Asia/Tokyo"
"London 08:00" => "Europe/London"
=> "America/New_York"
int aLenMin = switch anchorKey
"UTC 00:00" => 1440
"Показано первые 50% кода (символов: 38971)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.