Gold Breakout 15M Strategy
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «indicator gold breakout 15m strategy for tradingview.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Gold Breakout 15M Strategy — это стратегия для TradingView, написанная на Pine Script v6, которая моделирует торговлю золотом на основе пробоя дневного диапазона. Диапазон формируется между настраиваемыми часами (по умолчанию 00:00–07:00 по времени брокера), а входные ордера размещаются стоп-ордерами на границах диапазона. Первое заполнение отменяет второй ордер, что позволяет совершать одну сделку в день.
Стратегия поддерживает два режима стоп-лосса: в процентах от цены входа или по противоположной границе диапазона. Размер позиции рассчитывается либо как процент риска от капитала, либо как фиксированное количество контрактов. Встроена защита Prop Firm — автоматическое закрытие при превышении дневного дидауна.
Продукт предоставляет обширные визуальные инструменты: дашборд со статистикой сделок, график эффективности, метки входа/выхода, торговые рамки и настраиваемые оповещения с поддержкой вебхуков. Стратегия предназначена для золота на 15-минутном графике и требует корректной настройки часового пояса брокера.
Настройки программы
| Настройка | Описание |
|---|---|
| tzModeInput | Способ определения времени сервера брокера. Фиксированный часовой пояс — используется указанный часовой пояс круглый год. Нью-Йорк + 7ч — серверные часы, используемые большинством FX/CFD брокеров (GMT+2 зимой, GMT+3 летом). |
| tzInput | Используется в режиме «Фиксированный часовой пояс». Часовой пояс сервера брокера: все указанные часы сессии в этом времени. Большинство FX/CFD брокеров используют GMT+2 зимой и GMT+3 летом. |
| rangeFromInput | Час (по времени брокера), когда начинается формирование дневного диапазона. По умолчанию: 0 (начало торгового дня брокера). |
| rangeToInput | Час, когда диапазон фиксируется и начинается торговля пробоем. По умолчанию 7: диапазон 00:00–06:59, торговля с 07:00. Поздний час — более широкий диапазон, меньше пробоев. |
| closeHourInput | Час, когда все открытые позиции принудительно закрываются. Стратегия не имеет тейк-профита, поэтому это основной выход. |
| slModeInput | Расположение стоп-лосса: фиксированный процент от цены входа или противоположная граница диапазона. |
| slPctInput | Расстояние стопа в процентах от цены входа (используется в режиме «% от входа»). Шире — более широкий стоп, меньший размер. По умолчанию: 1.0. |
| sizeModeInput | Способ расчёта количества ордера: процент капитала под риск или фиксированное количество контрактов. |
| riskPctInput | Доля капитала, теряемая при срабатывании стоп-лосса. Консервативно: 0.5, сбалансированно: 1.0, агрессивно: 2.0. Это целевое значение — комиссия, спред, проскальзывание и разрывы добавляются к фактическому убытку. |
| fixedQtyInput | Количество контрактов, используемое в режиме «Фиксированное количество». |
| lotOzInput | Используется только для отображения размера в лотах (метки, дашборд, плейсхолдер {{lots}}) на инструментах, котируемых в унциях. Не влияет на сделки. |
| maxLeverageInput | Верхний лимит для отношения номинала позиции к капиталу. Размер — меньшее из рискованного размера и этого ограничения. Маржа стратегии объявлена как 5%, поэтому этот параметр является эффективным ограничителем. |
| qtyStepInput | Количество контрактов округляется вниз до этого шага, чтобы запланированный риск оставался в рамках бюджета. 0 — минимальный размер контракта, сообщаемый TradingView. Если размер меньше одного шага, вход пропускается. |
| guardOnInput | Закрывает все позиции и останавливает торговлю до следующего дня при падении капитала от дневного пика на указанный лимит. Реагирует только на закрытии свечи. |
| guardDdInput | Лимит дневного дидауна для защиты Prop Firm. Типичный лимит проп-фирмы: 4–5%. |
| showSlInput | Рисует линии цены входа и стоп-лосса с зоной риска при открытой позиции. |
| themeInput | Цветовая тема графика: Auto — определяется из фона графика, Dark — для тёмного фона, Light — для светлого фона. |
| showRangeInput | Рисует коробку дневного диапазона и её линии высокого/низкого, продлённые через торговую сессию. |
| showEntryLabelsInput | Метка при каждом входе: направление, цена входа, стоп, размер и риск. |
| showExitLabelsInput | Метка при каждом выходе: прибыль/убыток в деньгах и в R, изменение цены, цена выхода и причина. |
| showTradeBoxInput | Зелёная/красная рамка между входом и выходом каждой закрытой сделки. |
| labelSizeInput | Размер текста меток входа и выхода. |
| showWarningsInput | Отображает предупреждения о точности диапазона на последнем баре: таймфрейм больше 1H или не делящийся на час ровно, либо нестандартный график (Heikin Ashi, Renko и т.д.). Только для информации: торговля не отключается. |
| showWatermarkInput | Отображает водяной знак на графике. |
| showDashInput | Панель состояния с калькулятором диапазона, сессии и позиции. |
| showMathInput | Статистика сделок: процент побед, процент безубыточности, коэффициент прибыли, средняя прибыль/убыток, математическое ожидание в деньгах и в R, дидаун, серия убытков. |
| dashPosInput | Угол графика, в котором размещается дашборд. |
| dashSizeInput | Размер текста строк дашборда. |
| showPerfInput | Кривая кумулятивного PnL с ключевой статистикой, рисуемая поверх графика. Построена по закрытым сделкам на загруженных барах, а не по диапазону Deep Backtesting. |
| perfPosInput | Расположение графика эффективности на графике. При расположении в нижнем центре водяной знак скрывается. |
| perfColsInput | Горизонтальное разрешение кривой. Выше — более плавная кривая, медленнее отрисовка. Рекомендуется: 60–100. |
| perfRowsInput | Вертикальное разрешение кривой. Выше — более тонкие шаги, медленнее отрисовка. Рекомендуется: 24–40. |
| perfWidthInput | Ширина области кривой как доля панели графика. |
| perfHeightInput | Высота области кривой как доля панели графика. |
| enableAlertsInput | При отключении сообщения ордеров отправляются пустыми. Настройка: создать оповещение на стратегию и оставить только {{strategy.order.alert_message}} в поле Message. |
| webhookInput | Включено — отправляются шаблоны JSON (для ботов/вебхуков). Выключено — текстовые шаблоны. Заполняемые стратегией плейсхолдеры: {{ticker}}, {{tickerid}}, {{exchange}}, {{interval}}, {{event}}, {{side}}, {{action}}, {{reason}}, {{price}}, {{entry}}, {{sl}}, {{qty}}, {{lots}}, {{risk_usd}}, {{range_hig |
| jsonLongInInput | Шаблон JSON-сообщения для длинного входа, отправляемого при срабатывании ордера. |
| jsonShortInInput | Шаблон JSON-сообщения для короткого входа, отправляемого при срабатывании ордера. |
| jsonLongOutInput | Шаблон JSON-сообщения для длинного выхода, отправляемого при закрытии позиции. |
| jsonShortOutInput | Шаблон JSON-сообщения для короткого выхода, отправляемого при закрытии позиции. |
| textLongInInput | Текстовое сообщение для длинного входа, отправляемое при срабатывании ордера. |
| textShortInInput | Текстовое сообщение для короткого входа, отправляемое при срабатывании ордера. |
| textLongOutInput | Текстовое сообщение для длинного выхода, отправляемое при закрытии позиции. |
| textShortOutInput | Текстовое сообщение для короткого выхода, отправляемое при закрытии позиции. |
| showPreviewInput | Записывает все четыре сообщения в журнал Pine так, как они будут отправлены (значения последней исторической бары), с секретом бота, замаскированным как ***. Используется для проверки шаблона без ожидания сигнала. |
| bullColorInput | Цвет фона меток длинных входов, прибыльных меток выхода и прибыльных торговых рамок. |
| bearColorInput | Цвет фона меток коротких входов, убыточных меток выхода и убыточных торговых рамок. |
| rangeColorInput | Цвет дневного диапазона, его границ и меток диапазона. |
Поиск по коду файла
strategy(
title = "Gold Breakout 15M Strategy",
shorttitle = "Gold BO 15M",
overlay = true,
initial_capital = 10000,
default_qty_type = strategy.fixed,
default_qty_value = 1,
calc_on_every_tick = false,
process_orders_on_close = false,
margin_long = 5,
margin_short = 5,
commission_type = strategy.commission.cash_per_order,
commission_value = 0.4,
slippage = 0,
max_lines_count = 500,
max_labels_count = 500,
max_boxes_count = 500,
max_bars_back = 5000)
GRP_MAIN = "⚙️ Main Settings"
GRP_RISK = "🛡️ Risk Management"
GRP_VISUAL = "🎨 Visual Settings"
GRP_DASH = "📊 Dashboard"
GRP_PERF = "📈 Performance Chart"
GRP_ALERT = "🔔 Alerts"
GRP_COLORS = "🎨 Colors"
STRATEGY_VERSION = "v1.0.0"
TZ_MODE_FIXED = "Fixed timezone"
TZ_MODE_NY7 = "New York + 7h"
NY7_SHIFT_MS = 7 * 3600000
NY_TZ = "America/New_York"
SL_MODE_PCT = "% of entry"
SL_MODE_RANGE = "Range boundary"
SIZE_RISK = "% equity at risk"
SIZE_FIXED = "Fixed quantity"
OCA_GROUP = "RB"
NO_VALUE = "—"
DEF_JSON_IN = '{"strategy":"Gold Breakout 15M","event":"entry","action":"{{action}}","side":"{{side}}","ticker":"{{ticker}}","price":{{price}},"sl":{{sl}},"qty":{{qty}},"lots":{{lots}},"risk_usd":{{risk_usd}},"range_high":{{range_high}},"range_low":{{range_low}},"secret":"{{secret}}"}'
DEF_JSON_OUT = '{"strategy":"Gold Breakout 15M","event":"exit","action":"{{action}}","side":"{{side}}","ticker":"{{ticker}}","reason":"{{reason}}","price":{{price}},"qty":{{qty}},"secret":"{{secret}}"}'
DEF_TEXT_LONG_IN = "🟢 BUY | {{tickerid}} | TF: {{interval}} | Price: {{price}} | SL: {{sl}} | Qty: {{qty}} ({{lots}} lots) | Risk: {{risk_usd}}"
DEF_TEXT_SHORT_IN = "🔴 SELL | {{tickerid}} | TF: {{interval}} | Price: {{price}} | SL: {{sl}} | Qty: {{qty}} ({{lots}} lots) | Risk: {{risk_usd}}"
DEF_TEXT_LONG_OUT = "⚪ EXIT LONG | {{tickerid}} | TF: {{interval}} | Price: {{price}} | Reason: {{reason}} | Qty: {{qty}}"
DEF_TEXT_SHORT_OUT = "⚪ EXIT SHORT | {{tickerid}} | TF: {{interval}} | Price: {{price}} | Reason: {{reason}} | Qty: {{qty}}"
TIP_TEMPLATE = "Editable message template. Placeholders are listed in the tooltip of 'Webhook JSON Format'."
tzModeInput = input.string(TZ_MODE_FIXED, "Broker Time Mode", options = [TZ_MODE_FIXED, TZ_MODE_NY7], group = GRP_MAIN,
tooltip = "How broker server time is derived.\n" +
"• Fixed timezone: uses 'Broker Timezone' below all year round\n" +
"• New York + 7h: server clock used by most FX/CFD brokers (GMT+2 in winter, GMT+3 in summer, US daylight-saving calendar)\n" +
"Pick the one matching your broker's server time; a wrong choice shifts the range by an hour for part of the year.")
tzInput = input.string("GMT+3", "Broker Timezone", group = GRP_MAIN,
tooltip = "Used in 'Fixed timezone' mode. Timezone of your broker's server: all session hours below are in this time.\n" +
"• Most FX/CFD brokers use GMT+2 in winter and GMT+3 in summer\n" +
"• Examples: GMT+3, GMT+2, UTC, Europe/Moscow")
rangeFromInput = input.int(0, "Range Start Hour", minval = 0, maxval = 22, step = 1, group = GRP_MAIN,
tooltip = "Hour (broker time) when the daily range starts building.\n" +
"• Default: 0 (start of the broker day)")
rangeToInput = input.int(7, "Range End / Trading Start Hour", minval = 1, maxval = 23, step = 1, group = GRP_MAIN,
tooltip = "Hour when the range is fixed and breakout trading begins.\n" +
"• Default 7: range 00:00–06:59, trading from 07:00\n" +
"• Later hour = wider range, fewer breakouts")
closeHourInput = input.int(20, "Close All Positions Hour", minval = 2, maxval = 23, step = 1, group = GRP_MAIN,
tooltip = "Hour when any open position is force-closed.\n" +
"• Default: 20. The strategy has no take-profit, this is the main exit")
slModeInput = input.string(SL_MODE_PCT, "SL Mode", options = [SL_MODE_PCT, SL_MODE_RANGE], group = GRP_RISK,
tooltip = "Where the stop-loss is placed.\n" +
"• % of entry: fixed percent from the entry price (default 1%). Placed from the breakout level, then re-set from the actual fill price at the close of the entry bar\n" +
"• Range boundary: opposite side of the range; a narrow range means a tight stop and a larger position")
slPctInput = input.float(1.0, "SL, % of Entry Price", minval = 0.05, maxval = 20.0, step = 0.05, group = GRP_RISK,
tooltip = "Stop distance in percent of entry price (used in '% of entry' mode).\n" +
"• Higher = wider stop, smaller position\n" +
"• Default: 1.0")
sizeModeInput = input.string(SIZE_RISK, "Position Size Mode", options = [SIZE_RISK, SIZE_FIXED], group = GRP_RISK,
tooltip = "How the order quantity is calculated.\n" +
"• % equity at risk: qty = equity × risk% / loss to stop\n" +
"• Fixed quantity: constant number of contracts")
riskPctInput = input.float(1.0, "Risk per Trade, % of Equity", minval = 0.01, maxval = 100.0, step = 0.1, group = GRP_RISK,
tooltip = "Share of equity lost if the stop is hit.\n" +
"• Conservative 0.5, balanced 1.0, aggressive 2.0\n" +
"• This is a target: commission, spread, slippage and gaps add to the actual loss")
fixedQtyInput = input.float(1.0, "Fixed Quantity (contracts)", minval = 0.0001, maxval = 1000000.0, step = 0.01, group = GRP_RISK,
tooltip = "Order quantity used in 'Fixed quantity' mode.")
lotOzInput = input.float(0.0, "Ounces per Lot (0 = auto)", minval = 0.0, maxval = 1000000.0, step = 1.0, group = GRP_RISK,
tooltip = "Used only to show size in lots (labels, dashboard, {{lots}} placeholder) on ounce-quoted instruments.\n" +
"• 0 = auto: 100 oz for gold, 5000 oz for silver (standard broker lots)\n" +
"• Does not affect trades")
maxLeverageInput = input.float(10.0, "Max Leverage", minval = 0.1, maxval = 100.0, step = 1.0, group = GRP_RISK,
tooltip = "Upper limit for position notional ÷ equity. Size = the smaller of risk-based size and this cap.\n" +
"• 1% risk with 1% stop needs ×1; range-boundary stops usually need ×2–5\n" +
"• When the cap is hit, actual risk is lower than requested (shown in the dashboard)\n" +
"• Strategy margin is declared as 5% (20x in Properties), so this input is the effective limiter\n" +
"• Values near or above 20 also need a higher Long/Short leverage in Properties, otherwise the tester may reject the orders")
qtyStepInput = input.float(0.0, "Quantity Step (0 = auto)", minval = 0.0, maxval = 1000000.0, step = 0.01, group = GRP_RISK,
tooltip = "Order quantity is rounded DOWN to this step, so the planned risk (before commission, spread and gaps) stays within the budget.\n" +
"• 0 = minimum contract size reported by TradingView for the symbol\n" +
"• Set your exchange / bot step if it differs\n" +
"• If the size is below one step, the entry is skipped")
guardOnInput = input.bool(false, "Prop Firm Guard: Close on Daily Drawdown", group = GRP_RISK,
tooltip = "Closes everything and stops trading until the next day when equity falls from the daily peak by the limit below.\n" +
"• Drawdown is measured at the worst point of each candle (not on the entry candle), but the guard reacts only at candle close\n" +
"• For a live prop account use a low timeframe; this is not a guarantee of staying within a firm's limit")
guardDdInput = input.float(4.0, "Max Drawdown from Daily Equity Peak, %", minval = 0.1, maxval = 100.0, step = 0.1, group = GRP_RISK,
tooltip = "Daily drawdown limit for the Prop Firm Guard.\n" +
"• Typical prop firm daily limit: 4–5%")
showSlInput = input.bool(true, "Show Entry / SL Levels", group = GRP_RISK,
tooltip = "Draw entry price and stop-loss lines with a risk zone while a position is open.")
themeInput = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = GRP_VISUAL,
tooltip = "Chart color theme.\n" +
"• Auto: detects from chart background\n" +
"• Dark: optimized for dark backgrounds\n" +
"• Light: optimized for light/white backgrounds")
showRangeInput = input.bool(true, "Show Range Box & Boundaries", group = GRP_VISUAL,
tooltip = "Draw the daily range box and its high/low lines extended over the trading session.")
showEntryLabelsInput = input.bool(true, "Show Entry Labels", group = GRP_VISUAL,
tooltip = "Label at each entry: direction, entry price, stop, size and risk.")
showExitLabelsInput = input.bool(true, "Show Exit Labels (Trade Result)", group = GRP_VISUAL,
tooltip = "Label at each exit: P&L in money and in R, price move, exit price and reason.")
showTradeBoxInput = input.bool(true, "Show Trade Box (Entry → Exit)", group = GRP_VISUAL,
tooltip = "Green/red box between entry and exit of every closed trade.")
labelSizeInput = input.string("Small", "Label Size", options = ["Small", "Normal"], group = GRP_VISUAL,
tooltip = "Text size of entry/exit labels.")
showWarningsInput = input.bool(true, "Show Accuracy Warnings", group = GRP_VISUAL,
tooltip = "Note on the last bar when the range may be inaccurate: timeframe above 1H or not dividing an hour evenly, or a non-standard chart (Heikin Ashi, Renko…).\n" +
"Informational only: trading is not disabled.")
showWatermarkInput = input.bool(true, "Show Watermark", group = GRP_VISUAL,
tooltip = "Display 'WillyAlgoTrader' watermark on chart")
showDashInput = input.bool(true, "Show Dashboard", group = GRP_DASH,
tooltip = "Status panel with range, session and position calculator.")
showMathInput = input.bool(true, "Show Strategy Math", group = GRP_DASH,
tooltip = "Trade statistics: win rate, breakeven win rate, profit factor, payoff, expectancy in money and in R, drawdown, losing streak.\n" +
"R = trade result divided by the initial risk to the stop.")
dashPosInput = input.string("Top Right", "Dashboard Position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Middle Right"], group = GRP_DASH,
tooltip = "Corner of the chart where the dashboard is placed.")
dashSizeInput = input.string("Small", "Dashboard Text Size", options = ["Small", "Normal", "Large"], group = GRP_DASH,
tooltip = "Text size of dashboard rows.")
showPerfInput = input.bool(false, "Show Performance Chart", group = GRP_PERF,
tooltip = "Cumulative PnL curve with key stats, drawn over the chart.\n" +
"• Built from closed trades on the bars loaded on the chart — NOT from the Deep Backtesting range\n" +
"• Covers the candles behind it while enabled")
perfPosInput = input.string("Bottom Left", "Chart Position", options = ["Bottom Left", "Bottom Center", "Bottom Right", "Middle Center", "Top Left", "Top Center"], group = GRP_PERF,
tooltip = "Where the performance chart is placed.\n" +
"• Bottom Center: the watermark is hidden while the chart is there\n" +
"• Same corner as the dashboard: a warning is shown, move one of them")
perfColsInput = input.int(80, "Chart Columns", minval = 20, maxval = 150, step = 10, group = GRP_PERF,
tooltip = "Horizontal resolution of the curve.\n" +
"• Higher = smoother curve, slower drawing\n" +
"• Recommended: 60–100")
perfRowsInput = input.int(30, "Chart Rows", minval = 10, maxval = 60, step = 5, group = GRP_PERF,
tooltip = "Vertical resolution of the curve.\n" +
"• Higher = finer steps, slower drawing\n" +
"• Recommended: 24–40")
perfWidthInput = input.float(50.0, "Chart Width, % of Screen", minval = 20.0, maxval = 90.0, step = 5.0, group = GRP_PERF,
tooltip = "Width of the curve area as a share of the chart pane.")
perfHeightInput = input.float(35.0, "Chart Height, % of Screen", minval = 10.0, maxval = 70.0, step = 5.0, group = GRP_PERF,
tooltip = "Height of the curve area as a share of the chart pane.")
enableAlertsInput = input.bool(true, "Enable Alert Messages", group = GRP_ALERT,
tooltip = "When off, order alert messages are sent empty.\n" +
"Setup: create an alert on this strategy and leave only {{strategy.order.alert_message}} in the Message field.")
webhookInput = input.bool(false, "Webhook JSON Format", group = GRP_ALERT,
tooltip = "On: JSON templates are sent (for bots / webhooks). Off: text templates.\n\n" +
"Placeholders filled by the strategy:\n" +
"{{ticker}} {{tickerid}} {{exchange}} {{interval}}\n" +
"{{event}} = entry / exit\n" +
"{{side}} = long / short\n" +
"{{action}} = buy / sell\n" +
"{{reason}} = breakout / sl / time / equity_guard\n" +
"{{price}} = order level (entry stop / SL) or bar close for time and guard exits — not the fill price\n" +
"{{entry}} = entry reference price, {{sl}} = planned stop-loss, {{sl_pct}} = stop distance in % of entry\n" +
"{{trade_id}} = ticker + day, identical in the entry and exit messages of one trade\n" +
"Note: in '% of entry' mode the stop is re-set from the actual fill and no separate alert is sent. " +
"A bot that places its own stop should compute it as {{sl_pct}} from its own fill price.\n" +
"{{qty}} = contracts, {{oz}} = qty × point value (ounces on ounce-quoted instruments), {{lots}} = lots\n" +
"{{risk_usd}} {{risk_pct}} = initial risk of the trade (entry to SL)\n" +
"{{equity}} {{range_high}} {{range_low}} {{secret}}\n\n" +
"TradingView's own placeholders (e.g. {{strategy.order.price}}, {{timenow}}) are NOT processed inside these templates. " +
"Put them into the Message field of the alert itself, next to {{strategy.order.alert_message}}.")
secretInput = input.string("", "*** ****** *** **********", group = GRP_ALERT,
tooltip = "******** ********** ** ************" +
"***** ****** ** ***** ******** *** ******* ** ****** *** ***** *** ***** *****")
jsonLongInInput = input.text_area(DEF_JSON_IN, "JSON · Long Entry", group = GRP_ALERT, tooltip = TIP_TEMPLATE)
jsonShortInInput = input.text_area(DEF_JSON_IN, "JSON · Short Entry", group = GRP_ALERT, tooltip = TIP_TEMPLATE)
jsonLongOutInput = input.text_area(DEF_JSON_OUT, "JSON · Long Exit", group = GRP_ALERT, tooltip = TIP_TEMPLATE)
jsonShortOutInput = input.text_area(DEF_JSON_OUT, "JSON · Short Exit", group = GRP_ALERT, tooltip = TIP_TEMPLATE)
textLongInInput = input.text_area(DEF_TEXT_LONG_IN, "Text · Long Entry", group = GRP_ALERT, tooltip = TIP_TEMPLATE)
textShortInInput = input.text_area(DEF_TEXT_SHORT_IN, "Text · Short Entry", group = GRP_ALERT, tooltip = TIP_TEMPLATE)
textLongOutInput = input.text_area(DEF_TEXT_LONG_OUT, "Text · Long Exit", group = GRP_ALERT, tooltip = TIP_TEMPLATE)
textShortOutInput = input.text_area(DEF_TEXT_SHORT_OUT, "Text · Short Exit", group = GRP_ALERT, tooltip = TIP_TEMPLATE)
showPreviewInput = input.bool(false, "Preview Messages in Pine Logs", group = GRP_ALERT,
tooltip = "Writes all four messages to Pine Logs as they would be sent (values of the last historical bar), with the bot secret masked as ***. Use it to check a template without waiting for a signal.")
bullColorInput = input.color(#00E676, "Bull", inline = "colors", group = GRP_COLORS,
tooltip = "Background of long entry labels, winning exit labels and winning trade boxes.")
bearColorInput = input.color(#FF5252, "Bear", inline = "colors", group = GRP_COLORS,
tooltip = "Background of short entry labels, losing exit labels and losing trade boxes.")
rangeColorInput = input.color(#2962FF, "Range", inline = "colors", group = GRP_COLORS,
tooltip = "Color of the daily range box, its boundaries and range labels.")
isDark = switch themeInput
"Dark" => true
"Light" => false
=> color.r(chart.bg_color) < 128 // Auto
TEXT_COLOR = isDark ? #E0E0E0 : #1A1A1A
TEXT_MUTED = isDark ? color.new(#9E9E9E, 0) : color.new(#757575, 0)
BULL_TEXT = isDark ? #00E676 : #00A152
BEAR_TEXT = isDark ? #FF5252 : #D32F2F
NEUTRAL_TEXT = isDark ? #FFEB3B : #F57F17
BULL_LABEL_TEXT = #004D25
BEAR_LABEL_TEXT = #FFFFFF
WARN_BG = #FFEB3B
WARN_TEXT = #1A1A1A
BULL_BG = color.new(bullColorInput, 85)
BEAR_BG = color.new(bearColorInput, 85)
RANGE_BG = color.new(rangeColorInput, 85)
RANGE_BORDER = color.new(rangeColorInput, 40)
TABLE_BG = isDark ? color.new(#131722, 5) : color.new(#FFFFFF, 5)
TABLE_BORDER = isDark ? color.new(#2A2E39, 0) : color.new(#D0D0D0, 0)
TABLE_ROW_ALT = isDark ? color.new(#1C2030, 0) : color.new(#F0F4F8, 0)
HEADER_BG = isDark ? color.new(#0D47A1, 0) : color.new(#1565C0, 0)
HEADER_TEXT = #FFFFFF
SL_COLOR = color.new(#FF5252, 0)
ENTRY_COLOR = color.new(#2962FF, 0)
WM_COLOR = isDark ? color.new(#FFFFFF, 80) : color.new(#000000, 80)
TRANSPARENT = color.new(#000000, 100)
PERF_FILL_UP = color.new(BULL_TEXT, 82)
PERF_FILL_DN = color.new(BEAR_TEXT, 82)
labelSize = labelSizeInput == "Normal" ? size.normal : size.small
dashSize = dashSizeInput == "Large" ? size.large : dashSizeInput == "Normal" ? size.normal : size.small
dashPos = switch dashPosInput
"Top Left" => position.top_left
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
"Middle Right" => position.middle_right
=> position.top_right
perfPos = switch perfPosInput
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
"Middle Center" => position.middle_center
"Top Left" => position.top_left
"Top Center" => position.top_center
=> position.bottom_left
bool useNy7 = tzModeInput == TZ_MODE_NY7
string calcTz = useNy7 ? "UTC" : tzInput
string tzLabel = useNy7 ? "NY+7h" : tzInput
string tickerUpper = str.upper(syminfo.ticker)
string rootUpper = str.upper(syminfo.root)
string prefixUpper = str.upper(syminfo.prefix)
bool isFutures = syminfo.type == "futures"
bool isXauName = str.contains(tickerUpper, "XAU") and not str.startswith(tickerUpper, "XAG")
bool isGoldName = str.contains(tickerUpper, "GOLD") or str.contains(tickerUpper, "PAXG") or str.startswith(tickerUpper, "GLDRUB")
bool isCmeRoot = isFutures and (rootUpper == "GC" or rootUpper == "MGC" or rootUpper == "1OZ" or rootUpper == "QO")
bool isHkexRoot = isFutures and (rootUpper == "GDU" or rootUpper == "GDR")
bool isShfeRoot = isFutures and rootUpper == "AU" and syminfo.currency == "CNY"
bool isMoexRoot = isFutures and rootUpper == "GD" and (prefixUpper == "MOEX" or prefixUpper == "RUS")
bool isSgeName = prefixUpper == "SGE" and (str.startswith(tickerUpper, "AU") or str.startswith(tickerUpper, "MAU"))
bool isGold = isXauName or isGoldName or isCmeRoot or isHkexRoot or isShfeRoot or isMoexRoot or isSgeName
bool isXagName = str.contains(tickerUpper, "XAG")
bool isSilverName = str.contains(tickerUpper, "SILVER") or str.startswith(tickerUpper, "SLVRUB")
bool isCmeSilver = isFutures and (rootUpper == "SIL" or rootUpper == "QI" or (rootUpper == "SI" and syminfo.currency == "USD"))
bool isShfeSilver = isFutures and rootUpper == "AG" and syminfo.currency == "CNY"
bool isMoexSilver = isFutures and (rootUpper == "SV" or rootUpper == "SILV") and (prefixUpper == "MOEX" or prefixUpper == "RUS")
bool isSgeSilver = prefixUpper == "SGE" and str.startswith(tickerUpper, "AG")
bool isSilver = not isGold and (isXagName or isSilverName or isCmeSilver or isShfeSilver or isMoexSilver or isSgeSilver)
float lotOz = lotOzInput > 0 ? lotOzInput : isSilver ? 5000.0 : 100.0
bool isOunceGold = isXauName or str.contains(tickerUpper, "PAXG") or isCmeRoot or isMoexRoot or (str.contains(tickerUpper, "GOLD") and syminfo.currency == "USD")
bool isOunceSilver = isSilver and (isXagName or isCmeSilver or isMoexSilver or (str.contains(tickerUpper, "SILVER") and syminfo.currency == "USD"))
bool isOunceQuoted = isOunceGold or isOunceSilver
string unitLabel = isOunceQuoted ? "oz" : "units"
safeDiv(float num, float den, float fallback = 0.0) =>
den != 0 and not na(num) and not na(den) ? num / den : fallback
roundQtyDown(float qty, float step) =>
float q = math.max(nz(qty), 0.0)
step > 0 ? math.floor(q / step + 1e-9) * step : q
signedStr(float x, string fmt) =>
na(x) ? NO_VALUE : (x > 0 ? "+" : "") + str.tostring(x, fmt)
priceStr(float x) =>
na(x) ? NO_VALUE : str.tostring(x, format.mintick)
numStr(float x, string fmt) =>
na(x) ? NO_VALUE : str.tostring(x, fmt)
maskSecret(string s) =>
secretInput == "" ? s : str.replace_all(s, secretInput, "***")
fillTemplate(string tpl, bool isLong, string event, string reason, float price, float entryRef, float sl, float qty, float rHigh, float rLow, string tradeId, float equityRef) =>
string s = ""
if enableAlertsInput
float oz = nz(qty) * syminfo.pointvalue
float riskUsd = math.abs(nz(entryRef) - nz(sl)) * oz
s := tpl
s := str.replace_all(s, "{{ticker}}", syminfo.ticker)
s := str.replace_all(s, "{{tickerid}}", syminfo.tickerid)
s := str.replace_all(s, "{{exchange}}", syminfo.prefix)
s := str.replace_all(s, "{{interval}}", timeframe.period)
s := str.replace_all(s, "{{event}}", event)
s := str.replace_all(s, "{{trade_id}}", tradeId)
s := str.replace_all(s, "{{side}}", isLong ? "long" : "short")
s := str.replace_all(s, "{{action}}", (event == "entry") == isLong ? "buy" : "sell")
s := str.replace_all(s, "{{reason}}", reason)
s := str.replace_all(s, "{{price}}", str.tostring(nz(price), format.mintick))
s := str.replace_all(s, "{{entry}}", str.tostring(nz(entryRef), format.mintick))
s := str.replace_all(s, "{{sl}}", str.tostring(nz(sl), format.mintick))
s := str.replace_all(s, "{{sl_pct}}", str.tostring(safeDiv(math.abs(nz(entryRef) - nz(sl)), entryRef) * 100.0, "0.####"))
s := str.replace_all(s, "{{qty}}", str.tostring(nz(qty), "0.########"))
s := str.replace_all(s, "{{oz}}", str.tostring(oz, "0.########"))
s := str.replace_all(s, "{{lots}}", str.tostring(safeDiv(oz, lotOz), "0.########"))
s := str.replace_all(s, "{{risk_usd}}", str.tostring(riskUsd, "0.00"))
s := str.replace_all(s, "{{risk_pct}}", str.tostring(safeDiv(riskUsd, equityRef) * 100.0, "0.00"))
s := str.replace_all(s, "{{equity}}", str.tostring(strategy.equity, "0.00"))
s := str.replace_all(s, "{{range_high}}", str.tostring(nz(rHigh), format.mintick))
s := str.replace_all(s, "{{range_low}}", str.tostring(nz(rLow), format.mintick))
s := str.replace_all(s, "{{secret}}", secretInput)
s
brokerClock(int t) =>
useNy7 ? timestamp("UTC", year(t, NY_TZ), month(t, NY_TZ), dayofmonth(t, NY_TZ), hour(t, NY_TZ), minute(t, NY_TZ), second(t, NY_TZ)) + NY7_SHIFT_MS : t
perfLevel(float v, float vMin, float span, int rows) =>
span > 0 ? math.round((v - vMin) / span * (rows - 1)) : 0
drawEntryLabel(bool isLong, float price, float sl, float qty) =>
label result = na
if showEntryLabelsInput and not na(price) and not na(sl)
float oz = nz(qty) * syminfo.pointvalue
string txt = (isLong ? "▲ LONG" : "▼ SHORT") + "\nEntry " + priceStr(price) + "\nSL " + priceStr(sl) + " (" + str.tostring(safeDiv(math.abs(price - sl), price) * 100.0, "0.00") + "%)" + "\nSize " + str.tostring(oz, "0.####") + " " + unitLabel + (isOunceQuoted ? " · " + str.tostring(safeDiv(oz, lotOz), "0.####") + " lots" : "") + "\nRisk " + str.tostring(math.abs(price - sl) * oz, "0.00") + " " + syminfo.currency
result := label.new(bar_index, price, txt,
yloc = isLong ? yloc.belowbar : yloc.abovebar,
style = isLong ? label.style_label_up : label.style_label_down,
color = isLong ? bullColorInput : bearColorInput,
textcolor = isLong ? BULL_LABEL_TEXT : BEAR_LABEL_TEXT,
size = labelSize,
textalign = text.align_left,
tooltip = (isLong ? "Buy Signal" : "Sell Signal") + "\nReason: range breakout")
result
dashHeader(table t, int r, string s) =>
table.cell(t, 0, r, s, text_color = HEADER_TEXT, bgcolor = HEADER_BG, text_size = dashSize, text_halign = text.align_center)
table.merge_cells(t, 0, r, 1, r)
r + 1
dashRow(table t, int r, string k, string v, color valueColor) =>
color rowBg = r % 2 == 0 ? TABLE_BG : TABLE_ROW_ALT
table.cell(t, 0, r, k, text_color = TEXT_MUTED, bgcolor = rowBg, text_size = dashSize, text_halign = text.align_left)
table.cell(t, 1, r, v, text_color = valueColor, bgcolor = rowBg, text_size = dashSize, text_halign = text.align_right)
r + 1
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)
bool isLastBar = barstate.islast or barstate.islastconfirmedhistory
int tfSec = timeframe.in_seconds()
bool tfOk = tfSec > 0 and tfSec <= 3600 and 3600 % tfSec == 0
bool hoursOk = rangeFromInput < rangeToInput and rangeToInput < closeHourInput
bool envOk = hoursOk
int barTime = brokerClock(time)
int barHour = hour(barTime, calcTz)
int nextHour = hour(brokerClock(time_close), calcTz)
int dayKey = year(barTime, calcTz) * 10000 + month(barTime, calcTz) * 100 + dayofmonth(barTime, calcTz)
bool isNewDay = dayKey != nz(dayKey[1], -1)
bool inRange = barHour >= rangeFromInput and barHour < rangeToInput
var float rangeHigh = na
var float rangeLow = na
var int rangeStartBar = na
var int tradedDay = -1
var bool isHalted = false
var float dayEquityPeak = na
var float slActiveLong = na
var float slActiveShort = na
var int firstDayKey = na
if na(firstDayKey)
firstDayKey := dayKey
float prevEquity = nz(strategy.equity[1], strategy.equity)
if isNewDay
rangeHigh := na
rangeLow := na
rangeStartBar := na
isHalted := false
dayEquityPeak := prevEquity
if inRange
if na(rangeHigh)
rangeStartBar := bar_index
rangeHigh := na(rangeHigh) ? high : math.max(rangeHigh, high)
rangeLow := na(rangeLow) ? low : math.min(rangeLow, low)
bool rangeReady = not na(rangeHigh) and not na(rangeLow) and rangeHigh > rangeLow
bool nextInWindow = nextHour >= rangeToInput and nextHour < closeHourInput
bool inPos = strategy.position_size != 0
bool posLong = strategy.position_size > 0
bool justOpened = inPos and strategy.position_size[1] == 0
if justOpened
tradedDay := dayKey // one trade per day
strategy.cancel("Long")
strategy.cancel("Short")
if slModeInput == SL_MODE_PCT
if posLong
slActiveLong := math.round_to_mintick(strategy.position_avg_price * (1.0 - slPctInput / 100.0))
else
slActiveShort := math.round_to_mintick(strategy.position_avg_price * (1.0 + slPctInput / 100.0))
var int seenClosed = 0
var int tradeCount = 0
var int winCount = 0
var int lossCount = 0
var float grossWin = 0.0
var float grossLoss = 0.0
var float sumR = 0.0
var int lossStreak = 0
var int maxLossStreak = 0
var float lastPnl = na
var float lastR = na
var array<float> equityCurve = array.new<float>()
var float cumPnl = 0.0
var int firstTradeTime = na
var int lastTradeTime = na
int newClosedFrom = seenClosed
int newClosedTo = strategy.closedtrades - 1
if newClosedTo >= newClosedFrom
for i = newClosedFrom to newClosedTo
float tSize = strategy.closedtrades.size(i)
float tPnl = strategy.closedtrades.profit(i)
float tEntry = strategy.closedtrades.entry_price(i)
float tSl = tSize > 0 ? slActiveLong : slActiveShort
float tRisk = strategy.convert_to_account(math.abs(tEntry - nz(tSl, tEntry)) * math.abs(tSize) * syminfo.pointvalue)
float tR = tRisk > 0 ? tPnl / tRisk : na
if strategy.closedtrades.entry_bar_index(i) == strategy.closedtrades.exit_bar_index(i)
tradedDay := dayKey
tradeCount += 1
if tPnl > 0
winCount += 1
grossWin += tPnl
lossStreak := 0
else if tPnl < 0
lossCount += 1
grossLoss += -tPnl
lossStreak Показано первые 50% кода (символов: 45035)