← К каталогу
Исходный код · ID 4131

Day Type Radar

indicator day type radar for tradingview.pine

Похожие материалы по тегам

#__slope direction line.mq5MQL5 / MetaTrader 5 · 1 общих теговrange breakout @meowforex1.pineTradingView · 1 общих тегов#1.mtf_collider_h4_close_13_v18bar.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit3.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit2.mq4MQL4 / MetaTrader 4 · 1 общих тегов!mth_fasttmaline_edit.mq4MQL4 / MetaTrader 4 · 1 общих тегов
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

Day Type Radar — индикатор анализа для TradingView, работающий поверх графика. Он автоматически отслеживает внутридневные торговые сессии и классифицирует их по фазам: формирование Initial Balance, баланс и тренд. Индикатор определяет шесть типов событий: Drive, Probe-Reject, Accepted Break, Trap, Rotation и Late Expansion.

Все расстояния нормализуются через ATR, что позволяет правилам адаптироваться к волатильности разных инструментов. Индикатор отображает зону Initial Balance, фазовую ленту, графические метки событий и два информационных дашборда: Radar-карту с типом дня и цепочкой событий, а также таблицу статистики по типам дня.

Поддерживаются внутридневные таймфреймы от 1 минуты до 4 часов. Сессии для акций, фондов и индексов берутся по бирже, для крипто, форекса и других круглосуточных рынков — по фиксированному якорю дня. Индикатор не размещает ордера и предназначен для образовательного использования.

Настройки программы

НастройкаОписание
sessMode Auto: акции, фонды и индексы используют биржевую сессию. Крипто, форекс, CFD, фьючерсы и товары (круглосуточные рынки) используют фиксированный якорь дня. Остальные варианты принудительно задают выбор. Биржевая сессия требует рынка с дневным пробитием.
anchor24 Используется при активном якоре дня. Авто: крипто = UTC полные сутки. Форекс и EUREX/ICE Europe = Лондон 08:00. Всё остальное = Нью-Йорк 09:30. Выбор вручную позволяет использовать другой открытие.
customSess Используется только в режиме пользовательского окна. Определяет временной диапазон торговой сессии.
customTz Часовой пояс для считывания пользовательского окна: часовой пояс биржи или UTC.
dispTzIn Изменяет только отображаемое время на карте и под рамкой сессии. Логика сигналов не меняется.
ibOverride 0 = автоматически, номинально около 16% сессии с ограничением 120 минут до ограничений бара графика. Ручные значения увеличиваются минимум до одного бара графика и минимум до окна Drive плюс один бар.
sens Calm = более жёсткие ATR-порогы для Drive, Probe, буфера пробития и Late Expansion. Active = более мягкие. Временные окна и другие структурные ограничения не меняются.
onDrive Переключатель отключает метки, уровни, подсчёт в журнале и оповещения для события Drive. Событие продолжает оцениваться в движке.
onProbe Переключатель отключает метки, уровни, подсчёт в журнале и оповещения для события Probe-Reject. Событие продолжает оцениваться в движке.
onAccept Переключатель отключает метки, уровни, подсчёт в журнале и оповещения для события Accepted Break. Событие продолжает оцениваться в движке.
onTrap Переключатель отключает метки, уровни, подсчёт в журнале и оповещения для события Trap. Событие продолжает оцениваться в движке.
onRot Переключатель отключает метки, уровни, подсчёт в журнале и оповещения для события Rotation. Событие продолжает оцениваться в движке.
onLate Переключатель отключает метки, уровни, подсчёт в журнале и оповещения для события Late Expansion. Событие продолжает оцениваться в движке.
acceptMin Время, в течение которого цена должна удерживаться вне зоны Initial Balance (с учётом буфера), чтобы пробитие считаться принятым.
trapMin Пробитие, которое закрывается обратно внутри IB в течение этого времени от первого закрытия снаружи, называется Trap.
pokeATR На какое расстояние за край IB цена должна выступать без закрытия снаружи, чтобы засчитываться как зондирование.
bufATR Закрытие должно находиться на этом расстоянии за краем IB, чтобы считаться вне зоны. Фильтрует шум на границе.
driveATR Минимальный диапазон сессии в контрольной точке Drive (в ATR).
driveEdge Открытие должно находиться во внешней доле диапазона с одного конца, а закрытие — в той же доле с другого конца.
edgePct Ширина зон краёв IB, используемых для обнаружения сквозного вращения от края до края.
minIBATR Rotation игнорируется, если IB уже этого значения в ATR.
compFrac Диапазон непосредственно перед баром пробития должен быть уже этой долей от IB для определения Late Expansion.
expATR Бар пробития должен быть не менее чем столько ATR в высоту.
atrLen Длина ATR, используемая для нормализации всех расстояний.
maxFails Это количество неудачных пробитий блокирует день как Churn. Неудача после принятого пробития считается удвоенной.
unlockATR Закрытие на таком расстоянии за краем IB снимает блокировку Churn.
endCut Прекращает появление новых событий вблизи окончания сессии. 0 = отключено.
lateExtreme Late Expansion должен закрываться за максимум/минимум сессии, установленный до бара пробития.
oneAndDone Каждый класс событий выводится один раз за сессию. Тип дня всё равно обновляется при каждом изменении состояния. Цепочка событий включает выведенные события и маркеры состояния (IB, Lock, Free).
outcomeMeasure Измерение, отображаемое в последнем столбце Radar-карты. 1R, 2R, 3R показывают процент достижения цели. Average R восстанавливает среднее разрешённое значение. При Average R геометрия ссылки основана на 2R.
minRiskATR Расстояние границы ссылки никогда не меньше этого кратного ATR и никогда меньше 2 тиков.
minSample Строки с меньшим количеством разрешённых событий затемняются и помечаются звёздочкой.
showOutcome Отмечает, где завершённое событие достигло своей ссылочной цели или границы первым.
showLadder Рисует цену события, границу ссылки и уровни R для неразрешённых событий. Только информационно.
ladderMode Определяет, для каких событий отображаются уровни R: только последние или все открытые.
labelOffset Насколько правее последнего бара располагаются метки уровней.
layout Мобильный вариант использует компактную таблицу исторических результатов с пятью столбцами.
showDash1 Отображает Radar-карту: тип дня, цепочку событий, наблюдаемые события и исторические результаты уровней ссылки.
d1Pos Положение Radar-карты на графике.
d1Size Размер текста Radar-карты.
showDash2 Исторические наблюдения от каждого считывания до закрытия сессии. По умолчанию отключён для чистоты графика.
d2Pos Положение таблицы статистики типов дня. Не используйте ту же позицию, что и Radar-карта, чтобы таблицы не перекрывали друг друга.
d2Size Размер текста таблицы статистики типов дня.
showLabels Отображает метки событий на графике.
lblSize Размер меток событий на графике.
minorMode Определяет отображение меток Probe и Rotation: точки (тихо) или текст.
showBox Отображает рамку сессии и текст под ней.
narrStyle Стиль текста под рамкой сессии: «Story + stats» (история и статистика), «Tag only» (только тег) или «Off» (отключено).
showIB Отображает зону Initial Balance на графике.
showOpen Отображает линию открытия сессии.
showExt Проецирует диапазон IB на одну ширину IB выше и ниже.
showRibbon Цветная полоса внизу графика: IB, Balance, Тренд вверх/вниз, Churn.
showChurnMarks Отображает маркеры блокировки Churn и разблокировки Free.
showSessLines Тонкие пунктирные вертикальные линии на открытии и закрытии сессии. Для круглосуточных рынков с якорем UTC полных суток показываются только линии начала. Первая загруженная сессия пропускается.
cSessLine Цвет линий начала и окончания сессии.
cDrive Цвет события Drive.
cProbe Цвет события Probe-Reject.
cAccept Цвет события Accepted Break.
cTrap Цвет события Trap.
cRot Цвет события Rotation.
cLate Цвет события Late Expansion.
cIB Цвет фазы Initial Balance.
cBal Цвет фазы Balance.
cUp Цвет восходящего тренда.
cDn Цвет нисходящего тренда.
cChurn Цвет фазы Churn.
alertFilter Фильтр оповещений: «Все события» или «Только основные» (пропускает Probe-Reject и Rotation). Создайте одно оповещение через Day Type Radar > любое вызов alert(). События срабатывают на закрытии подтверждённых баров.
alertFmt Формат сообщения оповещения: текст для уведомлений или JSON для вебхуков. Оба варианта содержат символ, таймфрейм, событие, направление, цену события, границу ссылки и уровень 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 wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @SimpleForexTools", 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

if not chart.is_standard
    runtime.error("Day Type Radar needs a standard chart type (Candles, Bars, Line, Area). Heikin Ashi, Renko, Kagi, Line Break, Range and Point & Figure change the prices.")
if not timeframe.isintraday or timeframe.in_seconds() < MIN_TF_SEC or timeframe.in_seconds() > MAX_TF_SEC
    runtime.error("Day Type Radar supports intraday charts from 1 minute to 4 hours.")

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 a

Показано первые 50% кода (символов: 38427)

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
3 842,70₽ ≈ $46.97