Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Simple_RSI+PA+DCA Strategy

A Pine Script v5 strategy built on SMA (close, 100) and RMA or Change (14). It has 7 order rules, 2 entries among them, and trades long only with the default settings. Exits use a profit target and no stop loss. Each trade commits 1% of equity and pays 0.075% commission. 13 settings; defaults include Take Profit % 3, Close All % 6 and Max Amount of DCA Layers 8.

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 Simple_RSI+PA+DCA Strategy repaint?
Yes
In a live replay, it did not match history on 19 of 20 trades, and it produced 67 trades that history does not have.
How did Simple_RSI+PA+DCA Strategy do on BTCUSDT 1D with default settings?
+9.57%
From 26 Jan 2024 to 21 Oct 2026, over 71 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Simple_RSI+PA+DCA Strategy run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 71 before, 71 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download.
Does Simple_RSI+PA+DCA Strategy use a stop loss?
No
Its exits set a profit target but no stop.
Does Simple_RSI+PA+DCA Strategy run in Zeal Terminal?
Yes
It compiles in 57 ms and runs 1,000 bars in 138 ms, in the browser.

BTCUSDT · 1D · default settings

  • SMA
  • RMA
  • RMA
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (13)
0.0050,000100,000AprJulOct2025AprJulOct2026AprJulOct$548$1,013Equity from $500
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. The script plots nothing itself; the lines and the lower pane are its own calculations, drawn for reference. Lines, boxes and labels are the script's own drawings, the most recent ones its limits keep. Zeal Terminal's engine currently reads an order side written as direction = strategy.long as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 86, 100) so the engine trades the way the script says.
Net profit
+9.57%
$47.84
Buy and hold
+102.5%
same period
Closed trades
71
46 won · 25 lost
Profitable
64.8%
of closed trades
Profit factor
2.23
gross profit ÷ gross loss
Max drawdown
12.32%
−$67.57

One run with the author's default settings, $500 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

    No stop loss

    strategy.exit is used without a stop, loss or trailing stop.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    No slippage

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

Settings

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

SettingDefaultType and rangeFeeds
Backtest Window
Start Timetimestamp("01 April 2021 20:00")timeline 25
End Timetimestamp("01 Aug 2030 20:00")timeline 25
Risk
Take Profit %3float · step 0.1take_profit_price
Close All %6float · step 0.1stop_level
DCA Settings
Switch to linear DCA Layersfalsebooldca_level_mode
Max Amount of DCA Layers8intlinesArray q base_number entry entry_id line 80 line 97 line 104
Base % to calculate DCA layers2float · min 1.1 · step 0.5dca_level_calc
Lines Bar Lookback4999int · max 4999max_bar line 71
Moving Average
Plot Moving Averagefalseboolplot
MA Length100intmovingaverage_signal
RSI Settings
RSI Length14int · min 1up down
Sourceclosesourceup down
Oversold, Trigger to Enter First Position29intco

What it calculates

  • SMAclose, MA Length (100)movingaverage_signal · line 52
  • RMA / Changemath.max(ta.change(rsiSourceInput), 0), RSI Length (14)up · line 55
  • RMA / Change-math.min(ta.change(rsiSourceInput), 0), RSI Length (14)down · line 56

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.

closecloseprice datamoving_averageMA Lengthsetting · 100rsiLengthInputRSI Lengthsetting · 14bar_lookbackLines Bar Lookbacksetting · 4999posCountMax Amount of DCA Layerssetting · 8openopenprice datatakeProfitAllClose All %setting · 6takeProfitTake Profit %setting · 3incrementBase % to calculate DCA…setting · 2overSoldOversold, Trigger to En…setting · 29movingaverage_signalSMA→ movingaverage_signalupRMA / Change→ updownRMA / Change→ downentry_priceentry_pricevaluedca_pricedca_pricevaluecountcountvaluemax_barmax_barvaluelinesArraylinesArrayvalueqqvaluersirsivaluestop_levelstop_levelvaluetake_profit_pricetake_profit_pricevaluebase_numberbase_numbervaluedca_level_calcdca_level_calcvaluedca_level_mode, entry_id, exit_from, exit_iddca_level_mode · entry_…4 valuescococonditiondca_line, average_price, stop_line, first_entry_line, last_entry_priceColourdca_line · average_price +3entry:FE1Open FE1strategy.entryentry:entry_idOpen entry_idstrategy.entryexit:Exit FEexit Exit FEstrategy.exitexit:exit_idexit exit_idstrategy.exitclose_all:close_all strategy.close_allcancel_all:cancel_all strategy.cancel_allplot:53plotplot

Order rules

OrderFires whenBy defaultLine
Open FE1 longco and strategy.position_size == 0 and window()On86
Open entry_id longstrategy.opentrades == i and i < posCountOn100
Exit Exit FE limitstrategy.opentrades > 0 and window()On114
Exit exit_id limitstrategy.opentrades > 0 and window()On120
Close strategy.opentrades > 0 and ta.crossover(close,stop_level) and window()On123
cancel_all strategy.position_size[1] > 0 and strategy.position_size == 0On126
Close strategy.position_size[1] > 0 and strategy.position_size == 0On127

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

Does it repaint?

Yes

The live replay did not match history.

1/20trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • 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 1D+9.6%+102.5%7165%2.2312.3%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−1.1%+5.5%1747%0.7812.2%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−6.3%+9.8%5456%0.5816.6%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+1.3%+8.4%2255%1.3213.8%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−6.5%+16.7%2846%0.4014.7%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.7%+21.5%2352%1.187.2%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+2.3%+148.3%4367%1.3912.4%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+4.5%+17.1%2277%7.921.5%8 May 2026 – 21 Oct 2026

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

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market0—$0.00
Sideways market13100%$17.34
Falling market5857%$30.50

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

3.2%

The 95th percentile of the worst drawdown when the same 71 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 1.6% to 3.2%; the tick is what actually happened, 4.3%. Order luck alone moves it this much.

0%5%
All 71 trades
SideEntryExitBarsP&L
long26 Jun 2024 61,806.0030 Jun 2024 62,395.604$0.52
long26 Jun 2024 61,806.001 Jul 2024 63,689.205$0.02
long28 Jun 2024 60,566.001 Jul 2024 63,689.203$3.16
long7 Jul 2024 58,230.108 Jul 2024 56,309.901−$2.19
long7 Jul 2024 58,230.108 Jul 2024 57,564.201−$0.03
long7 Jul 2024 57,061.708 Jul 2024 57,564.201$0.44
long7 Jul 2024 57,061.7010 Jul 2024 58,803.203$0.07
long7 Jul 2024 55,862.7010 Jul 2024 58,803.203$3.00
long7 Jul 2024 55,862.7014 Jul 2024 59,204.007$0.13
long8 Jul 2024 54,608.5014 Jul 2024 59,204.006$4.91
long7 Aug 2024 56,022.007 Aug 2024 56,551.800$0.51
long7 Aug 2024 56,022.007 Aug 2024 57,676.000$0.07
long7 Aug 2024 54,897.707 Aug 2024 57,676.000$3.11
long6 Sep 2024 53,743.909 Sep 2024 55,390.103$1.81
long6 Sep 2024 53,743.909 Sep 2024 55,390.103$1.82
long6 Sep 2024 53,743.909 Sep 2024 55,390.103$1.82
long2 Mar 2025 86,064.502 Mar 2025 88,892.600$2.11
long4 Mar 2025 84,339.204 Mar 2025 85,189.500$0.56
long4 Mar 2025 84,339.204 Mar 2025 86,957.600$0.00
long4 Mar 2025 84,339.204 Mar 2025 86,957.600$1.92
long4 Mar 2025 82,571.104 Mar 2025 86,957.600$0.01
long4 Mar 2025 82,571.104 Mar 2025 86,957.600$3.28
long9 Mar 2025 84,339.2010 Mar 2025 81,058.701−$2.61
long9 Mar 2025 84,339.2010 Mar 2025 83,088.001−$0.01
long9 Mar 2025 84,339.2010 Mar 2025 83,088.001−$1.04
long9 Mar 2025 84,339.2011 Mar 2025 81,058.702−$0.06
long9 Mar 2025 82,571.1011 Mar 2025 81,058.702−$1.25
long9 Mar 2025 80,730.1011 Mar 2025 81,058.702$0.01
long9 Mar 2025 80,730.1012 Mar 2025 83,240.603$1.75
long10 Mar 2025 78,700.9012 Mar 2025 83,240.602$0.54
long10 Mar 2025 78,700.9014 Mar 2025 83,163.604$2.80
long10 Mar 2025 78,700.9014 Mar 2025 83,163.604$0.75
long10 Mar 2025 78,700.9014 Mar 2025 84,929.004$3.92
long12 Mar 2025 80,730.1014 Mar 2025 84,929.002$0.51
long12 Mar 2025 80,730.1019 Mar 2025 85,052.507$3.07
long13 Mar 2025 80,730.1019 Mar 2025 85,052.506$0.34
long13 Mar 2025 80,730.1019 Mar 2025 85,052.506$3.09
long16 Mar 2025 82,571.1019 Mar 2025 85,052.503$1.91
long19 Nov 2025 92,960.8020 Nov 2025 91,935.101−$0.86
long19 Nov 2025 92,960.8021 Nov 2025 84,697.802−$0.06
long19 Nov 2025 91,097.5021 Nov 2025 84,697.802−$4.81
long19 Nov 2025 89,188.4021 Nov 2025 84,697.802−$0.16
long19 Nov 2025 89,188.4023 Nov 2025 87,240.004−$1.46
long20 Nov 2025 87,202.4023 Nov 2025 87,240.003−$0.01
long20 Nov 2025 87,202.4023 Nov 2025 87,623.003$0.19
long21 Nov 2025 85,018.1023 Nov 2025 87,623.002$0.19
long21 Nov 2025 85,018.1026 Nov 2025 89,823.505$3.10
long21 Nov 2025 82,143.9026 Nov 2025 89,823.505$0.58
long21 Nov 2025 82,143.9026 Nov 2025 89,823.505$5.29
long21 Nov 2025 84,697.8026 Nov 2025 89,823.505$3.90
long23 Nov 2025 87,202.4026 Nov 2025 89,823.503$2.01
long3 Feb 2026 78,738.604 Feb 2026 76,127.901−$2.39
long3 Feb 2026 78,738.606 Feb 2026 66,584.603−$0.32
long3 Feb 2026 77,159.806 Feb 2026 66,584.603−$8.96
long3 Feb 2026 77,159.806 Feb 2026 71,631.903−$0.23
long3 Feb 2026 75,541.506 Feb 2026 71,631.903−$3.47
long3 Feb 2026 75,541.508 Feb 2026 71,593.205−$0.05
long3 Feb 2026 73,854.808 Feb 2026 71,593.205−$2.08
long4 Feb 2026 71,990.508 Feb 2026 71,593.204−$0.10
long4 Feb 2026 71,990.5025 Feb 2026 66,619.1021−$3.92
long5 Feb 2026 69,514.5025 Feb 2026 66,619.1020−$0.77
long5 Feb 2026 69,514.5028 Feb 2026 66,706.5023−$1.89
long5 Feb 2026 64,697.3028 Feb 2026 66,706.5023$0.60
long5 Feb 2026 64,697.304 Mar 2026 71,564.6027$3.71
long7 Feb 2026 69,514.504 Mar 2026 71,564.6025$0.84
long7 Feb 2026 69,514.504 Mar 2026 71,564.6025$1.26
long8 Feb 2026 71,593.204 Mar 2026 71,564.6024−$0.13
long9 Feb 2026 69,514.504 Mar 2026 71,564.6023$1.90
long23 Feb 2026 64,697.304 Mar 2026 71,564.609$6.58
long28 Feb 2026 64,697.304 Mar 2026 71,564.604$6.53
long12 Jun 2026 63,626.0014 Jun 2026 65,559.802$2.07

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
Simple_RSI+PA+DCA Strategy this page—v5 strategy+9.6%7112.3%
Infiten Slope Strategy by spiritualhealer117sma rmav4 strategy+47.2%2635.5%
DMI Modified Strategy by dman103sma rmav4 strategy+42.4%3945.7%
Optimized Keltner Channels SL-TP Strategy for BTC by chanu_lev10ksma rmav4 strategy−19.4%3670.0%
volume rsi strategy by pro trader123 by VSliprma smav5 strategy−0.0%200.0%
Flawless Victory Strategy - 15min BTC Machine Learning Strategy by Bungholerma smav4 strategy+21.3%635.4%

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • No v6-only features. v6 is not needed to run this script.

Clean v5

Verified

Nothing to change.

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 71 before, 71 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © A3Sh-//@version=5+//@version=6// Study of a Simple RSI based, PA (priceaveraging) and DCA strategy that opens a new position everytime it hits a specified price level below the first entry.⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 57 msWith a workaround 1,000 bars in 138 msNot measured
PineTSNot testedNot testedNot measured

Zeal Terminal's engine currently reads an order side written as direction = strategy.long as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 86, 100) 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.

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///// © A3Sh//@version=5// Study of a Simple RSI based, PA (priceaveraging) and DCA strategy that opens a new position everytime it hits a specified price level below the first entry.// The first entry is opened when the specified rsi and moving average conditions are met. // The following DCA levels are calculated exponentially and set, starting with a specified % of price drop. // The disctance between the dca levels can be changed with the exponential scale.// Each position closes individually when it reaches a specified take profit.// The position can re-open again when it hits the price level again.// Each time a position is closed and reopened, the average price drops a little.// The position stays open until the first entry closes or when the price reaches the Stop level.// When the price reaches the Stop level, all positions will close at once.// The RSI and MA code for opening the entry is adapted from the Optimized RSI Buy the Dips strategy, by Coinrule.// This code is used for study purposes, but any other low/ dip finding indicator can be used.// https://www.tradingview.com/script/Pm1WAtyI-Optimized-RSI-Strategy-Buy-The-Dips-by-Coinrule/// Dynamic DCA layers are inspired by the Backtesting 3commas DCA Bot v2, by rouxam// This logic gives more flexibility because you can dyanically change the amount of dca entries.// https://www.tradingview.com/script/8d6Auyst-Backtesting-3commas-DCA-Bot-v2/// The use of for loops to (re)open and close different entries separately is based on the Simple_Pyramiding strategy.// https://www.tradingview.com/script/t6cNLqDN-Simple-Pyramiding/strategy('Simple_RSI+PA+DCA', overlay=true, pyramiding=99, initial_capital=500, calc_on_order_fills=true, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.075, close_entries_rule='FIFO')// Backtest Window //start_time   = input.time(defval=timestamp("01 April 2021 20:00"), group = "Backtest Window", title="Start Time")end_time     = input.time(defval=timestamp("01 Aug 2030 20:00"),   group = "Backtest Window", title="End Time")window() => time >= start_time and time <= end_time// Inputs //takeProfit      = input.float  (3,           group = 'Risk',           title = 'Take Profit %', step=0.1)takeProfitAll   = input.float  (6,           group = "Risk",           title = 'Close All %',   step=0.1)linear_mode     = input.bool   (false,       group = 'DCA Settings',   title = 'Switch to linear DCA Layers')posCount        = input.int    (8,           group = 'DCA Settings',   title = 'Max Amount of DCA Layers')increment       = input.float  (2,           group = 'DCA Settings',   title = 'Base % to calculate DCA layers', step=0.5, minval=1.1)bar_lookback    = input.int    (4999,        group = 'DCA Settings',   title = 'Lines Bar Lookback', maxval = 4999)plotMA          = input.bool   (false,       group = 'Moving Average', title = 'Plot Moving Average')moving_average  = input.int    (100,         group = 'Moving Average', title = 'MA Length' )rsiLengthInput  = input.int    (14,          group = 'RSI Settings',   title = "RSI Length", minval=1)rsiSourceInput  = input.source (close,       group = 'RSI Settings',   title = 'Source')overSold        = input.int    (29,          group = 'RSI Settings',   title = 'Oversold, Trigger to Enter First Position')// variables //var open_position    = true   // true when there are open positionsvar entry_price      = 0.0    // the entry price of the first entryvar dca_price        = 0.0    // the price of the different dca layersvar int count        = 0      // bar counter since first open positionvar int max_bar      = 0      // max bar buffer variable for DCA lines, stop lines, average pricevar line dca_line    = na     // lines variable for creating dca lines// arrays //linesArray = array.new_float(posCount,na)  // array to store different dca price levels for creating the dca lines// Create max bar buffer for DCA lines, Stop and average price lines ///max_bar := count >= bar_lookback ? bar_lookback : count// Order size based on first entry and amount of DCA layersq = (strategy.equity  / posCount + 1) / open// Calculate Moving Averagesmovingaverage_signal = ta.sma(close ,moving_average)plot (plotMA ? movingaverage_signal : na, color = color.new(#f5ff35, 0))// RSI calculations //up   = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)rsi  = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))// Buy Signal (co)co = ta.crossover(rsi, overSold) and close < movingaverage_signal// Create a white line for average price, since the last opened position //average_price = line.new(x1 = bar_index - max_bar, y1 = strategy.position_avg_price, x2 = bar_index, y2 = strategy.position_avg_price, color = color.white)    // Stop //// Create a red Stop level line based on a specified % above the average price //stop_level = strategy.position_avg_price + (strategy.position_avg_price / 100 * takeProfitAll)stop_line  = line.new(x1 = bar_index - max_bar, y1 = stop_level, x2 = bar_index, y2 = stop_level, color = color.red)    // Take profit definition per open position //take_profit_price = close * takeProfit / 100 / syminfo.mintick// Make sure the Stop level and average price level don't excied the bar buffer to avoid errors //if count <= bar_lookback    line.set_x1(stop_line,     strategy.opentrades.entry_bar_index(strategy.opentrades - 1))    line.set_x1(average_price, strategy.opentrades.entry_bar_index(strategy.opentrades - 1))// Exponential DCA Layer Calculation fucntion --> New caclulation, the base number is calculated based the range between the entry_price and 0 and the amount of DCA layers //dca_exponent_level(index) =>    base_number = math.pow(entry_price, (1 / posCount))    dca_level_calc = (entry_price - (math.pow(base_number,index))) * (1 - ((math.pow(1 + (increment / 100),index)) - 1))// Linear DCA Layer Calculation // Added option to switchdca_linear_level(index) =>      entry_price - ((entry_price / posCount) * index)// Set  Entries //// Open the first entry and set the entry price //if co and strategy.position_size == 0 and window()     open_position := true    entry_price   := close    strategy.entry(id = 'FE1', direction = strategy.long, qty = q)      first_entry_line = line.new(x1 = bar_index - max_bar, y1 = entry_price, x2 = bar_index, y2 = entry_price, color = color.blue)// Start bar counting since the position is open //if open_position == true    count := count + 1// Set the DCA entries //// Prices below 1 are not set to avoid negative prices //if strategy.position_size > 0 and window()    for i = 0 to strategy.opentrades        dca_level_mode = linear_mode ? dca_linear_level(i) : dca_exponent_level(i)        if strategy.opentrades == i and i < posCount            dca_price := dca_level_mode            entry_id = 'DCA' + str.tostring(i + 1)             strategy.entry(id = entry_id, direction = strategy.long, limit = dca_price, qty = q)  // Store the values of the different dca price levels in an array and create the dca lines // // Prices below 1 are not stored//if open_position==true and window()     for i = 1 to posCount -1        dca_level_mode = linear_mode ? dca_linear_level(i) : dca_exponent_level(i)        array.push(linesArray, dca_level_mode)         for i = 1 to array.size(linesArray) - 1        dca_line := line.new(x1 = bar_index - max_bar, y1 = array.get(linesArray, i), x2 = bar_index, y2 = array.get(linesArray, i),color = color.blue)// Create thick line to show the last Entry price //last_entry_price = line.new(x1 = bar_index[5], y1 = strategy.opentrades.entry_price(strategy.opentrades - 1), x2 = bar_index, y2 = strategy.opentrades.entry_price(strategy.opentrades - 1),color = color.rgb(255, 0, 204), width = 5)// Exit the first entry when the take profit triggered //   if strategy.opentrades > 0 and window()     strategy.exit(id = 'Exit FE', from_entry = 'FE1', profit = take_profit_price)// Exit DCA entries when take profit is triggered //if strategy.opentrades > 0 and window()     for i = 1 to strategy.opentrades         exit_from = 'DCA' + str.tostring(i + 1)        exit_id = 'Exit_' + str.tostring(i + 1)        strategy.exit(id = exit_id, from_entry = exit_from, profit = take_profit_price)// Close all positions at once when Stop is crossed //if strategy.opentrades > 0 and ta.crossover(close,stop_level) and window()     strategy.close_all()// Make sure nothing is open after alle positions are closed and set the condiftion back to be open for new entries //if strategy.position_size[1] > 0 and strategy.position_size == 0    strategy.cancel_all()    strategy.close_all()    line.delete(average_price)    line.delete(stop_line)    line.delete(dca_line)    open_position := false   // All position are closed, so back to false    count := 0               // Reset bar counter