Reputation: 1
I am currently using a strategy with 0.5% stop loss of position size and 4% and 8% take profit of position size.
Normally, the strategy works perfectly with the setting. However, tradingview cannot exit the position with the entered position in the same bar. It will therefore lead to a greater loss of my position (more than 0.5% as the photo below).
May I know how can I exit my position in the same bar entered but not causing other problems? (such as
calc_on_order_fills = true
, calc_on_every_tick = true
may influence my entries)
TP1 = strategy.position_avg_price + percentAsPoints(TP1Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
TP2 = strategy.position_avg_price + percentAsPoints(TP2Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
SL = strategy.position_avg_price - percentAsPoints(SLPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
//Stop loss for short position
if strategy.position_size > 0
strategy.exit('TP1', from_entry='Long', qty=initial_position_size * TP1_Ratio, limit=TP1, stop=SL)
strategy.exit('TP2', from_entry='Long', limit=TP2, stop=SL)
STP1 = strategy.position_avg_price + percentAsPoints(STP1Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
STP2 = strategy.position_avg_price + percentAsPoints(STP2Perc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
SSL = strategy.position_avg_price - percentAsPoints(SSLPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
//Stop loss for short position
if strategy.position_size < 0
strategy.exit('STP1', from_entry='Short', qty=initial_position_size * STP1_Ratio, limit=STP1, stop=SSL)
strategy.exit('STP2', from_entry='Short', limit=STP2, stop=SSL)
Upvotes: 0
Views: 1858
Reputation: 1927
So I was having the same issue but think I have figured it out
In strategy arguments set calc_on_order_fills = true. This is the same as the "After Order is Filled" checkbox on the strategy settings in the UI.
However you may notice that it also re-executes any long/ short entries that you have again after the order is filled on the same bar. See example https://www.tradingview.com/x/pwvyCOvl
Unless this is what you want, you can add this condition to you long entry IF Statement. It just makes sure that you only go long/ short if there is an existing closed trade on that same bar.
//Either first trade, or the most recent closed trade (identified by exit bar index) is not on the current bar (bar index)
if longEntry and ((strategy.closedtrades == 0) or (bar_index != strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1)))
strategy.entry("Long Entry", strategy.long)
if shortEntry and ((strategy.closedtrades == 0) or (bar_index != strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1)))
strategy.entry("Short Entry", strategy.short)
Upvotes: 0