At market open I'd like to check if current price jump 3% higher than yesterday's close, If so, I will set
contest.TrailingStop = True
And then price is monitored, if price continue to rise another 2%, all short position will be cleared. using the following code.
def handle_data(context,data):
if context.TrailingStop == True:
current = data.current(context.VXX,'price')
exchange_time = get_datetime('US/Eastern')
#log.info("realtime {}".format(current))
#if exchange_time.date() == context.startDate :
# log.info("realtime {}".format(current))
if current>context.stop:
rebalance(context.sidsLongVol, data, 0.0)
return
And trailing stop monitor will be canceled using
contest.TrailingStop = False
at market close .
During the backtest one day when the trailing stop order is triggered unexpected behavior just happened. The algorithm keeps selling and buying causing a dramatic loss in one day. Check the transactions in the plot [Big loss just happened ][1]
[1]: http://i.imgur.com/Y83boTx.png
The tricky part is when I begin the backtest from 2011/01/01 , the big loss happened.
But if i begin the backtest after 2012, the codes works correctly. I am confused now. I can't imagine what will happen if I use real money