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

Bitcoin Sniper Confluence

bitcoin sniper confluence.pine

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

volatility_gold_master.mq5MQL5 / MetaTrader 5 · 2 общих теговmomentum confluence engine.pineTradingView · 2 общих теговindicator stormcore smc & divergence master for tradingview.pineTradingView · 2 общих теговindicator god mode x - structure and confluence dashboard for tradingview.pineTradingView · 2 общих теговindicator momentum confluence engine for tradingview.pineTradingView · 2 общих теговindicator bitcoin sniper confluence for tradingview.pineTradingView · 2 общих тегов
Вы автор или правообладатель?

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

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

О программе

Bitcoin Sniper Confluence — это индикатор TradingView, предназначенный для анализа биткоина на внутридневных таймфреймах. Он вычисляет технические показатели средствами Pine Script и отображает их на графике в виде настраиваемого дашборда, чек-листа совпадений и сводки стратегии.

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

Индикатор включает визуальные элементы: заливку между скользящими средними, линию объёмно-взвешенной цены, маркеры сделок с уровнями стоп-лосса и тейк-профита, а также подсветку свечей возврата к быстрой скользящей средней. Поддерживаются условия оповещений TradingView для различных событий.

Управление рисками реализовано через множитель ATR для стоп-лосса, до трёх уровней тейк-профита и перевод стопа на безубыток после достижения первого таргета. Каждая сделка отслеживается отдельно с фиксацией результата.

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

НастройкаОписание
fastEmaLenInput Периус быстрой экспоненциальной скользящей средней. При пересечении быстрой и медленной скользящих формируется торговый сигнал. Меньшее значение — более отзывчивый индикатор.
slowEmaLenInput Периус медленной экспоненциальной скользящей средней. Чем выше значение, тем более сглаженная линия и меньше пересечений.
requireBarCloseInput При включении пересечение скользящих учитывается только после закрытия свечи, что предотвращает ложные сигналы от внутрисвечных движений.
confluenceGateOnInput При включении пересечение скользящих средних генерирует сигнал только при достижении заданного минимального количества совпадающих факторов из общего числа.
minScoreInput Минимальное количество из общего числа факторов, которые должны совпадать по направлению для генерации сигнала. Если макро-фактор отключён, максимум — 7 из 7.
btcOnlyInput При включении индикатор распознаёт только биткоин-инструменты: спот, перпетуальные контракты, CFD и CME-фьючерсы. На других инструментах сигналы подавляются, а дашборд окрашивается в красный цвет.
macroFactorOnInput Включает дополнительный фактор, основанный на корреляции биткоина с макро-символом. Бычий или медвежий балл начисляется только при активной корреляционной связи.
macroSymbolInput Символ, чей тренд голосует за направление оценки по макро-фактору. По умолчанию — фьючерсы на Nasdaq. Должен соответствовать выбранному направлению связи.
macroLinkModeInput Направление связи: положительный — рост макро-символа даёт бычий балл (режим Nasdaq/S&P); обратный — падение макро-символа даёт бычий балл (режим DXY).
macroEmaLenInput Периус экспоненциальной скользящей средней для макро-символа. Макро-символ считается бычьим, если его цена выше этой скользящей.
corrLenInput Количество баров, используемых для расчёта скользящей корреляции между биткоином и макро-символом.
corrThresholdInput Минимальная сила корреляции, при которой макро-фактор учитывается в оценке. Если корреляция недостаточна, фактор не начисляет баллы.
sessionFilterOnInput При включении пересечения вне европейских и американских торговых окон блокируются и помечаются на графике. На дневных и старших таймфреймах не действует.
europeSessionInput Временной диапазон европейской торговой сессии, заданный в выбранном часовом поясе.
usSessionInput Временной диапазон американской торговой сессии, заданный в выбранном часовом поясе.
blockWeekendInput Блокирует входы в выходные дни в выбранном часовом поясе. Работает независимо от фильтра торговых часов.
sessionTzInput Часовой пояс, в котором заданы торговые окна и проверка выходных. Режим «Exchange» использует часовой пояс торгового инструмента.
shadeSessionsInput При включении на графике отображается цветная заливка активных торговых окон: фиолетовая для Европы, оранжевая для США и более яркая для перекрытия.
adrFilterOnInput Включает блокировку входов, когда дневной диапазон цены уже исчерпал заданный процент от среднего дневного диапазона.
adrLenInput Количество завершённых дней, усредняемых для расчёта среднего дневного диапазона.
adrBlockPctInput Процент использования среднего дневного диапазона, при достижении которого новые входы блокируются. Чем выше значение, тем допускается больший дневной диапазон перед блокировкой.
slAtrMultInput Множитель ATR для определения расстояния стоп-лосса. Каждый уровень тейк-профита расположен на расстоянии одного стопа от входа.
atrLenInput Периус усреднения для расчёта среднего истинного диапазона, используемого при определении расстояния стоп-лосса и уровней тейк-профита.
tpLevelsInput Количество уровней тейк-профита от 1 до 3. Цели расположены на расстояниях 1R, 2R и 3R от входа. Сделка закрывается при достижении последнего уровня.
breakevenAtTp1Input При достижении первого тейк-профита рабочий стоп перемещается на цену входа. Если цена возвращается к входу, сделка закрывается безубыточно.
maxTradesInput Максимальное количество торговых лестниц (вход, стоп, таргеты), одновременно отображаемых на графике. Старые удаляются первыми.
confirmTfInput Таймфрейм, на котором рассчитывается дополнительный фактор RSI для подтверждения сигнала.
showDashboardInput Включает отображение дашборда с показателями всех факторов, биткоин-проверок, доминирования биткоина, открытых сделок и итоговой статистики.
dashPosInput Позиция на графике, в которой отображается дашборд с показателями.
dashTextSizeInput Размер текста в ячейках дашборда.
showDominanceInput Отображает строку доминирования биткоина — его долю от общей криптовалютной капитализации и соотношение с 20-барговым средним. Информационный элемент, не участвует в оценке.
showHowToInput Отображает статическую легенду, объясняющую поток сигнала в несколько строк.
howToPosInput Позиция на графике, в которой отображается статическая легенда с описанием принципа работы.
showChecklistInput Отображает живой чек-лист из 8 технических факторов и 4 биткоин-проверок для более сильной стороны.
checklistPosInput Позиция на графике, в которой отображается живой чек-лист совпадений.
showSummaryInput Отображает трёхячейечный футер со сводкой: стратегия, лучшие условия, рынки работы.
summaryPosInput Позиция на графике, в которой отображается футер со сводкой стратегии.
showRibbonInput Отображает заливку между быстрой и медленной скользящими средними: зелёную при бычьем расположении и красную при медвежьем.
ribbonAlphaInput Прозрачность заливки между быстрой и медленной скользящими средними: 0 — сплошная, 100 — невидимая.
showVwapInput Отображает линию объёмно-взвешенной средней цены, окрашенную в зависимости от расположения цены относительно неё.
showTradeLinesInput Отрисовывает линии входа, стоп-лосса и уровней тейк-профита для каждого сигнала. Лестница открытой сделки продлевается вместе с ценой.
tradeTextSizeInput Размер текста меток входа, стоп-лосса и тейк-профита на графике.
labelOffsetInput Количество баров вправо от последней свечи, на котором размещаются метки открытой сделки. Закрытые сделки отображают метки на баре закрытия.
showRetestInput Окрашивает свечу в оранжевый цвет, когда цена откатывается к быстрой скользящей средней при открытой последней сделке.
showBlockedInput Отображает маленький крестик на графике там, где квалифицированное пересечение было заблокировано фильтрами биткоина, часов, выходных или ADR.

Поиск по коду файла

indicator("Bitcoin Sniper Confluence", shorttitle = "VP - BSC", overlay = true,
     max_labels_count = 500, max_boxes_count = 500, max_lines_count = 500, max_bars_back = 1000)

const int    MAX_TARGETS      = 3
const color  CLR_BULL         = #00ffaa
const color  CLR_BEAR         = #ff3d71
const color  CLR_BTC          = #F7931A
const color  CLR_AMBER        = #FFD54F
const color  CLR_INFO         = #7B68EE
const color  CLR_MUTED        = #8a94a6
const color  CLR_TEXT         = #e6e9f0
const color  CLR_ENTRY        = #00bcd4
const color  CLR_STOP         = #ef4444
const color  CLR_TARGET       = #22c55e
const color  CLR_TARGET_HIT   = #40E0D0
const color  CLR_RETEST       = #FF9800
const color  CLR_PANEL_BG     = #111725
const color  CLR_PANEL_HDR    = #18233a
const color  CLR_PANEL_BORDER = #000000
const string BRAND_TAG        = "VIPRASOL"
const string MODE_POSITIVE    = "Positive (Nasdaq / S&P)"
const string MODE_INVERSE     = "Inverse (DXY)"

string GRP_SIGNAL = "1 · Signal Engine"
int  fastEmaLenInput      = input.int(9, "Fast EMA", minval = 2, maxval = 50, group = GRP_SIGNAL,
     tooltip = "Length of the fast exponential moving average. The fast EMA crossing the slow EMA is the entry trigger. Lower = more responsive, more crosses.")
int  slowEmaLenInput      = input.int(21, "Slow EMA", minval = 5, maxval = 200, group = GRP_SIGNAL,
     tooltip = "Length of the slow exponential moving average. Higher = smoother trend line, fewer crosses.")
bool requireBarCloseInput = input.bool(true, "Bar-close confirmation", group = GRP_SIGNAL,
     tooltip = "When on, a crossover only counts once the bar has closed, so an intra-bar wick that reverses cannot fire a signal. Bitcoin wicks are large, so this is on by default.")

string GRP_SCORE = "2 · Confluence Filter"
bool confluenceGateOnInput = input.bool(true, "Require minimum confluence score", group = GRP_SCORE,
     tooltip = "When on, a crossover only becomes a signal if enough of the 8 factors agree with its direction.")
int  minScoreInput         = input.int(5, "Minimum score (out of 8)", minval = 1, maxval = 8, group = GRP_SCORE,
     tooltip = "How many of the 8 factors must line up: VWAP side, RSI side, MACD side, EMA alignment, ADX trend power, volume push, confirmation-timeframe RSI and the macro-link factor. Higher = fewer, cleaner signals. If the macro factor is off the score is out of 7.")

string GRP_GUARD = "3 · Bitcoin Symbol Guard"
bool   btcOnlyInput    = input.bool(true, "Bitcoin-only mode", group = GRP_GUARD,
     tooltip = "Detects bitcoin from the symbol: BTC base currency, BTC or XBT in the ticker (spot, perpetual, CFD), or BTC / MBT CME futures. ETFs and trusts (stock type) are not treated as bitcoin. On any other chart the dashboard turns red and signals are suppressed. Turn off to run the engine on other markets.")
string btcKeywordInput = input.string("", "Extra bitcoin ticker keyword", group = GRP_GUARD,
     tooltip = "Optional. If your broker names bitcoin unusually (for example a custom CFD symbol) type part of that ticker here and it will be treated as bitcoin.")

string GRP_MACRO = "4 · Macro Link Factor"
bool   macroFactorOnInput = input.bool(true, "Use macro-link factor", group = GRP_MACRO,
     tooltip = "Bitcoin trades as a risk asset: it tends to move with the Nasdaq and against the dollar. When on, the macro symbol's trend adds one bull or one bear point, but only while the chosen correlation link is actually active.")
string macroSymbolInput   = input.symbol("CME_MINI:NQ1!", "Macro symbol", group = GRP_MACRO,
     tooltip = "Symbol whose trend votes on the score. CME_MINI:NQ1! (Nasdaq futures, near 24h) is the default. NASDAQ:NDX, CME_MINI:ES1! or SP:SPX also work in positive mode; TVC:DXY in inverse mode.")
string macroLinkModeInput = input.string(MODE_POSITIVE, "Link direction", options = [MODE_POSITIVE, MODE_INVERSE], group = GRP_MACRO,
     tooltip = "Positive: the macro symbol rising is a bull point (Nasdaq, S&P). Inverse: the macro symbol falling is a bull point (DXY). Match this to the symbol above.")
int    macroEmaLenInput   = input.int(21, "Macro trend EMA", minval = 2, maxval = 200, group = GRP_MACRO,
     tooltip = "The macro symbol is treated as rising when its close is above this EMA and falling when below it. Calculated on the chart timeframe.")
int    corrLenInput       = input.int(20, "Correlation lookback (bars)", minval = 5, maxval = 200, group = GRP_MACRO,
     tooltip = "Number of bars used to measure the rolling correlation between bitcoin and the macro symbol.")
float  corrThresholdInput = input.float(0.3, "Link strength threshold", minval = 0.0, maxval = 1.0, step = 0.05, group = GRP_MACRO,
     tooltip = "The macro factor only scores while the rolling correlation is at least this strong in the chosen direction (above +0.3 for positive, below -0.3 for inverse). When bitcoin decouples from macro, the factor gives zero to both sides instead of guessing.")

string GRP_SESSION = "5 · BTC Liquidity Windows"
bool   sessionFilterOnInput = input.bool(true, "Trade only during Europe / US hours", group = GRP_SESSION,
     tooltip = "Bitcoin trades 24/7 but its volume is concentrated in the European and US sessions, where CME futures, ETF flows and equity markets are open. When on, crossovers outside both windows are blocked and marked with a small x. Ignored on daily and higher charts.")
string europeSessionInput   = input.session("0300-1200", "Europe window", group = GRP_SESSION,
     tooltip = "European trading window, in the timezone selected below. Default 03:00-12:00 New York time (08:00-17:00 London).")
string usSessionInput       = input.session("0800-1700", "US window", group = GRP_SESSION,
     tooltip = "US trading window, in the timezone selected below. Default 08:00-17:00 New York time. The 08:00-12:00 overlap with Europe plus the 09:30 US equity open is bitcoin's most liquid period.")
bool   blockWeekendInput    = input.bool(true, "Block weekend entries", group = GRP_SESSION,
     tooltip = "Saturday and Sunday (in the timezone below) are blocked. CME futures and ETFs are closed, order books are thin and weekend moves are often retraced on Monday. Works independently of the hours filter; ignored on weekly and monthly charts.")
string sessionTzInput       = input.string("America/New_York", "Session timezone", options = ["America/New_York", "Europe/London", "UTC", "Exchange"], group = GRP_SESSION,
     tooltip = "Timezone the two windows and the weekend check are written in. 'Exchange' uses the chart symbol's own timezone (UTC on most crypto exchanges).")
bool   shadeSessionsInput   = input.bool(true, "Shade active window", group = GRP_SESSION,
     tooltip = "Light background tint: violet for Europe, orange for US, brighter orange for the overlap, grey for weekends.")

string GRP_ADR = "6 · ADR Exhaustion"
bool  adrFilterOnInput = input.bool(true, "Block entries when ADR is exhausted", group = GRP_ADR,
     tooltip = "ADR = average daily range over the last N completed days. Once today's high-to-low range has already used the percentage below, bitcoin has usually done its move for the day, so new entries are blocked. Ignored on weekly and monthly charts.")
int   adrLenInput      = input.int(14, "ADR lookback (days)", minval = 2, maxval = 100, group = GRP_ADR,
     tooltip = "Number of completed daily ranges averaged into the ADR. Only finished days are used, so the value never looks ahead. Crypto days roll at 00:00 UTC on most exchanges.")
float adrBlockPctInput = input.float(100, "Block at % of ADR used", minval = 30, maxval = 300, step = 5, group = GRP_ADR,
     tooltip = "Entries are blocked once today's range is at or above this percentage of ADR. 100 = the average day is fully used. Bitcoin can run well past its ADR on news; raise this to stay in on trend days, lower it to be more conservative.")

string GRP_RISK = "7 · Risk Management"
float slAtrMultInput      = input.float(1.5, "Stop-loss ATR multiplier", minval = 0.1, step = 0.1, group = GRP_RISK,
     tooltip = "Stop distance = ATR x this value. Each take-profit level sits one stop distance further from entry (1R, 2R, 3R).")
int   atrLenInput         = input.int(14, "ATR period", minval = 1, maxval = 50, group = GRP_RISK,
     tooltip = "Lookback for the Average True Range used for the stop and target ladder.")
int   tpLevelsInput       = input.int(3, "Take-profit levels", minval = 1, maxval = 3, group = GRP_RISK,
     tooltip = "How many take-profit levels to draw (1 to 3). Targets sit at 1R, 2R and 3R from entry. A trade is closed when its last level is touched.")
bool  breakevenAtTp1Input = input.bool(true, "Move stop to breakeven at TP1", group = GRP_RISK,
     tooltip = "When TP1 is touched the working stop moves to the entry price. The red SL line stays visible; the entry line turns into a dotted cyan breakeven stop. A return to entry then closes the trade as BE.")
int   maxTradesInput      = input.int(50, "Trades kept on chart", minval = 1, maxval = 100, group = GRP_RISK,
     tooltip = "How many trade ladders (entry, stop, targets) stay drawn. The oldest are removed first. Each trade uses up to 5 lines and 5 labels; 100 is the TradingView drawing limit. The dashboard tally covers the same trades.")

string GRP_MTF = "8 · Confirmation Timeframe"
string confirmTfInput = input.timeframe("15", "RSI confirmation timeframe", group = GRP_MTF,
     tooltip = "Timeframe of the secondary 14-period RSI factor. Default 15 minutes.")

string GRP_DASH = "9 · Dashboard"
bool   showDashboardInput = input.bool(true, "Show dashboard", group = GRP_DASH,
     tooltip = "Live read-out of every factor, the bitcoin gates, BTC dominance, the open trades and the outcome tally.")
string dashPosInput       = input.string("Top Right", "Dashboard position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = GRP_DASH,
     tooltip = "Where the dashboard sits. Every on-chart panel has its own position setting, so all four can be arranged without overlap.")
string dashTextSizeInput  = input.string("small", "Dashboard text size", options = ["tiny", "small", "normal", "large", "huge"], group = GRP_DASH,
     tooltip = "Text size for the dashboard cells.")
bool   showDominanceInput = input.bool(true, "Show BTC dominance row", group = GRP_DASH,
     tooltip = "Reads CRYPTOCAP:BTC.D (bitcoin's share of total crypto market cap) and shows whether it is above or below its 20-bar average. Informational only, not scored.")

string GRP_PANELS = "10 · On-Chart Panels"
bool   showHowToInput     = input.bool(true, "Show HOW IT WORKS legend", group = GRP_PANELS,
     tooltip = "Static legend that explains the signal flow in seven lines.")
string howToPosInput      = input.string("Top Left", "HOW IT WORKS position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = GRP_PANELS,
     tooltip = "Where the legend sits. Move it if it overlaps the TradingView symbol header or another panel.")
bool   showChecklistInput = input.bool(true, "Show live confluence checklist", group = GRP_PANELS,
     tooltip = "Tick / cross list of the 8 factors and the 4 bitcoin gates for the currently stronger side.")
string checklistPosInput  = input.string("Bottom Left", "Checklist position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = GRP_PANELS,
     tooltip = "Where the checklist sits. Bottom Left keeps it clear of the legend above it.")
bool   showSummaryInput   = input.bool(true, "Show strategy summary footer", group = GRP_PANELS,
     tooltip = "Three-cell footer: strategy, best-for, works-on.")
string summaryPosInput    = input.string("Bottom Center", "Summary position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = GRP_PANELS,
     tooltip = "Where the summary footer sits.")

string GRP_VISUAL = "11 · Visuals"
bool   showRibbonInput     = input.bool(true, "EMA ribbon fill", group = GRP_VISUAL,
     tooltip = "Fill between the two EMAs: green when the fast EMA is above the slow EMA, red when below.")
int    ribbonAlphaInput    = input.int(75, "Ribbon transparency", minval = 0, maxval = 100, group = GRP_VISUAL,
     tooltip = "0 = solid, 100 = invisible.")
bool   showVwapInput       = input.bool(true, "VWAP line", group = GRP_VISUAL,
     tooltip = "Volume-weighted average price, coloured by whether price is above or below it.")
bool   showTradeLinesInput = input.bool(true, "Entry / SL / TP lines and labels", group = GRP_VISUAL,
     tooltip = "Draws the entry, stop and take-profit ladder of every signal. Each ladder runs from its signal bar to the bar where the trade closed; the open trade keeps extending with price.")
string tradeTextSizeInput  = input.string("small", "Trade label size", options = ["tiny", "small", "normal", "large", "huge"], group = GRP_VISUAL,
     tooltip = "Text size of the entry / stop / target labels.")
int    labelOffsetInput    = input.int(12, "Label offset (bars right)", minval = 1, maxval = 50, group = GRP_VISUAL,
     tooltip = "How many bars to the right of the last candle the labels of an OPEN trade are placed. Closed trades keep their labels at the bar where they closed.")
bool   showRetestInput     = input.bool(true, "Highlight EMA retest candles", group = GRP_VISUAL,
     tooltip = "Colours a candle orange when price pulls back into the fast EMA while the latest trade is still open (possible add-on).")
bool   showBlockedInput    = input.bool(true, "Mark crossovers blocked by bitcoin filters", group = GRP_VISUAL,
     tooltip = "Draws a small grey x where a qualifying crossover was blocked by the symbol guard, the hours filter, the weekend gate or the ADR filter.")

textSizeOf(string sizeName) =>
    switch sizeName
        "tiny"   => size.tiny
        "small"  => size.small
        "normal" => size.normal
        "large"  => size.large
        "huge"   => size.huge
        => size.small

tablePositionOf(string positionName) =>
    switch positionName
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "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

string ccyPrefix = syminfo.currency == "USD" or syminfo.currency == "USDT" or syminfo.currency == "USDC" or syminfo.currency == "BUSD" ? "$" : syminfo.currency + " "

fmtMoneyPct(float distance, float refPrice) =>
    na(distance) or na(refPrice) or refPrice == 0 ? "—" : ccyPrefix + str.tostring(distance, "#.##") + " (" + str.tostring(distance / refPrice * 100, "#.##") + "%)"

pctText(float distance, float refPrice, bool isGain) =>
    na(distance) or na(refPrice) or refPrice == 0 ? "" : " (" + (isGain ? "+" : "-") + str.tostring(math.abs(distance) / refPrice * 100, "#.##") + "%)"

tickText(bool ok) =>
    ok ? "✓" : "✕"

tickColor(bool ok) =>
    ok ? CLR_BULL : CLR_MUTED

method setRow(table tbl, int rowIdx, string keyText, string valueText, color valueColor, string textSize) =>
    table.cell(tbl, 0, rowIdx, keyText, text_color = CLR_TEXT, text_halign = text.align_left, text_size = textSize, bgcolor = CLR_PANEL_BG)
    table.cell(tbl, 1, rowIdx, valueText, text_color = valueColor, text_halign = text.align_right, text_size = textSize, bgcolor = CLR_PANEL_BG)

float emaFast        = ta.ema(close, fastEmaLenInput)
float emaSlow        = ta.ema(close, slowEmaLenInput)
float sessionVwap    = ta.vwap(hlc3)
float atrValue       = ta.atr(atrLenInput)
float rsiNow         = ta.rsi(close, 14)
float rsiConfirmTf   = request.security(syminfo.tickerid, confirmTfInput, ta.rsi(close, 14), lookahead = barmerge.lookahead_off)
[macdLine, macdSignalLine, macdHistogram] = ta.macd(close, 12, 26, 9)
[diPlus, diMinus, adxNow] = ta.dmi(14, 14)
float volumeBaseline = ta.sma(volume, 20)
bool  hasVolume      = not na(volume) and volume > 0

string tickerUpper   = str.upper(syminfo.ticker)
bool   notEquityType = syminfo.type != "stock" and syminfo.type != "fund"
bool   btcByBase     = syminfo.basecurrency == "BTC" or syminfo.basecurrency == "XBT"
bool   btcByName     = (str.contains(tickerUpper, "BTC") or str.contains(tickerUpper, "XBT")) and notEquityType and not str.contains(tickerUpper, ".D")
bool   btcByRoot     = syminfo.root == "BTC" or syminfo.root == "MBT"
bool   btcByCustom   = str.length(btcKeywordInput) > 0 and str.contains(tickerUpper, str.upper(btcKeywordInput))
bool   isBtcChart    = btcByBase or btcByName or btcByRoot or btcByCustom
bool   symbolGateOk  = not btcOnlyInput or isBtcChart
bool   isPerpTicker  = str.endswith(tickerUpper, ".P") or str.contains(tickerUpper, "PERP") or str.contains(tickerUpper, "SWAP")
string btcKindText   = btcByRoot ? "CME FUTURES" : isBtcChart and isPerpTicker ? "PERPETUAL" : isBtcChart and syminfo.type == "cfd" ? "BTC CFD" : isBtcChart ? "SPOT BTC" : "NOT BITCOIN"

[macroClose, macroEma] = request.security(macroSymbolInput, timeframe.period, [close, ta.ema(close, macroEmaLenInput)], lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
bool  positiveLink   = macroLinkModeInput == MODE_POSITIVE
float btcMacroCorr   = ta.correlation(close, macroClose, corrLenInput)
bool  macroDataOk    = not na(macroClose) and not na(macroEma)
bool  macroLinkActive = macroDataOk and not na(btcMacroCorr) and (positiveLink ? btcMacroCorr >= corrThresholdInput : btcMacroCorr <= -corrThresholdInput)
bool  macroRising    = macroDataOk and macroClose > macroEma
bool  macroFalling   = macroDataOk and macroClose < macroEma
bool  macroBullPoint = macroFactorOnInput and macroLinkActive and (positiveLink ? macroRising : macroFalling)
bool  macroBearPoint = macroFactorOnInput and macroLinkActive and (positiveLink ? macroFalling : macroRising)
int   factorTotal    = macroFactorOnInput ? 8 : 7
int   minScoreEff    = math.min(minScoreInput, factorTotal)

float btcDominance    = showDominanceInput ? request.security("CRYPTOCAP:BTC.D", timeframe.period, close, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true) : na
float btcDominanceAvg = ta.sma(btcDominance, 20)

bool fVwapBull  = close > sessionVwap
bool fRsiBull   = rsiNow > 50
bool fMacdBull  = macdLine > macdSignalLine
bool fEmaBull   = emaFast > emaSlow
bool fAdxBull   = adxNow > 25 and close > emaFast
bool fVolBull   = hasVolume and volume > volumeBaseline and close > open
bool fMtfBull   = rsiConfirmTf > 50
bool fMacroBull = macroBullPoint

bool fVwapBear  = close < sessionVwap
bool fRsiBear   = rsiNow < 50
bool fMacdBear  = macdLine < macdSignalLine
bool fEmaBear   = emaFast < emaSlow
bool fAdxBear   = adxNow > 25 and close < emaFast
bool fVolBear   = hasVolume and volume > volumeBaseline and close < open
bool fMtfBear   = rsiConfirmTf < 50
bool fMacroBear = macroBearPoint

int bullScore = (fVwapBull ? 1 : 0) + (fRsiBull ? 1 : 0) + (fMacdBull ? 1 : 0) + (fEmaBull ? 1 : 0) +
     (fAdxBull ? 1 : 0) + (fVolBull ? 1 : 0) + (fMtfBull ? 1 : 0) + (fMacroBull ? 1 : 0)
int bearScore = (fVwapBear ? 1 : 0) + (fRsiBear ? 1 : 0) + (fMacdBear ? 1 : 0) + (fEmaBear ? 1 : 0) +
     (fAdxBear ? 1 : 0) + (fVolBear ? 1 : 0) + (fMtfBear ? 1 : 0) + (fMacroBear ? 1 : 0)
float bullPct = bullScore / factorTotal * 100
float bearPct = bearScore / factorTotal * 100

float  biasGap  = bullPct - bearPct
string biasText = biasGap >= 40 ? "STRONG BULL" : biasGap <= -40 ? "STRONG BEAR" : biasGap > 0 ? "MILD BULL" : biasGap < 0 ? "MILD BEAR" : "NEUTRAL"
color  biasColor = biasText == "STRONG BULL" ? CLR_BULL : biasText == "MILD BULL" ? color.new(CLR_BULL, 45) :
     biasText == "STRONG BEAR" ? CLR_BEAR : biasText == "MILD BEAR" ? color.new(CLR_BEAR, 45) : CLR_MUTED

string sessionTz     = sessionTzInput == "Exchange" ? syminfo.timezone : sessionTzInput
bool   inEurope      = not na(time(timeframe.period, europeSessionInput, sessionTz))
bool   inUs          = not na(time(timeframe.period, usSessionInput, sessionTz))
bool   inBtcWindow   = inEurope or inUs
int    barWeekday    = dayofweek(time, sessionTz)
bool   isWeekend     = barWeekday == dayofweek.saturday or barWeekday == dayofweek.sunday
bool   sessionGateOk = not sessionFilterOnInput or timeframe.isdwm or inBtcWindow
bool   weekendGateOk = not blockWeekendInput or timeframe.isweekly or timeframe.ismonthly or not isWeekend
string sessionText   = isWeekend ? "WEEKEND" : timeframe.isdwm ? "N/A (D+ chart)" : inEurope and inUs ? "EU + US OVERLAP" : inEurope ? "EUROPE" : inUs ? "US" : "ASIA / OFF-HOURS"

float adrValue = request.security(syminfo.tickerid, "D", ta.sma(high - low, adrLenInput)[1], lookahead = barmerge.lookahead_on)

int   dayStamp      = timeframe.isintraday ? time("D") : time
bool  newTradingDay = not timeframe.isintraday or nz(ta.change(dayStamp), 0) != 0
var float dayHigh = na
var float dayLow  = na
if newTradingDay or na(dayHigh)
    dayHigh := high
    dayLow  := low
else
    dayHigh := math.max(dayHigh, high)
    dayLow  := math.min(dayLow, low)
float todayRange    = dayHigh - dayLow
float adrUsedPct    = not na(adrValue) and adrValue > 0 ? todayRange / adrValue * 100 : na
bool  adrApplicable = adrFilterOnInput and not timeframe.isweekly and not timeframe.ismonthly
bool  adrExhausted  = adrApplicable and not na(adrUsedPct) and adrUsedPct >= adrBlockPctInput
bool  adrGateOk     = not adrExhausted

type TradeSetup
    int    side
    int    entryBar
    float  entry
    float  stop
    float  risk
    array<float> targets
    array<bool>  hits
    bool   beActive
    bool   closed
    int    closeBar
    string outcome
    line   entryLine
    line   stopLine
    array<line>  tpLines
    label  entryLabel
    label  stopLabel
    array<label> tpLabels

createTrade(int side) =>
    float risk = atrValue * slAtrMultInput
    array<float> levels = array.new<float>()
    array<bool>  flags  = array.new<bool>()
    for i = 1 to MAX_TARGETS
        array.push(levels, side == 1 ? close + risk * i : close - risk * i)
        array.push(flags, false)
    TradeSetup.new(side = side, entryBar = bar_index, entry = close, stop = side == 1 ? close - risk : close + risk, risk = risk,
     targets = levels, hits = flags, beActive = false, closed = false, closeBar = na, outcome = "OPEN",
     entryLine = na, stopLine = na, tpLines = array.new<line>(), entryLabel = na, stopLabel = na, tpLabels = array.new<label>())

method workingStop(TradeSetup t) =>
    t.beActive ? t.entry : t.stop

method drawLadder(TradeSetup t) =>
    string sz = textSizeOf(tradeTextSizeInput)
    int    x2 = t.entryBar + 1
    t.entryLine  := line.new(t.entryBar, t.entry, x2, t.entry, color = CLR_ENTRY, width = 1, style = line.style_dashed)
    t.stopLine   := line.new(t.entryBar, t.stop,  x2, t.stop,  color = CLR_STOP,  width = 2)
    t.entryLabel := label.new(x2, t.entry, "", color = CLR_ENTRY, textcolor = color.white, style = label.style_label_left, size = sz)
    t.stopLabel  := label.new(x2, t.stop,  "", color = CLR_STOP,  textcolor = color.white, style = label.style_label_left, size = sz)
    for i = 0 to tpLevelsInput - 1
        float lvl = array.get(t.targets, i)
        array.push(t.tpLines,  line.new(t.entryBar, lvl, x2, lvl, color = CLR_TARGET, width = 1, style = line.style_dashed))
        array.push(t.tpLabels, label.new(x2, lvl, "", color = CLR_TARGET, textcolor = color.white, style = label.style_label_left, size = sz))

method advance(TradeSetup t) =>
    if not t.closed and bar_index > t.entryBar
        float stopLvl = t.workingStop()
        bool  stopHit = t.side == 1 ? low <= stopLvl : high >= stopLvl
        if stopHit
            t.closed   := true
            t.closeBar := bar_index
            t.outcome  := t.beActive ? "BE" : "SL"
        else
            for i = 0 to MAX_TARGETS - 1
                float lvl     = array.get(t.targets, i)
                bool  touched = t.side == 1 ? high >= lvl : low <= lvl
                if touched
                    array.set(t.hits, i, true)
            if breakevenAtTp1Input and array.get(t.hits, 0)
                t.beActive := true
            if array.get(t.hits, tpLevelsInput - 1)
                t.closed   := true
                t.closeBar := bar_index
                t.outcome  := "TP" + str.tostring(tpLevelsInput)

method refresh(TradeSetup t) =>
    int endX = t.closed ? t.closeBar : bar_index
    int lblX = t.closed ? t.closeBar : bar_index + labelOffsetInput
    if not na(t.entryLine)
        line.set_x2(t.entryLine, endX)
        if t.beActive
            line.set_style(t.entryLine, line.style_dotted)
            line.set_width(t.entryLine, 2)
    if not na(t.stopLine)
        line.set_x2(t.stopLine, endX)
    if not na(t.entryLabel)
        label.set_xy(t.entryLabel, lblX, t.entry)
        label.set_text(t.entryLabel, "ENTRY: " + str.tostring(t.entry, format.mintick) + (t.outcome == "BE" ? " (BE EXIT)" : t.beActive ?

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