Dear Quantopians,
I wrote an algo which trades long (so far, for testing) when the following things happen:
- gap up on market opening in an asset (AAPL for testing). Gap has to be 0.5%
- momentum up (in a direction of the gap) is present even after the first 5 min bar . I detect the latter using the rule "body of the first 5 min bar is relatively small comparing to upper & lower wicks".
The overall logic here is that if gap was up and momentum is rolling on after 5 min we could jump in opening a long position
and then we are rolling on with an asset for some time until the momentum is exhausted. To achieve the latter, we need to implement a trailing stop loss. Once position is open, I am doing trailing stop loss (credit goes to John F and his post here.
The position is closed either when current price hits a trailing stop price (set to -5% of the highest price today) or, if position is held open until the last 5 min of a day, all positions will be closed 4 min before the market closes
Algo is generally working, however, something odd happens when I tested it with AAPL. Positions are often (not always) held over-night and/or not properly close (selling more than opened before resulting in exposure to short position over-night)
I think that my ordering management is poor or maybe some other errors too. Also, the commentators to the John F. post mentioned that one has to always check if there are unfilled orders every time when ordering again.
I would appreciate suggestions and/or code snippets to fix those things.
The algo and backtest are attached.