Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

2Tier Ichimoku Pyramiding [Takazudo]

A Pine Script v4 strategy built on Barssince or Change (change(time(_res))), CUM and EMA (_f). It has 16 order rules, 4 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade is one contract and pays no commission. 33 settings; defaults include Base Higher Timeframe D, Highest Timeframe W and Tenkan-Sen Bars 9.

Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.

Does 2Tier Ichimoku Pyramiding [Takazudo] repaint?
No
No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
Can 2Tier Ichimoku Pyramiding [Takazudo] be converted to Pine Script v5?
Not tested
The steps are shown below, but neither version placed a trade on any market tested, so there was nothing to compare and no download is offered.
Does 2Tier Ichimoku Pyramiding [Takazudo] use a stop loss?
Yes
strategy.exit sets a stop on line 878, 879, 880, 881, 882, 883.
Does 2Tier Ichimoku Pyramiding [Takazudo] run in Zeal Terminal?
Yes
It compiles in 129 ms and runs 1,000 bars in 1,061 ms, in the browser.

BTCUSDT · 1D · default settings

  • Base HTF: Senkou-Span A
  • Base HTF: Senkou-Span B
  • Chikou-Span
  • Tenkan-Sen
  • Kijun-Sen
  • Plot
  • Plot
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$0$0Equity from $0
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. Zeal Terminal's engine currently reads an order side written as long = true, long = false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 852, 856, 861, 867) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market. The live re-run is not offered here: the script requests BINANCE:BTCUSDT W, which this page cannot load in your browser.
Net profit
0.00%
$0.00
Buy and hold
0.0%
same period
Closed trades
0
0 won · 0 lost
Profitable
0.0%
of closed trades
Profit factor
—
gross profit ÷ gross loss
Max drawdown
0.00%
$0.00

One run with the author's default settings, $0 starting capital, commission as the script sets it. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.

Review

What a careful reader of this script would point out, found by checking the source and the backtest.

  • Check

    6 settings do nothing

    “═════════ HTF ══════════”, “═════════ Ichimoku ══════════”, “═════════ Smooth Line ══════════”, “═════════ MTF stuff ══════════”, “═════════ etc ══════════”, “═════════ Backtesting range ══════════” are declared but never read.

  • Check

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

  • Note

    Uses transp =, which v5 removed line 469

    transp = on line 469, 475, 481, 489, 495, 501, 507, 513, 519, 524, 531, 536, 917. v5 folds the transparency into the colour with color.new(c, transp).

  • Note

    Uses long =, which v5 renamed line 852

    long = on line 852, 856, 861, 867. v5 writes it as direction = strategy.long or strategy.short.

Upgrade and export

Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.

  • Upgrading to v5 renames security → request.security, max → math.max, tostring → str.tostring, round → math.round, min → math.min, barssince → ta.barssince, change → ta.change, cum → ta.cum, ema → ta.ema, abs → math.abs, avg → math.avg, lowest → ta.lowest, highest → ta.highest, crossover → ta.crossover, macd → ta.macd, atr → ta.atr.

v4 → v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 3: //@version=4 → //@version=5
  • Line 45: input(type = input.resolution) → input.timeframe()
  • Line 47: input(type = input.resolution) → input.timeframe()
  • Line 66: input(type = input.float) → input.float()
  • Line 67: input(type = input.float) → input.float()
  • Line 94: security → request.security
111 more edits
  • Line 110: max → math.max
  • Line 115: tostring → str.tostring
  • Line 115: round → math.round
  • Line 116: tostring → str.tostring
  • Line 116: round → math.round
  • Line 116: min → math.min
  • Line 117: tostring → str.tostring
  • Line 117: round → math.round
  • Line 117: min → math.min
  • Line 125: tostring → str.tostring
  • Line 125: round → math.round
  • Line 126: tostring → str.tostring
  • Line 126: round → math.round
  • Line 126: min → math.min
  • Line 127: tostring → str.tostring
  • Line 127: round → math.round
  • Line 127: min → math.min
  • Line 135: barssince → ta.barssince
  • Line 135: change → ta.change
  • Line 136: cum → ta.cum
  • Line 137: cum → ta.cum
  • Line 189: ema → ta.ema
  • Line 189: ema → ta.ema
  • Line 189: ema → ta.ema
  • Line 221: abs → math.abs
  • Line 222: max → math.max
  • Line 225: abs → math.abs
  • Line 226: min → math.min
  • Line 237: avg → math.avg
  • Line 237: lowest → ta.lowest
  • Line 237: highest → ta.highest
  • Line 243: avg → math.avg
  • Line 263: round → math.round
  • Line 264: round → math.round
  • Line 265: round → math.round
  • Line 266: round → math.round
  • Line 267: round → math.round
  • Line 268: round → math.round
  • Line 269: round → math.round
  • Line 270: round → math.round
  • Line 283: security → request.security
  • Line 284: security → request.security
  • Line 285: security → request.security
  • Line 286: security → request.security
  • Line 293: security → request.security
  • Line 294: security → request.security
  • Line 295: security → request.security
  • Line 296: security → request.security
  • Line 318: crossover → ta.crossover
  • Line 319: crossover → ta.crossover
  • Line 320: max → math.max
  • Line 321: min → math.min
  • Line 322: max → math.max
  • Line 323: min → math.min
  • Line 324: crossover → ta.crossover
  • Line 325: crossover → ta.crossover
  • Line 363: crossover → ta.crossover
  • Line 364: crossover → ta.crossover
  • Line 365: max → math.max
  • Line 366: min → math.min
  • Line 367: max → math.max
  • Line 368: min → math.min
  • Line 369: crossover → ta.crossover
  • Line 370: crossover → ta.crossover
  • Line 391: max → math.max
  • Line 393: max → math.max
  • Line 393: max → math.max
  • Line 394: min → math.min
  • Line 394: min → math.min
  • Line 395: max → math.max
  • Line 395: max → math.max
  • Line 396: min → math.min
  • Line 396: min → math.min
  • Line 398: max → math.max
  • Line 469: transp = 0 → color.new(COLOR_TRANSPARENT, 0)
  • Line 475: transp = 0 → color.new(COLOR_TRANSPARENT, 0)
  • Line 481: transp = 0 → color.new(COLOR_GAP_KUMO, 0)
  • Line 489: transp = 0 → color.new(COLOR_SENKOUA_HIGHESTTF, 0)
  • Line 495: transp = 0 → color.new(COLOR_SENKOUB_HIGHESTTF, 0)
  • Line 501: transp = 0 → color.new(color_kumo_highestTf, 0)
  • Line 507: transp = 0 → color.new(COLOR_SENKOUA_BASEHTF, 0)
  • Line 513: transp = 0 → color.new(COLOR_SENKOUB_BASEHTF, 0)
  • Line 519: transp = 0 → color.new(color_kumo_baseHtf, 0)
  • Line 524: transp = 0 → color.new(COLOR_CHIKOU, 0)
  • Line 531: transp = 0 → color.new(COLOR_TENKAN, 0)
  • Line 536: transp = 0 → color.new(COLOR_KIJUN, 0)
  • Line 578: macd → ta.macd
  • Line 588: max → math.max
  • Line 590: max → math.max
  • Line 596: min → math.min
  • Line 598: min → math.min
  • Line 607: atr → ta.atr
  • Line 608: atr → ta.atr
  • Line 623: min → math.min
  • Line 624: max → math.max
  • Line 633: max → math.max
  • Line 636: max → math.max
  • Line 642: min → math.min
  • Line 645: min → math.min
  • Line 772: max → math.max
  • Line 774: max → math.max
  • Line 780: min → math.min
  • Line 782: min → math.min
  • Line 827: abs → math.abs
  • Line 827: abs → math.abs
  • Line 840: abs → math.abs
  • Line 852: long = true → direction = strategy.long
  • Line 856: long = false → direction = strategy.short
  • Line 861: long = true → direction = strategy.long
  • Line 867: long = false → direction = strategy.short
  • Line 917: transp = 95 → color.new(value_bgcolor, 95)
⋯// https://www.tradingview.com/script/UhhFWEus-MTF-Ichimoku-Takazudo/-//@version=4+//@version=5//@author=Takazudo⋯var _1 = input(true, "═════════ HTF ══════════")-var config_baseHtf = input("D", "Base Higher Timeframe", type = input.resolution)+var config_baseHtf = input.timeframe("D", "Base Higher Timeframe")var config_useHighestTf = input(true, "use Highest Timeframe (Kumo only)")-var config_highestTf= input("W", "Highest Timeframe", type = input.resolution)+var config_highestTf= input.timeframe("W", "Highest Timeframe")var _2 = input(true, "═════════ Ichimoku ══════════")⋯var config_atrLength = input(4, title = "Trailing stop ATR Length")-var config_atrSlMult = input(1, title = "Trailing stop ATR Multiple factor", type=input.float)+var config_atrSlMult = input.float(1, title = "Trailing stop ATR Multiple factor")-var config_atrEntryPaddingMult = input(0.5, title = "Entry padding ATR Multiple factor", type=input.float)+var config_atrEntryPaddingMult = input.float(0.5, title = "Entry padding ATR Multiple factor")var config_atrEntryPaddingLength = input(10, title = "Entry padding ATR Length")⋯    // _res: resolution of any TF (in "timeframe.period" string format).-    security(syminfo.tickerid, _res, f_resInMinutes())+    request.security(syminfo.tickerid, _res, f_resInMinutes())// ————— Given current resolution, returns next step of HTF.⋯    // Convert current float TF in minutes to target string TF in "timeframe.period" format.-    _targetResInMin = _res * max(_mult, 1)+    _targetResInMin = _res * math.max(_mult, 1)    // Find best string to express the resolution.⋯      _targetResInMin <= 0.501 ? "30S" :-      _targetResInMin <= 1440  ? tostring(round(_targetResInMin)) :+      _targetResInMin <= 1440  ? str.tostring(math.round(_targetResInMin)) :-      _targetResInMin <= 43800 ? tostring(round(min(_targetResInMin / 1440, 365))) + "D" :+      _targetResInMin <= 43800 ? str.tostring(math.round(math.min(_targetResInMin / 1440, 365))) + "D" :-      tostring(round(min(_targetResInMin / 43800, 12))) + "M"+      str.tostring(math.round(math.min(_targetResInMin / 43800, 12))) + "M"// ————— Converts a resolution expressed in float minutes into a string usable by "security()".⋯      _minutes   <= 0.5000       ? "30S" :-      _minutes   <= 1440         ? tostring(round(_minutes)) :+      _minutes   <= 1440         ? str.tostring(math.round(_minutes)) :-      _minutes   <= 43800        ? tostring(round(min(_minutes / 1440, 365))) + "D" :+      _minutes   <= 43800        ? str.tostring(math.round(math.min(_minutes / 1440, 365))) + "D" :-      tostring(round(min(_minutes / 43800, 12))) + "M"+      str.tostring(math.round(math.min(_minutes / 43800, 12))) + "M"// Returns the theoretical numbers of current chart bars in the given target HTF resolution (note that this number maybe very different from actual number on certain symbols).⋯    // _res: resolution of any TF (in "timeframe.period" string format).-    b = barssince(change(time(_res)))+    b = ta.barssince(ta.change(time(_res)))-    cumTotal = cum(b == 0 ? b[1] + 1 : 0)+    cumTotal = ta.cum(b == 0 ? b[1] + 1 : 0)-    cumCount = cum(b == 0 ? 1 : 0)+    cumCount = ta.cum(b == 0 ? 1 : 0)    cumTotal / cumCount⋯    // This smooth factor blends the value with previous values using ema.-    _smoothed = ema(ema(ema(_series, _f), _f), _f)+    _smoothed = ta.ema(ta.ema(ta.ema(_series, _f), _f), _f)    useSmooth ? _smoothed : _series⋯    fullPriceHeight = high-low-    bodyPriceHeight = abs(close-open)+    bodyPriceHeight = math.abs(close-open)-    (bodyPriceHeight < fullPriceHeight * 1/7) and (max(open, close) > (low + (high-low) * 2/3))+    (bodyPriceHeight < fullPriceHeight * 1/7) and (math.max(open, close) > (low + (high-low) * 2/3))f_isDownDoji() =>    fullPriceHeight = high-low-    bodyPriceHeight = abs(close-open)+    bodyPriceHeight = math.abs(close-open)-    (bodyPriceHeight < fullPriceHeight * 1/7) and (min(open, close) < (high - (high-low) * 2/3))+    (bodyPriceHeight < fullPriceHeight * 1/7) and (math.min(open, close) < (high - (high-low) * 2/3))f_isLastCandleUp() =>⋯f_donchian(len) =>-    avg(lowest(len), highest(len))+    math.avg(ta.lowest(len), ta.highest(len))f_tenkan() =>⋯f_senkouA(_tenkan, _kijun) =>-    avg(_tenkan, _kijun)+    math.avg(_tenkan, _kijun)f_senkouB() =>⋯chikouOffset = -config_chikouSpan + 1-senkouOffset_baseHtf = round((config_senkouSpan - 1) * barsMultipiller_baseHtf)+senkouOffset_baseHtf = math.round((config_senkouSpan - 1) * barsMultipiller_baseHtf)-chikouOffset_baseHtf = round((config_chikouSpan - 1) * barsMultipiller_baseHtf)+chikouOffset_baseHtf = math.round((config_chikouSpan - 1) * barsMultipiller_baseHtf)-senkouOffsetForPlot_baseHtf = round(senkouOffset * barsMultipiller_baseHtf)+senkouOffsetForPlot_baseHtf = math.round(senkouOffset * barsMultipiller_baseHtf)-chikouOffsetForPlot_baseHtf = round(-chikouOffset_baseHtf)+chikouOffsetForPlot_baseHtf = math.round(-chikouOffset_baseHtf)-senkouOffset_highestTf = useHighestTf ? round((config_senkouSpan - 1) * barsMultipiller_highestTf) : 0+senkouOffset_highestTf = useHighestTf ? math.round((config_senkouSpan - 1) * barsMultipiller_highestTf) : 0-chikouOffset_highestTf = useHighestTf ? round((config_chikouSpan - 1) * barsMultipiller_highestTf) : 0+chikouOffset_highestTf = useHighestTf ? math.round((config_chikouSpan - 1) * barsMultipiller_highestTf) : 0-senkouOffsetForPlot_highestTf = useHighestTf ? round(senkouOffset * barsMultipiller_highestTf) : 0+senkouOffsetForPlot_highestTf = useHighestTf ? math.round(senkouOffset * barsMultipiller_highestTf) : 0-chikouOffsetForPlot_highestTf = useHighestTf ? round(-chikouOffset_highestTf) : 0+chikouOffsetForPlot_highestTf = useHighestTf ? math.round(-chikouOffset_highestTf) : 0senkouSpanIndexDiff = senkouOffsetForPlot_highestTf - senkouOffsetForPlot_baseHtf⋯    _senkouB = f_senkouB()-    _htfTenkan = _useCurrentRes ? _tenkan : security(syminfo.tickerid, config_baseHtf, _tenkan)+    _htfTenkan = _useCurrentRes ? _tenkan : request.security(syminfo.tickerid, config_baseHtf, _tenkan)-    _htfKijun = _useCurrentRes ? _kijun : security(syminfo.tickerid, config_baseHtf, _kijun)+    _htfKijun = _useCurrentRes ? _kijun : request.security(syminfo.tickerid, config_baseHtf, _kijun)-    _htfSenkouA = _useCurrentRes ? _senkouA : security(syminfo.tickerid, config_baseHtf, _senkouA)+    _htfSenkouA = _useCurrentRes ? _senkouA : request.security(syminfo.tickerid, config_baseHtf, _senkouA)-    _htfSenkouB = _useCurrentRes ? _senkouB : security(syminfo.tickerid, config_baseHtf, _senkouB)+    _htfSenkouB = _useCurrentRes ? _senkouB : request.security(syminfo.tickerid, config_baseHtf, _senkouB)    [_htfTenkan, _htfKijun, _htfSenkouA, _htfSenkouB]⋯    _senkouB = f_senkouB()-    _highestTfTenkan = useHighestTf ? security(syminfo.tickerid, config_highestTf, _tenkan) : _tenkan+    _highestTfTenkan = useHighestTf ? request.security(syminfo.tickerid, config_highestTf, _tenkan) : _tenkan-    _highestTfKijun = useHighestTf ? security(syminfo.tickerid, config_highestTf, _kijun) : _kijun+    _highestTfKijun = useHighestTf ? request.security(syminfo.tickerid, config_highestTf, _kijun) : _kijun-    _highestTfSenkouA = useHighestTf ? security(syminfo.tickerid, config_highestTf, _senkouA) : _senkouA+    _highestTfSenkouA = useHighestTf ? request.security(syminfo.tickerid, config_highestTf, _senkouA) : _senkouA-    _highestTfSenkouB = useHighestTf ? security(syminfo.tickerid, config_highestTf, _senkouB) : _senkouB+    _highestTfSenkouB = useHighestTf ? request.security(syminfo.tickerid, config_highestTf, _senkouB) : _senkouB    [_highestTfTenkan, _highestTfKijun, _highestTfSenkouA, _highestTfSenkouB]⋯    _kumoColor_bull = senkouALine_baseHtf > senkouBLine_baseHtf-    _senkouCross_bull = crossover(senkouALine_baseHtf, senkouBLine_baseHtf)+    _senkouCross_bull = ta.crossover(senkouALine_baseHtf, senkouBLine_baseHtf)-    _senkouCross_bear = crossover(senkouBLine_baseHtf, senkouALine_baseHtf)+    _senkouCross_bear = ta.crossover(senkouBLine_baseHtf, senkouALine_baseHtf)-    _senkouSpanHigh = max(senkouALine_baseHtf[senkouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf])+    _senkouSpanHigh = math.max(senkouALine_baseHtf[senkouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf])-    _senkouSpanLow = min(senkouALine_baseHtf[senkouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf])+    _senkouSpanLow = math.min(senkouALine_baseHtf[senkouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf])-    _chikouKumoHigh = max(senkouALine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf])+    _chikouKumoHigh = math.max(senkouALine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf])-    _chikouKumoLow = min(senkouALine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf])+    _chikouKumoLow = math.min(senkouALine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf])-    _tenkanCross_bull = crossover(tenkanLine_baseHtf, kijunLine_baseHtf)+    _tenkanCross_bull = ta.crossover(tenkanLine_baseHtf, kijunLine_baseHtf)-    _tenkanCross_bear = crossover(kijunLine_baseHtf, tenkanLine_baseHtf)+    _tenkanCross_bear = ta.crossover(kijunLine_baseHtf, tenkanLine_baseHtf)    _tenkanAboveKijun = tenkanLine_baseHtf > kijunLine_baseHtf⋯    _kumoColor_bull = senkouALine_highestTf > senkouBLine_highestTf-    _senkouCross_bull = crossover(senkouALine_highestTf, senkouBLine_highestTf)+    _senkouCross_bull = ta.crossover(senkouALine_highestTf, senkouBLine_highestTf)-    _senkouCross_bear = crossover(senkouBLine_highestTf, senkouALine_highestTf)+    _senkouCross_bear = ta.crossover(senkouBLine_highestTf, senkouALine_highestTf)-    _senkouSpanCurrentHigh = max(senkouALine_highestTf[senkouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf])+    _senkouSpanCurrentHigh = math.max(senkouALine_highestTf[senkouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf])-    _senkouSpanCurrentLow = min(senkouALine_highestTf[senkouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf])+    _senkouSpanCurrentLow = math.min(senkouALine_highestTf[senkouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf])-    _chikouKumoHigh = max(senkouALine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf])+    _chikouKumoHigh = math.max(senkouALine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf])-    _chikouKumoLow = min(senkouALine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf])+    _chikouKumoLow = math.min(senkouALine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf])-    _tenkanCross_bull = crossover(tenkanLine_highestTf, kijunLine_highestTf)+    _tenkanCross_bull = ta.crossover(tenkanLine_highestTf, kijunLine_highestTf)-    _tenkanCross_bear = crossover(kijunLine_highestTf, tenkanLine_highestTf)+    _tenkanCross_bear = ta.crossover(kijunLine_highestTf, tenkanLine_highestTf)    _chikouAboveCandle := close > close[chikouOffset_highestTf]⋯f_calcGapKumo(_tf1_senkouA, _tf1_senkouB, _tf2_senkouA, _tf2_senkouB) =>-    _max = max(_tf1_senkouA, _tf1_senkouB, _tf2_senkouA, _tf2_senkouB)+    _max = math.max(_tf1_senkouA, _tf1_senkouB, _tf2_senkouA, _tf2_senkouB)    _tf1IsHigher = (_tf1_senkouA == _max) or (_tf1_senkouB == _max)-    _kumoA_max = _tf1IsHigher ? max(_tf1_senkouA, _tf1_senkouB) : max(_tf2_senkouA, _tf2_senkouB)+    _kumoA_max = _tf1IsHigher ? math.max(_tf1_senkouA, _tf1_senkouB) : math.max(_tf2_senkouA, _tf2_senkouB)-    _kumoA_min = _tf1IsHigher ? min(_tf1_senkouA, _tf1_senkouB) : min(_tf2_senkouA, _tf2_senkouB)+    _kumoA_min = _tf1IsHigher ? math.min(_tf1_senkouA, _tf1_senkouB) : math.min(_tf2_senkouA, _tf2_senkouB)-    _kumoB_max = _tf1IsHigher ? max(_tf2_senkouA, _tf2_senkouB) : max(_tf1_senkouA, _tf1_senkouB)+    _kumoB_max = _tf1IsHigher ? math.max(_tf2_senkouA, _tf2_senkouB) : math.max(_tf1_senkouA, _tf1_senkouB)-    _kumoB_min = _tf1IsHigher ? min(_tf2_senkouA, _tf2_senkouB) : min(_tf1_senkouA, _tf1_senkouB)+    _kumoB_min = _tf1IsHigher ? math.min(_tf2_senkouA, _tf2_senkouB) : math.min(_tf1_senkouA, _tf1_senkouB)    _kumoCrossed = false-    _gapKumo_high = max(_kumoA_max, _kumoB_max)+    _gapKumo_high = math.max(_kumoA_max, _kumoB_max)    _gapKumo_low = _gapKumo_high⋯  offset=senkouOffsetForPlot_baseHtf,-  color=COLOR_TRANSPARENT,-  transp=0,+  color=color.new(COLOR_TRANSPARENT, 0),  linewidth=1,⋯  offset=senkouOffsetForPlot_baseHtf,-  color=COLOR_TRANSPARENT,-  transp=0,+  color=color.new(COLOR_TRANSPARENT, 0),  linewidth=1,⋯fill(plot_gapKumo_high, plot_gapKumo_low,-  color=COLOR_GAP_KUMO,-  transp=0,+  color=color.new(COLOR_GAP_KUMO, 0),  title="Gap Kumo")⋯  offset=senkouOffsetForPlot_highestTf,-  color=COLOR_SENKOUA_HIGHESTTF,-  transp=0,+  color=color.new(COLOR_SENKOUA_HIGHESTTF, 0),  linewidth=1,⋯  offset=senkouOffsetForPlot_highestTf,-  color=COLOR_SENKOUB_HIGHESTTF,-  transp=0,+  color=color.new(COLOR_SENKOUB_HIGHESTTF, 0),  linewidth=1,⋯fill(plot_senkouA_highestTf, plot_senkouB_highestTf,-  color=color_kumo_highestTf,-  transp=0,+  color=color.new(color_kumo_highestTf, 0),  title="Highest TF Kumo")⋯  offset=senkouOffsetForPlot_baseHtf,-  color=COLOR_SENKOUA_BASEHTF,-  transp=0,+  color=color.new(COLOR_SENKOUA_BASEHTF, 0),  linewidth=1,⋯  offset=senkouOffsetForPlot_baseHtf,-  color=COLOR_SENKOUB_BASEHTF,-  transp=0,+  color=color.new(COLOR_SENKOUB_BASEHTF, 0),  linewidth=1,⋯fill(plot_senkouA_baseHtf, plot_senkouB_baseHtf,-  color=color_kumo_baseHtf,-  transp=0,+  color=color.new(color_kumo_baseHtf, 0),  title="Base HTF Kumo")⋯  offset=chikouOffsetForPlot_baseHtf,-  color=COLOR_CHIKOU,+  color=color.new(COLOR_CHIKOU, 0),-  linewidth=1,-  transp=0,+  linewidth=1,  title="Chikou-Span")⋯plot(smooth_tenkanLine_baseHtf,-  color=COLOR_TENKAN,+  color=color.new(COLOR_TENKAN, 0),-  linewidth=1,-  transp=0,+  linewidth=1,  title="Tenkan-Sen")plot(smooth_kijunLine_baseHtf,-  color=COLOR_KIJUN,+  color=color.new(COLOR_KIJUN, 0),-  linewidth=3,-  transp=0,+  linewidth=3,  title="Kijun-Sen")⋯f_isMacdUpTrend() =>-    [_macdLine, _signalLine, _] = macd(close, 12, 26, 9)+    [_macdLine, _signalLine, _] = ta.macd(close, 12, 26, 9)    _upTrend = _macdLine > _signalLine⋯    startIndex = 1-    highest = max(open[startIndex], close[startIndex])+    highest = math.max(open[startIndex], close[startIndex])    for i = startIndex to (config_recentBars - 1)-        current = max(open[i], close[i])+        current = math.max(open[i], close[i])        if highest < current⋯    startIndex = 1-    lowest = min(open[startIndex], close[startIndex])+    lowest = math.min(open[startIndex], close[startIndex])    for i = startIndex to (config_recentBars - 1)-        current = min(open[i], close[i])+        current = math.min(open[i], close[i])        if lowest > current⋯//============================================================================-entryPadding = config_atrEntryPaddingMult * atr(config_atrEntryPaddingLength)+entryPadding = config_atrEntryPaddingMult * ta.atr(config_atrEntryPaddingLength)-sl_val = config_atrSlMult * atr(config_atrLength)+sl_val = config_atrSlMult * ta.atr(config_atrLength)atrSl_long = low - sl_val⋯var mixedTrailingSl_short = hl2-mixedSlLong = min(atrSl_long, kumoBasedSlLong, recentLow)+mixedSlLong = math.min(atrSl_long, kumoBasedSlLong, recentLow)-mixedSlShort = max(atrSl_short, kumoBasedSlShort, recentHigh)+mixedSlShort = math.max(atrSl_short, kumoBasedSlShort, recentHigh)//plot(mixedSlLong, color=color.green, linewidth=2)⋯    //highest = high[3]-    highest = max(open[3], close[3])+    highest = math.max(open[3], close[3])    for i = 4 to (config_rangeDetectBars - 1)        //current = high[i]-        current = max(open[i], close[i])+        current = math.max(open[i], close[i])        if highest < current⋯    //lowest = low[3]-    lowest = min(open[3], close[3])+    lowest = math.min(open[3], close[3])    for i = 4 to (config_rangeDetectBars - 1)        //current = low[i]-        current = min(open[i], close[i])+        current = math.min(open[i], close[i])        if lowest > current⋯    startIndex = 2-    highest = max(open[startIndex], close[startIndex])+    highest = math.max(open[startIndex], close[startIndex])    for i = startIndex to (config_extraEntryStopDetectBars - 1)-        current = max(open[i], close[i])+        current = math.max(open[i], close[i])        if highest < current⋯    startIndex = 2-    lowest = min(open[startIndex], close[startIndex])+    lowest = math.min(open[startIndex], close[startIndex])    for i = startIndex to (config_extraEntryStopDetectBars - 1)-        current = min(open[i], close[i])+        current = math.min(open[i], close[i])        if lowest > current⋯var initialQty = 0-slPercentage = bullish ? abs(mixedTrailingSl_long-hl2)/hl2*100 : abs(mixedTrailingSl_short-hl2)/hl2*100+slPercentage = bullish ? math.abs(mixedTrailingSl_long-hl2)/hl2*100 : math.abs(mixedTrailingSl_short-hl2)/hl2*100qtyForInitialEntry = f_calcQtyForInitialEntry(slPercentage)⋯    anyTpTriggered := false-if hasAnyPositions and not anyTpTriggered and (abs(strategy.position_size) < initialQty)+if hasAnyPositions and not anyTpTriggered and (math.abs(strategy.position_size) < initialQty)    anyTpTriggered := true⋯            initialQty := qtyForInitialEntry-            strategy.entry(id="Long", long=true, stop=initialEntryStopPrice_long, qty=initialQty)+            strategy.entry(id="Long", direction = strategy.long, stop=initialEntryStopPrice_long, qty=initialQty)            previousEntryPrice := entryLimitHigh⋯            initialQty := qtyForInitialEntry-            strategy.entry(id="Short", long=false, stop=initialEntryStopPrice_short, qty=initialQty)+            strategy.entry(id="Short", direction = strategy.short, stop=initialEntryStopPrice_short, qty=initialQty)            previousEntryPrice := entryLimitLow⋯        previousEntryPrice := extraEntryStopLong-        strategy.entry(id="LongExtra", long=true, limit=extraEntryLimitPrice_long, qty=qtyForExtraEntry)+        strategy.entry(id="LongExtra", direction = strategy.long, limit=extraEntryLimitPrice_long, qty=qtyForExtraEntry)    else⋯        previousEntryPrice := extraEntryStopShort-        strategy.entry(id="ShortExtra", long=false, limit=extraEntryLimitPrice_short, qty=qtyForExtraEntry)+        strategy.entry(id="ShortExtra", direction = strategy.short, limit=extraEntryLimitPrice_short, qty=qtyForExtraEntry)    else⋯//value_bgcolor = pyramidingReady ? color.green : COLOR_TRANSPARENT-bgcolor(value_bgcolor, transp=95)+bgcolor(color.new(value_bgcolor, 95))

Clean v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 44: input() → input.bool()
  • Line 46: input() → input.bool()
  • Line 48: input() → input.bool()
  • Line 49: input() → input.int()
  • Line 50: input() → input.int()
  • Line 51: input() → input.int()
23 more edits
  • Line 52: input() → input.int()
  • Line 53: input() → input.int()
  • Line 54: input() → input.bool()
  • Line 55: input() → input.bool()
  • Line 56: input() → input.int()
  • Line 57: input() → input.bool()
  • Line 58: input() → input.bool()
  • Line 59: input() → input.bool()
  • Line 60: input() → input.bool()
  • Line 61: input() → input.bool()
  • Line 62: input() → input.int()
  • Line 63: input() → input.int()
  • Line 64: input() → input.int()
  • Line 65: input() → input.int()
  • Line 68: input() → input.int()
  • Line 69: input() → input.int()
  • Line 70: input() → input.bool()
  • Line 72: input() → input.int()
  • Line 73: input() → input.int()
  • Line 74: input() → input.int()
  • Line 76: input() → input.int()
  • Line 77: input() → input.int()
  • Line 78: input() → input.int()
⋯// HTF-var _1 = input(true, "═════════ HTF ══════════")+var _1 = input.bool(true, "═════════ HTF ══════════")var config_baseHtf = input.timeframe("D", "Base Higher Timeframe")-var config_useHighestTf = input(true, "use Highest Timeframe (Kumo only)")+var config_useHighestTf = input.bool(true, "use Highest Timeframe (Kumo only)")var config_highestTf= input.timeframe("W", "Highest Timeframe")-var _2 = input(true, "═════════ Ichimoku ══════════")+var _2 = input.bool(true, "═════════ Ichimoku ══════════")-var config_tenkanSen = input(9, minval=1, title="Tenkan-Sen Bars")+var config_tenkanSen = input.int(9, minval=1, title="Tenkan-Sen Bars")-var config_kijunSen = input(26, minval=1, title="Kijun-Sen Bars")+var config_kijunSen = input.int(26, minval=1, title="Kijun-Sen Bars")-var config_senkouSpanB = input(52, minval=1, title="Senkou-Span B Bars")+var config_senkouSpanB = input.int(52, minval=1, title="Senkou-Span B Bars")-var config_chikouSpan = input(26, minval=1, title="Chikou-Span Offset")+var config_chikouSpan = input.int(26, minval=1, title="Chikou-Span Offset")-var config_senkouSpan = input(26, minval=1, title="Senkou-Span Offset")+var config_senkouSpan = input.int(26, minval=1, title="Senkou-Span Offset")-var _3 = input(true, "═════════ Smooth Line ══════════")+var _3 = input.bool(true, "═════════ Smooth Line ══════════")-var config_useSmooth = input(true, "enable smooth line")+var config_useSmooth = input.bool(true, "enable smooth line")-var config_smoothFactor = input(2, minval=2, title="smooth factor")+var config_smoothFactor = input.int(2, minval=2, title="smooth factor")-var _4 = input(true, "═════════ MTF stuff ══════════")+var _4 = input.bool(true, "═════════ MTF stuff ══════════")-var config_autoSwitchToHtf = input(true, "avoid to refer lower resolution indicator")+var config_autoSwitchToHtf = input.bool(true, "avoid to refer lower resolution indicator")-var config_avoidTooHighResolution = input(true, "avoid to refer too high resolution indicator")+var config_avoidTooHighResolution = input.bool(true, "avoid to refer too high resolution indicator")-var config_useGapKumo = input(true, "use Gap Kumo")+var config_useGapKumo = input.bool(true, "use Gap Kumo")-var _5 = input(true, "═════════ etc ══════════")+var _5 = input.bool(true, "═════════ etc ══════════")-var config_bullDetectBars = input(defval = 3, title = "bull detection min bar count",  minval = 1)+var config_bullDetectBars = input.int(defval = 3, title = "bull detection min bar count",  minval = 1)-var config_rangeDetectBars = input(defval = 200, title = "range detection bar count",  minval = 1)+var config_rangeDetectBars = input.int(defval = 200, title = "range detection bar count",  minval = 1)-var config_recentBars = input(defval = 50, title = "recent bar count for SL",  minval = 1)+var config_recentBars = input.int(defval = 50, title = "recent bar count for SL",  minval = 1)-var config_atrLength = input(4, title = "Trailing stop ATR Length")+var config_atrLength = input.int(4, title = "Trailing stop ATR Length")var config_atrSlMult = input.float(1, title = "Trailing stop ATR Multiple factor")var config_atrEntryPaddingMult = input.float(0.5, title = "Entry padding ATR Multiple factor")-var config_atrEntryPaddingLength = input(10, title = "Entry padding ATR Length")+var config_atrEntryPaddingLength = input.int(10, title = "Entry padding ATR Length")-var config_extraEntryStopDetectBars = input(defval = 10, title = "Pyramiding entry recent detect bar count",  minval = 1)+var config_extraEntryStopDetectBars = input.int(defval = 10, title = "Pyramiding entry recent detect bar count",  minval = 1)-var _6 = input(true, "═════════ Backtesting range ══════════")+var _6 = input.bool(true, "═════════ Backtesting range ══════════")// From Date Inputs-fromYear  = input(defval = 2019, title = "From Year",  minval = 1970)+fromYear  = input.int(defval = 2019, title = "From Year",  minval = 1970)-fromMonth = input(defval = 1,    title = "From Month", minval = 1, maxval = 12)+fromMonth = input.int(defval = 1,    title = "From Month", minval = 1, maxval = 12)-fromDay   = input(defval = 1,    title = "From Day",   minval = 1, maxval = 31)+fromDay   = input.int(defval = 1,    title = "From Day",   minval = 1, maxval = 31)// To Date Inputs-toYear  = input(defval = 2021, title = "To Year",  minval = 1970)+toYear  = input.int(defval = 2021, title = "To Year",  minval = 1970)-toMonth = input(defval = 3,    title = "To Month", minval = 1, maxval = 12)+toMonth = input.int(defval = 3,    title = "To Month", minval = 1, maxval = 12)-toDay   = input(defval = 10,    title = "To Day",   minval = 1, maxval = 31)+toDay   = input.int(defval = 10,    title = "To Day",   minval = 1, maxval = 31)//============================================================================⋯

Does it run in Pine Script v6?

Not tested

Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// https://www.tradingview.com/script/UhhFWEus-MTF-Ichimoku-Takazudo/-//@version=5+//@version=6//@author=Takazudo⋯

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
═════════ HTF ══════════trueboolunused
Base Higher TimeframeDtimeframe (written input.resolution)barsMultipiller_baseHtf _target _htfTenkan _htfKijun _htfSenkouA _htfSenkouB
use Highest Timeframe (Kumo only)trueboolline 254
Highest TimeframeWtimeframe (written input.resolution)_target barsMultipiller_highestTf _highestTfTenkan _highestTfKijun _highestTfSenkouA _highestTfSenkouB
═════════ Ichimoku ══════════trueboolunused
Tenkan-Sen Bars9int · min 1line 239
Kijun-Sen Bars26int · min 1line 241
Senkou-Span B Bars52int · min 1line 245
Chikou-Span Offset26int · min 1chikouOffset chikouOffset_baseHtf chikouOffset_highestTf
Senkou-Span Offset26int · min 1senkouOffset senkouOffset_baseHtf senkouOffset_highestTf
═════════ Smooth Line ══════════trueboolunused
enable smooth linetruebooluseSmooth
smooth factor2int · min 2_f
═════════ MTF stuff ══════════trueboolunused
avoid to refer lower resolution indicatortruebool_useCurrentRes
avoid to refer too high resolution indicatortrueboolline 181
use Gap Kumotrueboolval_gapKumo_high val_gapKumo_low line 275
═════════ etc ══════════trueboolunused
bull detection min bar count3int · min 1line 562 line 565 line 568 line 571
range detection bar count200int · min 1line 634 line 643
recent bar count for SL50int · min 1line 589 line 597
Trailing stop ATR Length4intsl_val
Trailing stop ATR Multiple factor1floatsl_val
Entry padding ATR Multiple factor0.5floatentryPadding
Entry padding ATR Length10intentryPadding
Pyramiding entry recent detect bar count10int · min 1line 773 line 781
═════════ Backtesting range ══════════trueboolunused
From Year2019int · min 1970startDate
From Month1int · min 1 · max 12startDate
From Day1int · min 1 · max 31startDate
To Year2021int · min 1970finishDate
To Month3int · min 1 · max 12finishDate
To Day10int · min 1 · max 31finishDate

What it calculates

  • Barssince / Change (barssince, ta.barssince in v5)change(time(_res))b · line 135
  • CUM (cum, ta.cum in v5)b == 0 ? b[1] + 1 : 0cumTotal · line 136
  • CUM (cum, ta.cum in v5)b == 0 ? 1 : 0cumCount · line 137
  • EMA (ema, ta.ema in v5)ema(ema(_series, _f), _f), _f_smoothed · line 189
  • Crossover (crossover, ta.crossover in v5)senkouALine_highestTf, senkouBLine_highestTf_senkouCross_bull · line 363
  • Crossover (crossover, ta.crossover in v5)senkouBLine_highestTf, senkouALine_highestTf_senkouCross_bear · line 364
  • Crossover (crossover, ta.crossover in v5)tenkanLine_highestTf, kijunLine_highestTf_tenkanCross_bull · line 369
  • Crossover (crossover, ta.crossover in v5)kijunLine_highestTf, tenkanLine_highestTf_tenkanCross_bear · line 370
  • MACD (macd, ta.macd in v5)close, 12, 26, 9_macdLine · line 578
  • MACD (macd, ta.macd in v5)close, 12, 26, 9_signalLine · line 578
  • ATR (atr, ta.atr in v5)Entry padding ATR Length (10)entryPadding · line 607
  • ATR (atr, ta.atr in v5)Trailing stop ATR Length (4)sl_val · line 608

Signal flow

How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.

The script has 151 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open Long longshouldMakeEntryLongOn852
Open Short shortshouldMakeEntryShortOn856
Open LongExtra long(strategy.position_size > 0) and pyramidingReadyOn861
cancel LongExtra(strategy.position_size > 0) and pyramidingReadyOn863
Open ShortExtra short(strategy.position_size < 0) and pyramidingReadyOn867
cancel ShortExtra(strategy.position_size < 0) and pyramidingReadyOn869
cancel Longnot continuousBullOn872
cancel LongExtranot continuousBullOn873
cancel Shortnot continuousBearOn875
cancel ShortExtranot continuousBearOn876
Exit Long-TP stop and limit(time >= startDate and time <= finishDate)On878
Exit Long-SL stop(time >= startDate and time <= finishDate)On879
Exit LongExtra-SL/TP stop and limit(time >= startDate and time <= finishDate)On880
Exit Short-TP stop and limit(time >= startDate and time <= finishDate)On881
Exit Short-SL stop(time >= startDate and time <= finishDate)On882
Exit ShortExtra-SL/TP stop and limit(time >= startDate and time <= finishDate)On883

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Does it repaint?

No

No repainting patterns in the source.

Not measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • ClearHigher-timeframe data9 security call(s), none with lookahead on.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Other markets

The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D0.0%0.0%00%—0.0%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h0.0%0.0%00%—0.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D0.0%0.0%00%—0.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h0.0%0.0%00%—0.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D0.0%0.0%00%—0.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h0.0%0.0%00%—0.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D0.0%0.0%00%—0.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h0.0%0.0%00%—0.0%8 May 2026 – 21 Oct 2026

Higher-timeframe data for request.security(): BINANCE:BTCUSDT W (Binance BTCUSDT 1w), fetched from Binance's public market data for each market.

Backtests are simulations on historical data and are not investment advice.

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
2Tier Ichimoku Pyramiding [Takazudo] this page—v4 strategy0.0%00.0%
Mathias & Christer EMA by mattehalenema atr barssincev4 strategyNo trades on this market
Dazzling Bolts by OrcChieftainema atr barssincev4 strategy+8.5%1413.0%
Twin Range Filter Algo by OrcChieftainema atr barssincev4 strategy+48.4%186.8%
Oath by OrcChieftainema atr barssincev4 strategy+0.2%450.0%
[2022] MACD Cross Strategy (version 1) by spuckles12macd ema atrv5 strategydoes not run in Zeal Terminal

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 129 msWith a workaround 1,000 bars in 1,061 msNot measured
PineTSNo v5 and v6 only—Not measured

Zeal Terminal's engine currently reads an order side written as long = true, long = false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 852, 856, 861, 867) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// https://www.tradingview.com/script/UhhFWEus-MTF-Ichimoku-Takazudo///@version=4//@author=Takazudostrategy("2Tier Ichimoku Pyramiding [Takazudo]",  pyramiding=2,  overlay=true,  default_qty_type=strategy.fixed,  initial_capital=0,  currency=currency.USD)//============================================================================// consts, inputs//============================================================================// colorsvar COLOR_KIJUN = color.new(#fcb103, 20)var COLOR_TENKAN = color.new(#f57f17, 20)var COLOR_CHIKOU = color.new(#ffffff, 50)var COLOR_KUMO_BASEHTF_BULL = color.new(#315F2E, 60)var COLOR_KUMO_BASEHTF_BEAR = color.new(#802A1C, 60)var COLOR_KUMO_HIGHESTTF_BULL = color.new(#1D4F8A, 60)var COLOR_KUMO_HIGHESTTF_BEAR = color.new(#6B2B55, 60)var COLOR_SENKOUA_BASEHTF = color.new(#315F2E, 30)var COLOR_SENKOUB_BASEHTF = color.new(#802A1C, 30)var COLOR_SENKOUA_HIGHESTTF = color.new(#1D4F8A, 30)var COLOR_SENKOUB_HIGHESTTF = color.new(#6B2B55, 30)var COLOR_CROSS_POINT_BULL = color.new(#315F2E, 20)var COLOR_CROSS_POINT_BEAR = color.new(#802A1C, 20)var COLOR_CHIKOU_CROSS_POINT_BULL = color.new(#315F2E, 20)var COLOR_CHIKOU_CROSS_POINT_BEAR = color.new(#802A1C, 20)var COLOR_CHIKOU_KUMO_BREAKOUT_BULL = color.new(#315F2E, 0)var COLOR_CHIKOU_KUMO_BREAKOUT_BEAR = color.new(#802A1C, 0)var COLOR_CHIKOU_HINT_BULL = color.new(#315F2E, 0)var COLOR_CHIKOU_HINT_BEAR = color.new(#802A1C, 0)var COLOR_SENKOU_CROSS_HINT_BULL = color.new(#315F2E, 0)var COLOR_SENKOU_CROSS_HINT_BEAR = color.new(#802A1C, 0)var COLOR_TENKAN_CROSS_BG = color.new(#f2931d, 90)var COLOR_CHIKOU_BREAKOUT_BG = color.new(#656565, 90)var COLOR_SENKOU_CROSS_BG = color.new(#7a73d8, 90)var COLOR_GAP_KUMO = color.new(#FCC02C, 97)var COLOR_RANGE_EDGE = color.new(#43A6F5, 30)var COLOR_RESISTANCE_PRICE_LINE = color.new(#e0f64d, 20)var COLOR_TRANSPARENT = color.new(#000000, 100)// HTFvar _1 = input(true, "═════════ HTF ══════════")var config_baseHtf = input("D", "Base Higher Timeframe", type = input.resolution)var config_useHighestTf = input(true, "use Highest Timeframe (Kumo only)")var config_highestTf= input("W", "Highest Timeframe", type = input.resolution)var _2 = input(true, "═════════ Ichimoku ══════════")var config_tenkanSen = input(9, minval=1, title="Tenkan-Sen Bars")var config_kijunSen = input(26, minval=1, title="Kijun-Sen Bars")var config_senkouSpanB = input(52, minval=1, title="Senkou-Span B Bars")var config_chikouSpan = input(26, minval=1, title="Chikou-Span Offset")var config_senkouSpan = input(26, minval=1, title="Senkou-Span Offset")var _3 = input(true, "═════════ Smooth Line ══════════")var config_useSmooth = input(true, "enable smooth line")var config_smoothFactor = input(2, minval=2, title="smooth factor")var _4 = input(true, "═════════ MTF stuff ══════════")var config_autoSwitchToHtf = input(true, "avoid to refer lower resolution indicator")var config_avoidTooHighResolution = input(true, "avoid to refer too high resolution indicator")var config_useGapKumo = input(true, "use Gap Kumo")var _5 = input(true, "═════════ etc ══════════")var config_bullDetectBars = input(defval = 3, title = "bull detection min bar count",  minval = 1)var config_rangeDetectBars = input(defval = 200, title = "range detection bar count",  minval = 1)var config_recentBars = input(defval = 50, title = "recent bar count for SL",  minval = 1)var config_atrLength = input(4, title = "Trailing stop ATR Length")var config_atrSlMult = input(1, title = "Trailing stop ATR Multiple factor", type=input.float)var config_atrEntryPaddingMult = input(0.5, title = "Entry padding ATR Multiple factor", type=input.float)var config_atrEntryPaddingLength = input(10, title = "Entry padding ATR Length")var config_extraEntryStopDetectBars = input(defval = 10, title = "Pyramiding entry recent detect bar count",  minval = 1)var _6 = input(true, "═════════ Backtesting range ══════════")// From Date InputsfromYear  = input(defval = 2019, title = "From Year",  minval = 1970)fromMonth = input(defval = 1,    title = "From Month", minval = 1, maxval = 12)fromDay   = input(defval = 1,    title = "From Day",   minval = 1, maxval = 31)// To Date InputstoYear  = input(defval = 2021, title = "To Year",  minval = 1970)toMonth = input(defval = 3,    title = "To Month", minval = 1, maxval = 12)toDay   = input(defval = 10,    title = "To Day",   minval = 1, maxval = 31)//============================================================================// MTF Selection Framework// http://www.pinecoders.com/faq_and_code/#other-intervals-mtf//============================================================================// ————— Converts current "timeframe.multiplier" plus the TF into minutes of type float.f_resInMinutes() =>    _resInMinutes = timeframe.multiplier * (      timeframe.isseconds ? 1. / 60. :      timeframe.isminutes ? 1.       :      timeframe.isdaily   ? 1440.    :      timeframe.isweekly  ? 10080.   :      timeframe.ismonthly ? 43800.   : na)// ————— Returns resolution of _resolution period in minutes.f_tfResInMinutes(_res) =>    // _res: resolution of any TF (in "timeframe.period" string format).    security(syminfo.tickerid, _res, f_resInMinutes())// ————— Given current resolution, returns next step of HTF.f_resNextStep(_res) =>    // _res: current TF in fractional minutes.    _res    <= 1        ? "15"  :      _res  <= 5        ? "60"  :      _res  <= 30       ? "240" :      _res  <= 60       ? "1D"  :      _res  <= 360      ? "3D"  :      _res  <= 1440     ? "1W"  :      _res  <= 10080    ? "1M"  : "12M"// ————— Returns a multiple of current resolution as a string in "timeframe.period" format usable with "security()".f_multipleOfRes(_res, _mult) =>    // _res:  current resolution in minutes, in the fractional format supplied by f_resInMinutes() companion function.    // _mult: Multiple of current TF to be calculated.    // Convert current float TF in minutes to target string TF in "timeframe.period" format.    _targetResInMin = _res * max(_mult, 1)    // Find best string to express the resolution.    _targetResInMin   <= 0.083 ? "5S"  :      _targetResInMin <= 0.251 ? "15S" :      _targetResInMin <= 0.501 ? "30S" :      _targetResInMin <= 1440  ? tostring(round(_targetResInMin)) :      _targetResInMin <= 43800 ? tostring(round(min(_targetResInMin / 1440, 365))) + "D" :      tostring(round(min(_targetResInMin / 43800, 12))) + "M"// ————— Converts a resolution expressed in float minutes into a string usable by "security()".// See our FAQ & Code for an example of using this function: http://www.pinecoders.com/faq_and_code/#how-can-i-convert-a-resolution-in-float-minutes-into-a-string-usable-with-securityf_resFromMinutes(_minutes) =>    _minutes     <= 0.0167       ? "1S"  :      _minutes   <= 0.0834       ? "5S"  :      _minutes   <= 0.2500       ? "15S" :      _minutes   <= 0.5000       ? "30S" :      _minutes   <= 1440         ? tostring(round(_minutes)) :      _minutes   <= 43800        ? tostring(round(min(_minutes / 1440, 365))) + "D" :      tostring(round(min(_minutes / 43800, 12))) + "M"// Returns the theoretical numbers of current chart bars in the given target HTF resolution (note that this number maybe very different from actual number on certain symbols).f_theoreticalDilationOf(_res) =>    // _res: resolution of any TF (in "timeframe.period" string format).    f_tfResInMinutes(_res) / f_resInMinutes()// Returns the average number of current chart bars in the given target HTF resolution (this reflects the dataset's history).f_avgDilationOf(_res) =>    // _res: resolution of any TF (in "timeframe.period" string format).    b = barssince(change(time(_res)))    cumTotal = cum(b == 0 ? b[1] + 1 : 0)    cumCount = cum(b == 0 ? 1 : 0)    cumTotal / cumCount// ————— Print a label at end of chart.f_htfLabel(_txt, _y, _color, _offsetLabels) =>    _t = int(time + (f_resInMinutes() * _offsetLabels * 60000))    // Create the label on the dataset's first bar.    var _lbl = label.new(_t, _y, _txt, xloc.bar_time, yloc.price, #00000000, label.style_none, color.gray, size.large)    if barstate.islast        // Rather than delete and recreate the label on every realtime bar update,        // simply update the label's information; it's more efficient.        label.set_xy(_lbl, _t, _y)        label.set_text(_lbl, _txt)        label.set_textcolor(_lbl, _color)// }//============================================================================// utils, setup//============================================================================// initializevar tenkanLine_baseHtf = 0.0var kijunLine_baseHtf = 0.0var senkouALine_baseHtf = 0.0var senkouBLine_baseHtf = 0.0var tenkanLine_highestTf = 0.0var kijunLine_highestTf = 0.0var senkouALine_highestTf = 0.0var senkouBLine_highestTf = 0.0var gapKumo_high = 0.0var gapKumo_low = 0.0f_isUsingHtf() =>    _current = f_resInMinutes()    _target = f_tfResInMinutes(config_baseHtf)    _current < _targetf_isOverHtf() =>    _current = f_resInMinutes()    _target = f_tfResInMinutes(config_baseHtf)    _current > _targetf_isOverHighestTf() =>    _current = f_resInMinutes()    _target = f_tfResInMinutes(config_highestTf)    _current >= _targetf_shouldAvoidHighestTf(barsMultipiller) =>    // it the resolution was too high, requested candle sticks    // hit the limit of trading view.    // this function detects the limit    config_avoidTooHighResolution and barsMultipiller > 150var useSmooth = f_isUsingHtf() and config_useSmoothf_smooth(_series) =>    _f = config_smoothFactor    // Tricky part. the lines that refers higher Timeframe got zig-zag    // because the granularity of the value per bar is the same    // inside the higher timeframe's one bar length.    // This smooth factor blends the value with previous values using ema.    _smoothed = ema(ema(ema(_series, _f), _f), _f)    useSmooth ? _smoothed : _serieslostPositionsInPrevBar = strategy.position_size == 0 and (strategy.position_size[0] != strategy.position_size[1])// remember entry pricevar previousEntryPrice = hl2//============================================================================// entry quantity caliculation// wider SL = less quantities//============================================================================f_calcQtyForInitialEntry(_percentage) =>    if _percentage < 1        10000    else if _percentage < 2        8000    else if _percentage < 3        6000    else        4000f_calcQtyForExtraEntry(_percentage) =>    if _percentage < 1        5000    else if _percentage < 2        4000    else if _percentage < 3        3000    else        2000//============================================================================// candle actions//============================================================================f_isUpDoji() =>    fullPriceHeight = high-low    bodyPriceHeight = abs(close-open)    (bodyPriceHeight < fullPriceHeight * 1/7) and (max(open, close) > (low + (high-low) * 2/3))f_isDownDoji() =>    fullPriceHeight = high-low    bodyPriceHeight = abs(close-open)    (bodyPriceHeight < fullPriceHeight * 1/7) and (min(open, close) < (high - (high-low) * 2/3))f_isLastCandleUp() =>    result = false    (close > open) or f_isUpDoji()f_isLastCandleDown() =>    result = false    (close < open) or f_isDownDoji()//============================================================================// Ichimoku calcs//============================================================================f_donchian(len) =>    avg(lowest(len), highest(len))f_tenkan() =>    f_donchian(config_tenkanSen)f_kijun() =>    f_donchian(config_kijunSen)f_senkouA(_tenkan, _kijun) =>    avg(_tenkan, _kijun)f_senkouB() =>    f_donchian(config_senkouSpanB)barsMultipiller_baseHtf = f_isOverHtf() ? 1 : f_theoreticalDilationOf(config_baseHtf)barsMultipiller_highestTf = f_isOverHighestTf() ? 1 : f_theoreticalDilationOf(config_highestTf)shouldAvoidHighestTf = f_shouldAvoidHighestTf(barsMultipiller_highestTf)f_calcUseHighestTf() =>    _result = true    if shouldAvoidHighestTf        _result := false    else        if config_useHighestTf            if f_isOverHighestTf()                _result := false            else                _result := true    _resultvar useHighestTf = f_calcUseHighestTf()senkouOffset = config_senkouSpan - 1chikouOffset = -config_chikouSpan + 1senkouOffset_baseHtf = round((config_senkouSpan - 1) * barsMultipiller_baseHtf)chikouOffset_baseHtf = round((config_chikouSpan - 1) * barsMultipiller_baseHtf)senkouOffsetForPlot_baseHtf = round(senkouOffset * barsMultipiller_baseHtf)chikouOffsetForPlot_baseHtf = round(-chikouOffset_baseHtf)senkouOffset_highestTf = useHighestTf ? round((config_senkouSpan - 1) * barsMultipiller_highestTf) : 0chikouOffset_highestTf = useHighestTf ? round((config_chikouSpan - 1) * barsMultipiller_highestTf) : 0senkouOffsetForPlot_highestTf = useHighestTf ? round(senkouOffset * barsMultipiller_highestTf) : 0chikouOffsetForPlot_highestTf = useHighestTf ? round(-chikouOffset_highestTf) : 0senkouSpanIndexDiff = senkouOffsetForPlot_highestTf - senkouOffsetForPlot_baseHtf// not sure why but it says negative index was detectedif senkouSpanIndexDiff < 0    senkouSpanIndexDiff := 0if not useHighestTf or not config_useGapKumo    senkouSpanIndexDiff := 0f_calcIchimoku_baseHtf() =>    _useCurrentRes = config_autoSwitchToHtf and f_isOverHtf()    _tenkan = f_tenkan()    _kijun = f_kijun()    _senkouA = f_senkouA(_tenkan[0], _kijun[0])    _senkouB = f_senkouB()    _htfTenkan = _useCurrentRes ? _tenkan : security(syminfo.tickerid, config_baseHtf, _tenkan)    _htfKijun = _useCurrentRes ? _kijun : security(syminfo.tickerid, config_baseHtf, _kijun)    _htfSenkouA = _useCurrentRes ? _senkouA : security(syminfo.tickerid, config_baseHtf, _senkouA)    _htfSenkouB = _useCurrentRes ? _senkouB : security(syminfo.tickerid, config_baseHtf, _senkouB)    [_htfTenkan, _htfKijun, _htfSenkouA, _htfSenkouB]f_calcIchimoku_highestTf() =>    _tenkan = f_tenkan()    _kijun = f_kijun()    _senkouA = f_senkouA(_tenkan[0], _kijun[0])    _senkouB = f_senkouB()    _highestTfTenkan = useHighestTf ? security(syminfo.tickerid, config_highestTf, _tenkan) : _tenkan    _highestTfKijun = useHighestTf ? security(syminfo.tickerid, config_highestTf, _kijun) : _kijun    _highestTfSenkouA = useHighestTf ? security(syminfo.tickerid, config_highestTf, _senkouA) : _senkouA    _highestTfSenkouB = useHighestTf ? security(syminfo.tickerid, config_highestTf, _senkouB) : _senkouB    [_highestTfTenkan, _highestTfKijun, _highestTfSenkouA, _highestTfSenkouB]//--------------------------------------// HTF Ichimoku values[_htfTenkan, _htfKijun, _htfSenkouA, _htfSenkouB] = f_calcIchimoku_baseHtf()tenkanLine_baseHtf := _htfTenkankijunLine_baseHtf := _htfKijunsenkouALine_baseHtf := _htfSenkouAsenkouBLine_baseHtf := _htfSenkouB//--------------------------------------// Highest TF Ichimoku values[_highestTfTenkan, _highestTfKijun, _highestTfSenkouA, _highestTfSenkouB] = f_calcIchimoku_highestTf()tenkanLine_highestTf := _highestTfTenkankijunLine_highestTf := _highestTfKijunsenkouALine_highestTf := _highestTfSenkouAsenkouBLine_highestTf := _highestTfSenkouBf_calcIchimokuSignals_baseHtf() =>    var _chikouAboveCandle = false    var _chikouBelowCandle = false    var _chikouAboveKumo = false    var _chikouBelowKumo = false    _kumoColor_bull = senkouALine_baseHtf > senkouBLine_baseHtf    _senkouCross_bull = crossover(senkouALine_baseHtf, senkouBLine_baseHtf)    _senkouCross_bear = crossover(senkouBLine_baseHtf, senkouALine_baseHtf)    _senkouSpanHigh = max(senkouALine_baseHtf[senkouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf])    _senkouSpanLow = min(senkouALine_baseHtf[senkouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf])    _chikouKumoHigh = max(senkouALine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf])    _chikouKumoLow = min(senkouALine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf])    _tenkanCross_bull = crossover(tenkanLine_baseHtf, kijunLine_baseHtf)    _tenkanCross_bear = crossover(kijunLine_baseHtf, tenkanLine_baseHtf)    _tenkanAboveKijun = tenkanLine_baseHtf > kijunLine_baseHtf    _tenkanBelowKijun = tenkanLine_baseHtf < kijunLine_baseHtf    _chikouAboveCandle := close > close[chikouOffset_baseHtf]    _chikouBelowCandle := close < close[chikouOffset_baseHtf]    _chikouCross_bull = _chikouAboveCandle and not _chikouAboveCandle[1]    _chikouCross_bear = _chikouBelowCandle and not _chikouBelowCandle[1]    _chikouAboveKumo := close > _chikouKumoHigh    _chikouBelowKumo := close < _chikouKumoLow    _currentInKumo = (_senkouSpanLow <= close) and (close <= _senkouSpanHigh)    _currentTouchingKumo = not _currentInKumo and      (((low <= _senkouSpanHigh) and (low >= _senkouSpanLow)) or      ((high >= _senkouSpanLow) and (high <= _senkouSpanHigh)))    _currentAboveKumo = close > _senkouSpanHigh    _currentBelowKumo = close < _senkouSpanLow    _chikouInKumo = (_chikouKumoLow <= close) and (close <= _chikouKumoHigh)    _chikouTouchingKumo = not _chikouInKumo and      (((low <= _chikouKumoHigh) and (low >= _chikouKumoLow)) or      ((high >= _chikouKumoLow) and (high <= _chikouKumoHigh)))    _chikouKumoBreakout_bull = _chikouAboveKumo and not _chikouAboveKumo[1]    _chikouKumoBreakout_bear = _chikouBelowKumo and not _chikouBelowKumo[1]    [_currentInKumo, _currentTouchingKumo, _kumoColor_bull, _senkouCross_bull, _senkouCross_bear,      _senkouSpanHigh, _senkouSpanLow,      _chikouKumoHigh, _chikouKumoLow,      _chikouAboveCandle, _chikouBelowCandle,      _tenkanCross_bull, _tenkanCross_bear,      _tenkanAboveKijun, _tenkanBelowKijun,      _chikouCross_bull, _chikouCross_bear,      _chikouAboveKumo, _chikouBelowKumo,      _chikouKumoBreakout_bull, _chikouKumoBreakout_bear,      _currentAboveKumo, _currentBelowKumo,      _chikouInKumo, _chikouTouchingKumo]f_calcIchimokuSignals_highestTf() =>    var _chikouAboveCandle = false    var _chikouBelowCandle = false    var _chikouAboveKumo = false    var _chikouBelowKumo = false    _kumoColor_bull = senkouALine_highestTf > senkouBLine_highestTf    _senkouCross_bull = crossover(senkouALine_highestTf, senkouBLine_highestTf)    _senkouCross_bear = crossover(senkouBLine_highestTf, senkouALine_highestTf)    _senkouSpanCurrentHigh = max(senkouALine_highestTf[senkouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf])    _senkouSpanCurrentLow = min(senkouALine_highestTf[senkouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf])    _chikouKumoHigh = max(senkouALine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf])    _chikouKumoLow = min(senkouALine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf])    _tenkanCross_bull = crossover(tenkanLine_highestTf, kijunLine_highestTf)    _tenkanCross_bear = crossover(kijunLine_highestTf, tenkanLine_highestTf)    _chikouAboveCandle := close > close[chikouOffset_highestTf]    _chikouBelowCandle := close < close[chikouOffset_highestTf]    _chikouCross_bull = _chikouAboveCandle and not _chikouAboveCandle[1]    _chikouCross_bear = _chikouBelowCandle and not _chikouBelowCandle[1]    _chikouAboveKumo := close > _chikouKumoHigh    _chikouBelowKumo := close < _chikouKumoLow    _chikouKumoBreakout_bull = _chikouAboveKumo and not _chikouAboveKumo[1]    _chikouKumoBreakout_bear = _chikouBelowKumo and not _chikouBelowKumo[1]    _currentAboveKumo = close > _senkouSpanCurrentHigh    _currentBelowKumo = close < _senkouSpanCurrentLow    [_kumoColor_bull, _senkouCross_bull, _senkouCross_bear,      _senkouSpanCurrentHigh, _senkouSpanCurrentLow,      _chikouKumoHigh, _chikouKumoLow,      _chikouAboveCandle, _chikouBelowCandle,      _tenkanCross_bull, _tenkanCross_bear,      _chikouCross_bull, _chikouCross_bear,      _chikouAboveKumo, _chikouBelowKumo,      _chikouKumoBreakout_bull, _chikouKumoBreakout_bear,      _currentAboveKumo, _currentBelowKumo]f_calcGapKumo(_tf1_senkouA, _tf1_senkouB, _tf2_senkouA, _tf2_senkouB) =>    _max = max(_tf1_senkouA, _tf1_senkouB, _tf2_senkouA, _tf2_senkouB)    _tf1IsHigher = (_tf1_senkouA == _max) or (_tf1_senkouB == _max)    _kumoA_max = _tf1IsHigher ? max(_tf1_senkouA, _tf1_senkouB) : max(_tf2_senkouA, _tf2_senkouB)    _kumoA_min = _tf1IsHigher ? min(_tf1_senkouA, _tf1_senkouB) : min(_tf2_senkouA, _tf2_senkouB)    _kumoB_max = _tf1IsHigher ? max(_tf2_senkouA, _tf2_senkouB) : max(_tf1_senkouA, _tf1_senkouB)    _kumoB_min = _tf1IsHigher ? min(_tf2_senkouA, _tf2_senkouB) : min(_tf1_senkouA, _tf1_senkouB)    _kumoCrossed = false    _gapKumo_high = max(_kumoA_max, _kumoB_max)    _gapKumo_low = _gapKumo_high    if _kumoA_max > _kumoB_max        if _kumoA_min < _kumoB_max            _kumoCrossed := true        else            _gapKumo_high := _kumoA_min            _gapKumo_low := _kumoB_max    else        if _kumoB_min < _kumoA_max            _kumoCrossed := true        else            _gapKumo_high := _kumoB_min            _gapKumo_low := _kumoA_max    [_kumoCrossed, _gapKumo_high, _gapKumo_low]//============================================================================// calc Ichimoku values for plot//============================================================================//--------------------------------------// HTF Ichimoku signals[currentInKumo_baseHtf, _, kumoColor_bull_baseHtf, _, _,  senkouSpanHigh_baseHtf, senkouSpanLow_baseHtf,  _, _,  chikouAboveCandle_baseHtf, chikouBelowCandle_baseHtf,  _, _,  tenkanAboveKijun_baseHtf, tenkanBelowKijun_baseHtf,  _, _,  chikouAboveKumo_baseHtf, chikouBelowKumo_baseHtf,  _, _,  currentAboveKumo_baseHtf, currentBelowKumo_baseHtf,  _, _] = f_calcIchimokuSignals_baseHtf()//--------------------------------------// Highest TF Ichimoku signals[kumoColor_bull_highestTf, senkouCross_bull_highestTf, senkouCross_bear_highestTf,  senkouSpanHigh_highestTf, senkouSpanLow_highestTf,  _, _,  _, _,  tenkanCross_bull_highestTf, tenkanCross_bear_highestTf,  chikouCross_bull_highestTf, chikouCross_bear_highestTf,  _, _,  chikouKumoBreakout_bull_highestTf, chikouKumoBreakout_bear_highestTf,  currentAboveKumo_highestTf, currentBelowKumo_highestTf] = f_calcIchimokuSignals_highestTf()//--------------------------------------// smooth linessmooth_tenkanLine_baseHtf = f_smooth(tenkanLine_baseHtf)smooth_kijunLine_baseHtf = f_smooth(kijunLine_baseHtf)smooth_senkouALine_baseHtf = f_smooth(senkouALine_baseHtf)smooth_senkouBLine_baseHtf = f_smooth(senkouBLine_baseHtf)//smooth_tenkanLine_highestTf = f_smooth(tenkanLine_highestTf)//smooth_kijunLine_highestTf = f_smooth(kijunLine_highestTf)smooth_senkouALine_highestTf = f_smooth(senkouALine_highestTf)smooth_senkouBLine_highestTf = f_smooth(senkouBLine_highestTf)//--------------------------------------// gap kumo//max_bars_back(senkouALine_highestTf, 600)//max_bars_back(senkouBLine_highestTf, 600)[_, _gapKumo_high, _gapKumo_low] = f_calcGapKumo(  senkouALine_baseHtf,  senkouBLine_baseHtf,  senkouALine_highestTf[senkouSpanIndexDiff],  senkouBLine_highestTf[senkouSpanIndexDiff])gapKumo_high := _gapKumo_highgapKumo_low := _gapKumo_lowsmooth_gapKumo_high = f_smooth(gapKumo_high)smooth_gapKumo_low = f_smooth(gapKumo_low)//============================================================================// plot stuffs//============================================================================// gap kumoval_gapKumo_high = useHighestTf and config_useGapKumo ? smooth_gapKumo_high : naval_gapKumo_low = useHighestTf and config_useGapKumo ? smooth_gapKumo_low : naplot_gapKumo_high = plot(val_gapKumo_high,  offset=senkouOffsetForPlot_baseHtf,  color=COLOR_TRANSPARENT,  transp=0,  linewidth=1,  title="Gap Kumo High")plot_gapKumo_low = plot(val_gapKumo_low,  offset=senkouOffsetForPlot_baseHtf,  color=COLOR_TRANSPARENT,  transp=0,  linewidth=1,  title="Gap Kumo LOW")fill(plot_gapKumo_high, plot_gapKumo_low,  color=COLOR_GAP_KUMO,  transp=0,  title="Gap Kumo")// kumo HighestTFplotVal_senkouA_highestTf = useHighestTf ? smooth_senkouALine_highestTf : naplotVal_senkouB_highestTf = useHighestTf ? smooth_senkouBLine_highestTf : nacolor_kumo_highestTf = kumoColor_bull_highestTf ? COLOR_KUMO_HIGHESTTF_BULL : COLOR_KUMO_HIGHESTTF_BEARplot_senkouA_highestTf = plot(plotVal_senkouA_highestTf,  offset=senkouOffsetForPlot_highestTf,  color=COLOR_SENKOUA_HIGHESTTF,  transp=0,  linewidth=1,  title="Highest TFSenkou-Span A")plot_senkouB_highestTf = plot(plotVal_senkouB_highestTf,  offset=senkouOffsetForPlot_highestTf,  color=COLOR_SENKOUB_HIGHESTTF,  transp=0,  linewidth=1,  title="Highest TFSenkou-Span B")fill(plot_senkouA_highestTf, plot_senkouB_highestTf,  color=color_kumo_highestTf,  transp=0,  title="Highest TF Kumo")// kumo HTFcolor_kumo_baseHtf = kumoColor_bull_baseHtf ? COLOR_KUMO_BASEHTF_BULL : COLOR_KUMO_BASEHTF_BEARplot_senkouA_baseHtf = plot(smooth_senkouALine_baseHtf,  offset=senkouOffsetForPlot_baseHtf,  color=COLOR_SENKOUA_BASEHTF,  transp=0,  linewidth=1,  title="Base HTF: Senkou-Span A")plot_senkouB_baseHtf = plot(smooth_senkouBLine_baseHtf,  offset=senkouOffsetForPlot_baseHtf,  color=COLOR_SENKOUB_BASEHTF,  transp=0,  linewidth=1,  title="Base HTF: Senkou-Span B")fill(plot_senkouA_baseHtf, plot_senkouB_baseHtf,  color=color_kumo_baseHtf,  transp=0,  title="Base HTF Kumo")// chikouplot(close,  offset=chikouOffsetForPlot_baseHtf,  color=COLOR_CHIKOU,  linewidth=1,  transp=0,  title="Chikou-Span")// tenkan & kijunplot(smooth_tenkanLine_baseHtf,  color=COLOR_TENKAN,  linewidth=1,  transp=0,  title="Tenkan-Sen")plot(smooth_kijunLine_baseHtf,  color=COLOR_KIJUN,  linewidth=3,  transp=0,  title="Kijun-Sen")//============================================================================// backtest duration//============================================================================// Calculate start/end date and time conditionstartDate  = timestamp(fromYear, fromMonth, fromDay, 00, 00)finishDate = timestamp(toYear,   toMonth,   toDay,   00, 00)//============================================================================// bullish / bearish detection//============================================================================var bullish = falsevar bearish = false// detect bullish or bearish by many incidentsbullish := kumoColor_bull_baseHtf and chikouAboveCandle_baseHtf and  tenkanAboveKijun_baseHtf and chikouAboveKumo_baseHtf and  currentAboveKumo_baseHtf and currentAboveKumo_highestTfbearish := not kumoColor_bull_baseHtf and chikouBelowCandle_baseHtf and  tenkanBelowKijun_baseHtf and chikouBelowKumo_baseHtf and  currentBelowKumo_baseHtf and currentBelowKumo_highestTf// calc continuous bullish or bearishf_isContinuousBull() =>    inTrend = 0    for i = 0 to (config_bullDetectBars-1)        if bullish[i]            inTrend := inTrend + 1    inTrend == config_bullDetectBarsf_isContinuousBear() =>    inTrend = 0    for i = 0 to (config_bullDetectBars-1)        if bearish[i]            inTrend := inTrend + 1    inTrend == config_bullDetectBarscontinuousBull = f_isContinuousBull()continuousBear = f_isContinuousBear()//============================================================================// MACD//============================================================================f_isMacdUpTrend() =>    [_macdLine, _signalLine, _] = macd(close, 12, 26, 9)    _upTrend = _macdLine > _signalLine// calc macd for entrymacdUpTrend = f_isMacdUpTrend()macdDownTrend = not macdUpTrend//============================================================================// recent high / low//============================================================================f_calcRecentHigh() =>    startIndex = 1    highest = max(open[startIndex], close[startIndex])    for i = startIndex to (config_recentBars - 1)        current = max(open[i], close[i])        if highest < current            highest := current    highestf_calcRecentLow() =>    startIndex = 1    lowest = min(open[startIndex], close[startIndex])    for i = startIndex to (config_recentBars - 1)        current = min(open[i], close[i])        if lowest > current            lowest := current    lowestrecentHigh = f_calcRecentHigh()recentLow = f_calcRecentLow()//============================================================================// ATR based stuff//============================================================================entryPadding = config_atrEntryPaddingMult * atr(config_atrEntryPaddingLength)sl_val = config_atrSlMult * atr(config_atrLength)atrSl_long = low - sl_valatrSl_short = high + sl_val//============================================================================// Kumo based SL//============================================================================kumoBasedSlLong = (senkouSpanHigh_baseHtf + atrSl_long) / 2kumoBasedSlShort = (senkouSpanLow_baseHtf + atrSl_short) / 2//============================================================================// Mixed SL//============================================================================var initialEntryTpPrice_long = hl2var initialEntryTpPrice_short = hl2var mixedTrailingSl_long = hl2var mixedTrailingSl_short = hl2mixedSlLong = min(atrSl_long, kumoBasedSlLong, recentLow)mixedSlShort = max(atrSl_short, kumoBasedSlShort, recentHigh)//plot(mixedSlLong, color=color.green, linewidth=2)//plot(mixedSlShort, color=color.red, linewidth=2)//============================================================================// Range Edge caliculation//============================================================================// calc range edgef_calcRangeEdge_high() =>    //highest = high[3]    highest = max(open[3], close[3])    for i = 4 to (config_rangeDetectBars - 1)        //current = high[i]        current = max(open[i], close[i])        if highest < current            highest := current    highestf_calcRangeEdge_low() =>    //lowest = low[3]    lowest = min(open[3], close[3])    for i = 4 to (config_rangeDetectBars - 1)        //current = low[i]        current = min(open[i], close[i])        if lowest > current            lowest := current    lowestentryLimitHigh = f_calcRangeEdge_high()entryLimitLow = f_calcRangeEdge_low()plot(entryLimitHigh, color=COLOR_RANGE_EDGE, linewidth=1)plot(entryLimitLow, color=COLOR_RANGE_EDGE, linewidth=1)//============================================================================// entry timing judge//============================================================================f_trendStatsChanged() =>    var trendStats = 0    var kumoBull = false    var kumoBear = false    var kumoRanged = false    kumoBull := currentAboveKumo_baseHtf and currentAboveKumo_highestTf    kumoBear := currentBelowKumo_baseHtf and currentBelowKumo_highestTf    kumoRanged := not kumoBull and not kumoBear    if kumoRanged        trendStats := 0        // respect recent bullish or bearish        if kumoBull[1] or kumoBull[2] or kumoBull[3] or kumoBear[1] or kumoBear[2] or kumoBear[3]            trendStats := trendStats[1]    if kumoBull        trendStats := 1    if kumoBear        trendStats := -1    trendStats[1] != trendStats[0]trendStatsChanged = f_trendStatsChanged()var isFirstEntry = truevar resistancePrice = hl2var rangeBreakSignalDetected = falsevar rangeBreakMacdReversalDetected = falsevar rangeBreakConfirmed = false//--------------------------------------// reset flags// if trend stats changed, reset flagsif trendStatsChanged    isFirstEntry := true    rangeBreakSignalDetected := false    rangeBreakMacdReversalDetected := false    rangeBreakConfirmed := falseelse    // if has no positions    if strategy.position_size == 0        isFirstEntry := isFirstEntry[1]        // if lost positions in prev bar        if lostPositionsInPrevBar            rangeBreakSignalDetected := false            rangeBreakConfirmed := false        else            rangeBreakSignalDetected := rangeBreakSignalDetected[1]            rangeBreakConfirmed := rangeBreakConfirmed[1]    // if has any position    else        isFirstEntry := false // no more first entry        resistancePrice := hl2 // no resistance price//--------------------------------------// 1st entry confirmationvar firstReverseAfterTrendChange = falsevar trendConfirmed = false// this operation is for the 1st entryif isFirstEntry    if bullish        // wait for the short reversal for confirmation        if not firstReverseAfterTrendChange and not rangeBreakMacdReversalDetected            if macdDownTrend                rangeBreakMacdReversalDetected := true        if rangeBreakMacdReversalDetected            if macdUpTrend                trendConfirmed := true    if bearish        if not firstReverseAfterTrendChange and not rangeBreakMacdReversalDetected            if macdUpTrend                rangeBreakMacdReversalDetected := true        if rangeBreakMacdReversalDetected            if macdDownTrend                trendConfirmed := trueelse    trendConfirmed := false    firstReverseAfterTrendChange := falseif (bullish[0] != bullish[1]) or (bearish[0] != bearish[1])    trendConfirmed := false// plot trend confirmationif (trendConfirmed[0] == true) and (trendConfirmed[1] == false)    if bullish        label.new(bar_index, low, 'Trend Confirmed', style=label.style_triangleup, size=size.tiny, color=#ffffff, textcolor=#ffffff)    else        label.new(bar_index, high, 'Trend Confirmed', style=label.style_triangledown, size=size.tiny, color=#ffffff, textcolor=#ffffff)//--------------------------------------// later entry confirmationif strategy.position_size == 0    // this operation is for later entry    if isFirstEntry        resistancePrice := hl2    else        // if range break was detected, set flag        if not rangeBreakSignalDetected and continuousBull and entryLimitHigh < close            rangeBreakSignalDetected := true        if not rangeBreakSignalDetected and continuousBear and close < entryLimitLow            rangeBreakSignalDetected := true        // after range break, wait for short MACD reversal.        // after this confirmation, make stop entry        if rangeBreakSignalDetected            if senkouSpanHigh_baseHtf < close                resistancePrice := entryLimitHigh                if macdDownTrend                    rangeBreakConfirmed := true            if senkouSpanLow_baseHtf > close                resistancePrice := entryLimitLow                if macdUpTrend                    rangeBreakConfirmed := true// plot rangebreak detectionif (rangeBreakSignalDetected[0] == true) and (rangeBreakSignalDetected[1] == false)    if bullish        label.new(bar_index, low, 'Rangebreak detected', style=label.style_triangleup, size=size.tiny, color=#ffffff, textcolor=#ffffff)    else        label.new(bar_index, high, 'Rangebreak detected', style=label.style_triangledown, size=size.tiny, color=#ffffff, textcolor=#ffffff)// plot resistance price lineresitancePriceColor = rangeBreakConfirmed and strategy.position_size == 0 ? COLOR_RESISTANCE_PRICE_LINE : COLOR_TRANSPARENTplot(resistancePrice, linewidth=4, color=resitancePriceColor)//============================================================================// Pyramiding entry judge//============================================================================f_calcExtraEntryStopForShort() =>    startIndex = 2    highest = max(open[startIndex], close[startIndex])    for i = startIndex to (config_extraEntryStopDetectBars - 1)        current = max(open[i], close[i])        if highest < current            highest := current    highestf_calcExtraEntryStopForLong() =>    startIndex = 2    lowest = min(open[startIndex], close[startIndex])    for i = startIndex to (config_extraEntryStopDetectBars - 1)        current = min(open[i], close[i])        if lowest > current            lowest := current    lowestextraEntryStopLong = f_calcExtraEntryStopForLong() + entryPaddingextraEntryStopShort = f_calcExtraEntryStopForShort() - entryPaddingextraEntryStop = bullish ? extraEntryStopLong :  bearish ? extraEntryStopShort :  hl2extraEntryStopColor = (bullish or bearish) ? color.green : COLOR_TRANSPARENT// plot as lineplot(extraEntryStop, color=extraEntryStopColor, linewidth=2)//============================================================================// entry, TP, SL//============================================================================shouldMakeEntryLong = continuousBull and ((isFirstEntry and trendConfirmed) or (rangeBreakConfirmed and close > resistancePrice))shouldMakeEntryShort = continuousBear and ((isFirstEntry and trendConfirmed) or (rangeBreakConfirmed and close < resistancePrice))// TP caliculationif strategy.position_size == 0    initialEntryTpPrice_long := entryLimitHigh + (hl2 - extraEntryStopLong)    initialEntryTpPrice_short := entryLimitLow - (extraEntryStopShort - hl2)// SL caliculationmixedTrailingSl_long := if ((strategy.position_size == 0) and shouldMakeEntryLong) or ((strategy.position_size > 0) and (mixedTrailingSl_long < mixedSlLong))    mixedSlLongelse if (strategy.position_size == 0) or (strategy.position_size < 0)    hl2else    mixedTrailingSl_long[1]mixedTrailingSl_short := if ((strategy.position_size == 0) and shouldMakeEntryShort) or ((strategy.position_size < 0) and (mixedTrailingSl_short > mixedSlShort))    mixedSlShortelse if (strategy.position_size == 0) or (strategy.position_size > 0)    hl2else    mixedTrailingSl_short[1]// final entry priceinitialEntryStopPrice_long = entryLimitHigh + entryPaddinginitialEntryStopPrice_short = entryLimitLow - entryPaddingextraEntryLimitPrice_long = extraEntryStopLongextraEntryLimitPrice_short = extraEntryStopShortextraEntryTpPrice_long = entryLimitHigh + entryPaddingextraEntryTpPrice_short = entryLimitLow - entryPadding//============================================================================// Quantitiy caliculation//============================================================================var initialQty = 0slPercentage = bullish ? abs(mixedTrailingSl_long-hl2)/hl2*100 : abs(mixedTrailingSl_short-hl2)/hl2*100qtyForInitialEntry = f_calcQtyForInitialEntry(slPercentage)qtyForExtraEntry = f_calcQtyForExtraEntry(slPercentage)//============================================================================// Pyramiding judge//============================================================================var anyTpTriggered = falsevar hasAnyPositions = falseif strategy.position_size != 0 and strategy.position_size[1] == 0    hasAnyPositions := trueif strategy.position_size == 0 and strategy.position_size[1] != 0    hasAnyPositions := false    anyTpTriggered := falseif hasAnyPositions and not anyTpTriggered and (abs(strategy.position_size) < initialQty)    anyTpTriggered := truepyramidingReady =  (anyTpTriggered and bullish and (extraEntryStopLong > previousEntryPrice) and f_isLastCandleUp()) or  (anyTpTriggered and bearish and (extraEntryStopShort < previousEntryPrice) and f_isLastCandleDown())//============================================================================// make entries//============================================================================if (time >= startDate and time <= finishDate)    if strategy.position_size == 0        if shouldMakeEntryLong            initialQty := qtyForInitialEntry            strategy.entry(id="Long", long=true, stop=initialEntryStopPrice_long, qty=initialQty)            previousEntryPrice := entryLimitHigh        if shouldMakeEntryShort            initialQty := qtyForInitialEntry            strategy.entry(id="Short", long=false, stop=initialEntryStopPrice_short, qty=initialQty)            previousEntryPrice := entryLimitLow    // Long pyramiding    if (strategy.position_size > 0) and pyramidingReady        previousEntryPrice := extraEntryStopLong        strategy.entry(id="LongExtra", long=true, limit=extraEntryLimitPrice_long, qty=qtyForExtraEntry)    else        strategy.cancel(id="LongExtra")    // Short pyramiding    if (strategy.position_size < 0) and pyramidingReady        previousEntryPrice := extraEntryStopShort        strategy.entry(id="ShortExtra", long=false, limit=extraEntryLimitPrice_short, qty=qtyForExtraEntry)    else        strategy.cancel(id="ShortExtra")    // cancel stop entries    if not continuousBull        strategy.cancel(id="Long")        strategy.cancel(id="LongExtra")    if not continuousBear        strategy.cancel(id="Short")        strategy.cancel(id="ShortExtra")    // TP, SL    strategy.exit('Long-TP', 'Long', stop=mixedTrailingSl_long, limit=initialEntryTpPrice_long, qty=(initialQty/2))    strategy.exit('Long-SL', 'Long', stop=mixedTrailingSl_long)    strategy.exit('LongExtra-SL/TP', 'LongExtra', stop=mixedTrailingSl_long, limit=extraEntryTpPrice_long)    strategy.exit('Short-TP', 'Short', stop=mixedTrailingSl_short, limit=initialEntryTpPrice_short, qty=(initialQty/2))    strategy.exit('Short-SL', 'Short', stop=mixedTrailingSl_short)    strategy.exit('ShortExtra-SL/TP', 'ShortExtra', stop=mixedTrailingSl_short, limit=extraEntryTpPrice_short)//============================================================================// plot SL, TP//============================================================================sl = if strategy.position_size > 0    mixedTrailingSl_longelse if strategy.position_size < 0    mixedTrailingSl_shortelse    natp = if hasAnyPositions and not anyTpTriggered    strategy.position_size > 0 ? initialEntryTpPrice_long : initialEntryTpPrice_shortelse    naplot(sl, color=color.red, style=plot.style_cross, linewidth=2, title="SL")plot(tp, color=color.blue, style=plot.style_cross, linewidth=2, title="T")//============================================================================// debug//============================================================================// continuous bull / bear checkvalue_bgcolor = continuousBull ? color.green : continuousBear ? color.red: color.new(#000000, 100)// MACD up or down check//value_bgcolor = macdUpTrend ? color.green : color.red// both kumo bull//value_bgcolor = (kumoColor_bull_baseHtf and kumoColor_bull_highestTf) ? color.green://  (not kumoColor_bull_baseHtf and not kumoColor_bull_highestTf) ? color.red: color.new(#000000, 100)// doji//dojiUp = bullish and f_isUpDoji()//dojiDown = bearish and f_isDownDoji()//value_bgcolor = dojiUp ? color.green ://  dojiDown ? color.red ://  COLOR_TRANSPARENT//value_bgcolor = f_isLastCandleUp() ? color.green : COLOR_TRANSPARENT//value_bgcolor = pyramidingReady ? color.green : COLOR_TRANSPARENTbgcolor(value_bgcolor, transp=95)