3

I am modifying a strategy to only exit the trade after a set number of candles.

I put in an input for timeframe (in inputs section of script) and set the exit rule at the bottom (barssince) - it is working a lot of the time, but some trades are still closing sooner. Can't figure out what is causing this.

What else needs to be done so that it exclusively exits the trade only on the number of bars specified?

Here is the script: https://pastebin.com/8HQyJxa0 (updated)

It seems like when longer expiry times are set, that an UP trade is prematurely closing a DOWN, and vice versa. I really need both trades to be able to run concurrently, closing only after the number of bars specified by timeframe

UPDATE: Apparently using strategy.position_size <= 0 to specify no shares or borrowed could avoid it closing my currently open positions - but not sure how this could fit into the current script.

enter image description here

Drewdavid
  • 3,071
  • 7
  • 29
  • 53

2 Answers2

5

The issue with using strategy.opentrades == 0 is that it does not consider new trades. So if you take a long order, then take a short afterwards, the counting will not restart, since the number of open trades is the same, and the counting will keep as if it were from the long order.

That is why I like to use strategy.position_size, since it is based upon the quantity of the position. So if there is a change on the quantity, it is either because one position was closed (so it drops to 0), or because a new position was opened. I had to add 1 to the bars variable because of it, but it works.

opened_order = strategy.position_size[0] != strategy.position_size[1] and strategy.position_size[0] != 0
bars = barssince(opened_order) + 1
strategy.close_all(when=(bars>=timeframe))
Eduardo
  • 184
  • 8
  • I'll elaborate - trades will end before the timeframe limit, but the timeframe seems to be acting as a max. So something else is closing them first... Don't see what! Guessing it's something built into how TradingView works? – Drewdavid Sep 29 '20 at 04:11
  • Someone in the TradingView pine script chat said I should try using `strategy.position_size <= 0` to specify no shares or borrowed to avoid it closing my first position - but not sure how this could fit into the current script. – Drewdavid Sep 29 '20 at 18:23
2

try this;

BarsSinceFirstEntry() =>
    bar_index - strategy.opentrades.entry_bar_index(0)

if BarsSinceFirstEntry() == 20
    strategy.close_all()
Hevzek
  • 21
  • 3