i have setup conditions for entries on shorts and longs and have setup and open trades limit, set by the pyramiding value.
when pyramiding = 1 allowing only 1 open order, everything works great.
when pyramiding = 2 or more , the strategy tester at some point begins closing short positions when opening long positions
In order to achieve this i have:
- created unique id’s for entries
- cycled through opentrades
- established strategy.exit parameters binding to unique entry id’s.
- established quantity parameters.
strategy configuration ->
//@version=5
strategy("EMA - RSI - CCI strategy",overlay=true, max_labels_count=300, calc_on_every_tick=true, default_qty_type=strategy.cash, default_qty_value=100, pyramiding=2, close_entries_rule = "ANY")
//----------------------------------------------------
// User Inputs
rsiLength = input.int(14, "RSI Length")
cciLength = input.int(20, "CCI Length")
emaFastLength = input.int(10, "Fast EMA Length")
emaSlowLength = input.int(20, "Slow EMA Length")
pyramid = input.int(2, "pyramid")
here is the code in question ->
// Execute trades only within the specified date range
if (withinDateRange) and (strategy.opentrades < pyramid)
if (longCond)
strid = str.format("Long_{0}_{1}", tickerName, str.tostring(totalTrades))
strategy.entry(strid, strategy.long, alert_message = 'entry')
totalTrades += 1
//strategy.entry("Long", strategy.long)
if (shortCond and noPosition)
strid = str.format("Short_{0}_{1}", tickerName, str.tostring(totalTrades))
strategy.entry(strid, strategy.short, alert_message = 'entry')
totalTrades += 1
//strategy.entry("Short", strategy.short)
// Exit logic
atrValue = ta.atr(6)
for i = 0 to (strategy.opentrades - 1)
lastOpentradeId = strategy.opentrades.entry_id(i)
lastOpentradePrice = strategy.opentrades.entry_price(i)
lastOpentradeSize = strategy.opentrades.size(i)
if str.contains(lastOpentradeId, "Long")
float stopLossPrice = lastOpentradePrice - (500* atrValue)
float takeProfitPrice = lastOpentradePrice + (5 * atrValue)
strategy.exit('Exit_' + lastOpentradeId, from_entry=lastOpentradeId, stop=stopLossPrice, qty = lastOpentradeSize, limit=takeProfitPrice, alert_message = "close")
else if str.contains(lastOpentradeId, "Short")
float stopLossPrice = lastOpentradePrice + (5 * atrValue)
float takeProfitPrice = lastOpentradePrice - (5 * atrValue)
strategy.exit('Exit_' + lastOpentradeId, from_entry=lastOpentradeId, stop=stopLossPrice, qty = lastOpentradeSize, limit=takeProfitPrice, alert_message = "close")