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

MarketMind

indicator marketmind for tradingview.pine

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

ea robofibo source v.11.2.mq4MQL4 / MetaTrader 4 · 2 общих теговea_price_action_v6_grid.mq4MQL4 / MetaTrader 4 · 2 общих теговindo run 1.5.mq4MQL4 / MetaTrader 4 · 2 общих теговclevrfx v3.0@lifeindreamsworld.mq4MQL4 / MetaTrader 4 · 2 общих теговtriodancer_4.4.6.mq4MQL4 / MetaTrader 4 · 2 общих теговtriodancer_4.4.5.mq4MQL4 / MetaTrader 4 · 2 общих тегов
Вы автор или правообладатель?

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

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

О программе

MarketMind — индикатор TradingView на Pine Script v6, предназначенный для мультитаймфреймового анализа рыночной ситуации и отображения торговых сигналов на графике. Индикатор рассчитывает совокупную оценку направления (бычья/медвежья) на основе восьми компонентов: трендов шести таймфреймов, RSI и импульса, а также формирует сигналы покупки и продажи на основе супер-тренда или режима фильтрации пробоев.

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

Дополнительно поддерживаются отображение новостей (через внешние данные), данные о позиции COT, финансовая информация, фильтрация сигналов вокруг новостей, макроэкономический фильтр (DXY/US10Y), пользовательский часовой пояс и отображение свечей старшего таймфрейма. Все функции активируются через соответствующие настройки.

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

НастройкаОписание
i_mode Режим работы индикатора: MarketMind, MarketMind + или MarketMind + FILTER
i_multF Множитель супер-тренда для быстрого режима определения направления тренда
i_multS Множитель супер-тренда для медленного режима определения направления тренда
i_filtLook Количество свечей для окна фильтрации пробоев в режиме MarketMind + FILTER
i_sig Включает или отключает отображение основных торговых сигналов покупки и продажи
i_sigText Включает или отключает отображение текстовых меток BUY/SELL рядом с сигналами
i_confirm Включает или отключает режим подтверждения торговых сигналов на основе характеристик свечей
i_rrBox Включает или отключает отображение блоков риска и награды (Risk/Reward) на графике
i_tsl Включает или отключает отображение и работу стоп-лосса с последующим движением (Trailing Stop Loss)
i_slLabel Включает или отключает отображение меток уровня стоп-лосса на графике
i_tpHit Включает или отключает отображение меток достижения целей тейк-профита
i_tpShow Включает или отключает отображение текущих уровней целей TP1, TP2 и TP3 на графике
i_geShow Включает или отключает отображение метки золотого входа (GE) на графике
i_slMult Множитель ATR для расчёта уровня стоп-лосса
i_geM Множитель ATR для расчёта уровня золотого входа
i_tp1M Множитель ATR для расчёта первой цели тейк-профита
i_tp2M Множитель ATR для расчёта второй цели тейк-профита
i_tp3M Множитель ATR для расчёта третьей цели тейк-профита
i_lblSize Размер меток уровней стоп-лосса, тейк-профита и золотого входа на графике
i_sr Включает или отключает отображение зон поддержки и сопротивления на графике
i_srVol Включает или отключает отображение информации об объёме в зонах поддержки и сопротивления
i_srBreak Включает или отключает отображение маркировки пробоя уровней поддержки и сопротивления
i_ma Включает или отключает отображение скользящей средней MarketMind на графике
i_channel Включает или отключает отображение ценового канала MarketMind, построенного на основе линейной регрессии с отклонением
i_fib Включает или отключает отображение уровней Фибоначчи на графике
i_fibType Тип уровней Фибоначчи: внутренний, внешний или оба сразу
i_struct Включает или отключает отображение структурных пробоев CHoCH и BoS на графике
i_structTyp Тип структурного анализа: внутренний, внешний или оба сразу
i_paint Включает или отключает раскрашивание свечей по направлению тренда
i_colDn Цвет свечей, окрашенных в нисходящем тренде
i_colUp Цвет свечей, окрашенных в восходящем тренде
i_pdhl Включает или отключает отображение уровней максимума и минимума предыдущего торгового дня
i_dayDiv Включает или отключает отображение ежедневного разделителя на графике
i_pwhl Включает или отключает отображение уровней максимума и минимума предыдущей торговой недели
i_weekDiv Включает или отключает отображение еженедельного разделителя на графике
i_nextPct Включает или отключает отображение вероятности направления следующей свечи на графике
i_htf Включает или отключает отображение свечей старшего (высшего) таймфрейма на графике
i_htfVP Включает или отключает отображение объёмного профиля на графике
i_htfTF Таймфрейм для отображения свечей старшего таймфрейма и объёмного профиля
i_htfCount Количество свечей старшего таймфрейма для отображения на графике
i_table Включает или отключает отображение информационной таблицы MarketMind на графике
i_tblV Вертикальная позиция таблицы MarketMind на графике
i_tblH Горизонтальная позиция таблицы MarketMind на графике
i_tblSize Размер таблицы MarketMind
i_tblTheme Цветовая тема таблицы MarketMind: классическая или тёмная
i_news Включает или отключает отображение таблицы новостей на графике
i_newsType Тип таблицы новостей: за сегодня или за неделю
i_newsTime Формат отображения времени в таблице новостей: 24-часовой или AM/PM
i_newsH Горизонтальное выравнивание таблицы новостей
i_newsV Вертикальное выравнивание таблицы новостей
i_newsSize Размер таблицы новостей на графике
i_newsCur При включении отображаются новости только для валюты текущего инструмента
i_newsHigh Включает или отключает отображение новостей с высоким уровнем влияния
i_newsMed Включает или отключает отображение новостей со средним уровнем влияния
i_newsLow Включает или отключает отображение новостей с низким уровнем влияния
i_newsHol Включает или отключает отображение новостей в праздничные дни
i_tzOn Включает или отключает использование пользовательского часового пояса для отображения времени
i_tzH Часовая составляющая пользовательского часового пояса (UTC)
i_tzM Минутная составляющая пользовательского часового пояса (UTC)
i_nbOn Включает или отключает блокировку торговых сигналов вокруг новостных событий
i_nbBefore Количество минут до новостного события, в течение которых блокируются сигналы
i_nbAfter Количество минут после новостного события, в течение которых блокируются сигналы
i_nbRedOnly При включении блокируют сигналы только события с высоким влиянием
i_macroOn Включает или отключает макроэкономический фильтр по DXY или US10Y для блокировки сигналов
i_macroSrc Источник макроэкономического фильтра: индекс доллара DXY, доходность US10Y или оба
i_macroLen Период скользящей средней для макроэкономического фильтра DXY или US10Y
i_cotOn Включает или отключает отображение строки данных COT в таблице индикатора
i_cotCode Код CFTC для получения данных о позиции непрофессиональных участников рынка
i_finOn Включает или отключает отображение строки финансовой информации в таблице индикатора
i_finField Поле финансовой информации компании для отображения в таблице: выручка, EPS, чистая прибыль или долг/капитал
Получить полный код

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

import toodegrees/forex_factory_utility/17 as ffUtil
import toodegrees/forex_factory_decoding/46 as ffDec
indicator("MarketMind", "MarketMind", overlay = true,
     max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500)

g1  = "① MarketMind Signal / MarketMind Signals"
g2  = "② Signals Display / Signals Display"
g3  = "③ TP / SL / GE / Targets and Stop"
g4  = "④ Support & Resistance / Support & Resistance"
g5  = "⑤ Chart Drawing / Chart Drawing"
g6  = "⑥ Candles / Candles"
g7  = "⑦ Daily & Weekly / Daily and Weekly"
g8  = "⑧ Probability / Candle Probability"
g9  = "⑨ HTF Candles / Higher Timeframe Candles"
g10 = "⑩ MarketMind Table / MarketMind Table"
g11 = "⑪ News / News"
g12 = "⑫ Timezone / Timezone"

i_mode      = input.string("MarketMind + ", "MarketMind Mode / MarketMind Mode", options = ["MarketMind", "MarketMind + ", "MarketMind + FILTER"], group = g1)

i_multF     = input.float(3.0, "Fast Multiplier / Fast Multiplier", minval = 1.0, maxval = 10.0, step = 0.1, group = g1)
i_multS     = input.float(4.0, "Slow Multiplier / Slow Multiplier", minval = 1.0, maxval = 10.0, step = 0.1, group = g1)
i_filtLook  = input.int(120,   "Filter Breakout Bars / Filter Breakout Bars", minval = 20, maxval = 300, group = g1)

i_sig       = input.bool(true,  "MarketMind Signals / MarketMind Signals", group = g2)
i_sigText   = input.bool(false, "Show Buy/Sell Text / Show Buy/Sell Text", group = g2)
i_confirm   = input.bool(true,  "Enable MarketMind Confirm Signals / Enable MarketMind Confirm Signals", group = g2)

i_rrBox     = input.bool(false, "Show Risk/Reward Boxes / Show Risk/Reward Boxes", group = g3)
i_tsl       = input.bool(true,  "Enable TSL / Enable TSL", group = g3)
i_slLabel   = input.bool(true,  "Show Stop Loss Labels / Show Stop Loss Labels", group = g3)
i_tpHit     = input.bool(true,  "Show TP Hit Labels / Show TP Hit Labels", group = g3)
i_tpShow    = input.bool(true,  "Show TP Targets / Show TP1 TP2 TP3 Targets", group = g3)
i_geShow    = input.bool(true,  "Show Golden Entry Label / Show Golden Entry Label GE", group = g3)
i_slMult    = input.float(4.0, "Stop × ATR / Stop Multiplier",   minval = 0.5, maxval = 15.0, step = 0.1, group = g3)
i_geM       = input.float(1.0, "Golden Entry × ATR / Golden Entry", minval = 0.1, maxval = 5.0, step = 0.1, group = g3)
i_tp1M      = input.float(2.0, "TP1 × ATR", minval = 0.5, maxval = 20.0, step = 0.1, group = g3)
i_tp2M      = input.float(4.0, "TP2 × ATR", minval = 0.5, maxval = 20.0, step = 0.1, group = g3)
i_tp3M      = input.float(6.0, "TP3 × ATR", minval = 0.5, maxval = 20.0, step = 0.1, group = g3)
i_lblSize   = input.int(3,      "Labels Size / Size of Targets, Stop Loss, and Golden Entry", minval = 1, maxval = 5, group = g3)

i_sr        = input.bool(true,  "Support & Resistance / Support & Resistance", group = g4)
i_srVol     = input.bool(true,  "Show Volume Info / Volume Info for Support & Resistance", group = g4)
i_srBreak   = input.bool(false, "Show Break of S&R ($) / Show Break of Support & Resistance", group = g4)

i_ma        = input.bool(false, "MarketMind MA / MarketMind Moving Average", group = g5)
i_channel   = input.bool(true,  "MarketMind Channel / MarketMind Price Channel", group = g5)
i_fib       = input.bool(false, "Fibonacci / Fibonacci", group = g5)
i_fibType   = input.string("Internal", "Fibonacci Type / Fibonacci Type", options = ["Internal", "External", "Both"], group = g5)
i_struct    = input.bool(false, "Structure Breaks (CHoCH & BoS) / Structure", group = g5)
i_structTyp = input.string("Internal", "Structure Type / Structure Type", options = ["Internal", "External", "Both"], group = g5)

i_paint     = input.bool(true,  "Paint Bars / Paint Bars", group = g6)
i_colDn     = input.color(#e91e63, "DownTrend Color / DownTrend Color", group = g6)
i_colUp     = input.color(#00bcd4, "UpTrend Color / UpTrend Color", group = g6)

i_pdhl      = input.bool(false, "Previous Day High/Low (PDH/PDL) / Previous Day High/Low", group = g7)
i_dayDiv    = input.bool(false, "Daily Divider / Daily Divider", group = g7)
i_pwhl      = input.bool(false, "Previous Week High/Low (PWH/PWL) / Previous Week High/Low", group = g7)
i_weekDiv   = input.bool(false, "Weekly Divider / Weekly Divider", group = g7)

i_nextPct   = input.bool(false, "Next Candles % / Next Candle Probability", group = g8)

i_htf       = input.bool(false, "Show HTF Candles / Show Higher Timeframe Candles", group = g9)
i_htfVP     = input.bool(false, "Show Volume Profile / Show Volume Profile", group = g9)
i_htfTF     = input.timeframe("D", "Timeframe / Timeframe", group = g9)
i_htfCount  = input.int(1, "Amount of Candles / Amount of Candles", minval = 1, maxval = 10, group = g9)

i_table     = input.bool(true,  "Show MarketMind Table / MarketMind Table", group = g10)
i_tblV      = input.string("bottom", "Vertical Position / Vertical Position", options = ["top", "middle", "bottom"], group = g10)
i_tblH      = input.string("right", "Horizontal Position / Horizontal Position", options = ["left", "center", "right"], group = g10)
i_tblSize   = input.string("Tiny / Tiny", "Table Size / Table Size", options = ["Tiny / Tiny", "Small / Small", "Normal / Normal", "Large / Large", "Huge / Huge"], group = g10)
i_tblTheme  = input.string("Classic / Classic", "Table Colors / Table Colors", options = ["Classic / Classic", "Dark / Black Background"], group = g10)

i_news      = input.bool(true,  "Show News / Show News", group = g11)
i_newsType  = input.string("Today", "Table Type / Table Type", options = ["Today", "This Week"], group = g11)
i_newsTime  = input.string("AM/PM", "Time Format / Time Format", options = ["24H", "AM/PM"], group = g11)
i_newsH     = input.string("Right", "Horizontal Align / Horizontal Align", options = ["Left", "Center", "Right"], group = g11)
i_newsV     = input.string("Top", "Vertical Align / Vertical Align", options = ["Top", "Middle", "Bottom"], group = g11)
i_newsSize  = input.string("Tiny / Tiny", "Table Size / Table Size", options = ["Tiny / Tiny", "Small / Small", "Normal / Normal", "Large / Large", "Huge / Huge"], group = g11)
i_newsCur   = input.bool(false, "Symbol currency only / Symbol Currency Only", group = g11)
i_newsHigh  = input.bool(true,  "🔴 High / High",      group = g11, inline = "imp")
i_newsMed   = input.bool(true,  "🟠 Medium / Medium",   group = g11, inline = "imp")
i_newsLow   = input.bool(false, "🟡 Low / Low",      group = g11, inline = "imp2")
i_newsHol   = input.bool(false, "⚪ Holiday / Holiday",    group = g11, inline = "imp2")

i_tzOn      = input.bool(true, "Custom Timezone (UTC) / Custom Timezone", group = g12)
i_tzH       = input.int(3, "Hours / Hours", minval = -12, maxval = 14, group = g12)
i_tzM       = input.int(0, "Minutes / Minutes", minval = 0, maxval = 59, group = g12)

g13 = "⑬ External Data / External Data"

i_nbOn      = input.bool(false, "Block signals around news / Block Signals Around News", group = g13)
i_nbBefore  = input.int(15,  "Minutes before / Minutes Before", minval = 0, maxval = 240, group = g13, inline = "nb")
i_nbAfter   = input.int(15,  "Minutes after / Minutes After",  minval = 0, maxval = 240, group = g13, inline = "nb")
i_nbRedOnly = input.bool(true, "High impact only / Red Only", group = g13)

i_macroOn   = input.bool(false, "Macro filter (DXY / US10Y) / Dollar and Yield Filter", group = g13)
i_macroSrc  = input.string("Both", "Source / Source", options = ["DXY", "US10Y", "Both"], group = g13)
i_macroLen  = input.int(20, "MA length / MA Length", minval = 2, maxval = 200, group = g13)

i_cotOn     = input.bool(false, "Show COT row / Show COT Row", group = g13)
i_cotCode   = input.string("088691", "CFTC code / CFTC Code (Gold 088691 · Nasdaq 209742 · S&P 13874A)", group = g13)

i_finOn     = input.bool(false, "Show fundamentals row / Show Company Fundamentals Row", group = g13)
i_finField  = input.string("Revenue", "Field / Field", options = ["Revenue", "EPS", "Net income", "Debt/Equity"], group = g13)

SIG_UP   = #61c1fd
SIG_DN   = #ff0000
CONF_UP  = #00ddff
CONF_DN  = #ff0000
TP_COL   = #4caf50
GE_COL   = #fdd835
SL_COL   = #f23645
TSL_COL  = #ff5252
ZONE_SUP = #f02424
ZONE_DEM = #00ddfb

var float haOpen = na
haClose = (open + high + low + close) / 4
haOpen := na(haOpen[1]) ? (open + close) / 2 : (haOpen[1] + haClose[1]) / 2
haHigh  = math.max(high, math.max(haOpen, haClose))
haLow   = math.min(low,  math.min(haOpen, haClose))
haUp    = haClose >= haOpen

mmLine = (haOpen + haClose) / 2

ATR_LEN   = 14

haTR   = na(haClose[1]) ? haHigh - haLow : math.max(haHigh - haLow, math.max(math.abs(haHigh - haClose[1]), math.abs(haLow - haClose[1])))
haATR  = ta.rma(haTR, ATR_LEN)

f_supertrend(float _mult) =>
    float src = (haHigh + haLow) / 2
    var float up = na
    var float dn = na
    var int   tr = 1
    float u = src - _mult * haATR
    float d = src + _mult * haATR
    up := na(up[1]) ? u : (haClose[1] > up[1] ? math.max(u, up[1]) : u)
    dn := na(dn[1]) ? d : (haClose[1] < dn[1] ? math.min(d, dn[1]) : d)
    tr := na(tr[1]) ? 1 : (tr[1] == -1 and haClose > dn[1] ? 1 : tr[1] == 1 and haClose < up[1] ? -1 : tr[1])
    [up, dn, tr]

[upFast, dnFast, trFast] = f_supertrend(i_multF)
[upSlow, dnSlow, trSlow] = f_supertrend(i_multS)

fastMode = i_mode == "MarketMind"
trendDir = fastMode ? trFast : trSlow
trendLvl = fastMode ? (trFast == 1 ? upFast : dnFast) : (trSlow == 1 ? upSlow : dnSlow)

flipUp = trendDir == 1  and trendDir[1] == -1
flipDn = trendDir == -1 and trendDir[1] == 1

f_tfBias() => close < ta.ema(close, 20) ? -1 : 1
f_tfTrend(string tf) =>
    request.security(syminfo.tickerid, tf, f_tfBias(), lookahead = barmerge.lookahead_off)

t3m  = f_tfTrend("3")
t5m  = f_tfTrend("5")
t15m = f_tfTrend("15")
t1h  = f_tfTrend("60")
t4h  = f_tfTrend("240")
t1d  = f_tfTrend("D")

rsiV   = ta.rsi(close, 14)
rsiBull = rsiV > 55
rsiBear = rsiV < 45
momBull = haClose > haOpen
momBear = haClose < haOpen

bullCnt = (t3m == 1 ? 1 : 0) + (t5m == 1 ? 1 : 0) + (t15m == 1 ? 1 : 0) + (t1h == 1 ? 1 : 0) + (t4h == 1 ? 1 : 0) + (t1d == 1 ? 1 : 0) + (rsiBull ? 1 : 0) + (momBull ? 1 : 0)
bearCnt = (t3m == -1 ? 1 : 0) + (t5m == -1 ? 1 : 0) + (t15m == -1 ? 1 : 0) + (t1h == -1 ? 1 : 0) + (t4h == -1 ? 1 : 0) + (t1d == -1 ? 1 : 0) + (rsiBear ? 1 : 0) + (momBear ? 1 : 0)

bullPct = math.round(bullCnt / 8 * 100)
bearPct = math.round(bearCnt / 8 * 100)

f_ffSeed(string slot) =>
    request.seed("seed_toodegrees_toogit", slot,
         str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume))

f_ffRequest() =>
    [f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_1"), f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_2"),
     f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_3"), f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_4"),
     f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_5"), f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_6"),
     f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_7"), f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_8"),
     f_ffSeed("TOODEGREES_FOREX_FACTORY_SLOT_9")]

method ffRead(ffUtil.News[] N, string S1, string S2, string S3, string S4, string S5, string S6, string S7, string S8, string S9) =>
    ffDec.readNews(N, S1), ffDec.readNews(N, S2), ffDec.readNews(N, S3)
    ffDec.readNews(N, S4), ffDec.readNews(N, S5), ffDec.readNews(N, S6)
    ffDec.readNews(N, S7), ffDec.readNews(N, S8), ffDec.readNews(N, S9)

f_ffSize(string sz) => sz == "Tiny / Tiny" ? "Tiny" : sz == "Small / Small" ? "Small" : sz == "Normal / Normal" ? "Normal" : sz == "Large / Large" ? "Large" : "Huge"

newsOK = timeframe.in_seconds(timeframe.period) <= 86400 and timeframe.in_seconds(timeframe.period) >= 30

var bool ffMidnight = false
if hour(time, "America/New_York") == 0 and hour(time[1], "America/New_York") != 0 and not ffMidnight
    ffMidnight := true
ffNewDay = ffMidnight ? hour(time, "America/New_York") == 0 and hour(time[1], "America/New_York") != 0 : timeframe.change("D")

var ffCurr = array.new<ffUtil.News>()
var ffNext = array.new<ffUtil.News>()
var ffDay  = array.new<ffUtil.News>()
var ffLoc  = ffUtil.boxLoc(i_newsH, i_newsV)
var ffImp  = ffUtil.impFilter(i_newsHol, i_newsLow, i_newsMed, i_newsHigh)

f_curOn(string c) => not i_newsCur or syminfo.currency == c or syminfo.basecurrency == c
var ffCurF = ffUtil.curFilter(false, f_curOn("AUD"), f_curOn("CAD"), f_curOn("CHF"), f_curOn("CNY"), f_curOn("EUR"), f_curOn("GBP"), f_curOn("JPY"), f_curOn("NZD"), f_curOn("USD"))

[fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9] = f_ffRequest()

if newsOK
    if timeframe.change("W")
        ffNext := ffUtil.bubbleSort_News(ffNext)
        if i_tzOn
            ffNext := ffUtil.adjustTimezone(ffNext, i_tzH, i_tzM)
        if i_newsTime == "AM/PM"
            ffNext := ffUtil.NewsAMPM_TOD(ffNext)
        ffCurr := ffNext.copy()
        ffCurr := ffUtil.weekNews(ffCurr, ffCurF, ffImp)
        ffNext.clear()
    if ffNewDay
        ffDay.clear()
        ffDay := ffUtil.todayNews(ffCurr, ffDay, ffMidnight)
    ffNext.ffRead(fs1, fs2, fs3, fs4, fs5, fs6, fs7, fs8, fs9)

f_newsBlackout() =>
    bool hit = false
    if i_nbOn and ffCurr.size() > 0
        for i = 0 to ffCurr.size() - 1
            ffUtil.News n = ffCurr.get(i)
            bool impOK = not i_nbRedOnly or n.imp == color.red
            if impOK and not na(n.tmst)
                if time >= n.tmst - i_nbBefore * 60000 and time <= n.tmst + i_nbAfter * 60000
                    hit := true
    hit
newsBlackout = f_newsBlackout()

dxyD  = request.security("TVC:DXY",   "D", close, ignore_invalid_symbol = true)
us10D = request.security("TVC:US10Y", "D", close, ignore_invalid_symbol = true)
dxyEma  = ta.ema(dxyD,  i_macroLen)
us10Ema = ta.ema(us10D, i_macroLen)
dxyUp  = not na(dxyD)  and dxyD  > dxyEma
us10Up = not na(us10D) and us10D > us10Ema
macroUp   = i_macroSrc == "DXY" ? dxyUp : i_macroSrc == "US10Y" ? us10Up : (dxyUp and us10Up)
macroDown = i_macroSrc == "DXY" ? not dxyUp : i_macroSrc == "US10Y" ? not us10Up : (not dxyUp and not us10Up)

macroBlockBuy  = i_macroOn and macroUp
macroBlockSell = i_macroOn and macroDown

cotLong  = request.security("COT:" + i_cotCode + "_F_NCP_L", "W", close, ignore_invalid_symbol = true)
cotShort = request.security("COT:" + i_cotCode + "_F_NCP_S", "W", close, ignore_invalid_symbol = true)
cotNet   = nz(cotLong) - nz(cotShort)
cotRise  = cotNet > nz(cotNet[1], cotNet)

finField = i_finField == "Revenue" ? "TOTAL_REVENUE" : i_finField == "EPS" ? "EARNINGS_PER_SHARE_BASIC" : i_finField == "Net income" ? "NET_INCOME" : "DEBT_TO_EQUITY"
finVal   = request.financial(syminfo.tickerid, finField, "FQ", ignore_invalid_symbol = true)

brkHi = ta.highest(high, i_filtLook)[1]
brkLo = ta.lowest(low,  i_filtLook)[1]
filterUp = trendDir ==  1 and high > brkHi
filterDn = trendDir == -1 and low  < brkLo

var int lastFilt = 0
filterBuy  = filterUp and lastFilt !=  1
filterSell = filterDn and lastFilt != -1
if filterBuy
    lastFilt :=  1
else if filterSell
    lastFilt := -1

bool rawBuy  = false
bool rawSell = false
if i_mode == "MarketMind + FILTER"
    rawBuy  := filterBuy
    rawSell := filterSell
else
    rawBuy  := flipUp
    rawSell := flipDn

buySignal  = i_sig and rawBuy  and not newsBlackout and not macroBlockBuy
sellSignal = i_sig and rawSell and not newsBlackout and not macroBlockSell

plotshape(buySignal  and not i_sigText ? low  : na, "Buy",  shape.triangleup,   location.belowbar, SIG_UP, size = size.small)
plotshape(sellSignal and not i_sigText ? high : na, "Sell", shape.triangledown, location.abovebar, SIG_DN, size = size.small)
plotshape(buySignal  and i_sigText ? trendLvl : na, "Buy With Text",  shape.labelup,   location.absolute, color.new(#61c1fd, 54), text = "◈BUY",  textcolor = chart.fg_color, size = size.small)
plotshape(sellSignal and i_sigText ? trendLvl : na, "Sell With Text", shape.labeldown, location.absolute, color.new(#ff0000, 80), text = "◈SELL", textcolor = chart.fg_color, size = size.small)

CONF_RUN   = 3
CONF_TAIL  = 0.25
CONF_BODYR = 0.30
CONF_BODY  = 0.70
CONF_GAP   = 6

var int haRun = 1
haRun := haUp == haUp[1] ? haRun + 1 : 1
haBody    = math.abs(haClose - haOpen)
haRng     = math.max(haHigh - haLow, syminfo.mintick)
haLowWick = math.min(haOpen, haClose) - haLow
haUpWick  = haHigh - math.max(haOpen, haClose)
confBase  = haRun <= CONF_RUN and haBody >= CONF_BODY * haATR and haBody >= CONF_BODYR * haRng
pullbackUp = trendDir ==  1 and haUp     and confBase and haLowWick <= CONF_TAIL * haRng
pullbackDn = trendDir == -1 and not haUp and confBase and haUpWick  <= CONF_TAIL * haRng

var int confBar = -10000
rawConfUp = pullbackUp and bar_index - confBar >= CONF_GAP
rawConfDn = pullbackDn and bar_index - confBar >= CONF_GAP
if rawConfUp or rawConfDn
    confBar := bar_index

nearSignal = buySignal or sellSignal or buySignal[1] or sellSignal[1]
confBuy  = i_confirm and rawConfUp and not nearSignal
confSell = i_confirm and rawConfDn and not nearSignal
plotshape(confBuy,  "MarketMind Confirm Buy",  shape.circle, location.belowbar, color.new(CONF_UP, 100), text = "◆", textcolor = CONF_UP, size = size.tiny)
plotshape(confSell, "MarketMind Confirm Sell", shape.circle, location.abovebar, color.new(CONF_DN, 100), text = "◆", textcolor = CONF_DN, size = size.tiny)

alertcondition(confBuy,  "MarketMind Confirm Buy Alert",  "{{interval}} - {{ticker}} 🔵 MarketMind Confirm Buy\n")
alertcondition(confSell, "MarketMind Confirm Sell Alert", "{{interval}} - {{ticker}} 🔴 MarketMind Confirm Sell\n")

var int   posDir  = 0
var float entry   = na
var float slLvl   = na
var float geLvl   = na
var float tp1Lvl  = na
var float tp2Lvl  = na
var float tp3Lvl  = na
var float tslLvl  = na
var bool  tp1Hit  = false
var bool  tp2Hit  = false
var bool  tp3Hit  = false
var int   entryBar = na
var label lSL     = na

if buySignal or sellSignal
    posDir   := buySignal ? 1 : -1
    entry    := close
    entryBar := bar_index
    slLvl    := close - posDir * i_slMult  * haATR
    geLvl    := close - posDir * i_geM  * haATR
    tp1Lvl   := close + posDir * i_tp1M * haATR
    tp2Lvl   := close + posDir * i_tp2M * haATR
    tp3Lvl   := close + posDir * i_tp3M * haATR
    tslLvl   := slLvl
    tp1Hit   := false
    tp2Hit   := false
    tp3Hit   := false
    label.delete(lSL)
    if i_slLabel
        lSL := label.new(bar_index, slLvl, "SL · " + str.tostring(slLvl, "#.####"), style = label.style_label_left, color = color.new(SL_COL, 100), textcolor = SL_COL, size = size.normal)

if i_tsl and posDir != 0
    float trail = posDir == 1 ? upSlow : dnSlow
    tslLvl := posDir == 1 ? math.max(nz(tslLvl, trail), trail) : math.min(nz(tslLvl, trail), trail)

if posDir == 1
    if not tp1Hit and high >= tp1Lvl
        tp1Hit := true
        if i_tpHit
            label.new(bar_index, na, "✓" + "1", yloc = yloc.abovebar, style = label.style_label_up, color = color.new(TP_COL, 100), textcolor = TP_COL, size = size.tiny)
    if not tp2Hit and high >= tp2Lvl
        tp2Hit := true
        if i_tpHit
            label.new(bar_index, na, "✓" + "2", yloc = yloc.abovebar, style = label.style_label_up, color = color.new(TP_COL, 100), textcolor = TP_COL, size = size.tiny)
    if not tp3Hit and high >= tp3Lvl
        tp3Hit := true
        if i_tpHit
            label.new(bar_index, na, "✓" + "3", yloc = yloc.abovebar, style = label.style_label_up, color = color.new(TP_COL, 100), textcolor = TP_COL, size = size.tiny)
if posDir == -1
    if not tp1Hit and low <= tp1Lvl
        tp1Hit := true
        if i_tpHit
            label.new(bar_index, na, "✓" + "1", yloc = yloc.belowbar, style = label.style_label_down, color = color.new(TP_COL, 100), textcolor = TP_COL, size = size.tiny)
    if not tp2Hit and low <= tp2Lvl
        tp2Hit := true
        if i_tpHit
            label.new(bar_index, na, "✓" + "2", yloc = yloc.belowbar, style = label.style_label_down, color = color.new(TP_COL, 100), textcolor = TP_COL, size = size.tiny)
    if not tp3Hit and low <= tp3Lvl
        tp3Hit := true
        if i_tpHit
            label.new(bar_index, na, "✓" + "3", yloc = yloc.belowbar, style = label.style_label_down, color = color.new(TP_COL, 100), textcolor = TP_COL, size = size.tiny)

f_lblSize(int n) => n <= 1 ? size.tiny : n == 2 ? size.small : n == 3 ? size.normal : n == 4 ? size.large : size.huge
var label lTP1 = na
var label lTP2 = na
var label lTP3 = na
var label lGE  = na
var label lTSL = na
if barstate.islast and posDir != 0
    label.delete(lTP1), label.delete(lTP2), label.delete(lTP3), label.delete(lGE), label.delete(lTSL)
    string dash = ""
    if i_tpShow
        lTP1 := label.new(bar_index, tp1Lvl, dash + "TP1 · " + str.tostring(tp1Lvl, "#.####"), style = label.style_label_left, color = color.new(color.white, 100), textcolor = TP_COL, size = f_lblSize(i_lblSize))
        lTP2 := label.new(bar_index, tp2Lvl, dash + "TP2 · " + str.tostring(tp2Lvl, "#.####"), style = label.style_label_left, color = color.new(color.white, 100), textcolor = TP_COL, size = f_lblSize(i_lblSize))
        lTP3 := label.new(bar_index, tp3Lvl, dash + "TP3 · " + str.tostring(tp3Lvl, "#.####"), style = label.style_label_left, color = color.new(color.white, 100), textcolor = TP_COL, size = f_lblSize(i_lblSize))
    if i_geShow
        lGE := label.new(bar_index, geLvl, dash + "GE · " + str.tostring(geLvl, "#.####"), style = label.style_label_left, color = color.new(GE_COL, 100), textcolor = GE_COL, size = f_lblSize(i_lblSize))
    if i_tsl
        lTSL := label.new(bar_index + 4, tslLvl, "TSL · " + str.tostring(tslLvl, "#.####"), style = label.style_label_left, color = color.new(color.white, 100), textcolor = TSL_COL, size = f_lblSize(i_lblSize))

var box rrRisk = na
var box rrRew  = na
if i_rrBox and barstate.islast and posDir != 0
    box.delete(rrRisk), box.delete(rrRew)
    rrRisk := box.new(entryBar, entry, bar_index, slLvl,  bgcolor = color.new(#f23645, 85), border_color = color.new(#f23645, 60))
    rrRew  := box.new(entryBar, entry, bar_index, tp3Lvl, bgcolor = color.new(#4caf50, 85), border_color = color.new(#4caf50, 60))

SR_PIVOT   = 10      // ta.pivothigh/low(10, 10)
SR_HEIGHT  = 0.40    // × ta.atr(50) at the confirmation candle
SR_MINGAP  = 2.0     // × ta.atr(50)  — minimum spacing between levels of the same type
SR_EXTEND  = 50      //Box extends to the right
SR_LBLOFF  = 50     //Volume label offset = total length of the two volume columns
SR_VOLLEN  = 50     //The two volume columns always total 49 candles
SR_MAXLIVE = 12      //Maximum number of live zones (oldest is deleted)

atr50    = ta.atr(50)
volSma20 = ta.sma(volume, 20)
atrAvg50 = ta.sma(haATR, 50)

var array<int>   zKind = array.new<int>()    //1 = resistance, -1 = support
var array<float> zLvl  = array.new<float>()
var array<box>   zBox  = array.new<box>()
var array<label> zLbl  = array.new<label>()
var array<box>   zVolA = array.new<box>()   //Buy column
var array<box>   zVolB = array.new<box>()   //Sell column

f_farEnough(int kind, float lvl, float gap) =>
    bool ok = true
    if array.size(zLvl) > 0
        for i = 0 to array.size(zLvl) - 1
            if array.get(zKind, i) == kind and math.abs(lvl - array.get(zLvl, i)) < gap
                ok := false
    ok

f_zoneDrop(int i) =>
    box.delete(array.get(zBox, i))
    label.delete(array.get(zLbl, i))
    box.delete(array.get(zVolA, i))
    box.delete(array.get(zVolB, i))
    array.remove(zKind, i), array.remove(zLvl, i), array.remove(zBox, i), array.remove(zLbl, i)
    array.remove(zVolA, i), array.remove(zVolB, i)

ph = ta.pivothigh(high, SR_PIVOT, SR_PIVOT)
pl = ta.pivotlow(low,  SR_PIVOT, SR_PIVOT)

upVol   = math.sum(close >= open ? volume : 0, SR_PIVOT * 2 + 1)
dnVol   = math.sum(close <  open ? volume : 0, SR_PIVOT * 2 + 1)
totVol  = na(volume) ? float(na) : upVol + dnVol

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

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

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

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

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

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

Стоимость полного кода
3 733,90₽ ≈ $45.64