Roger Keulen
Roger Keulen

Reputation: 82

TradingView Strategy Tester Trade List showing closed trades in order of execution

I'm trying to understand how i can make a strategy where i can use pyramiding and have multiple order ids. So that i can exit a trade with a specified ID and correct comments.

Is there a way to enter and exit trades in different order ?

enter image description here

I have writen this piece of code to test with unqiue ids. I am trying to see, if i can exit a trade with limit and stoploss. But in the Tradelist everything looks ordered in time. Thus the entries are ordered and the exit`s are ordered in time. Thus when i exit a trade out of sequense, the trade list will have different types of trades mixed together. I expected only A entries with A exits.

//@version=5
strategy("My strategy", overlay=true, precision=2, pyramiding=100, commission_type=strategy.commission.percent, commission_value=0.02, initial_capital=100, currency=currency.USD, default_qty_type=strategy.cash, calc_on_order_fills=false, calc_on_every_tick=false, process_orders_on_close=false, slippage=0, backtest_fill_limits_assumption=200)

s(value) => str.tostring(value)
p(value, percentage) => value * (1 + (percentage / 100))

id(id) => id + ' ' + s(bar_index)

limitA=p(close, 2)
stopA=p(close, -2)
limitB=p(close, 4)
stopB=p(close, -4)
    
if (bar_index % 20 == 0)
    strategy.entry(id('A'), strategy.long, qty=0.001, comment=id('A') + ' ' + s(close))
    strategy.exit(id('Exit-A'), id('A'), limit=limitA, stop=stopA, comment=id('A') + ' ' + s(limitA) + "/" + s(stopA))

if (bar_index % 20 == 10)
    strategy.entry(id('B'), strategy.long, qty=0.002, comment=id('B') + ' ' + s(close))
    strategy.exit(id('Exit-B'), id('B'), limit=limitB, stop=stopB, comment=id('B') + ' ' + s(limitB) + "/" + s(stopB))

Upvotes: 1

Views: 482

Answers (1)

e2e4
e2e4

Reputation: 3828

The issue could be resolved by declaring the close_entries_rule= parameter of the strategy() function. By default, it's 'First-In-First-Out' (FIFO), so whichever exit signal is triggered - it will close the specified amount from the first entry, if anything is left - it will move to the second entry etc.

By declaring close_entries_rule='ANY' you can force the strategy to close the positions in any order, that way they will be linked to the specified ID.

strategy("My strategy", ... , close_entries_rule = 'ANY')

enter image description here

Upvotes: 1

Related Questions