Hi,
I need to code an intraday strategy that has multiple positions open. Positions are only held intraday, so at the last Bar all positions need to be closed. Pretty simple so far.
However, due to liquidtiy issues I´d like to start exit positions prior to the close. If I have for example 5 positions open I want to start exit the oldes position 5 bars before the last bar of the day.
First step would be to determine the bar number of the last bar each trading day. I cannot do this static, since trading hours used to change in my test period. Any suggestions on how to implement this?
Regards,
dansmo
Size:
Color:
Hi Daniel,
Here's a way to do it (the largest code block, of course):
Intraday / Multi-Time Frame | Keep from holding positions overnightThe logic is pretty straightforward, so to exit N bars before the close you'd need to modify this line accordingly:
CODE:
Please log in to see this code.
The actual market close time can be determined through the MarketInfo.CloseTimeNative property (set either in your data provider or in Market Manager).
Size:
Color:
Hi Eugene,
your solution does need a market close time.
The problem is that in a multi-year backtest the close time is not always the same, i.e due to overall change in market hours, holidays etc.
I found this code in WealthSCript QuickRef:
CODE:
Please log in to see this code.
However, this will also only work if the number of bars is constant, which is not the case.
Size:
Color:
You can check the SpecialHours first to see if the day is a shortened trading session.
Or as long a multi-year backtest is considered, peek ahead with IsLastBarOfDay, subtract the number of bars (e.g. 5), and come with the right bar to exit.
Size:
Color:
QUOTE:
peek ahead with IsLastBarOfDay
That´s probably the way to go. Looping though all bars and create a <Date, LastBar> Dictionary.
Size:
Color:
How would you find the oldest active position at a specified bar? As this is a multiple positions strategy all my exits are handled with an positions-loop.
I am thinking in this direction:
CODE:
Please log in to see this code.
How would you approach this?
Size:
Color:
Position.EntryBar?
Size:
Color:
Haha. Good answer.
Does ActivePositions list all active positions at the current bar?
How can I get a list of those positions open at the current bar? Do I need to create it myself?
That was my try but it did not work:
CODE:
Please log in to see this code.
So the only way would be to have another positions loop to create a list of active positions for the current bar and iterate to find the oldest?
Size:
Color:
The oldest Position is:
CODE:
Please log in to see this code.
Size:
Color:
So this list is "synchronized" to this bar already?
Size:
Color:
Yep, you can use it in a loop. Only a Position with .Active == true will make its way to the ActivePositions.
Size:
Color:
Good to know. Somehow I thought that this only works for the last bar. So I tried to program something that is already there....now it works fine.
Size:
Color: