def testSL(self): #stop loss/take profit b1 = Bar(self.sym, "20010102-230000,EURUSD,0.9507,0.9509,0.9505,0.9506") b2 = Bar(self.sym, "20010102-230000,EURUSD,0.9507,0.9509,0.9499,0.9506") #buy order at 9505 o1 = Order(self.sym, dir=Order.BUY, type=Order.MARKET, level=0.9505, size=10000) #stop loss at 9499 sl = Order(self.sym, dir=Order.SELL, type=Order.STOP, level=0.9499, size=-10000) #take profit at 9510 tp = Order(self.sym, dir=Order.SELL, type=Order.LIMIT, level=0.9510, size=-10000) #stop loss hit cancels tp and vice versa Order.OCO(sl, tp) #when the order is filled it activates sl/tp o1.trigger(sl, tp) self.bt.book.add(o1, sl, tp) self.bt.next_bar(self.sym, b1) #the order should be filled self.aEq(len(self.bt.poslist.open), 1) self.aItEq([sl.id, tp.id], self.bt.book.active) self.bt.next_bar(self.sym, b2) self.aEq(len(self.bt.poslist.open), 0) self.aEq(len(self.bt.poslist.closed), 1) self.aEq(len(self.bt.book.active), 0) self.aEq(self.bt.equity, 99994)
def testOpenRewind(self): #in this case we have a sl/tp, and get a bar which triggers them both #when this happens, we cancel both the orders and unwind the original position #as if it never happened. If this is happening a lot you need lower time frame data #stop loss/take profit b1 = Bar(self.sym, "20010102-230000,EURUSD,0.9507,0.9510,0.9499,0.9506") #buy order at 9505 o1 = Order(self.sym, dir=Order.BUY, type=Order.MARKET, level=0.9505, size=10000) #stop loss at 9499 sl = Order(self.sym, dir=Order.SELL, type=Order.STOP, level=0.9499, size=-10000) #take profit at 9510 tp = Order(self.sym, dir=Order.SELL, type=Order.LIMIT, level=0.9510, size=-10000) #stop loss hit cancels tp and vice versa Order.OCO(sl, tp) #when the order is filled it activates sl/tp o1.trigger(sl, tp) self.bt.book.add(o1, sl, tp) self.bt.next_bar(self.sym, b1) #the order should be filled self.aEq(len(self.bt.poslist.open), 1) self.aItEq([sl.id, tp.id], self.bt.book.active) self.bt.next_bar(self.sym, b1) self.aEq(len(self.bt.poslist.open), 0) self.aEq(len(self.bt.poslist.closed), 0) self.aEq(len(self.bt.poslist.rewinded), 1) self.aEq(len(self.bt.book.active), 0) self.aEq(self.bt.equity, 100000)
def test_oco(self): o1 = Order() o2 = Order() Order.OCO(o1, o2) self.aEq(len(o1.cancels), 1) self.aIn(o2.id, o1.cancels) self.aEq(o2.cancel_parent, o1.id) self.aEq(len(o2.cancels), 1) self.aIn(o1.id, o2.cancels) self.aEq(o1.cancel_parent, o2.id) with self.aRaise(InvalidOrderException): Order.OCO(o1, None) with self.aRaise(InvalidOrderException): Order.OCO(o1, (o2,)) with self.aRaise(TypeError): Order.OCO((o1,), o2)