Пример #1
0
    def testCancelAllOpenOrders(self):
        order1 = Order(accountId='accountId',
                       side=Side.BUY,
                       symbol='symbol1',
                       price=13.2,
                       share=10,
                       orderId='id1')
        order2 = Order(accountId='accountId',
                       side=Side.BUY,
                       symbol='symbol1',
                       price=13.25,
                       share=10,
                       orderId='id2')

        tc = TradingCenter()
        tc._TradingCenter__openOrders = {'symbol1': [order1, order2]}

        tc.cancelAllOpenOrders()
        print(tc._TradingCenter__openOrders)
        print(tc._TradingCenter__closedOrders)
        self.assertEquals({}, tc._TradingCenter__openOrders)
        self.assertEquals({
            'id1': order1,
            'id2': order2
        }, tc._TradingCenter__closedOrders)
Пример #2
0
    def testIsOrderMet(self):
        tc = TradingCenter()
        tick1 = Tick('time', 'open', 'high', 'low', 13.20, 'volume')
        order1 = Order(accountId=None,
                       side=Side.BUY,
                       symbol='symbol',
                       price=13.25,
                       share=10)
        order2 = Order(accountId=None,
                       side=Side.BUY,
                       symbol='symbol',
                       price=13.15,
                       share=10)
        order3 = Order(accountId=None,
                       side=Side.SELL,
                       symbol='symbol',
                       price=13.25,
                       share=10)
        order4 = Order(accountId=None,
                       side=Side.SELL,
                       symbol='symbol',
                       price=13.15,
                       share=10)

        self.assertEquals(True, tc.isOrderMet(tick1, order1))
        self.assertEquals(False, tc.isOrderMet(tick1, order2))
        self.assertEquals(False, tc.isOrderMet(tick1, order3))
        self.assertEquals(True, tc.isOrderMet(tick1, order4))
Пример #3
0
    def testValidOrder(self):
        tc = TradingCenter()

        accountId = 'accountId'
        order1 = Order(accountId=accountId,
                       side=Side.BUY,
                       symbol='symbol',
                       price=13.25,
                       share=10)
        order2 = Order(accountId='unknowAccount',
                       side=Side.BUY,
                       symbol='symbol',
                       price=13.25,
                       share=10)
        account = self.mock.CreateMock(Account)
        account.validate(order1).AndReturn(True)
        account.validate(order1).AndReturn(False)
        tc._TradingCenter__accounts = {accountId: account}

        self.mock.ReplayAll()
        self.assertEquals(False,
                          tc.validateOrder(order2))  # invalid account id
        self.assertEquals(True, tc.validateOrder(order1))  # True
        self.assertEquals(False, tc.validateOrder(order1))  # False
        self.mock.VerifyAll()
    def testGetOpenOrdersBySymbol(self):
        order1 = Order(accountId = 'accountId', side = Side.BUY, symbol = 'symbol1', price = 13.2, share = 10, orderId = 'id1')
        order2 = Order(accountId = 'accountId', side = Side.BUY, symbol = 'symbol1', price = 13.25, share = 10, orderId = 'id2')

        tc = TradingCenter()
        tc._TradingCenter__openOrders = {'symbol1': [order1, order2]}
        orders = tc.getOpenOrdersBySymbol('symbol1')
        self.assertEquals([order1, order2], orders)
    def testValidOrder(self):
        tc = TradingCenter()
        account = Account(1000, 10)
        accountId = tc.accountManager.addAccount(account)

        order1 = Order(accountId = accountId, side = Side.BUY, symbol = 'symbol', price = 13.25, share = 10)
        order2 = Order(accountId = 'unknowAccount', side = Side.BUY, symbol = 'symbol', price = 13.25, share = 10)

        self.assertEquals(False, tc.validateOrder(order2) ) # invalid account id
        self.assertEquals(True, tc.validateOrder(order1) ) # True
    def testIsOrderMet(self):
        tc = TradingCenter()
        tick1 = Tick(datetime.now(), 30.0, 35.0, 13.20, 13.20, 100000)
        order1 = Order(accountId = None, side = Side.BUY, symbol = 'symbol', price = 13.25, share = 10)
        order2 = Order(accountId = None, side = Side.BUY, symbol = 'symbol', price = 13.15, share = 10)
        order3 = Order(accountId = None, side = Side.SELL, symbol = 'symbol', price = 13.25, share = 10)
        order4 = Order(accountId = None, side = Side.SELL, symbol = 'symbol', price = 13.15, share = 10)

        self.assertEquals(True, tc.isOrderMet(tick1, order1))
        self.assertEquals(False, tc.isOrderMet(tick1, order2))
        self.assertEquals(False, tc.isOrderMet(tick1, order3))
        self.assertEquals(True, tc.isOrderMet(tick1, order4))
Пример #7
0
 def __tupleToResult(self, row):
     ''' convert tuple queried from sql to BackTestResult'''
     try:
         return BackTestResult(row['time'],
                               row[STATE_SAVER_ACCOUNT],
                               row[STATE_SAVER_HOLDING_VALUE],
                               row[STATE_SAVER_INDEX_PRICE],
                               [Order.fromStr(orderString) for orderString in json.loads(row[STATE_SAVER_UPDATED_ORDERS])],
                               [Order.fromStr(orderString) for orderString in json.loads(row[STATE_SAVER_PLACED_ORDERS])])
     except Exception as ex:
         LOG.error("Unknown exception doing __tupleToResult in sqlSaver " + str(ex) + " --row-- " + str(row))
         return BackTestResult('-1', '-1', [], [], [], [])
    def testPlaceOrder_invalidAccountId(self):
        tc = TradingCenter()

        order2 = Order(accountId = 'unknowAccount', side = Side.BUY, symbol = 'symbol', price = 13.25, share = 10)

        self.mock.ReplayAll()
        self.assertEquals(None, tc.placeOrder(order2) ) # invalid account id
        self.mock.VerifyAll()
Пример #9
0
 def __tupleToResult(self, row):
     ''' convert tuple queried from sql to BackTestResult'''
     try:
         return BackTestResult(row['time'], row[STATE_SAVER_ACCOUNT],
                               row[STATE_SAVER_HOLDING_VALUE],
                               row[STATE_SAVER_INDEX_PRICE], [
                                   Order.fromStr(orderString)
                                   for orderString in json.loads(
                                       row[STATE_SAVER_UPDATED_ORDERS])
                               ], [
                                   Order.fromStr(orderString)
                                   for orderString in json.loads(
                                       row[STATE_SAVER_PLACED_ORDERS])
                               ])
     except Exception as ex:
         LOG.error("Unknown exception doing __tupleToResult in sqlSaver " +
                   str(ex) + " --row-- " + str(row))
         return BackTestResult('-1', '-1', '-1', '-1', '[]', '[]')
Пример #10
0
    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)
Пример #11
0
    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)
Пример #12
0
    def testPlaceOrder_existedOrder(self):
        tc = TradingCenter()

        accountId = 'accountId'
        order1 = Order(accountId=accountId,
                       side=Side.BUY,
                       symbol='symbol',
                       price=13.25,
                       share=10,
                       orderId='orderId1')
        self.assertRaises(UfException, tc.placeOrder, order1)
Пример #13
0
    def testValidate(self):
        share = 10
        price = 9.1
        symbol = 'stock1'
        account = Account(1000, 1)
        account._Account__holdings = {symbol: (share, price)}

        # can't buy because price too high
        order1 = Order(accountId = 'id1', side = Side.BUY, symbol = symbol, price = 10000, share = 100000)
        self.assertEquals(False, account.validate(order1) )

        # can't buy because of commission fee
        order1 = Order(accountId = 'id1', side = Side.BUY, symbol = symbol, price = 100, share = 10)
        self.assertEquals(False, account.validate(order1) )

        # buy it
        order1 = Order(accountId = 'id1', side = Side.BUY, symbol = symbol, price = 100, share = 9)
        self.assertEquals(True, account.validate(order1) )

        # can't sell because don't have the stock
        order1 = Order(accountId = 'id1', side = Side.SELL, symbol = 'fas89ph2', price = 100, share = 9)
        self.assertEquals(False, account.validate(order1) )

        # can't sell because don't have the enough share
        order1 = Order(accountId = 'id1', side = Side.SELL, symbol = symbol, price = 100, share = 9000)
        self.assertEquals(False, account.validate(order1) )

        # sell it
        order1 = Order(accountId = 'id1', side = Side.SELL, symbol = symbol, price = 100, share = 9)
        self.assertEquals(True, account.validate(order1) )
    def testPlaceOrder_failed(self):
        tc = TradingCenter()

        account = Account(1000, 0)
        self.mock.StubOutWithMock(account, "validate")
        accountId = tc.accountManager.addAccount(account)
        
        order1 = Order(accountId = accountId, side = Side.BUY, symbol = 'symbol', price = 13.25, share = 10)
        account.validate(order1).AndReturn(False)

        self.mock.ReplayAll()
        self.assertEquals(None, tc.placeOrder(order1) ) # True
        self.mock.VerifyAll()
Пример #15
0
    def __placeSellOrder(self, tick):
        ''' place sell order '''
        if self.__position < 0:
            return

        share = self.__position
        order = Order(accountId=self.__strategy.accountId,
                      action=Action.SELL,
                      type=Type.MARKET,
                      symbol=self.__symbol,
                      share=-share)
        if self.__strategy.placeOrder(order):
            self.__position = 0
Пример #16
0
    def __placeBuyOrder(self, tick):
        ''' place buy order'''
        cash = self.__getCashToBuyStock()
        if cash == 0 or self.__position > 0:
            return

        share = math.floor(cash / float(tick.close)) - self.__position
        order = Order(accountId=self.__strategy.accountId,
                      action=Action.BUY,
                      type=Type.MARKET,
                      symbol=self.__symbol,
                      share=share)
        if self.__strategy.placeOrder(order):
            self.__position = math.floor(cash / float(tick.close))
Пример #17
0
    def tickUpdate(self, tickDict):
        ''' consume ticks '''
        assert self.symbols
        assert self.symbols[0] in tickDict.keys()
        symbol = self.symbols[0]
        tick = tickDict[symbol]

        if self.increaseAndCheckCounter():
            self.placeOrder(
                Order(accountId=self.accountId,
                      side=Side.BUY,
                      symbol=symbol,
                      price=tick.close,
                      share=self.perAmount / float(tick.close)))
Пример #18
0
    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()
Пример #19
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)
Пример #20
0
    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)
Пример #21
0
    def testPlaceOrder_failed(self):
        tc = TradingCenter()

        accountId = 'accountId'
        order1 = Order(accountId=accountId,
                       side=Side.BUY,
                       symbol='symbol',
                       price=13.25,
                       share=10)
        account = self.mock.CreateMock(Account)
        account.validate(order1).AndReturn(False)
        tc._TradingCenter__accounts = {accountId: account}

        self.mock.ReplayAll()
        self.assertEquals(None, tc.placeOrder(order1))  # True
        self.mock.VerifyAll()