class OneTraker(object): ''' tracker for one stock ''' def __init__(self, security, strategy, buyingRatio): ''' constructor ''' self.__security = security self.__strategy = strategy self.__startDate = strategy.startDate self.__buyingRatio = buyingRatio # order id self.__stopOrderId = None self.__stopOrder = None self.__buyOrder = None self.__smaShort = Sma(10) self.__smaMid = Sma(60) self.__smaLong = Sma(200) self.__smaVolumeShort = Sma(10) self.__smaVolumeMid = Sma(60) self.__movingLowShort = MovingLow(10) self.__movingLowWeek = MovingLow(3) # state of previous day self.__previousTick = None self.__previousSmaShort = None self.__previousMovingLowShort = None self.__previousMovingLowWeek = None self.__previousSmaMid = None self.__previousSmaLong = None self.__previousSmaVolumeShort = None self.__previousSmaVolumeMid = None def __buyIfMeet(self, tick): ''' place buy order if conditions meet ''' # place short sell order ''' if (self.__smaShort.getLastValue() < self.__smaLong.getLastValue() or self.__smaMid.getLastValue() < self.__smaLong.getLastValue()): if tick.close/self.__previousMovingLowWeek < 0.95: return if self.__previousSmaShort > self.__previousSmaLong and self.__smaShort.getLastValue() < self.__smaLong.getLastValue() and self.__previousSmaVolumeMid < (self.__previousSmaVolumeShort/1.1): # assume no commission fee for now self.__placeSellShortOrder(tick) elif self.__previousSmaLong > self.__previousSmaShort > self.__previousSmaMid and self.__smaLong.getLastValue() > self.__smaMid.getLastValue() > self.__smaShort.getLastValue(): # assume no commission fee for now self.__placeSellShortOrder(tick) ''' # place buy order if (self.__smaShort.getLastValue() > self.__smaLong.getLastValue() or self.__smaMid.getLastValue() > self.__smaLong.getLastValue()): if tick.close / self.__previousMovingLowWeek > 1.05: return if self.__previousSmaShort < self.__previousSmaLong and self.__smaShort.getLastValue( ) > self.__smaLong.getLastValue( ) and self.__previousSmaVolumeMid < ( self.__previousSmaVolumeShort / 1.1): # assume no commission fee for now self.__placeBuyOrder(tick) elif self.__previousSmaLong < self.__previousSmaShort < self.__previousSmaMid and self.__smaLong.getLastValue( ) < self.__smaMid.getLastValue() < self.__smaShort.getLastValue( ) and self.__previousSmaVolumeMid < ( self.__previousSmaVolumeShort / 1.1): # assume no commission fee for now self.__placeBuyOrder(tick) def __placeSellShortOrder(self, tick): ''' place short sell order''' share = math.floor(self.__strategy.getAccountCopy().getCash() / float(tick.close)) sellShortOrder = Order(accountId=self.__strategy.accountId, action=Action.SELL_SHORT, is_market=True, security=self.__security, share=share) if self.__strategy.placeOrder(sellShortOrder): self.__buyOrder = sellShortOrder # place stop order stopOrder = Order(accountId=self.__strategy.accountId, action=Action.BUY_TO_COVER, is_stop=True, security=self.__security, price=tick.close * 1.05, share=0 - share) self.__placeStopOrder(stopOrder) def __getCashToBuyStock(self): ''' calculate the amount of money to buy stock ''' account = self.__strategy.getAccountCopy() if (account.getCash() >= account.getTotalValue() / self.__buyingRatio): return account.getTotalValue() / self.__buyingRatio else: return 0 def __placeBuyOrder(self, tick): ''' place buy order''' cash = self.__getCashToBuyStock() if cash == 0: return share = math.floor(cash / float(tick.close)) buyOrder = Order(accountId=self.__strategy.accountId, action=Action.BUY, is_market=True, security=self.__security, share=share) if self.__strategy.placeOrder(buyOrder): self.__buyOrder = buyOrder # place stop order stopOrder = Order(accountId=self.__strategy.accountId, action=Action.SELL, is_stop=True, security=self.__security, price=tick.close * 0.95, share=0 - share) self.__placeStopOrder(stopOrder) def __placeStopOrder(self, order): ''' place stop order ''' orderId = self.__strategy.placeOrder(order) if orderId: self.__stopOrderId = orderId self.__stopOrder = order else: LOG.error("Can't place stop order %s" % order) def __sellIfMeet(self, tick): ''' place sell order if conditions meet ''' pass def orderExecuted(self, orderId): ''' call back for executed order ''' if orderId == self.__stopOrderId: LOG.debug("smaStrategy stop order canceled %s" % orderId) # stop order executed self.__clearStopOrder() def __clearStopOrder(self): ''' clear stop order status ''' self.__stopOrderId = None self.__stopOrder = None def __adjustStopOrder(self, tick): ''' update stop order if needed ''' if not self.__stopOrderId: return if self.__stopOrder.action == Action.SELL: orgStopPrice = self.__buyOrder.price * 0.95 newStopPrice = max(((tick.close + orgStopPrice) / 2), tick.close * 0.85) newStopPrice = min(newStopPrice, tick.close * 0.95) if newStopPrice > self.__stopOrder.price: self.__strategy.tradingEngine.cancelOrder( self.__security, self.__stopOrderId) stopOrder = Order(accountId=self.__strategy.accountId, action=Action.SELL, is_stop=True, security=self.__security, price=newStopPrice, share=self.__stopOrder.share) self.__placeStopOrder(stopOrder) ''' elif self.__stopOrder.action == Action.BUY_TO_COVER: orgStopPrice=self.__buyOrder.price * 1.05 newStopPrice=min(((orgStopPrice + tick.close) / 2), tick.close * 1.15) newStopPrice=max(newStopPrice, tick.close * 1.05) if newStopPrice < self.__stopOrder.price: self.__strategy.tradingEngine.cancelOrder(self.__security, self.__stopOrderId) stopOrder=Order(accountId=self.__strategy.accountId, action=Action.BUY_TO_COVER, type=Type.STOP, security=self.__security, price=newStopPrice, share=self.__stopOrder.share) self.__placeStopOrder(stopOrder) ''' def __updatePreviousState(self, tick): ''' update previous state ''' self.__previousTick = tick self.__previousSmaShort = self.__smaShort.getLastValue() self.__previousSmaMid = self.__smaMid.getLastValue() self.__previousSmaLong = self.__smaLong.getLastValue() self.__previousSmaVolumeShort = self.__smaVolumeShort.getLastValue() self.__previousSmaVolumeMid = self.__smaVolumeMid.getLastValue() self.__previousMovingLowShort = self.__movingLowShort.getLastValue() self.__previousMovingLowWeek = self.__movingLowWeek.getLastValue() def tickUpdate(self, tick): ''' consume ticks ''' LOG.debug("tickUpdate %s with tick %s, price %s" % (self.__security, tick.time, tick.close)) # update sma self.__smaShort(tick.close) self.__smaMid(tick.close) self.__smaLong(tick.close) self.__smaVolumeShort(tick.volume) self.__smaVolumeMid(tick.volume) self.__movingLowShort(tick.close) self.__movingLowWeek(tick.close) # if not enough data, skip to reduce risk -- SKIP NEWLY IPOs if not self.__smaLong.getLastValue() or not self.__smaMid.getLastValue( ) or not self.__smaShort.getLastValue(): self.__updatePreviousState(tick) return # if haven't started, don't do any trading if tick.time <= self.__startDate: return # already have some holdings if self.__stopOrderId: self.__sellIfMeet(tick) self.__adjustStopOrder(tick) # don't have any holdings if not self.__stopOrderId and self.__getCashToBuyStock(): self.__buyIfMeet(tick) self.__updatePreviousState(tick)
class OneTraker(object): ''' tracker for one stock ''' def __init__(self, security, strategy, buying_ratio): ''' constructor ''' self.__security=security self.__strategy=strategy self.start_date=strategy.start_date self.buying_ratio=buying_ratio # order id self.__stopOrderId=None self.__stopOrder=None self.__buyOrder=None self.__smaShort=Sma(10) self.__smaMid=Sma(60) self.__smaLong=Sma(200) self.__smaVolumeShort=Sma(10) self.__smaVolumeMid=Sma(60) self.__movingLowShort=MovingLow(10) self.__movingLowWeek=MovingLow(3) # state of previous day self.__previousTick=None self.__previousSmaShort=None self.__previousMovingLowShort=None self.__previousMovingLowWeek=None self.__previousSmaMid=None self.__previousSmaLong=None self.__previousSmaVolumeShort=None self.__previousSmaVolumeMid=None def __buyIfMeet(self, tick): ''' place buy order if conditions meet ''' # place short sell order ''' if (self.__smaShort.getLastValue() < self.__smaLong.getLastValue() or self.__smaMid.getLastValue() < self.__smaLong.getLastValue()): if tick.close/self.__previousMovingLowWeek < 0.95: return if self.__previousSmaShort > self.__previousSmaLong and self.__smaShort.getLastValue() < self.__smaLong.getLastValue() and self.__previousSmaVolumeMid < (self.__previousSmaVolumeShort/1.1): # assume no commission fee for now self.__placeSellShortOrder(tick) elif self.__previousSmaLong > self.__previousSmaShort > self.__previousSmaMid and self.__smaLong.getLastValue() > self.__smaMid.getLastValue() > self.__smaShort.getLastValue(): # assume no commission fee for now self.__placeSellShortOrder(tick) ''' # place buy order if (self.__smaShort.getLastValue() > self.__smaLong.getLastValue() or self.__smaMid.getLastValue() > self.__smaLong.getLastValue()): if tick.close / self.__previousMovingLowWeek > 1.05: return if self.__previousSmaShort < self.__previousSmaLong and self.__smaShort.getLastValue() > self.__smaLong.getLastValue() and self.__previousSmaVolumeMid < (self.__previousSmaVolumeShort / 1.1): # assume no commission fee for now self.__placeBuyOrder(tick) elif self.__previousSmaLong < self.__previousSmaShort < self.__previousSmaMid and self.__smaLong.getLastValue() < self.__smaMid.getLastValue() < self.__smaShort.getLastValue() and self.__previousSmaVolumeMid < (self.__previousSmaVolumeShort / 1.1): # assume no commission fee for now self.__placeBuyOrder(tick) def __placeSellShortOrder(self, tick): ''' place short sell order''' share=math.floor(self.__strategy.getAccountCopy().getCash() / float(tick.close)) sellShortOrder=Order(accountId=self.__strategy.accountId, action=Action.SELL_SHORT, is_market=True, security=self.__security, share=share) if self.__strategy.placeOrder(sellShortOrder): self.__buyOrder=sellShortOrder # place stop order stopOrder=Order(accountId=self.__strategy.accountId, action=Action.BUY_TO_COVER, is_stop=True, security=self.__security, price=tick.close * 1.05, share=0 - share) self.__placeStopOrder(stopOrder) def __getCashToBuyStock(self): ''' calculate the amount of money to buy stock ''' account=self.__strategy.getAccountCopy() if (account.getCash() >= account.getTotalValue() / self.buying_ratio): return account.getTotalValue() / self.buying_ratio else: return 0 def __placeBuyOrder(self, tick): ''' place buy order''' cash=self.__getCashToBuyStock() if cash == 0: return share=math.floor(cash / float(tick.close)) buyOrder=Order(accountId=self.__strategy.accountId, action=Action.BUY, is_market=True, security=self.__security, share=share) if self.__strategy.placeOrder(buyOrder): self.__buyOrder=buyOrder # place stop order stopOrder=Order(accountId=self.__strategy.accountId, action=Action.SELL, is_stop=True, security=self.__security, price=tick.close * 0.95, share=0 - share) self.__placeStopOrder(stopOrder) def __placeStopOrder(self, order): ''' place stop order ''' orderId=self.__strategy.placeOrder(order) if orderId: self.__stopOrderId=orderId self.__stopOrder=order else: LOG.error("Can't place stop order %s" % order) def __sellIfMeet(self, tick): ''' place sell order if conditions meet ''' pass def orderExecuted(self, orderId): ''' call back for executed order ''' if orderId == self.__stopOrderId: LOG.debug("smaStrategy stop order canceled %s" % orderId) # stop order executed self.__clearStopOrder() def __clearStopOrder(self): ''' clear stop order status ''' self.__stopOrderId=None self.__stopOrder=None def __adjustStopOrder(self, tick): ''' update stop order if needed ''' if not self.__stopOrderId: return if self.__stopOrder.action == Action.SELL: orgStopPrice=self.__buyOrder.price * 0.95 newStopPrice=max(((tick.close + orgStopPrice) / 2), tick.close * 0.85) newStopPrice=min(newStopPrice, tick.close * 0.95) if newStopPrice > self.__stopOrder.price: self.__strategy.tradingEngine.cancelOrder(self.__security, self.__stopOrderId) stopOrder=Order(accountId=self.__strategy.accountId, action=Action.SELL, is_stop=True, security=self.__security, price=newStopPrice, share=self.__stopOrder.share) self.__placeStopOrder(stopOrder) ''' elif self.__stopOrder.action == Action.BUY_TO_COVER: orgStopPrice=self.__buyOrder.price * 1.05 newStopPrice=min(((orgStopPrice + tick.close) / 2), tick.close * 1.15) newStopPrice=max(newStopPrice, tick.close * 1.05) if newStopPrice < self.__stopOrder.price: self.__strategy.tradingEngine.cancelOrder(self.__security, self.__stopOrderId) stopOrder=Order(accountId=self.__strategy.accountId, action=Action.BUY_TO_COVER, type=Type.STOP, security=self.__security, price=newStopPrice, share=self.__stopOrder.share) self.__placeStopOrder(stopOrder) ''' def __updatePreviousState(self, tick): ''' update previous state ''' self.__previousTick=tick self.__previousSmaShort=self.__smaShort.getLastValue() self.__previousSmaMid=self.__smaMid.getLastValue() self.__previousSmaLong=self.__smaLong.getLastValue() self.__previousSmaVolumeShort=self.__smaVolumeShort.getLastValue() self.__previousSmaVolumeMid=self.__smaVolumeMid.getLastValue() self.__previousMovingLowShort=self.__movingLowShort.getLastValue() self.__previousMovingLowWeek=self.__movingLowWeek.getLastValue() def tickUpdate(self, tick): ''' consume ticks ''' LOG.debug("tickUpdate %s with tick %s, price %s" % (self.__security, tick.time, tick.close)) # update sma self.__smaShort(tick.close) self.__smaMid(tick.close) self.__smaLong(tick.close) self.__smaVolumeShort(tick.volume) self.__smaVolumeMid(tick.volume) self.__movingLowShort(tick.close) self.__movingLowWeek(tick.close) # if not enough data, skip to reduce risk -- SKIP NEWLY IPOs if not self.__smaLong.getLastValue() or not self.__smaMid.getLastValue() or not self.__smaShort.getLastValue(): self.__updatePreviousState(tick) return # if haven't started, don't do any trading if tick.time <= self.start_date: return # already have some holdings if self.__stopOrderId: self.__sellIfMeet(tick) self.__adjustStopOrder(tick) # don't have any holdings if not self.__stopOrderId and self.__getCashToBuyStock(): self.__buyIfMeet(tick) self.__updatePreviousState(tick)
class SMAStrategy(BaseStrategy): def __init__(self, config, securities): super(SMAStrategy, self).__init__("smaStrategy", securities) self.config = config # order id self.stop_orderrId = None self.stop_orderr = None self.buy_order = None self.__smaShort = Sma(10) self.__smaMid = Sma(60) self.__smaLong = Sma(300) # state of privious day self.__previousTick = None self.__previousSmaShort = None self.__previousSmaMid = None self.__previousSmaLong = None def __buyIfMeet(self, tick, security): ''' place buy order if conditions meet ''' # place short sell order if (self.__smaShort.getLastValue() < self.__smaLong.getLastValue() or self.__smaMid.getLastValue() < self.__smaLong.getLastValue()): if tick.close / self.__previousTick.close < 0.9: return if self.__previousSmaShort > self.__previousSmaLong and self.__smaShort.getLastValue( ) < self.__smaLong.getLastValue(): # assume no commission fee for now self.__placeSellShortOrder(tick, security) elif self.__previousSmaLong > self.__previousSmaShort > self.__previousSmaMid and self.__smaLong.getLastValue( ) > self.__smaMid.getLastValue() > self.__smaShort.getLastValue(): # assume no commission fee for now self.__placeSellShortOrder(tick, security) # place buy order if (self.__smaShort.getLastValue() > self.__smaLong.getLastValue() or self.__smaMid.getLastValue() > self.__smaLong.getLastValue()): if tick.close / self.__previousTick.close > 1.1: return if self.__previousSmaShort < self.__previousSmaLong and self.__smaShort.getLastValue( ) > self.__smaLong.getLastValue(): # assume no commission fee for now self.__placeBuyOrder(tick, security) elif self.__previousSmaLong < self.__previousSmaShort < self.__previousSmaMid and self.__smaLong.getLastValue( ) < self.__smaMid.getLastValue() < self.__smaShort.getLastValue(): # assume no commission fee for now self.__placeBuyOrder(tick, security) def __placeSellShortOrder(self, tick, security): ''' place short sell order''' share = math.floor(self.getAccountCopy().getCash() / float(tick.close)) sellShortOrder = Order(accountId=self.accountId, action=Action.SELL_SHORT, is_market=True, security=symbol, share=share) if self.placeOrder(sellShortOrder): self.buy_order = sellShortOrder # place stop order stopOrder = Order(accountId=self.accountId, action=Action.BUY_TO_COVER, is_stop=True, security=symbol, price=tick.close * 1.05, share=share) self.__placeStopOrder(stopOrder) def __placeBuyOrder(self, tick, security): ''' place buy order''' share = math.floor(self.getAccountCopy().getCash() / float(tick.close)) buyOrder = Order(accountId=self.accountId, action=Action.BUY, is_market=True, security=symbol, share=share) if self.placeOrder(buyOrder): self.buy_order = buyOrder # place stop order stopOrder = Order(accountId=self.accountId, action=Action.SELL, is_stop=True, security=symbol, price=tick.close * 0.95, share=share) self.__placeStopOrder(stopOrder) def __placeStopOrder(self, order): ''' place stop order ''' orderId = self.placeOrder(order) if orderId: self.stop_orderrId = orderId self.stop_orderr = order else: LOG.error("Can't place stop order %s" % order) def __sellIfMeet(self, tick, security): ''' place sell order if conditions meet ''' if self.stop_orderr.action == Action.BUY_TO_COVER and self.__previousSmaShort < self.__previousSmaMid and self.__previousSmaShort < self.__previousSmaLong\ and (self.__smaShort.getLastValue() > self.__smaLong.getLastValue() or self.__smaShort.getLastValue() > self.__smaMid.getLastValue()): self.placeOrder( Order(accountId=self.accountId, action=Action.BUY_TO_COVER, is_market=True, security=symbol, share=self.stop_orderr.share)) self.tradingEngine.cancelOrder(security, self.stop_orderrId) self.__clearStopOrder() elif self.stop_orderr.action == Action.SELL and self.__previousSmaShort > self.__previousSmaMid and self.__previousSmaShort > self.__previousSmaLong\ and (self.__smaShort.getLastValue() < self.__smaLong.getLastValue() or self.__smaShort.getLastValue() < self.__smaMid.getLastValue()): self.placeOrder( Order(accountId=self.accountId, action=Action.SELL, is_market=True, security=symbol, share=self.stop_orderr.share)) self.tradingEngine.cancelOrder(security, self.stop_orderrId) self.__clearStopOrder() def order_executed(self, order): ''' call back for executed order ''' for orderId in order.keys(): if orderId == self.stop_orderrId: LOG.debug("smaStrategy stop order canceled %s" % orderId) # stop order executed self.__clearStopOrder() break def __clearStopOrder(self): ''' clear stop order status ''' self.stop_orderrId = None self.stop_orderr = None def __adjustStopOrder(self, tick, security): ''' update stop order if needed ''' if not self.stop_orderrId: return if self.stop_orderr.action == Action.SELL: orgStopPrice = self.buy_order.price * 0.95 newStopPrice = max(((tick.close + orgStopPrice) / 2), tick.close * 0.85) newStopPrice = min(newStopPrice, tick.close * 0.95) if newStopPrice > self.stop_orderr.price: self.tradingEngine.cancelOrder(security, self.stop_orderrId) stopOrder = Order(accountId=self.accountId, action=Action.SELL, is_stop=True, security=symbol, price=newStopPrice, share=self.stop_orderr.share) self.__placeStopOrder(stopOrder) elif self.stop_orderr.action == Action.BUY_TO_COVER: orgStopPrice = self.buy_order.price * 1.05 newStopPrice = min(((orgStopPrice + tick.close) / 2), tick.close * 1.15) newStopPrice = max(newStopPrice, tick.close * 1.05) if newStopPrice < self.stop_orderr.price: self.tradingEngine.cancelOrder(security, self.stop_orderrId) stopOrder = Order(accountId=self.accountId, action=Action.BUY_TO_COVER, is_stop=True, security=symbol, price=newStopPrice, share=self.stop_orderr.share) self.__placeStopOrder(stopOrder) def update_previous_state(self, tick): ''' update privous state ''' self.__previousTick = tick self.__previousSmaShort = self.__smaShort.getLastValue() self.__previousSmaMid = self.__smaMid.getLastValue() self.__previousSmaLong = self.__smaLong.getLastValue() def update(self, tick): ''' consume ticks ''' assert self.securities # assert self.securitys[0] in tickDict.keys() security = self.securities[0] # tick=tickDict[security] LOG.debug("tickUpdate security %s with tick %s, price %s" % (security.symbol, tick.time, tick.close)) # update sma self.__smaShort(tick.close) self.__smaMid(tick.close) self.__smaLong(tick.close) # if not enough data, skip to reduce risk -- SKIP NEWLY IPOs if not self.__smaLong.getLastValue() or not self.__smaMid.getLastValue( ) or not self.__smaShort.getLastValue(): self.updatePreviousState(tick) return # don't have any holdings if not self.stop_orderrId: self.__buyIfMeet(tick, security) # already have some holdings else: self.__sellIfMeet(tick, security) self.__adjustStopOrder(tick, security) self.updatePreviousState(tick)