Close position after 5 bar passes
Close position after 5 bar passes
20 Sep 2022, 09:27
Hello
I need a method to close the position only if there are least 5 bars after opening the position.
It means should be at least 5 bars between opening and closing a position.
Thank you very much
Replies
firemyst
04 Oct 2022, 03:18
RE:
r.stipriaan said:
Hi hamirady60,
I think its not posible to close positon on bars, i use this method, it works with time.
var SellPosition = Positions.Find("Short", SymbolName, TradeType.Sell); if (SellPosition != null && SellPosition.EntryTime.AddHours(5) < TimeInUtc) { ClosePosition(Positions.Find("Short", SymbolName, TradeType.Sell)); }
Positions can be closed on bars.
Here's one way to do it:
1) set a global variable for keeping track:
int _indexOrderPlaced = 0;
int _currentIndex = 0;
2) in OnStart, reset the value to zero:
_indexOrderPlaced = 0;
_currentIndex = Bars.OpenTimes.GetIndexByTime(Bars.OpenTimes.LastValue);
3) When an order is placed, get the bar's current index similar to:
_indexOrderPlaced = Bars.OpenTimes.GetIndexByTime(Bars.OpenTimes.LastValue);
Every time OnBar is called:
//Get the current index
_currentIndex = Bars.OpenTimes.GetIndexByTime(Bars.OpenTimes.LastValue);
//Check if it's within 5 of the order being placed
if (_currentIndex - _indexOrderPlaced > 5)
{
//close the position here
//reset this
_indexOrderPlaced = 0;
}
Just a schematic, but should help to get you started.
@firemyst
r.stipriaan
27 Sep 2022, 21:40
Hi hamirady60,
I think its not posible to close positon on bars, i use this method, it works with time.
@r.stipriaan