Streak Reversal
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «indicator streak reversal for tradingview.pine» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Streak Reversal — индикатор для TradingView, написанный на Pine Script v6. Он выявляет сигналы разворота цены на основе серий свечей одного цвета и отображает их на графике с помощью графических маркеров и подписей.
Индикатор классифицирует сигналы на трендовые (цена по одну сторону от EMA) и противотрендовые (цена по другую сторону). Для каждого сигнала доступно множество пользовательских фильтров: длина серии, движение по ATR, размеры и тени свечей, расстояние от EMA.
Streak Reversal поддерживает отрисовку уровней Stop Loss и Take Profit 1–3, настраиваемую линию EMA со свечением, информационную таблицу-чеклист условий и условия для оповещений TradingView.
Настройки программы
| Настройка | Описание |
|---|---|
| showLong | Показать лонг (после медвежьей серии) — Включение/отключение бычьих (лонг) сигналов разворота после медвежьей серии. |
| showShort | Показать шорт (после бычьей серии) — Включение/отключение медвежьих (шорт) сигналов разворота после бычьей серии. |
| showTrendSignals | Показать трендовые сигналы — Включение/отключение трендовых сигналов (лонг при цене выше EMA, шорт при цене ниже EMA). |
| showCounterSignals | Показать противотрендовые сигналы — Включение/отключение противотрендовых сигналов (лонг при цене ниже EMA, шорт при цене выше EMA). |
| minStreak | Мин. длина серии (свечей) — Минимальное количество свечей одного цвета подряд, необходимое перед разворотом. |
| useAtrFilter | Фильтр движения серии (ATR) — Включение фильтра минимального движения серии, измеренного в ATR. |
| minAtrMove | Мин. движение серии (ATR) — Минимальное движение серии в ATR, необходимое для прохождения фильтра движения серии. |
| atrLenStreak | Длина ATR (движение серии) — Период ATR, используемый для измерения движения серии свечей. |
| confirmLevel | Уровень подтверждения — Уровень подтверждения для первого противоположного свечения: по телу свечи или по максимуму/минимуму. |
| useOppWickFilter | Фильтр противоположной тени — Включение фильтра противоположной тени: отклонение свечей с чрезмерно большой тенью. |
| maxOppWickPct | Макс. противоположная тень (% диапазона) — Максимальная доля противоположной тени свечи в процентах от полного диапазона свечи. |
| useSignalSizeFilter | Фильтр размера свечи — Включение фильтра размера сигнальной свечи: отклонение слишком маленьких свечей. |
| signalSizeMode | Режим измерения размера свечи — Режим измерения размера сигнальной свечи: по телу свечи или по диапазону (high−low). |
| minSignalSizeAtr | Мин. размер свечи (ATR) — Минимальный размер сигнальной свечи в ATR, используемый при включённом фильтре размера свечи. |
| atrLenSize | Длина ATR (размер свечи) — Период ATR, используемый для измерения размера свечи сигнала. |
| emaLen | Длина EMA — Период экспоненциальной скользящей средней (EMA), определяющей трендовую категорию сигнала. |
| useEmaMoveFilter | Фильтр плоской EMA — Включение фильтра плоской EMA: если движение EMA за окно ниже порога, сигнал отклоняется. |
| emaMoveLen | Окно движения EMA (баров) — Окно в барах для расчёта движения EMA и оценки силы тренда. |
| minEmaMoveAtr | Мин. движение EMA (ATR) — Пороговое значение движения EMA в ATR для фильтра плоской EMA. |
| atrLenEmaMove | Длина ATR (движение EMA) — Период ATR, используемый для расчёта движения EMA и фильтра плоской EMA. |
| strongTrendAtr | Порог сильного тренда (ATR) — Пороговое значение движения EMA в ATR для оценки силы тренда (информационное): ниже — слабый, выше — сильный. |
| vStrongTrendAtr | Порог очень сильного тренда (ATR) — Пороговое значение движения EMA в ATR для оценки очень сильного тренда (информационное). |
| useTrendMaxDist | Макс. фильтр расстояния от EMA — тренд — Включение максимального фильтра расстояния от EMA для трендовых сигналов. |
| maxTrendDistAtr | Макс. расстояние от EMA (ATR) — тренд — Максимальное расстояние от EMA в ATR, при котором трендовый сигнал не блокируется фильтром. |
| useCounterMinDist | Мин. фильтр расстояния от EMA — противотренд — Включение минимального фильтра расстояния от EMA для противотрендовых сигналов. |
| minCounterDistAtr | Мин. расстояние от EMA (ATR) — противотренд — Минимальное расстояние от EMA в ATR, при котором противотрендовый сигнал не блокируется фильтром. |
| atrLenDist | Длина ATR (расстояние от EMA) — Период ATR, используемый для измерения расстояния от EMA, значений подписей и смещения меток. |
| bullCol | Цвет бычьих (лонг) — Основной цвет для бычьих (лонг) сигналов, линии EMA при цене выше EMA и соответствующих элементов отображения. |
| bearCol | Цвет медвежьих (шорт) — Основной цвет для медвежьих (шорт) сигналов, линии EMA при цене ниже EMA и соответствующих элементов отображения. |
| trendLabelCol | Цвет текста (тренд) — Цвет текста подписей трендовых сигналов. |
| counterLabelCol | Цвет текста (противотренд) — Цвет текста подписей противотрендовых сигналов. |
| tblBgCol | Цвет фона таблицы — Цвет фона таблицы-чеклиста. |
| tblTxtCol | Цвет текста таблицы — Цвет текста названий условий в первом столбце таблицы. |
| tblHdrCol | Цвет заголовка таблицы — Цвет фона заголовка и строки результата в таблице. |
| showShapes | Показать фигуры сигналов — Отображение графических маркеров: треугольник для трендовых сигналов, ромб для противотрендовых. |
| shapeSizeStr | Размер фигур сигналов — Размер графических фигур сигналов: Tiny, Small или Normal. |
| highlightOpp | Отметить противоположное свечение — Отображение круга на противоположном свечении (том, уровень которого был пробит сигнальной свечой). |
| showDistLabel | Показать подписи — Отображение подписей с категорией сигнала и расстоянием от EMA в ATR. |
| labelSizeStr | Размер подписей — Размер текста подписей сигналов: Tiny, Small или Normal. |
| labelOffsetAtr | Смещение подписи (× ATR) — Вертикальное смещение подписи от свечи, выраженное в кратных ATR. |
| showEma | Показать EMA — Отображение линии EMA на графике. Цвет линии меняется в зависимости от положения цены. |
| emaWidth | Толщина линии EMA — Толщина линии EMA на графике. |
| showEmaGlow | Показать свечение EMA — Отображение свечения (градиента) вокруг линии EMA. |
| glowOffsetMult | Ширина свечения (× ATR) — Множитель ATR, определяющий ширину зоны свечения вокруг линии EMA. |
| glowNearTransp | Прозрачность свечения — Прозрачность свечения EMA: 0 — сплошной цвет, 99 — почти невидимо. |
| atrLenGlow | Длина ATR (свечение) — Период ATR, определяющий ширину свечения линии EMA. |
| showTable | Показать таблицу — Отображение таблицы-чеклиста условий сигнала для текущего бара отдельно для лонг и шорт. |
| tblPosStr | Положение таблицы — Положение таблицы на графике: верхний/средний/нижний левый, центральный или правый. |
| tblSizeStr | Размер текста таблицы — Размер текста в таблице: Tiny, Small, Normal или Large. |
| showTargets | Показать уровни TP/SL — Отрисовка уровней входа, Stop Loss и Take Profit 1–3 для каждого нового сигнала. |
| useAtrSL | Stop Loss на основе ATR — Режим расчёта Stop Loss: по ATR (расстояние = ATR × множитель) или фиксированный процент от цены входа. |
| tpAtrPeriod | Длина ATR (TP/SL) — Период ATR, используемый для расчёта расстояния Stop Loss и Take Profit. |
| slAtrMult | Множитель SL (ATR) — Множитель ATR для расчёта расстояния Stop Loss при включённом режиме ATR-стоп-лосса. |
| slPercent | Процент SL от входа — Процент от цены входа для расчёта расстояния Stop Loss при отключённом режиме ATR-стоп-лосса. |
| rrTP1 | Соотношение прибыли/риска — TP1 — Соотношение прибыли к риску для первого уровня Take Profit. |
| rrTP2 | Соотношение прибыли/риска — TP2 — Соотношение прибыли к риску для второго уровня Take Profit. |
| rrTP3 | Соотношение прибыли/риска — TP3 — Соотношение прибыли к риску для третьего уровня Take Profit. |
| showSlLevel | Показать Stop Loss — Отображение уровня Stop Loss: линия, подпись и заливка зоны риска. |
| showTp1Level | Показать TP1 — Отображение первого уровня Take Profit: линия и подпись. |
| showTp2Level | Показать TP2 — Отображение второго уровня Take Profit: линия и подпись. |
| showTp3Level | Показать TP3 — Отображение третьего уровня Take Profit: линия и подпись. |
Поиск по коду файла
indicator("Streak Reversal", overlay = true, max_labels_count = 500)
string SIZE_OPTS_TINY = "Tiny"
string SIZE_OPTS_SMALL = "Small"
string SIZE_OPTS_NORMAL = "Normal"
string SIZE_OPTS_LARGE = "Large"
string GRP_SIG = "1. Signals"
bool showLong = input.bool(true, "Long (after bearish streak)", group = GRP_SIG, tooltip = "Looks for an upside reversal: a streak of red candles followed by 2 green candles.\nThe signal appears on the close of the second green candle.")
bool showShort = input.bool(true, "Short (after bullish streak)", group = GRP_SIG, tooltip = "Looks for a downside reversal: a streak of green candles followed by 2 red candles.\nThe signal appears on the close of the second red candle.")
bool showTrendSignals = input.bool(true, "Trend (end of pullback)", group = GRP_SIG, tooltip = "Long when price is ABOVE the EMA / Short when price is BELOW the EMA.\nQuality improves the CLOSER the signal candle is to the EMA.\nDistance limit: section 5.")
bool showCounterSignals = input.bool(true, "Counter-trend", group = GRP_SIG, tooltip = "Long when price is BELOW the EMA / Short when price is ABOVE the EMA.\nQuality improves the FARTHER the signal candle is from the EMA (move exhaustion).\nDistance limit: section 5.")
string GRP_STREAK = "2. Streak"
int minStreak = input.int(2, "Min. same-color candles", minval = 1, maxval = 50, group = GRP_STREAK, tooltip = "How many consecutive candles of one color must precede the reversal.\nA doji candle (close = open) breaks the streak.")
bool useAtrFilter = input.bool(true, "Streak move filter", group = GRP_STREAK, tooltip = "The streak must cover a minimum distance measured in ATR.")
float minAtrMove = input.float(1.5, "Min. streak move (ATR)", minval = 0.1, step = 0.1, group = GRP_STREAK, tooltip = "Bearish streak: high of the first candle − low of the last candle.\nBullish streak: high of the last candle − low of the first candle.\nThe result is divided by the ATR at the last candle of the streak.")
int atrLenStreak = input.int(100, "ATR length (streak move)", minval = 1, maxval = 500, group = GRP_STREAK, tooltip = "ATR period used to measure the streak move.")
string GRP_SIGCANDLE = "3. Signal candle"
string confirmLevel = input.string("Body", "Confirmation level", options = ["Body", "High/Low"], group = GRP_SIGCANDLE, tooltip = "Level of the first opposite candle that the signal candle's close must break.\nBody: top (long) / bottom (short) edge of the body.\nHigh/Low: high (long) / low (short).")
bool useOppWickFilter = input.bool(true, "Opposite wick filter", group = GRP_SIGCANDLE, tooltip = "Long: rejects a signal candle with an upper wick that is too large.\nShort: rejects a signal candle with a lower wick that is too large.")
float maxOppWickPct = input.float(40.0, "Max. opposite wick (% of range)", minval = 5.0, maxval = 90.0, step = 1.0, group = GRP_SIGCANDLE, tooltip = "Maximum share of the opposite wick in the candle's full range (high−low).")
bool useSignalSizeFilter = input.bool(false, "Candle size filter", group = GRP_SIGCANDLE, tooltip = "Filters out tiny confirmation candles.")
string signalSizeMode = input.string("Body", "Measure size as", options = ["Body", "Range"], group = GRP_SIGCANDLE, tooltip = "Body = |close−open|.\nRange = high−low.")
float minSignalSizeAtr = input.float(0.30, "Min. size (ATR)", minval = 0.05, maxval = 5.0, step = 0.05, group = GRP_SIGCANDLE, tooltip = "Minimum size of the signal candle in ATR.")
int atrLenSize = input.int(100, "ATR length (candle size)", minval = 1, maxval = 500, group = GRP_SIGCANDLE, tooltip = "ATR period used to measure the signal candle size.")
string GRP_EMA = "4. EMA (trend)"
int emaLen = input.int(100, "EMA length", minval = 2, maxval = 400, group = GRP_EMA, tooltip = "Determines the signal category: trend / counter-trend.")
bool useEmaMoveFilter = input.bool(false, "Flat EMA filter", group = GRP_EMA, tooltip = "EMA move = highest(EMA) − lowest(EMA) over the window, in ATR.\nIf it is below the minimum, the signal is rejected.")
int emaMoveLen = input.int(20, "EMA move window (bars)", minval = 2, maxval = 300, group = GRP_EMA, tooltip = "Shared by the flat EMA filter and the trend strength rating in the table.")
float minEmaMoveAtr = input.float(0.50, "Min. EMA move (ATR)", minval = 0.05, maxval = 10.0, step = 0.05, group = GRP_EMA, tooltip = "Flat EMA filter threshold.")
int atrLenEmaMove = input.int(100, "ATR length (EMA move)", minval = 1, maxval = 500, group = GRP_EMA, tooltip = "Shared by the flat EMA filter and the trend strength rating.")
float strongTrendAtr = input.float(1.0, "Strong trend threshold (ATR)", minval = 0.05, maxval = 20.0, step = 0.05, group = GRP_EMA, tooltip = "Trend strength rating in the table (EMA move over the window, in ATR):\n< strong threshold → weak (flat EMA)\n≥ strong threshold → strong\n≥ very strong threshold → very strong\nInformational only — does not block signals.")
float vStrongTrendAtr = input.float(2.5, "Very strong trend threshold (ATR)", minval = 0.05, maxval = 30.0, step = 0.05, group = GRP_EMA, tooltip = "Should be greater than the strong trend threshold.")
string GRP_DIST = "5. Distance from EMA"
bool useTrendMaxDist = input.bool(false, "Max. distance filter — trend", group = GRP_DIST, tooltip = "A trend signal is rejected when the signal candle's close is too FAR from the EMA.")
float maxTrendDistAtr = input.float(2.0, "Max. distance from EMA (ATR)", minval = 0.0, maxval = 20.0, step = 0.1, group = GRP_DIST, tooltip = "Applies to trend signals only.")
bool useCounterMinDist = input.bool(false, "Min. distance filter — counter-trend", group = GRP_DIST, tooltip = "A counter-trend signal is rejected when the signal candle's close is too CLOSE to the EMA.")
float minCounterDistAtr = input.float(3.0, "Min. distance from EMA (ATR)", minval = 0.0, maxval = 20.0, step = 0.1, group = GRP_DIST, tooltip = "Applies to counter-trend signals only.")
int atrLenDist = input.int(100, "ATR length (EMA distance)", minval = 1, maxval = 500, group = GRP_DIST, tooltip = "Shared by both distance filters; also used for label values and label offset (section 8).")
string GRP_COL = "6. Colors"
color bullCol = input.color(#26a69a, "Bullish (long / above EMA)", group = GRP_COL, tooltip = "Main long-side color, used throughout the indicator:\n• long signals — triangle, diamond, opposite-candle circle, label background\n• EMA line and glow when price is ABOVE the EMA\n• TP/SL: long entry, TP and reward zone; short SL and risk zone\n• table: LONG header, ✓ statuses, aligned trend, last long signal")
color bearCol = input.color(#ef5350, "Bearish (short / below EMA)", group = GRP_COL, tooltip = "Main short-side color, used throughout the indicator:\n• short signals — triangle, diamond, opposite-candle circle, label background\n• EMA line and glow when price is BELOW the EMA\n• TP/SL: short entry, TP and reward zone; long SL and risk zone\n• table: SHORT header, ✗ statuses, last short signal")
color trendLabelCol = input.color(color.white, "Label text — trend", group = GRP_COL, tooltip = "Text color of trend signal labels.")
color counterLabelCol = input.color(color.white, "Label text — counter-trend", group = GRP_COL, tooltip = "Text color of counter-trend signal labels.")
color tblBgCol = input.color(color.new(#131722, 0), "Table — background", group = GRP_COL, tooltip = "Table background color and transparency.")
color tblTxtCol = input.color(color.new(#d1d4dc, 0), "Table — text", group = GRP_COL, tooltip = "Color of the condition names (first table column).")
color tblHdrCol = input.color(color.new(#2a2e39, 0), "Table — header background", group = GRP_COL, tooltip = "Background of the header row and the result row.")
string GRP_VIS_SHAPE = "7. Display — shapes"
bool showShapes = input.bool(false, "Show signal shapes", group = GRP_VIS_SHAPE, tooltip = "Triangle = trend, diamond = counter-trend.")
string shapeSizeStr = input.string(SIZE_OPTS_TINY, "Shape size", options = [SIZE_OPTS_TINY, SIZE_OPTS_SMALL, SIZE_OPTS_NORMAL], group = GRP_VIS_SHAPE, tooltip = "Size of the signal triangles and diamonds.")
bool highlightOpp = input.bool(true, "Mark opposite candle", group = GRP_VIS_SHAPE, tooltip = "Circle below/above the first opposite candle (the one whose level was broken by the signal candle).")
string GRP_VIS_LAB = "8. Display — labels"
bool showDistLabel = input.bool(true, "Show labels", group = GRP_VIS_LAB, tooltip = "Signal category + distance from the EMA in ATR (ATR from section 5).")
string labelSizeStr = input.string(SIZE_OPTS_SMALL, "Label size", options = [SIZE_OPTS_TINY, SIZE_OPTS_SMALL, SIZE_OPTS_NORMAL], group = GRP_VIS_LAB, tooltip = "Text size of the signal labels.")
float labelOffsetAtr = input.float(0.6, "Offset from candle (x ATR)", minval = 0.0, maxval = 5.0, step = 0.1, group = GRP_VIS_LAB, tooltip = "Vertical distance of the label from the low (long) / high (short), in ATR from section 5.\n0 = the label touches the candle. Consider a smaller value when shapes are hidden.")
string GRP_VIS_EMA = "9. Display — EMA"
bool showEma = input.bool(true, "Show EMA", group = GRP_VIS_EMA, tooltip = "The EMA line changes color: bullish when price is above it, bearish when below.")
int emaWidth = input.int(3, "Line width", minval = 1, maxval = 8, group = GRP_VIS_EMA, tooltip = "EMA line width.")
bool showEmaGlow = input.bool(true, "Show glow", group = GRP_VIS_EMA, tooltip = "Gradient in a channel around the EMA — strongest at the EMA, fading toward the edges.")
float glowOffsetMult = input.float(4, "Glow width (x ATR)", minval = 0.1, maxval = 5.0, step = 0.01, group = GRP_VIS_EMA, tooltip = "Distance of the glow edge from the EMA, in ATR.")
int glowNearTransp = input.int(80, "Glow transparency", minval = 0, maxval = 99, group = GRP_VIS_EMA, tooltip = "0 = solid color, 99 = nearly invisible.")
int atrLenGlow = input.int(100, "ATR length (glow width)", minval = 1, maxval = 500, group = GRP_VIS_EMA, tooltip = "ATR period used for the glow width.")
string GRP_TBL = "10. Table"
bool showTable = input.bool(true, "Show table", group = GRP_TBL, tooltip = "Checklist of signal conditions for the current bar, shown separately for long and short.\n✓ met · ✗ blocking · … waiting for more bars · ○ filter off.\nHover over a table cell to see details.")
string tblPosStr = input.string("Top right", "Position", options = ["Top left", "Top center", "Top right", "Middle left", "Middle center", "Middle right", "Bottom left", "Bottom center", "Bottom right"], group = GRP_TBL, tooltip = "Table position on the chart.")
string tblSizeStr = input.string(SIZE_OPTS_SMALL, "Text size", options = [SIZE_OPTS_TINY, SIZE_OPTS_SMALL, SIZE_OPTS_NORMAL, SIZE_OPTS_LARGE], group = GRP_TBL, tooltip = "Table text size.")
string GRP_TPSL = "11. TP/SL"
bool showTargets = input.bool(true, "Show TP/SL levels", group = GRP_TPSL, tooltip = "Draws the entry, Stop Loss and Take Profit 1–3 for each new signal.\nEntry = signal candle close.\nA new signal replaces the previous levels. Levels stop extending once SL or the farthest visible TP is hit.")
bool useAtrSL = input.bool(true, "ATR-based SL", group = GRP_TPSL, tooltip = "On: SL distance from entry = ATR × multiplier.\nOff: fixed percentage of the entry price (SL % from entry).")
int tpAtrPeriod = input.int(14, "ATR length (TP/SL)", minval = 1, maxval = 500, group = GRP_TPSL, tooltip = "ATR period used to calculate the SL distance. Independent of the other ATR settings.")
float slAtrMult = input.float(1.5, "SL ATR multiplier", minval = 0.1, step = 0.1, group = GRP_TPSL, tooltip = "SL distance from entry as a multiple of ATR. Applies when “ATR-based SL” is enabled.")
float slPercent = input.float(1.0, "SL % from entry", minval = 0.01, step = 0.1, group = GRP_TPSL, tooltip = "SL distance from the entry price as a percentage. Applies when “ATR-based SL” is disabled.")
float rrTP1 = input.float(1.0, "TP1 risk:reward", minval = 0.1, step = 0.1, group = GRP_TPSL, tooltip = "Reward-to-risk ratio for TP1.\n1.0 = TP1 at the same distance from entry as the SL.")
float rrTP2 = input.float(2.0, "TP2 risk:reward", minval = 0.1, step = 0.1, group = GRP_TPSL, tooltip = "Reward-to-risk ratio for TP2.")
float rrTP3 = input.float(3.0, "TP3 risk:reward", minval = 0.1, step = 0.1, group = GRP_TPSL, tooltip = "Reward-to-risk ratio for TP3.")
string GRP_TPSL_DISP = "12. TP/SL — display"
bool showSlLevel = input.bool(true, "Show SL", group = GRP_TPSL_DISP, tooltip = "Stop Loss line and label, plus the risk zone fill.")
bool showTp1Level = input.bool(true, "Show TP1", group = GRP_TPSL_DISP, tooltip = "Take Profit 1 line and label.")
bool showTp2Level = input.bool(true, "Show TP2", group = GRP_TPSL_DISP, tooltip = "Take Profit 2 line and label.")
bool showTp3Level = input.bool(true, "Show TP3", group = GRP_TPSL_DISP, tooltip = "Take Profit 3 line and label.\nWhen the farthest visible TP is hit, the levels stop extending.")
bool isBull = close > open
bool isBear = close < open
int bullStreak = 0
int bearStreak = 0
bullStreak := isBull ? nz(bullStreak[1]) + 1 : 0
bearStreak := isBear ? nz(bearStreak[1]) + 1 : 0
float bearFirstHigh = na
float bullFirstLow = na
bearFirstHigh := isBear ? (bearStreak == 1 ? high : nz(bearFirstHigh[1])) : na
bullFirstLow := isBull ? (bullStreak == 1 ? low : nz(bullFirstLow[1])) : na
float oppBodyHigh = math.max(open[1], close[1])
float oppBodyLow = math.min(open[1], close[1])
float longLevel = confirmLevel == "Body" ? oppBodyHigh : high[1]
float shortLevel = confirmLevel == "Body" ? oppBodyLow : low[1]
float atrStreak = ta.atr(atrLenStreak)
float atrSize = ta.atr(atrLenSize)
float atrEmaMove = ta.atr(atrLenEmaMove)
float atrDist = ta.atr(atrLenDist)
float atrGlow = ta.atr(atrLenGlow)
float emaVal = ta.ema(close, emaLen)
bool aboveEma = close > emaVal
bool belowEma = close < emaVal
float emaRange = ta.highest(emaVal, emaMoveLen) - ta.lowest(emaVal, emaMoveLen)
float emaMoveAtr = nz(atrEmaMove) > 0 ? emaRange / atrEmaMove : na
bool emaMoveOk = not useEmaMoveFilter or (not na(emaMoveAtr) and emaMoveAtr >= minEmaMoveAtr)
bool emaRising = emaVal >= nz(emaVal[emaMoveLen], emaVal)
float bearDrop = nz(bearFirstHigh[2]) - low[2]
float bullRise = high[2] - nz(bullFirstLow[2])
bool longMoveOk = not useAtrFilter or (nz(atrStreak[2]) > 0 and bearDrop / atrStreak[2] >= minAtrMove)
bool shortMoveOk = not useAtrFilter or (nz(atrStreak[2]) > 0 and bullRise / atrStreak[2] >= minAtrMove)
float candleRange = high - low
float upperWick = high - math.max(open, close)
float lowerWick = math.min(open, close) - low
float bodySize = math.abs(close - open)
float oppWickPct = candleRange > 0 ? (upperWick / candleRange) * 100.0 : 0.0
float lowWickPct = candleRange > 0 ? (lowerWick / candleRange) * 100.0 : 0.0
bool longWickOk = not useOppWickFilter or (candleRange > 0 and oppWickPct <= maxOppWickPct)
bool shortWickOk = not useOppWickFilter or (candleRange > 0 and lowWickPct <= maxOppWickPct)
float signalSize = signalSizeMode == "Body" ? bodySize : candleRange
float signalSizeAtr = nz(atrSize) > 0 ? signalSize / atrSize : na
bool signalSizeOk = not useSignalSizeFilter or (not na(signalSizeAtr) and signalSizeAtr >= minSignalSizeAtr)
bool longIsTrend = aboveEma
bool shortIsTrend = belowEma
bool categoryOkLong = (longIsTrend and showTrendSignals) or (not longIsTrend and showCounterSignals)
bool categoryOkShort = (shortIsTrend and showTrendSignals) or (not shortIsTrend and showCounterSignals)
float emaDistAtr = nz(atrDist) > 0 ? math.abs(close - emaVal) / atrDist : na
bool trendDistOk = not useTrendMaxDist or (not na(emaDistAtr) and emaDistAtr <= maxTrendDistAtr)
bool counterDistOk = not useCounterMinDist or (not na(emaDistAtr) and emaDistAtr >= minCounterDistAtr)
bool longDistOk = longIsTrend ? trendDistOk : counterDistOk
bool shortDistOk = shortIsTrend ? trendDistOk : counterDistOk
bool longSignal =
showLong
and bearStreak[2] >= minStreak
and isBull[1]
and isBull
and longMoveOk
and longWickOk
and signalSizeOk
and emaMoveOk
and categoryOkLong
and longDistOk
and close > longLevel
bool shortSignal =
showShort
and bullStreak[2] >= minStreak
and isBear[1]
and isBear
and shortMoveOk
and shortWickOk
and signalSizeOk
and emaMoveOk
and categoryOkShort
and shortDistOk
and close < shortLevel
bool longTrendSig = longSignal and longIsTrend
bool longCounterSig = longSignal and not longIsTrend
bool shortTrendSig = shortSignal and shortIsTrend
bool shortCounterSig = shortSignal and not shortIsTrend
bool sigIsTrend = longTrendSig or shortTrendSig
float bearMoveNow = isBear and nz(atrStreak) > 0 ? (bearFirstHigh - low) / atrStreak : na
float bullMoveNow = isBull and nz(atrStreak) > 0 ? (high - bullFirstLow) / atrStreak : na
float bearMove1 = bearMoveNow[1]
float bearMove2 = bearMoveNow[2]
float bullMove1 = bullMoveNow[1]
float bullMove2 = bullMoveNow[2]
int bearLen1 = nz(bearStreak[1])
int bearLen2 = nz(bearStreak[2])
int bullLen1 = nz(bullStreak[1])
int bullLen2 = nz(bullStreak[2])
int lOpp = isBull and isBull[1] ? 2 : isBull and isBear[1] ? 1 : 0
int lLen = lOpp == 2 ? bearLen2 : lOpp == 1 ? bearLen1 : bearStreak
float lMove = lOpp == 2 ? bearMove2 : lOpp == 1 ? bearMove1 : bearMoveNow
int sOpp = isBear and isBear[1] ? 2 : isBear and isBull[1] ? 1 : 0
int sLen = sOpp == 2 ? bullLen2 : sOpp == 1 ? bullLen1 : bullStreak
float sMove = sOpp == 2 ? bullMove2 : sOpp == 1 ? bullMove1 : bullMoveNow
var int lastLongBar = na
var bool lastLongTrend = false
var int lastShortBar = na
var bool lastShortTrend = false
if longSignal
lastLongBar := bar_index
lastLongTrend := longIsTrend
if shortSignal
lastShortBar := bar_index
lastShortTrend := shortIsTrend
color emaCol = close >= emaVal ? bullCol : bearCol
float glowOffset = atrGlow * glowOffsetMult
float emaUpperBound = emaVal + glowOffset
float emaLowerBound = emaVal - glowOffset
pCore = plot(showEma ? emaVal : na, "EMA", emaCol, emaWidth)
pGlowUp = plot(showEma and showEmaGlow ? emaUpperBound : na, "EMA Glow Upper", color.new(emaCol, 100), 1, display = display.none)
pGlowDn = plot(showEma and showEmaGlow ? emaLowerBound : na, "EMA Glow Lower", color.new(emaCol, 100), 1, display = display.none)
fill(pCore, pGlowUp, emaUpperBound, emaVal, showEmaGlow ? color.new(emaCol, 100) : na, showEmaGlow ? color.new(emaCol, glowNearTransp) : na)
fill(pGlowDn, pCore, emaVal, emaLowerBound, showEmaGlow ? color.new(emaCol, glowNearTransp) : na, showEmaGlow ? color.new(emaCol, 100) : na)
bool szT = showShapes and shapeSizeStr == SIZE_OPTS_TINY
bool szS = showShapes and shapeSizeStr == SIZE_OPTS_SMALL
bool szN = showShapes and shapeSizeStr == SIZE_OPTS_NORMAL
plotshape(szT and longTrendSig, "Long trend (tiny)", shape.triangleup, location.belowbar, bullCol, size = size.tiny)
plotshape(szT and longCounterSig, "Long counter (tiny)", shape.diamond, location.belowbar, bullCol, size = size.tiny)
plotshape(szT and shortTrendSig, "Short trend (tiny)", shape.triangledown, location.abovebar, bearCol, size = size.tiny)
plotshape(szT and shortCounterSig, "Short counter (tiny)", shape.diamond, location.abovebar, bearCol, size = size.tiny)
plotshape(szS and longTrendSig, "Long trend (small)", shape.triangleup, location.belowbar, bullCol, size = size.small)
plotshape(szS and longCounterSig, "Long counter (small)", shape.diamond, location.belowbar, bullCol, size = size.small)
plotshape(szS and shortTrendSig, "Short trend (small)", shape.triangledown, location.abovebar, bearCol, size = size.small)
plotshape(szS and shortCounterSig, "Short counter (small)", shape.diamond, location.abovebar, bearCol, size = size.small)
plotshape(szN and longTrendSig, "Long trend (normal)", shape.triangleup, location.belowbar, bullCol, size = size.normal)
plotshape(szN and longCounterSig, "Long counter (normal)", shape.diamond, location.belowbar, bullCol, size = size.normal)
plotshape(szN and shortTrendSig, "Short trend (normal)", shape.triangledown, location.abovebar, bearCol, size = size.normal)
plotshape(szN and shortCounterSig, "Short counter (normal)", shape.diamond, location.abovebar, bearCol, size = size.normal)
plotshape(highlightOpp and longSignal, "Opposite candle (long)", shape.circle, location.belowbar, color.new(bullCol, 30), offset = -1, size = size.tiny)
plotshape(highlightOpp and shortSignal, "Opposite candle (short)", shape.circle, location.abovebar, color.new(bearCol, 30), offset = -1, size = size.tiny)
string labelSizeSel = switch labelSizeStr
SIZE_OPTS_TINY => size.tiny
SIZE_OPTS_SMALL => size.small
=> size.normal
if sПоказано первые 50% кода (символов: 33786)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.