Beispiel #1
0
    def __init__(self, symbol, strategy, buyingRatio):
        ''' constructor '''

        self.__symbol = symbol
        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 __init__(self, symbol, strategy, buyingRatio):
        ''' constructor '''

        self.__symbol = symbol
        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(300)
        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
Beispiel #3
0
    def __init__(self, configDict):
        """ constructor """
        super(SMAStrategy, self).__init__("smaStrategy")
        self.configDict = configDict

        self.symbols = None

        # order id
        self.__stopLossOrderId = None
        self.__stopLossOrder = None
        self.__buyOrder = None

        self.__smaShort = Sma(10)
        self.__smaMid = Sma(20)
        self.__smaLong = Sma(60)

        # state of privious day
        self.__previousTick = None
        self.__previousSmaShort = None
        self.__previousSmaMid = None
        self.__previousSmaLong = None
Beispiel #4
0
    def __init__(self, configDict):
        ''' constructor '''
        super(SMAStrategy, self).__init__("smaStrategy")
        self.configDict = configDict

        self.symbols = None

        # order id
        self.__stopOrderId = None
        self.__stopOrder = None
        self.__buyOrder = 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
class OneTraker(object):
    ''' tracker for one stock '''
    def __init__(self, symbol, strategy, buyingRatio):
        ''' constructor '''

        self.__symbol = symbol
        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(300)
        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,
                                  type = Type.MARKET,
                                  symbol = self.__symbol,
                                  share = share)

        if self.__strategy.placeOrder(sellShortOrder):
            self.__buyOrder = sellShortOrder

            #place stop order
            stopOrder = Order(accountId = self.__strategy.accountId,
                          action = Action.BUY_TO_COVER,
                          type = Type.STOP,
                          symbol = self.__symbol,
                          price = tick.close * 1.05,
                          share = 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,
                                  type = Type.MARKET,
                                  symbol = self.__symbol,
                                  share = share)
        if self.__strategy.placeOrder(buyOrder):
            self.__buyOrder = buyOrder

            #place stop order
            stopOrder = Order(accountId = self.__strategy.accountId,
                          action = Action.SELL,
                          type = Type.STOP,
                          symbol = self.__symbol,
                          price = tick.close * 0.95,
                          share = 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.__symbol, self.__stopOrderId)
                stopOrder = Order(accountId = self.__strategy.accountId,
                                  action = Action.SELL,
                                  type = Type.STOP,
                                  symbol = self.__symbol,
                                  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.__symbol, self.__stopOrderId)
                stopOrder = Order(accountId = self.__strategy.accountId,
                                  action = Action.BUY_TO_COVER,
                                  type = Type.STOP,
                                  symbol = self.__symbol,
                                  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.__symbol, 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)
Beispiel #6
0
class OneTraker(object):
    ''' tracker for one stock '''
    def __init__(self, symbol, strategy, buyingRatio):
        ''' constructor '''

        self.__symbol = symbol
        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,
                               type=Type.MARKET,
                               symbol=self.__symbol,
                               share=share)

        if self.__strategy.placeOrder(sellShortOrder):
            self.__buyOrder = sellShortOrder

            #place stop order
            stopOrder = Order(accountId=self.__strategy.accountId,
                              action=Action.BUY_TO_COVER,
                              type=Type.STOP,
                              symbol=self.__symbol,
                              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,
                         type=Type.MARKET,
                         symbol=self.__symbol,
                         share=share)
        if self.__strategy.placeOrder(buyOrder):
            self.__buyOrder = buyOrder

            #place stop order
            stopOrder = Order(accountId=self.__strategy.accountId,
                              action=Action.SELL,
                              type=Type.STOP,
                              symbol=self.__symbol,
                              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.__symbol, self.__stopOrderId)
                stopOrder = Order(accountId=self.__strategy.accountId,
                                  action=Action.SELL,
                                  type=Type.STOP,
                                  symbol=self.__symbol,
                                  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.__symbol, self.__stopOrderId)
                stopOrder = Order(accountId = self.__strategy.accountId,
                                  action = Action.BUY_TO_COVER,
                                  type = Type.STOP,
                                  symbol = self.__symbol,
                                  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.__symbol, 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)
Beispiel #7
0
class SMAStrategy(BaseStrategy):
    """ period strategy """

    def __init__(self, configDict):
        """ constructor """
        super(SMAStrategy, self).__init__("smaStrategy")
        self.configDict = configDict

        self.symbols = None

        # order id
        self.__stopLossOrderId = None
        self.__stopLossOrder = None
        self.__buyOrder = None

        self.__smaShort = Sma(10)
        self.__smaMid = Sma(20)
        self.__smaLong = Sma(60)

        # state of privious day
        self.__previousTick = None
        self.__previousSmaShort = None
        self.__previousSmaMid = None
        self.__previousSmaLong = None

    def __openOrderIfMeet(self, tick, symbol):
        """ 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, symbol)

            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, symbol)

        # 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, symbol)

            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, symbol)

    def __placeSellShortOrder(self, tick, symbol):
        """ place short sell order"""
        share = math.floor(self.getAccountCopy().getCash() / float(tick.close))
        sellShortOrder = Order(
            accountId=self.accountId, action=Action.SELL_SHORT, type=Type.MARKET, symbol=symbol, share=share
        )
        if self.placeOrder(sellShortOrder):
            self.__buyOrder = sellShortOrder

            # place stop order
            stopOrder = Order(
                accountId=self.accountId,
                action=Action.BUY_TO_COVER,
                type=Type.STOP,
                symbol=symbol,
                price=tick.close * 1.05,
                share=share,
            )
            self.__placeStopLossOrder(stopOrder)

    def __placeBuyOrder(self, tick, symbol):
        """ place buy order"""
        share = math.floor(self.getAccountCopy().getCash() / float(tick.close))
        buyOrder = Order(accountId=self.accountId, action=Action.BUY, type=Type.MARKET, symbol=symbol, share=share)
        if self.placeOrder(buyOrder):
            self.__buyOrder = buyOrder

            # place stop order
            stopOrder = Order(
                accountId=self.accountId,
                action=Action.SELL,
                type=Type.STOP,
                symbol=symbol,
                price=tick.close * 0.95,
                share=share,
            )
            self.__placeStopLossOrder(stopOrder)

    def __placeStopLossOrder(self, order):
        """ place stop loss order """
        orderId = self.placeOrder(order)
        if orderId:
            self.__stopLossOrderId = orderId
            self.__stopLossOrder = order
        else:
            LOG.error("Can't place stop order %s" % order)

    def __closeOrderIfMeet(self, tick, symbol):
        """ place sell order if conditions meet """
        if (
            self.__stopLossOrder.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,
                    type=Type.MARKET,
                    symbol=symbol,
                    share=self.__stopLossOrder.share,
                )
            )
            self.tradingEngine.cancelOrder(symbol, self.__stopLossOrderId)
            self.__clearStopLossOrder()

        elif (
            self.__stopLossOrder.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,
                    type=Type.MARKET,
                    symbol=symbol,
                    share=self.__stopLossOrder.share,
                )
            )
            self.tradingEngine.cancelOrder(symbol, self.__stopLossOrderId)
            self.__clearStopLossOrder()

    def orderExecuted(self, orderDict):
        """ call back for executed order """
        for orderId in orderDict.keys():
            if orderId == self.__stopLossOrderId:
                LOG.debug("smaStrategy stop loss order canceled %s" % orderId)
                # stop order executed
                self.__clearStopLossOrder()
                break

    def __clearStopLossOrder(self):
        """ clear stop loss order status """
        self.__stopLossOrderId = None
        self.__stopLossOrder = None

    def __adjustStopLossOrder(self, tick, symbol):
        """ update stop loss order if needed """
        if not self.__stopLossOrderId:
            return

        if self.__stopLossOrder.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.__stopLossOrder.price:
                self.tradingEngine.cancelOrder(symbol, self.__stopLossOrderId)
                stopOrder = Order(
                    accountId=self.accountId,
                    action=Action.SELL,
                    type=Type.STOP,
                    symbol=symbol,
                    price=newStopPrice,
                    share=self.__stopLossOrder.share,
                )
                self.__placeStopLossOrder(stopOrder)

        elif self.__stopLossOrder.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.__stopLossOrder.price:
                self.tradingEngine.cancelOrder(symbol, self.__stopLossOrderId)
                stopOrder = Order(
                    accountId=self.accountId,
                    action=Action.BUY_TO_COVER,
                    type=Type.STOP,
                    symbol=symbol,
                    price=newStopPrice,
                    share=self.__stopLossOrder.share,
                )
                self.__placeStopLossOrder(stopOrder)

    def updatePreviousState(self, tick):
        """ update privous state """
        self.__previousTick = tick
        self.__previousSmaShort = self.__smaShort.getLastValue()
        self.__previousSmaMid = self.__smaMid.getLastValue()
        self.__previousSmaLong = self.__smaLong.getLastValue()

    def tickUpdate(self, tickDict):
        """ consume ticks """
        assert self.symbols
        assert self.symbols[0] in tickDict.keys()
        symbol = self.symbols[0]
        tick = tickDict[symbol]

        LOG.debug("tickUpdate symbol %s with tick %s, price %s" % (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.__stopLossOrderId:
            self.__openOrderIfMeet(tick, symbol)

        # already have some holdings
        else:
            self.__closeOrderIfMeet(tick, symbol)
            self.__adjustStopLossOrder(tick, symbol)

        self.updatePreviousState(tick)
 def testSma(self):
     sma = Sma(period=3)
     expectedAvgs = [1, 1.5, 2, 3, 4]
     for index, number in enumerate(range(1, 6)):
         self.assertEqual(expectedAvgs[index], sma(number))
Beispiel #9
0
class SMAStrategy(BaseStrategy):
    ''' period strategy '''
    def __init__(self, configDict):
        ''' constructor '''
        super(SMAStrategy, self).__init__("smaStrategy")
        self.configDict = configDict

        self.symbols = None

        # order id
        self.__stopOrderId = None
        self.__stopOrder = None
        self.__buyOrder = 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, symbol):
        ''' 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, symbol)

            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, symbol)

        # 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, symbol)

            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, symbol)

    def __placeSellShortOrder(self, tick, symbol):
        ''' place short sell order'''
        share = math.floor(self.getAccountCopy().getCash() / float(tick.close))
        sellShortOrder = Order(accountId=self.accountId,
                               action=Action.SELL_SHORT,
                               type=Type.MARKET,
                               symbol=symbol,
                               share=share)
        if self.placeOrder(sellShortOrder):
            self.__buyOrder = sellShortOrder

            #place stop order
            stopOrder = Order(accountId=self.accountId,
                              action=Action.BUY_TO_COVER,
                              type=Type.STOP,
                              symbol=symbol,
                              price=tick.close * 1.05,
                              share=share)
            self.__placeStopOrder(stopOrder)

    def __placeBuyOrder(self, tick, symbol):
        ''' place buy order'''
        share = math.floor(self.getAccountCopy().getCash() / float(tick.close))
        buyOrder = Order(accountId=self.accountId,
                         action=Action.BUY,
                         type=Type.MARKET,
                         symbol=symbol,
                         share=share)
        if self.placeOrder(buyOrder):
            self.__buyOrder = buyOrder

            #place stop order
            stopOrder = Order(accountId=self.accountId,
                              action=Action.SELL,
                              type=Type.STOP,
                              symbol=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.__stopOrderId = orderId
            self.__stopOrder = order
        else:
            LOG.error("Can't place stop order %s" % order)

    def __sellIfMeet(self, tick, symbol):
        ''' place sell order if conditions meet '''
        if self.__stopOrder.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,
                      type=Type.MARKET,
                      symbol=symbol,
                      share=self.__stopOrder.share))
            self.tradingEngine.cancelOrder(symbol, self.__stopOrderId)
            self.__clearStopOrder()

        elif self.__stopOrder.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,
                      type=Type.MARKET,
                      symbol=symbol,
                      share=self.__stopOrder.share))
            self.tradingEngine.cancelOrder(symbol, self.__stopOrderId)
            self.__clearStopOrder()

    def orderExecuted(self, orderDict):
        ''' call back for executed order '''
        for orderId in orderDict.keys():
            if orderId == self.__stopOrderId:
                LOG.debug("smaStrategy stop order canceled %s" % orderId)
                # stop order executed
                self.__clearStopOrder()
                break

    def __clearStopOrder(self):
        ''' clear stop order status '''
        self.__stopOrderId = None
        self.__stopOrder = None

    def __adjustStopOrder(self, tick, symbol):
        ''' 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.tradingEngine.cancelOrder(symbol, self.__stopOrderId)
                stopOrder = Order(accountId=self.accountId,
                                  action=Action.SELL,
                                  type=Type.STOP,
                                  symbol=symbol,
                                  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.tradingEngine.cancelOrder(symbol, self.__stopOrderId)
                stopOrder = Order(accountId=self.accountId,
                                  action=Action.BUY_TO_COVER,
                                  type=Type.STOP,
                                  symbol=symbol,
                                  price=newStopPrice,
                                  share=self.__stopOrder.share)
                self.__placeStopOrder(stopOrder)

    def updatePreviousState(self, tick):
        ''' update privous state '''
        self.__previousTick = tick
        self.__previousSmaShort = self.__smaShort.getLastValue()
        self.__previousSmaMid = self.__smaMid.getLastValue()
        self.__previousSmaLong = self.__smaLong.getLastValue()

    def tickUpdate(self, tickDict):
        ''' consume ticks '''
        assert self.symbols
        assert self.symbols[0] in tickDict.keys()
        symbol = self.symbols[0]
        tick = tickDict[symbol]

        LOG.debug("tickUpdate symbol %s with tick %s, price %s" %
                  (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.__stopOrderId:
            self.__buyIfMeet(tick, symbol)

        # already have some holdings
        else:
            self.__sellIfMeet(tick, symbol)
            self.__adjustStopOrder(tick, symbol)

        self.updatePreviousState(tick)