Zeal Terminal Open Zeal Terminal

Pine Script v4 · Strategy

Backtesting 3commas DCA Bot v2

A Pine Script v4 strategy built on RSI (close, 7), SMA or Stoch (rsi1, rsi1, rsi1, 14, 3) and SMA (K, 3). It has 10 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 0.1% commission. 18 settings; defaults include Take Profit (%) 4.5, Trailing Take Profit (%) [0 = Disabled] 0.0 and Stop Loss (%) [0 = Disabled] 0.0.

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 Backtesting 3commas DCA Bot v2 repaint?
No
No repainting patterns were found in the source.
Can Backtesting 3commas DCA Bot v2 be converted to Pine Script v5?
Not tested
The steps are shown below, but the original does not run in Zeal Terminal's engine, so they could not be checked.
Does Backtesting 3commas DCA Bot v2 use a stop loss?
Yes
strategy.exit sets a stop on line 426, 430, 446.
Does Backtesting 3commas DCA Bot v2 run in Zeal Terminal?
No
Not yet: Pine Script v4 Error at @L479:C34: Undeclared identifier 'tonumber'.
Does not run in Zeal Terminal yetPine Script v4 Error at @L479:C34: Undeclared identifier 'tonumber'. The settings, logic and review below are read from the source, which does not need a run.

Review

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

  • Note

    No slippage

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

  • Note

    Uses long =, which v5 renamed line 395

    long = on line 395, 397, 405, 407. 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 tostring → str.tostring, pow → math.pow, rsi → ta.rsi, sma → ta.sma, stoch → ta.stoch, sum → math.sum, avg → math.avg, lowest → ta.lowest, highest → ta.highest, ema → ta.ema, hma → ta.hma, vwma → ta.vwma, cci → ta.cci, dmi → ta.dmi, mom → ta.mom, macd → ta.macd, wpr → ta.wpr, crossover → ta.crossover, crossunder → ta.crossunder, security → request.security, abs → math.abs, max → math.max, min → math.min.

v4 → v5

Not verified

The v4 script does not run in Zeal Terminal's engine (Pine Script v4 Error at @L479:C34: Undeclared identifier 'tonumber'.), so this step could not be checked.

  • Line 3: //@version=4 → //@version=5
  • Line 12: input(type = input.float) → input.float()
  • Line 14: input(type = input.float) → input.float()
  • Line 15: input(type = input.float) → input.float()
  • Line 17: input(type = input.float) → input.float()
  • Line 18: input(type = input.float) → input.float()
102 more edits
  • Line 20: input(type = input.float) → input.float()
  • Line 21: input(type = input.float) → input.float()
  • Line 22: input(type = input.float) → input.float()
  • Line 26: input(type = input.resolution) → input.timeframe()
  • Line 28: input(type = input.time) → input.time()
  • Line 29: input(type = input.time) → input.time()
  • Line 54: tostring → str.tostring
  • Line 54: tostring → str.tostring
  • Line 54: tostring → str.tostring
  • Line 58: pow → math.pow
  • Line 64: pow → math.pow
  • Line 94: rsi → ta.rsi
  • Line 107: sma → ta.sma
  • Line 107: sma → ta.sma
  • Line 110: rsi → ta.rsi
  • Line 111: sma → ta.sma
  • Line 111: stoch → ta.stoch
  • Line 112: sma → ta.sma
  • Line 117: sum → math.sum
  • Line 117: tr → ta.tr
  • Line 118: sum → math.sum
  • Line 118: tr → ta.tr
  • Line 119: sum → math.sum
  • Line 119: tr → ta.tr
  • Line 120: sum → math.sum
  • Line 121: sum → math.sum
  • Line 122: sum → math.sum
  • Line 133: avg → math.avg
  • Line 133: lowest → ta.lowest
  • Line 133: highest → ta.highest
  • Line 137: avg → math.avg
  • Line 144: sma → ta.sma
  • Line 145: sma → ta.sma
  • Line 146: sma → ta.sma
  • Line 147: sma → ta.sma
  • Line 148: sma → ta.sma
  • Line 149: sma → ta.sma
  • Line 151: ema → ta.ema
  • Line 152: ema → ta.ema
  • Line 153: ema → ta.ema
  • Line 154: ema → ta.ema
  • Line 155: ema → ta.ema
  • Line 156: ema → ta.ema
  • Line 158: hma → ta.hma
  • Line 161: vwma → ta.vwma
  • Line 167: rsi → ta.rsi
  • Line 173: sma → ta.sma
  • Line 173: stoch → ta.stoch
  • Line 174: sma → ta.sma
  • Line 177: cci → ta.cci
  • Line 181: dmi → ta.dmi
  • Line 189: mom → ta.mom
  • Line 191: macd → ta.macd
  • Line 195: wpr → ta.wpr
  • Line 198: ema → ta.ema
  • Line 199: ema → ta.ema
  • Line 206: ema → ta.ema
  • Line 294: crossover → ta.crossover
  • Line 294: crossunder → ta.crossunder
  • Line 378: security → request.security
  • Line 379: security → request.security
  • Line 395: long = strategy.long → direction = strategy.long
  • Line 397: long = strategy.short → direction = strategy.short
  • Line 403: tostring → str.tostring
  • Line 405: long = strategy.long → direction = strategy.long
  • Line 407: long = strategy.short → direction = strategy.short
  • Line 412: abs → math.abs
  • Line 439: max → math.max
  • Line 442: min → math.min
  • Line 448: crossunder → ta.crossunder
  • Line 454: max → math.max
  • Line 461: text is reserved in v5: renamed text_
  • Line 461: tostring → str.tostring
  • Line 471: tostring → str.tostring
  • Line 472: tostring → str.tostring
  • Line 474: tostring → str.tostring
  • Line 476: tostring → str.tostring
  • Line 478: tostring → str.tostring
  • Line 478: tostring → str.tostring
  • Line 482: tostring → str.tostring
  • Line 482: tostring → str.tostring
  • Line 494: tostring → str.tostring
  • Line 494: tostring → str.tostring
  • Line 495: tostring → str.tostring
  • Line 496: tostring → str.tostring
  • Line 496: tostring → str.tostring
  • Line 497: tostring → str.tostring
  • Line 497: tostring → str.tostring
  • Line 497: tostring → str.tostring
  • Line 498: tostring → str.tostring
  • Line 499: tostring → str.tostring
  • Line 499: tostring → str.tostring
  • Line 501: tostring → str.tostring
  • Line 502: tostring → str.tostring
  • Line 502: max → math.max
  • Line 503: tostring → str.tostring
  • Line 503: tostring → str.tostring
  • Line 504: tostring → str.tostring
  • Line 506: tostring → str.tostring
  • Line 512: tostring → str.tostring
  • Line 512: tostring → str.tostring
  • Line 513: tostring → str.tostring
⋯// © rouxam-//@version=4+//@version=5// Author: rouxam⋯// -----------------------------------take_profit             = input(4.5, type=input.float,  title="Take Profit (%)", minval=0.0, step=0.1)/100+take_profit             = input.float(4.5,  title="Take Profit (%)", minval=0.0, step=0.1)/100take_profit_type        = input(defval="% from total volume", title="Take Profit Type", options=["% from total volume", "% from base order"])-ttp                     = input(0.0, type=input.float,  title="Trailing Take Profit (%) [0 = Disabled]", minval=0.0, step=0.1)/100+ttp                     = input.float(0.0,  title="Trailing Take Profit (%) [0 = Disabled]", minval=0.0, step=0.1)/100-stop_loss               = input(0.0, type=input.float,  title="Stop Loss (%) [0 = Disabled]", minval=0.0, step=0.1)/100+stop_loss               = input.float(0.0,  title="Stop Loss (%) [0 = Disabled]", minval=0.0, step=0.1)/100order_size_type         = input(defval="Fixed",         title="Order Size Type", options=["Fixed", "% of equity"])-base_order              = input(100.0, type=input.float,title="Base Order") +base_order              = input.float(100.0,title="Base Order") -safe_order              = input(140.0, type=input.float,title="Safety Order") +safe_order              = input.float(140.0,title="Safety Order") max_safe_order          = input(6,                      title="Max Safety Trades Count", minval=0, maxval=99, step=1) -price_deviation         = input(1.5, type=input.float,  title="Price deviation to open safety order (%)", minval=0.0, step=0.1)/100+price_deviation         = input.float(1.5,  title="Price deviation to open safety order (%)", minval=0.0, step=0.1)/100-safe_order_volume_scale = input(1.5, type=input.float,  title="Safety Order Volume Scale", step=0.1) +safe_order_volume_scale = input.float(1.5,  title="Safety Order Volume Scale", step=0.1) -safe_order_step_scale   = input(1.6, type=input.float,  title="Safety Order Step Scale", step=0.1) +safe_order_step_scale   = input.float(1.6,  title="Safety Order Step Scale", step=0.1) dsc                     = input(defval="RSI-7",         title="Deal Start Condition", options=["Start ASAP", "RSI-7", "TV presets"])⋯dsc_technicals          = input(defval="Strong",        title="[TV presets only] Strength", options=["Strong", "Weak"])-dsc_res                 = input("",                     title="[RSI-7 and TV presets Only] Indicator Timeframe", type=input.resolution)+dsc_res                 = input.timeframe("",                     title="[RSI-7 and TV presets Only] Indicator Timeframe")bot_direction           = input(defval="Long",          title="Bot Direction", options=["Long", "Short"])-start_time              = input(defval=timestamp("15 June 2021 06:00"),   title="Start Time",     type=input.time)+start_time              = input.time(defval=timestamp("15 June 2021 06:00"),   title="Start Time")-end_time                = input(defval=timestamp("31 Dec 2021 20:00"),   title="End Time",       type=input.time)+end_time                = input.time(defval=timestamp("31 Dec 2021 20:00"),   title="End Time")// ----------------------------------⋯// -----------------------------------pretty_date(t) => tostring(dayofmonth(t)) + "/" + tostring(month(t)) + "/" + tostring(year(t))+pretty_date(t) => str.tostring(dayofmonth(t)) + "/" + str.tostring(month(t)) + "/" + str.tostring(year(t))within_window() => time >= start_time and time <= end_time⋯safe_order_size() => order_size_type == "Fixed" ? safe_order : safe_order/100 * strategy.equity-safety_order_deviation(index) => price_deviation * pow(safe_order_step_scale,  index - 1)+safety_order_deviation(index) => price_deviation * math.pow(safe_order_step_scale,  index - 1)safety_order_price(index, last_safety_order_price) => ⋯        last_safety_order_price * (1 + safety_order_deviation(index))-safety_order_qty(index) => safe_order_size() * pow(safe_order_volume_scale, index - 1)+safety_order_qty(index) => safe_order_size() * math.pow(safe_order_volume_scale, index - 1)max_amount_for_bot_usage() =>⋯    // Regular strat would be crossover but not for 3C DCA Bot-    rsi7 = rsi(close, 7)+    rsi7 = ta.rsi(close, 7)    if IS_LONG⋯AO() => -    sma(hl2, 5) - sma(hl2, 34)+    ta.sma(hl2, 5) - ta.sma(hl2, 34)// Stochastic RSIStochRSI() =>-    rsi1 = rsi(close, 14)+    rsi1 = ta.rsi(close, 14)-    K = sma(stoch(rsi1, rsi1, rsi1, 14), 3)+    K = ta.sma(ta.stoch(rsi1, rsi1, rsi1, 14), 3)-    D = sma(K, 3)+    D = ta.sma(K, 3)    [K, D]⋯uo(ShortLen, MiddlLen, LongLen) =>-    Value1 = sum(tr, ShortLen)+    Value1 = math.sum(ta.tr, ShortLen)-    Value2 = sum(tr, MiddlLen)+    Value2 = math.sum(ta.tr, MiddlLen)-    Value3 = sum(tr, LongLen)+    Value3 = math.sum(ta.tr, LongLen)-    Value4 = sum(close - tl(), ShortLen)+    Value4 = math.sum(close - tl(), ShortLen)-    Value5 = sum(close - tl(), MiddlLen)+    Value5 = math.sum(close - tl(), MiddlLen)-    Value6 = sum(close - tl(), LongLen)+    Value6 = math.sum(close - tl(), LongLen)    float UO = na⋯// Ichimoku Cloud-donchian(len) => avg(lowest(len), highest(len))+donchian(len) => math.avg(ta.lowest(len), ta.highest(len))ichimoku_cloud() =>⋯    baseLine = donchian(26)-    leadLine1 = avg(conversionLine, baseLine)+    leadLine1 = math.avg(conversionLine, baseLine)    leadLine2 = donchian(52)⋯    //============== MA =================-    SMA10 = sma(close, 10)+    SMA10 = ta.sma(close, 10)-    SMA20 = sma(close, 20)+    SMA20 = ta.sma(close, 20)-    SMA30 = sma(close, 30)+    SMA30 = ta.sma(close, 30)-    SMA50 = sma(close, 50)+    SMA50 = ta.sma(close, 50)-    SMA100 = sma(close, 100)+    SMA100 = ta.sma(close, 100)-    SMA200 = sma(close, 200)+    SMA200 = ta.sma(close, 200)    -    EMA10 = ema(close, 10)+    EMA10 = ta.ema(close, 10)-    EMA20 = ema(close, 20)+    EMA20 = ta.ema(close, 20)-    EMA30 = ema(close, 30)+    EMA30 = ta.ema(close, 30)-    EMA50 = ema(close, 50)+    EMA50 = ta.ema(close, 50)-    EMA100 = ema(close, 100)+    EMA100 = ta.ema(close, 100)-    EMA200 = ema(close, 200)+    EMA200 = ta.ema(close, 200)    -    HullMA9 = hma(close, 9)+    HullMA9 = ta.hma(close, 9)        // Volume Weighted Moving Average (VWMA)-    VWMA = vwma(close, 20)+    VWMA = ta.vwma(close, 20)    ⋯    // Relative Strength Index, RSI-    RSI = rsi(close,14)+    RSI = ta.rsi(close,14)    ⋯    smoothDStoch = 3-    kStoch = sma(stoch(close, high, low, lengthStoch), smoothKStoch)+    kStoch = ta.sma(ta.stoch(close, high, low, lengthStoch), smoothKStoch)-    dStoch = sma(kStoch, smoothDStoch)+    dStoch = ta.sma(kStoch, smoothDStoch)        // Commodity Channel Index, CCI-    CCI = cci(close, 20)+    CCI = ta.cci(close, 20)    ⋯    float adxValue = na, float adxPlus = na, float adxMinus = na-    [P, M, V] = dmi(14, 14)+    [P, M, V] = ta.dmi(14, 14)    adxValue := V⋯    // Momentum-    Mom = mom(close, 10)+    Mom = ta.mom(close, 10)    // Moving Average Convergence/Divergence, MACD-    [macdMACD, signalMACD, _] = macd(close, 12, 26, 9)+    [macdMACD, signalMACD, _] = ta.macd(close, 12, 26, 9)    // Stochastic RSI⋯    // Williams Percent Range-    WR = wpr(14)+    WR = ta.wpr(14)        // Bull / Bear Power-    BullPower = high - ema(close, 13)+    BullPower = high - ta.ema(close, 13)-    BearPower = low - ema(close, 13)+    BearPower = low - ta.ema(close, 13)    // Ultimate Oscillator⋯    -    PriceAvg = ema(close, 50)+    PriceAvg = ta.ema(close, 50)    DownTrend = close < PriceAvg⋯        ratingOtherC := ratingOtherC + 1-        ratingOther := ratingOther + calcRating(crossover(ao,0) or (ao > 0 and ao[1] > 0 and ao > ao[1] and ao[2] > ao[1]), crossunder(ao,0) or (ao < 0 and ao[1] < 0 and ao < ao[1] and ao[2] < ao[1]))+        ratingOther := ratingOther + calcRating(ta.crossover(ao,0) or (ao > 0 and ao[1] > 0 and ao > ao[1] and ao[2] > ao[1]), ta.crossunder(ao,0) or (ao < 0 and ao[1] < 0 and ao < ao[1] and ao[2] < ao[1]))    ⋯// -----------------------------------[dsc_rsi, bo_level_rsi] = security(syminfo.tickerid, dsc_res, rsi_signal())+[dsc_rsi, bo_level_rsi] = request.security(syminfo.tickerid, dsc_res, rsi_signal())-[dsc_ta, bo_level_ta] = security(syminfo.tickerid, dsc_res, ta_presets_signal())+[dsc_ta, bo_level_ta] = request.security(syminfo.tickerid, dsc_res, ta_presets_signal())if(strategy.opentrades == 0 and within_window() and close > 0 and strategy.equity > 0.0)⋯        if IS_LONG-            strategy.entry("BO", limit=bo_level, long=strategy.long, qty=base_order_size()/bo_level)+            strategy.entry("BO", limit=bo_level, direction = strategy.long, qty=base_order_size()/bo_level)        else-            strategy.entry("BO", limit=bo_level, long=strategy.short, qty=base_order_size()/bo_level)+            strategy.entry("BO", limit=bo_level, direction = strategy.short, qty=base_order_size()/bo_level)        last_so_level := bo_level⋯                so_level := safety_order_price(index, last_so_level)-                so_name = "SO" + tostring(index) +                so_name = "SO" + str.tostring(index)                 if IS_LONG-                    strategy.entry(so_name, long=strategy.long, limit=so_level, qty=safety_order_qty(index)/so_level)+                    strategy.entry(so_name, direction = strategy.long, limit=so_level, qty=safety_order_qty(index)/so_level)                else-                    strategy.entry(so_name, long=strategy.short, limit=so_level, qty=safety_order_qty(index)/so_level)+                    strategy.entry(so_name, direction = strategy.short, limit=so_level, qty=safety_order_qty(index)/so_level)                last_so_level := so_level⋯// -----------------------------------if abs(strategy.position_size) > 0+if math.abs(strategy.position_size) > 0    take_profit_factor = IS_LONG ? (1 + take_profit) : (1 - take_profit)⋯            if IS_LONG and high >= take_profit_level -                ttp_extremum := max(high, ttp_extremum)+                ttp_extremum := math.max(high, ttp_extremum)                ttp_active := true            if not IS_LONG and low <= take_profit_level-                ttp_extremum := min(low, ttp_extremum)+                ttp_extremum := math.min(low, ttp_extremum)                ttp_active := true⋯// Cleanup-if (crossunder(strategy.opentrades, 0.5))+if (ta.crossunder(strategy.opentrades, 0.5))    strategy.close_all()⋯// -----------------------------------profit = max(strategy.equity, 0.0) - strategy.initial_capital+profit = math.max(strategy.equity, 0.0) - strategy.initial_capitalprofit_pct = profit / strategy.initial_capital⋯    is_title    = na(the_value) ? true : false-    text        = is_title ? "" : tostring(the_value)+    text_        = is_title ? "" : str.tostring(the_value)    bg_color    = is_title ? color.black : is_warning ? color.red : is_even ? color.silver : color.white⋯    table.cell(the_table, 0, the_row, the_label, bgcolor=bg_color, text_color=text_color,  text_size=size.auto, text_halign=left_cell_align)-    table.cell(the_table, 1, the_row, text,      bgcolor=bg_color, text_color=text_color,  text_size=size.auto, text_halign=text.align_right) +    table.cell(the_table, 1, the_row, text_,      bgcolor=bg_color, text_color=text_color,  text_size=size.auto, text_halign=text.align_right) var string warnings_text = ""⋯    if order_size_type == "Fixed"-        array.push(warnings, "Strategy Initial Capital (currently " + tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency+        array.push(warnings, "Strategy Initial Capital (currently " + str.tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency-                           + ") must match Max Amount For Bot Usage (" + tostring(max_amount, currency_format()) + " " + syminfo.currency + ")")+                           + ") must match Max Amount For Bot Usage (" + str.tostring(max_amount, currency_format()) + " " + syminfo.currency + ")")    else-        array.push(warnings, "Please adjust Base Order and Safe Order percentage to reach 100% of usage of capital. Currently using " + tostring(max_amount / strategy.initial_capital, "#.##%"))+        array.push(warnings, "Please adjust Base Order and Safe Order percentage to reach 100% of usage of capital. Currently using " + str.tostring(max_amount / strategy.initial_capital, "#.##%"))if (max_dev >= 1.0)-    array.push(warnings, "Max Price Deviation (" + tostring(max_dev, "#.##%") + ") cannot be >= 100.0%")+    array.push(warnings, "Max Price Deviation (" + str.tostring(max_dev, "#.##%") + ") cannot be >= 100.0%")if (stop_loss > 0.0 and stop_loss <= max_dev)-    array.push(warnings, "Stop Loss (" + tostring(stop_loss, "#.##%") + ") should be greater than Max Price Deviation (" + tostring(max_dev, "#.##%") + ")")+    array.push(warnings, "Stop Loss (" + str.tostring(stop_loss, "#.##%") + ") should be greater than Max Price Deviation (" + str.tostring(max_dev, "#.##%") + ")")if ((timeframe.isminutes and not (tonumber(timeframe.period) < 30)) or timeframe.isdwm)⋯if (ttp >= take_profit)-    array.push(warnings, "Trailing Take Profit (" + tostring(ttp, "#.##%") + ") cannot be greater than Take Profit (" + tostring(take_profit, "#.##%") + ")")+    array.push(warnings, "Trailing Take Profit (" + str.tostring(ttp, "#.##%") + ") cannot be greater than Take Profit (" + str.tostring(take_profit, "#.##%") + ")")// Making the results table⋯curr_row += 1, add_line(results_table, curr_row, "Deal Start Condition", dsc, false)-curr_row += 1, add_line(results_table, curr_row, "Base and Safety Orders", "BO: " + tostring(base_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency + " / " + "SO: " + tostring(safe_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency, false)+curr_row += 1, add_line(results_table, curr_row, "Base and Safety Orders", "BO: " + str.tostring(base_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency + " / " + "SO: " + str.tostring(safe_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency, false)-curr_row += 1, add_line(results_table, curr_row, "Price Deviation", tostring(price_deviation, "#.##%"), false)+curr_row += 1, add_line(results_table, curr_row, "Price Deviation", str.tostring(price_deviation, "#.##%"), false)-curr_row += 1, add_line(results_table, curr_row, "Safe Order Scale", "Volume: " + tostring(safe_order_volume_scale) + " / Scale: " + tostring(safe_order_step_scale), false)+curr_row += 1, add_line(results_table, curr_row, "Safe Order Scale", "Volume: " + str.tostring(safe_order_volume_scale) + " / Scale: " + str.tostring(safe_order_step_scale), false)-curr_row += 1, add_line(results_table, curr_row, "Take Profit / Stop Loss", tostring(take_profit, "#.##%") + (ttp > 0.0 ?  "( Trailing: " + tostring(ttp, "#.##%") + ")" : "") + "/ " + (stop_loss > 0.0 ? tostring(stop_loss, "#.##%") : "No Stop Loss"), false)+curr_row += 1, add_line(results_table, curr_row, "Take Profit / Stop Loss", str.tostring(take_profit, "#.##%") + (ttp > 0.0 ?  "( Trailing: " + str.tostring(ttp, "#.##%") + ")" : "") + "/ " + (stop_loss > 0.0 ? str.tostring(stop_loss, "#.##%") : "No Stop Loss"), false)-curr_row += 1, add_line(results_table, curr_row, "Max Amount For Bot Usage", tostring(max_amount, currency_format()) + " " + syminfo.currency, false)+curr_row += 1, add_line(results_table, curr_row, "Max Amount For Bot Usage", str.tostring(max_amount, currency_format()) + " " + syminfo.currency, false)-curr_row += 1, add_line(results_table, curr_row, "Max Coverage", tostring(max_safe_order) + " Safety Orders / " + tostring(max_dev, "#.##%"), false)+curr_row += 1, add_line(results_table, curr_row, "Max Coverage", str.tostring(max_safe_order) + " Safety Orders / " + str.tostring(max_dev, "#.##%"), false)curr_row += 1, add_line(results_table, curr_row, "Summary", None, false)-curr_row += 1, add_line(results_table, curr_row, "Initial Capital", tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency, false)+curr_row += 1, add_line(results_table, curr_row, "Initial Capital", str.tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency, false)-curr_row += 1, add_line(results_table, curr_row, "Final Capital",   tostring(max(strategy.equity, 0.0), currency_format()) + " " + syminfo.currency, false)+curr_row += 1, add_line(results_table, curr_row, "Final Capital",   str.tostring(math.max(strategy.equity, 0.0), currency_format()) + " " + syminfo.currency, false)-curr_row += 1, add_line(results_table, curr_row, "Net Result",      tostring(profit, currency_format()) + " " + syminfo.currency + " (" +  tostring(profit_pct, "#.##%") + ")", false)+curr_row += 1, add_line(results_table, curr_row, "Net Result",      str.tostring(profit, currency_format()) + " " + syminfo.currency + " (" +  str.tostring(profit_pct, "#.##%") + ")", false)-curr_row += 1, add_line(results_table, curr_row, "Total Deals",     tostring(deal_counter), false)+curr_row += 1, add_line(results_table, curr_row, "Total Deals",     str.tostring(deal_counter), false)if stop_loss > 0.0-    curr_row += 1, add_line(results_table, curr_row, "Deals Closed on Stop Loss", tostring(stop_loss_counter), false)+    curr_row += 1, add_line(results_table, curr_row, "Deals Closed on Stop Loss", str.tostring(stop_loss_counter), false)if IS_LONG⋯    curr_row += 1, add_line(results_table, curr_row, "Comparison to Buy-And-Hold",                      None, false)-    curr_row += 1, add_line(results_table, curr_row, "Net Result for Buy-and-hold",                     tostring(buy_hold_profit, currency_format()) + " " + syminfo.currency + " (" +  tostring(buy_hold_profit_pct, "#.##%") + ")", false)+    curr_row += 1, add_line(results_table, curr_row, "Net Result for Buy-and-hold",                     str.tostring(buy_hold_profit, currency_format()) + " " + syminfo.currency + " (" +  str.tostring(buy_hold_profit_pct, "#.##%") + ")", false)-    curr_row += 1, add_line(results_table, curr_row, "(Bot Performance) / (Buy-and-hold Performance)",  tostring(ratio, "#.###"), false)+    curr_row += 1, add_line(results_table, curr_row, "(Bot Performance) / (Buy-and-hold Performance)",  str.tostring(ratio, "#.###"), false)

Clean v5

Not verified

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L479:C34: 'tonumber' was renamed to 'str.tonumber' in Pine Script v5.), so this step could not be checked.

  • Line 13: input() → input.string()
  • Line 16: input() → input.string()
  • Line 19: input() → input.int()
  • Line 23: input() → input.string()
  • Line 24: input() → input.int()
  • Line 25: input() → input.string()
  • Line 27: input() → input.string()
⋯take_profit             = input.float(4.5,  title="Take Profit (%)", minval=0.0, step=0.1)/100-take_profit_type        = input(defval="% from total volume", title="Take Profit Type", options=["% from total volume", "% from base order"])+take_profit_type        = input.string(defval="% from total volume", title="Take Profit Type", options=["% from total volume", "% from base order"])ttp                     = input.float(0.0,  title="Trailing Take Profit (%) [0 = Disabled]", minval=0.0, step=0.1)/100stop_loss               = input.float(0.0,  title="Stop Loss (%) [0 = Disabled]", minval=0.0, step=0.1)/100-order_size_type         = input(defval="Fixed",         title="Order Size Type", options=["Fixed", "% of equity"])+order_size_type         = input.string(defval="Fixed",         title="Order Size Type", options=["Fixed", "% of equity"])base_order              = input.float(100.0,title="Base Order") safe_order              = input.float(140.0,title="Safety Order") -max_safe_order          = input(6,                      title="Max Safety Trades Count", minval=0, maxval=99, step=1) +max_safe_order          = input.int(6,                      title="Max Safety Trades Count", minval=0, maxval=99, step=1) price_deviation         = input.float(1.5,  title="Price deviation to open safety order (%)", minval=0.0, step=0.1)/100⋯safe_order_step_scale   = input.float(1.6,  title="Safety Order Step Scale", step=0.1) -dsc                     = input(defval="RSI-7",         title="Deal Start Condition", options=["Start ASAP", "RSI-7", "TV presets"])+dsc                     = input.string(defval="RSI-7",         title="Deal Start Condition", options=["Start ASAP", "RSI-7", "TV presets"])-dsc_rsi_threshold       = input(defval=30,              title="[RSI-7 only] RSI Threshold", minval=1, maxval=99)+dsc_rsi_threshold       = input.int(defval=30,              title="[RSI-7 only] RSI Threshold", minval=1, maxval=99)-dsc_technicals          = input(defval="Strong",        title="[TV presets only] Strength", options=["Strong", "Weak"])+dsc_technicals          = input.string(defval="Strong",        title="[TV presets only] Strength", options=["Strong", "Weak"])dsc_res                 = input.timeframe("",                     title="[RSI-7 and TV presets Only] Indicator Timeframe")-bot_direction           = input(defval="Long",          title="Bot Direction", options=["Long", "Short"])+bot_direction           = input.string(defval="Long",          title="Bot Direction", options=["Long", "Short"])start_time              = input.time(defval=timestamp("15 June 2021 06:00"),   title="Start Time")⋯

Does it run in Pine Script v6?

Not tested

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L479:C34: 'tonumber' was renamed to 'str.tonumber' in Pine Script v5.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © rouxam-//@version=5+//@version=6// Author: rouxam⋯

Settings

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

SettingDefaultType and rangeFeeds
Take Profit (%)4.5float · min 0.0 · step 0.1take_profit_factor line 481 line 482 line 497
Take Profit Type% from total volumestring · options ["% from total volume", "% from base order"]line 417
Trailing Take Profit (%) [0 = Disabled]0.0float · min 0.0 · step 0.1ttp_factor exit x line 433 line 481 line 482 line 497
Stop Loss (%) [0 = Disabled]0.0float · min 0.0 · step 0.1stop_loss_factor line 423 line 477 line 478 line 497 line 505
Order Size TypeFixedstring · options ["Fixed", "% of equity"]line 56 line 57 line 470 line 494
Base Order100.0floatline 56 line 494
Safety Order140.0floatline 57 line 494
Max Safety Trades Count6int · min 0 · max 99 · step 1line 70 line 71 line 77 line 400 line 401 line 499
Price deviation to open safety order (%)1.5float · min 0.0 · step 0.1line 58 line 495
Safety Order Volume Scale1.5float · step 0.1line 64 line 496
Safety Order Step Scale1.6float · step 0.1line 58 line 496
Deal Start ConditionRSI-7string · options ["Start ASAP", "RSI-7", "TV presets"]line 382 line 385 line 388 line 493
[RSI-7 only] RSI Threshold30int · min 1 · max 99line 96 line 98
[TV presets only] StrengthStrongstring · options ["Strong", "Weak"]bound
[RSI-7 and TV presets Only] Indicator Timeframetimeframe (written input.resolution)dsc_rsi bo_level_rsi dsc_ta bo_level_ta
Bot DirectionLongstring · options ["Long", "Short"]IS_LONG
Start Timetimestamp("15 June 2021 06:00")timestart_time_actual end_time_actual line 55
End Timetimestamp("31 Dec 2021 20:00")timeend_time_actual line 55

What it calculates

  • RSI (rsi, ta.rsi in v5)close, 7rsi7 · line 94
  • RSI (rsi, ta.rsi in v5)close, 14rsi1 · line 110
  • SMA / Stoch (sma, ta.sma in v5)stoch(rsi1, rsi1, rsi1, 14), 3K · line 111
  • SMA (sma, ta.sma in v5)K, 3D · line 112
  • SMA (sma, ta.sma in v5)close, 10SMA10 · line 144
  • SMA (sma, ta.sma in v5)close, 20SMA20 · line 145
  • SMA (sma, ta.sma in v5)close, 30SMA30 · line 146
  • SMA (sma, ta.sma in v5)close, 50SMA50 · line 147
  • SMA (sma, ta.sma in v5)close, 100SMA100 · line 148
  • SMA (sma, ta.sma in v5)close, 200SMA200 · line 149
  • EMA (ema, ta.ema in v5)close, 10EMA10 · line 151
  • EMA (ema, ta.ema in v5)close, 20EMA20 · line 152
  • EMA (ema, ta.ema in v5)close, 30EMA30 · line 153
  • EMA (ema, ta.ema in v5)close, 50EMA50 · line 154
  • EMA (ema, ta.ema in v5)close, 100EMA100 · line 155
  • EMA (ema, ta.ema in v5)close, 200EMA200 · line 156
  • HMA (hma, ta.hma in v5)close, 9HullMA9 · line 158
  • VWMA (vwma, ta.vwma in v5)close, 20VWMA · line 161
  • RSI (rsi, ta.rsi in v5)close, 14RSI · line 167
  • SMA / Stoch (sma, ta.sma in v5)stoch(close, high, low, lengthStoch), smoothKStochkStoch · line 173
  • SMA (sma, ta.sma in v5)kStoch, smoothDStochdStoch · line 174
  • CCI (cci, ta.cci in v5)close, 20CCI · line 177
  • DMI (dmi, ta.dmi in v5)14, 14P · line 181
  • DMI (dmi, ta.dmi in v5)14, 14M · line 181
  • DMI (dmi, ta.dmi in v5)14, 14V · line 181
  • MOM (mom, ta.mom in v5)close, 10Mom · line 189
  • MACD (macd, ta.macd in v5)close, 12, 26, 9macdMACD · line 191
  • MACD (macd, ta.macd in v5)close, 12, 26, 9signalMACD · line 191
  • WPR (wpr, ta.wpr in v5)14WR · line 195
  • EMA (ema, ta.ema in v5)close, 13BullPower · line 198
  • EMA (ema, ta.ema in v5)close, 13BearPower · line 199
  • EMA (ema, ta.ema in v5)close, 50PriceAvg · line 206
  • Crossover / Crossunder (crossover, ta.crossover in v5)ao, 0ratingOther · line 277

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 106 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open BO longIS_LONGOn395
Open BO shortIS_LONGOn397
Open so_name longIS_LONGOn405
Open so_name shortIS_LONGOn407
Exit x stopIS_LONG and low < stop_levelOn426
Exit x stopnot IS_LONG and high > stop_levelOn430
Exit x limitttp == 0.0On435
Exit x stopttp_activeOn446
Close (crossunder(strategy.opentrades, 0.5))On449
cancel_all (crossunder(strategy.opentrades, 0.5))On450

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.

The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.

  • ClearHigher-timeframe data2 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 timingprocess_orders_on_close = true: orders fill at the signal bar's close.

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

Similar scripts

Indicators and strategies built from the same calculations.

ScriptSharesTypeNetTradesMax drawdown
Crypto MF S-R Strategy - cespanol by cespanolrsi sma ema hma vwma cci dmi mom macd wprv4 strategydoes not run in Zeal Terminal
All in One Strategy no RSI Label - For higher dollar crypto by Solutions1978rsi ema stoch sma vwma macdv4 strategyNo trades on this market
All in One Strategy by Solutions1978rsi ema stoch sma vwma macdv4 strategyNo trades on this market
Divergence for Many Indicators v4 ST by CannyTolany01rsi macd mom cci sma vwmav4 strategy+25.6%1245.2%
ELIA MULTI INDICATORS STRATEGY by ally17ema macd rsi sma momv4 strategy−2.5%6014.9%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No Pine Script v4 Error at @L479:C34: Undeclared identifier 'tonumber'.Not measured
PineTSNo v5 and v6 only—Not measured

Zeal Terminal's engine currently reads an order side written as long = strategy.long, long = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 395, 397, 405, 407) so the engine trades the way the script says.

“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/// © rouxam//@version=4// Author: rouxamstrategy("Backtesting 3commas DCA Bot v2", overlay=true, pyramiding=99, process_orders_on_close=true, commission_type=strategy.commission.percent, commission_value=0.1, initial_capital=3009)// Important Note : Initial Capital above is written to match the default value based on bot parameters.//                  It is expected the user will update the initial_capital via the GUI Parameters > Properties tab//                  A warning will displayed in case initial capital and max amount for bot usage do not match.// ----------------------------------// Strategy Inputs// ----------------------------------take_profit             = input(4.5, type=input.float,  title="Take Profit (%)", minval=0.0, step=0.1)/100take_profit_type        = input(defval="% from total volume", title="Take Profit Type", options=["% from total volume", "% from base order"])ttp                     = input(0.0, type=input.float,  title="Trailing Take Profit (%) [0 = Disabled]", minval=0.0, step=0.1)/100stop_loss               = input(0.0, type=input.float,  title="Stop Loss (%) [0 = Disabled]", minval=0.0, step=0.1)/100order_size_type         = input(defval="Fixed",         title="Order Size Type", options=["Fixed", "% of equity"])base_order              = input(100.0, type=input.float,title="Base Order") safe_order              = input(140.0, type=input.float,title="Safety Order") max_safe_order          = input(6,                      title="Max Safety Trades Count", minval=0, maxval=99, step=1) price_deviation         = input(1.5, type=input.float,  title="Price deviation to open safety order (%)", minval=0.0, step=0.1)/100safe_order_volume_scale = input(1.5, type=input.float,  title="Safety Order Volume Scale", step=0.1) safe_order_step_scale   = input(1.6, type=input.float,  title="Safety Order Step Scale", step=0.1) dsc                     = input(defval="RSI-7",         title="Deal Start Condition", options=["Start ASAP", "RSI-7", "TV presets"])dsc_rsi_threshold       = input(defval=30,              title="[RSI-7 only] RSI Threshold", minval=1, maxval=99)dsc_technicals          = input(defval="Strong",        title="[TV presets only] Strength", options=["Strong", "Weak"])dsc_res                 = input("",                     title="[RSI-7 and TV presets Only] Indicator Timeframe", type=input.resolution)bot_direction           = input(defval="Long",          title="Bot Direction", options=["Long", "Short"])start_time              = input(defval=timestamp("15 June 2021 06:00"),   title="Start Time",     type=input.time)end_time                = input(defval=timestamp("31 Dec 2021 20:00"),   title="End Time",       type=input.time)// ----------------------------------// Declarations// ----------------------------------var bo_level = 0.0var last_so_level = 0.0var so_level = 0.0var ttp_active = falsevar ttp_extremum = 0.0var ttp_level = 0.0var stop_level = 0.0var take_profit_level = 0.0var deal_counter = 0var stop_loss_counter = 0var stop_loss_on_bar = falsevar latest_price = closevar deal_start_condition = falsevar start_time_actual = start_timevar end_time_actual = start_time// CONSTANTSvar float init_price = navar IS_LONG = bot_direction == "Long"// ----------------------------------// Utilities functions// ----------------------------------pretty_date(t) => tostring(dayofmonth(t)) + "/" + tostring(month(t)) + "/" + tostring(year(t))within_window() => time >= start_time and time <= end_timebase_order_size() => order_size_type == "Fixed" ? base_order : base_order/100 * strategy.equitysafe_order_size() => order_size_type == "Fixed" ? safe_order : safe_order/100 * strategy.equitysafety_order_deviation(index) => price_deviation * pow(safe_order_step_scale,  index - 1)safety_order_price(index, last_safety_order_price) =>     if IS_LONG        last_safety_order_price * (1 - safety_order_deviation(index))    else        last_safety_order_price * (1 + safety_order_deviation(index))safety_order_qty(index) => safe_order_size() * pow(safe_order_volume_scale, index - 1)max_amount_for_bot_usage() =>    var total_qty = 0.0    var last_order_qty = 0.0    total_qty := base_order_size()    last_order_qty := safe_order_size()    if max_safe_order > 0        for index = 1 to max_safe_order            total_qty := total_qty + safety_order_qty(index)    total_qty // returned valuemax_deviation() =>    var total_deviation = 0.0    total_deviation := 0.0    for index = 1 to max_safe_order        total_deviation := total_deviation + safety_order_deviation(index)currency_format() =>    if syminfo.currency == "USDT" or syminfo.currency == "USD" or syminfo.currency == "TUSD" or syminfo.currency == "BUSD" or syminfo.currency == "USDC" or syminfo.currency == "EUR" or syminfo.currency == "AUD"        "#.##"    else if syminfo.currency == "BTC"        "#.########"    else        // TODO (rouxam) list more options        "#.####"// ***********************************// Deal Start Condition Strategies// ***********************************// RSI-7 // ***********************************rsi_signal() =>    // Regular strat would be crossover but not for 3C DCA Bot    rsi7 = rsi(close, 7)    if IS_LONG        [rsi7 < dsc_rsi_threshold, close]    else        [rsi7 > dsc_rsi_threshold, close]// TV presets// ***********************************// This whole section is from the TradingView "Technical Ratings" code.// Adding the Technical Ratings "indicator" as input to this "strategy" is not sufficient for our purpose,// Therefore the code is copy-pasted.// ***********************************// Awesome OscillatorAO() =>     sma(hl2, 5) - sma(hl2, 34)// Stochastic RSIStochRSI() =>    rsi1 = rsi(close, 14)    K = sma(stoch(rsi1, rsi1, rsi1, 14), 3)    D = sma(K, 3)    [K, D]// Ultimate Oscillatortl() => close[1] < low ? close[1]: lowuo(ShortLen, MiddlLen, LongLen) =>    Value1 = sum(tr, ShortLen)    Value2 = sum(tr, MiddlLen)    Value3 = sum(tr, LongLen)    Value4 = sum(close - tl(), ShortLen)    Value5 = sum(close - tl(), MiddlLen)    Value6 = sum(close - tl(), LongLen)    float UO = na    if Value1 != 0 and Value2 != 0 and Value3 != 0        var0 = LongLen / ShortLen        var1 = LongLen / MiddlLen        Value7 = (Value4 / Value1) * (var0)        Value8 = (Value5 / Value2) * (var1)        Value9 = (Value6 / Value3)        UO := (Value7 + Value8 + Value9) / (var0 + var1 + 1)    UO// Ichimoku Clouddonchian(len) => avg(lowest(len), highest(len))ichimoku_cloud() =>    conversionLine = donchian(9)    baseLine = donchian(26)    leadLine1 = avg(conversionLine, baseLine)    leadLine2 = donchian(52)    [conversionLine, baseLine, leadLine1, leadLine2]calcRatingMA(ma, src) => na(ma) or na(src) ? na : (ma == src ? 0 : ( ma < src ? 1 : -1 ))calcRating(buy, sell) => buy ? 1 : ( sell ? -1 : 0 )ta_presets_signal() =>    //============== MA =================    SMA10 = sma(close, 10)    SMA20 = sma(close, 20)    SMA30 = sma(close, 30)    SMA50 = sma(close, 50)    SMA100 = sma(close, 100)    SMA200 = sma(close, 200)        EMA10 = ema(close, 10)    EMA20 = ema(close, 20)    EMA30 = ema(close, 30)    EMA50 = ema(close, 50)    EMA100 = ema(close, 100)    EMA200 = ema(close, 200)        HullMA9 = hma(close, 9)        // Volume Weighted Moving Average (VWMA)    VWMA = vwma(close, 20)        [IC_CLine, IC_BLine, IC_Lead1, IC_Lead2] = ichimoku_cloud()        // ======= Other =============    // Relative Strength Index, RSI    RSI = rsi(close,14)        // Stochastic    lengthStoch = 14    smoothKStoch = 3    smoothDStoch = 3    kStoch = sma(stoch(close, high, low, lengthStoch), smoothKStoch)    dStoch = sma(kStoch, smoothDStoch)        // Commodity Channel Index, CCI    CCI = cci(close, 20)        // Average Directional Index    float adxValue = na, float adxPlus = na, float adxMinus = na    [P, M, V] = dmi(14, 14)    adxValue := V    adxPlus := P    adxMinus := M    // Awesome Oscillator    ao = AO()        // Momentum    Mom = mom(close, 10)    // Moving Average Convergence/Divergence, MACD    [macdMACD, signalMACD, _] = macd(close, 12, 26, 9)    // Stochastic RSI    [Stoch_RSI_K, Stoch_RSI_D] = StochRSI()    // Williams Percent Range    WR = wpr(14)        // Bull / Bear Power    BullPower = high - ema(close, 13)    BearPower = low - ema(close, 13)    // Ultimate Oscillator    UO = uo(7,14,28)    if not na(UO)        UO := UO * 100    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////        PriceAvg = ema(close, 50)    DownTrend = close < PriceAvg    UpTrend = close > PriceAvg    // calculate trading recommendation based on SMA/EMA    float ratingMA = 0    float ratingMAC = 0        if not na(SMA10)        ratingMA := ratingMA + calcRatingMA(SMA10, close)        ratingMAC := ratingMAC + 1    if not na(SMA20)        ratingMA := ratingMA + calcRatingMA(SMA20, close)        ratingMAC := ratingMAC + 1    if not na(SMA30)        ratingMA := ratingMA + calcRatingMA(SMA30, close)        ratingMAC := ratingMAC + 1    if not na(SMA50)        ratingMA := ratingMA + calcRatingMA(SMA50, close)        ratingMAC := ratingMAC + 1    if not na(SMA100)        ratingMA := ratingMA + calcRatingMA(SMA100, close)        ratingMAC := ratingMAC + 1    if not na(SMA200)        ratingMA := ratingMA + calcRatingMA(SMA200, close)        ratingMAC := ratingMAC + 1    if not na(EMA10)        ratingMA := ratingMA + calcRatingMA(EMA10, close)        ratingMAC := ratingMAC + 1    if not na(EMA20)        ratingMA := ratingMA + calcRatingMA(EMA20, close)        ratingMAC := ratingMAC + 1    if not na(EMA30)        ratingMA := ratingMA + calcRatingMA(EMA30, close)        ratingMAC := ratingMAC + 1    if not na(EMA50)        ratingMA := ratingMA + calcRatingMA(EMA50, close)        ratingMAC := ratingMAC + 1    if not na(EMA100)        ratingMA := ratingMA + calcRatingMA(EMA100, close)        ratingMAC := ratingMAC + 1    if not na(EMA200)        ratingMA := ratingMA + calcRatingMA(EMA200, close)        ratingMAC := ratingMAC + 1        if not na(HullMA9)        ratingHullMA9 = calcRatingMA(HullMA9, close)        ratingMA := ratingMA + ratingHullMA9        ratingMAC := ratingMAC + 1        if not na(VWMA)        ratingVWMA = calcRatingMA(VWMA, close)        ratingMA := ratingMA + ratingVWMA        ratingMAC := ratingMAC + 1        float ratingIC = na    if not (na(IC_Lead1) or na(IC_Lead2) or na(close) or na(close[1]) or na(IC_BLine) or na(IC_CLine))        ratingIC := calcRating(         IC_Lead1 > IC_Lead2 and close > IC_Lead1 and close < IC_BLine and close[1] < IC_CLine and close > IC_CLine,         IC_Lead2 > IC_Lead1 and close < IC_Lead2 and close > IC_BLine and close[1] > IC_CLine and close < IC_CLine)    if not na(ratingIC)        ratingMA := ratingMA + ratingIC        ratingMAC := ratingMAC + 1        ratingMA := ratingMAC > 0 ? ratingMA / ratingMAC : na        float ratingOther = 0    float ratingOtherC = 0        ratingRSI = RSI    if not(na(ratingRSI) or na(ratingRSI[1]))        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + calcRating(ratingRSI < 30 and ratingRSI[1] < ratingRSI, ratingRSI > 70 and ratingRSI[1] > ratingRSI)        if not(na(kStoch) or na(dStoch) or na(kStoch[1]) or na(dStoch[1]))        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + calcRating(kStoch < 20 and dStoch < 20 and kStoch > dStoch and kStoch[1] < dStoch[1], kStoch > 80 and dStoch > 80 and kStoch < dStoch and kStoch[1] > dStoch[1])        ratingCCI = CCI    if not(na(ratingCCI) or na(ratingCCI[1]))        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + calcRating(ratingCCI < -100 and ratingCCI > ratingCCI[1], ratingCCI > 100 and ratingCCI < ratingCCI[1])        if not(na(adxValue) or na(adxPlus[1]) or na(adxMinus[1]) or na(adxPlus) or na(adxMinus))        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + calcRating(adxValue > 20 and adxPlus[1] < adxMinus[1] and adxPlus > adxMinus, adxValue > 20 and adxPlus[1] > adxMinus[1] and adxPlus < adxMinus)        if not(na(ao) or na(ao[1]))        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + calcRating(crossover(ao,0) or (ao > 0 and ao[1] > 0 and ao > ao[1] and ao[2] > ao[1]), crossunder(ao,0) or (ao < 0 and ao[1] < 0 and ao < ao[1] and ao[2] < ao[1]))        if not(na(Mom) or na(Mom[1]))        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + calcRating(Mom > Mom[1], Mom < Mom[1])        if not(na(macdMACD) or na(signalMACD))        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + calcRating(macdMACD > signalMACD, macdMACD < signalMACD)        float ratingStoch_RSI = na    if not(na(DownTrend) or na(UpTrend) or na(Stoch_RSI_K) or na(Stoch_RSI_D) or na(Stoch_RSI_K[1]) or na(Stoch_RSI_D[1]))        ratingStoch_RSI := calcRating(         DownTrend and Stoch_RSI_K < 20 and Stoch_RSI_D < 20 and Stoch_RSI_K > Stoch_RSI_D and Stoch_RSI_K[1] < Stoch_RSI_D[1],         UpTrend and Stoch_RSI_K > 80 and Stoch_RSI_D > 80 and Stoch_RSI_K < Stoch_RSI_D and Stoch_RSI_K[1] > Stoch_RSI_D[1])    if not na(ratingStoch_RSI)        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + ratingStoch_RSI        float ratingWR = na    if not(na(WR) or na(WR[1]))        ratingWR := calcRating(WR < -80 and WR > WR[1], WR > -20 and WR < WR[1])    if not na(ratingWR)        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + ratingWR        float ratingBBPower = na    if not(na(UpTrend) or na(DownTrend) or na(BearPower) or na(BearPower[1]) or na(BullPower) or na(BullPower[1]))        ratingBBPower := calcRating(         UpTrend and BearPower < 0 and BearPower > BearPower[1],         DownTrend and BullPower > 0 and BullPower < BullPower[1])    if not na(ratingBBPower)        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + ratingBBPower        float ratingUO = na    if not(na(UO))        ratingUO := calcRating(UO > 70, UO < 30)    if not na(ratingUO)        ratingOtherC := ratingOtherC + 1        ratingOther := ratingOther + ratingUO        ratingOther := ratingOtherC > 0 ? ratingOther / ratingOtherC : na        float ratingTotal = 0    float ratingTotalC = 0    if not na(ratingMA)        ratingTotal := ratingTotal + ratingMA        ratingTotalC := ratingTotalC + 1    if not na(ratingOther)        ratingTotal := ratingTotal + ratingOther        ratingTotalC := ratingTotalC + 1    ratingTotal := ratingTotalC > 0 ? ratingTotal / ratingTotalC : na        // little piece of @rouxam logic    var bool start_condition = false    float bound = dsc_technicals == "Strong" ? 0.5 : 0.1    if IS_LONG        start_condition := ratingTotal > bound    else        start_condition := ratingTotal < -bound    [start_condition, close]    // ----------------------------------// (Re-)Initialize// ----------------------------------var max_amount = max_amount_for_bot_usage()var max_dev = max_deviation()init_price := na(init_price) and within_window() ? open : init_pricelatest_price := within_window() ? close : latest_price// Actualize the start and end time of the backtesting window because number of bars is limited.// NOTE: limits on number of available bars://      TradingView FREE account: 5000 bars available,//      TradingView PRO/PRO+ account: 10000 bars available,//      TradingView PREMIUM account: 20000 bars available.start_time_actual := barstate.isfirst and time > start_time_actual ?  time : start_time_actualend_time_actual := time > end_time_actual and time <= end_time ? time : end_time_actualif strategy.position_size == 0.0    ttp_extremum := 0.0    ttp_active := false    deal_start_condition := false// ----------------------------------// Open deal with Base Order on Deal Start Condition// ----------------------------------[dsc_rsi, bo_level_rsi] = security(syminfo.tickerid, dsc_res, rsi_signal())[dsc_ta, bo_level_ta] = security(syminfo.tickerid, dsc_res, ta_presets_signal())if(strategy.opentrades == 0 and within_window() and close > 0 and strategy.equity > 0.0)    // Compute deal start condition    if dsc == "Start ASAP"        deal_start_condition := true        bo_level := close    if dsc == "RSI-7"        deal_start_condition := dsc_rsi        bo_level := bo_level_rsi    if dsc == "TV presets"        deal_start_condition := dsc_ta        bo_level := bo_level_ta    // Place Buy Order    if deal_start_condition        deal_counter := deal_counter + 1        if IS_LONG            strategy.entry("BO", limit=bo_level, long=strategy.long, qty=base_order_size()/bo_level)        else            strategy.entry("BO", limit=bo_level, long=strategy.short, qty=base_order_size()/bo_level)        last_so_level := bo_level        // Place Safety Orders        if max_safe_order > 0            for index = 1 to max_safe_order                so_level := safety_order_price(index, last_so_level)                so_name = "SO" + tostring(index)                 if IS_LONG                    strategy.entry(so_name, long=strategy.long, limit=so_level, qty=safety_order_qty(index)/so_level)                else                    strategy.entry(so_name, long=strategy.short, limit=so_level, qty=safety_order_qty(index)/so_level)                last_so_level := so_level// ----------------------------------// Close Deal on SL, TP or TTP// ----------------------------------if abs(strategy.position_size) > 0    take_profit_factor = IS_LONG ? (1 + take_profit) : (1 - take_profit)    stop_loss_factor = IS_LONG ? (1 - stop_loss) : (1 + stop_loss)    ttp_factor = IS_LONG ? (1 - ttp) : (1 + ttp)    stop_level := bo_level * stop_loss_factor    if take_profit_type == "% from total volume"        take_profit_level := strategy.position_avg_price * take_profit_factor    else        take_profit_level := bo_level * take_profit_factor    // Stop Loss    stop_loss_on_bar := false    if stop_loss > max_dev and not ttp_active        if IS_LONG and low < stop_level            stop_loss_counter := stop_loss_counter + 1            strategy.exit(id="x", stop=stop_level, comment="SL")            stop_loss_on_bar := true        else if not IS_LONG and high > stop_level            stop_loss_counter := stop_loss_counter + 1            strategy.exit(id="x", stop=stop_level, comment="SL")            stop_loss_on_bar := true    if not stop_loss_on_bar        if ttp == 0.0            // Simple take profit            strategy.exit(id="x", limit=take_profit_level, comment="TP")        else            // Trailing take profit            if IS_LONG and high >= take_profit_level                 ttp_extremum := max(high, ttp_extremum)                ttp_active := true            if not IS_LONG and low <= take_profit_level                ttp_extremum := min(low, ttp_extremum)                ttp_active := true            if ttp_active                 ttp_level := ttp_extremum * ttp_factor                strategy.exit(id="x", stop=ttp_level, comment="TTP")// Cleanupif (crossunder(strategy.opentrades, 0.5))    strategy.close_all()    strategy.cancel_all()// ----------------------------------// Results// ----------------------------------profit = max(strategy.equity, 0.0) - strategy.initial_capitalprofit_pct = profit / strategy.initial_capitaladd_line(the_table, the_row, the_label, the_value, is_warning) =>    // if providing a value, the row is shown as: the_label | the_value    // else: the_label is considered to be a title    is_even     = (the_row % 2) == 1    is_title    = na(the_value) ? true : false    text        = is_title ? "" : tostring(the_value)    bg_color    = is_title ? color.black : is_warning ? color.red : is_even ? color.silver : color.white    text_color  = is_title ? color.white : color.black    left_cell_align = is_title ? text.align_right : text.align_left    table.cell(the_table, 0, the_row, the_label, bgcolor=bg_color, text_color=text_color,  text_size=size.auto, text_halign=left_cell_align)    table.cell(the_table, 1, the_row, text,      bgcolor=bg_color, text_color=text_color,  text_size=size.auto, text_halign=text.align_right) var string warnings_text = ""var warnings = array.new_string(0, "")if (max_amount / strategy.initial_capital > 1.005 or max_amount / strategy.initial_capital < 0.995)    if order_size_type == "Fixed"        array.push(warnings, "Strategy Initial Capital (currently " + tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency                           + ") must match Max Amount For Bot Usage (" + tostring(max_amount, currency_format()) + " " + syminfo.currency + ")")    else        array.push(warnings, "Please adjust Base Order and Safe Order percentage to reach 100% of usage of capital. Currently using " + tostring(max_amount / strategy.initial_capital, "#.##%"))if (max_dev >= 1.0)    array.push(warnings, "Max Price Deviation (" + tostring(max_dev, "#.##%") + ") cannot be >= 100.0%")if (stop_loss > 0.0 and stop_loss <= max_dev)    array.push(warnings, "Stop Loss (" + tostring(stop_loss, "#.##%") + ") should be greater than Max Price Deviation (" + tostring(max_dev, "#.##%") + ")")if ((timeframe.isminutes and not (tonumber(timeframe.period) < 30)) or timeframe.isdwm)    array.push(warnings, "Backtesting may be inaccurate. Recommended to use timeframe of 15m or less")if (ttp >= take_profit)    array.push(warnings, "Trailing Take Profit (" + tostring(ttp, "#.##%") + ") cannot be greater than Take Profit (" + tostring(take_profit, "#.##%") + ")")// Making the results tablevar results_table  = table.new(position.top_right, 2, 20, frame_color=color.black)curr_row = -1None = int(na)curr_row += 1, add_line(results_table, curr_row, "Bot setup", None, false)if (array.size(warnings) > 0)    for index = 1 to array.size(warnings)        curr_row += 1        add_line(results_table, curr_row, "Please review your strategy settings", array.pop(warnings), true)curr_row += 1, add_line(results_table, curr_row, "Dates", pretty_date(start_time_actual) + " to " + pretty_date(end_time_actual), false)curr_row += 1, add_line(results_table, curr_row, "Deal Start Condition", dsc, false)curr_row += 1, add_line(results_table, curr_row, "Base and Safety Orders", "BO: " + tostring(base_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency + " / " + "SO: " + tostring(safe_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency, false)curr_row += 1, add_line(results_table, curr_row, "Price Deviation", tostring(price_deviation, "#.##%"), false)curr_row += 1, add_line(results_table, curr_row, "Safe Order Scale", "Volume: " + tostring(safe_order_volume_scale) + " / Scale: " + tostring(safe_order_step_scale), false)curr_row += 1, add_line(results_table, curr_row, "Take Profit / Stop Loss", tostring(take_profit, "#.##%") + (ttp > 0.0 ?  "( Trailing: " + tostring(ttp, "#.##%") + ")" : "") + "/ " + (stop_loss > 0.0 ? tostring(stop_loss, "#.##%") : "No Stop Loss"), false)curr_row += 1, add_line(results_table, curr_row, "Max Amount For Bot Usage", tostring(max_amount, currency_format()) + " " + syminfo.currency, false)curr_row += 1, add_line(results_table, curr_row, "Max Coverage", tostring(max_safe_order) + " Safety Orders / " + tostring(max_dev, "#.##%"), false)curr_row += 1, add_line(results_table, curr_row, "Summary", None, false)curr_row += 1, add_line(results_table, curr_row, "Initial Capital", tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency, false)curr_row += 1, add_line(results_table, curr_row, "Final Capital",   tostring(max(strategy.equity, 0.0), currency_format()) + " " + syminfo.currency, false)curr_row += 1, add_line(results_table, curr_row, "Net Result",      tostring(profit, currency_format()) + " " + syminfo.currency + " (" +  tostring(profit_pct, "#.##%") + ")", false)curr_row += 1, add_line(results_table, curr_row, "Total Deals",     tostring(deal_counter), false)if stop_loss > 0.0    curr_row += 1, add_line(results_table, curr_row, "Deals Closed on Stop Loss", tostring(stop_loss_counter), false)if IS_LONG    buy_hold_profit = (latest_price - init_price) / init_price * strategy.initial_capital    buy_hold_profit_pct = buy_hold_profit / strategy.initial_capital    ratio = profit_pct / buy_hold_profit_pct    curr_row += 1, add_line(results_table, curr_row, "Comparison to Buy-And-Hold",                      None, false)    curr_row += 1, add_line(results_table, curr_row, "Net Result for Buy-and-hold",                     tostring(buy_hold_profit, currency_format()) + " " + syminfo.currency + " (" +  tostring(buy_hold_profit_pct, "#.##%") + ")", false)    curr_row += 1, add_line(results_table, curr_row, "(Bot Performance) / (Buy-and-hold Performance)",  tostring(ratio, "#.###"), false)