Пример #1
0
    def commitOrderExecution(self, order, price, quantity, dateTime):
        if order.getAction() in [broker.Order.Action.BUY, broker.Order.Action.BUY_TO_COVER]:
            cost = price * quantity * -1
            assert(cost < 0)
            sharesDelta = quantity
        elif order.getAction() in [broker.Order.Action.SELL, broker.Order.Action.SELL_SHORT]:
            cost = price * quantity
            assert(cost > 0)
            sharesDelta = quantity * -1
        else:  # Unknown action
            assert(False)

        ret = False
        commission = self.getCommission().calculate(order, price, quantity)
        cost -= commission
        resultingCash = self.getCash() + cost

        # Check that we're ok on cash after the commission.
        if resultingCash >= 0 or self.__allowNegativeCash:
            # Commit the order execution.
            self.setCash(resultingCash)
            self.__shares[order.getInstrument()] = self.getShares(order.getInstrument()) + sharesDelta
            ret = True

            # Update the order.
            orderExecutionInfo = broker.OrderExecutionInfo(price, quantity, commission, dateTime)
            order.setExecuted(orderExecutionInfo)
        else:
            logger.debug("Not enough money to fill order %s" % (order))

        return ret
Пример #2
0
 def stop(self):
     try:
         if self.__wsClient is not None:
             logger.debug("Stopping websocket client")
             self.__wsClient.stopClient()
     except Exception as e:
         logger.error("Error stopping websocket client: %s" % e)
Пример #3
0
 def run(self):
     logger.debug("Thread started.")
     while not self.__stopped:
         self.__wait()
         if not self.__stopped:
             try:
                 self.doCall()
             except Exception, e:
                 logger.critical("Unhandled exception", exc_info=e)
Пример #4
0
 def run(self, *args, **kwargs):
     assert self.__current_state is not None
     new_state = self.__states[self.__current_state](*args, **kwargs)
     self.__last_state = self.__current_state
     if new_state != self.__current_state:
         logger.debug('Switch state [%s] -> [%s]' % (self.__current_state,
                                                     new_state))
     assert new_state in self.__states
     self.__current_state = new_state
Пример #5
0
 def run(self):
     logger.debug("Thread started.")
     while not self.__stopped:
         self.__wait()
         if not self.__stopped:
             try:
                 self.doCall()
             except Exception, e:
                 logger.critical("Unhandled exception", exc_info=e)
Пример #6
0
    def onDayEnd(self):
        # Cancel non-GTC orders on day end
        activeOrders = copy.copy(self.__activeOrders)

        for order in activeOrders:
            if order.isAccepted() and not order.getGoodTillCanceled(): #and not order.getType() == Order.Type.MARKET:
                logger.debug("Cancelling non-GTC order: %s" % order)
                order.setState(broker.Order.State.CANCELED)
                self.__activeOrders.remove(order)
                self.getOrderUpdatedEvent().emit(self, order)
Пример #7
0
 def run(self):
     # We create the WebSocketClient right in the thread, instead of doing so in the constructor,
     # because it has thread affinity.
     try:
         self.__wsClient = self.__wsCls(self.__queue, *self.__args,
                                        **self.__kwargs)
         logger.debug("Running websocket client")
         self.__wsClient.startClient()
     except Exception as e:
         logger.exception("Unhandled exception %s" % e)
         self.__wsClient.stopClient()
Пример #8
0
 def run(self):
     logger.debug("Thread started.")
     ret = True
     while not self.__stopped:
         if ret:
             self.__wait()
         if not self.__stopped:
             ret = False
             try:
                 ret = self.doCall()
             except Exception, e:
                 logger.critical("Unhandled exception", exc_info=e)
Пример #9
0
    def doCall(self):
        endDateTime = self.__nextBarClose
        self.__updateNextBarClose()
        barDict = {}

        for indentifier in self.__identifiers:
            try:
                logger.debug("Requesting bars with precision %s and period %s for %s" % (self.__precision, self.__period, indentifier))
                response = api.XigniteGlobalRealTime_GetBar(self.__apiToken, indentifier, "Symbol", endDateTime, self.__precision, self.__period)
                # logger.debug(response)
                barDict[indentifier] = build_bar(response["Bar"], indentifier, self.__frequency)
            except api.XigniteError, e:
                logger.error(e)
Пример #10
0
class PollingThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.__stopped = False

    def __wait(self):
        # Wait until getNextCallDateTime checking for cancelation every 0.5 second.
        nextCall = self.getNextCallDateTime()
        #        nextCall = self.getNextCallDateTime() - datetime.timedelta(seconds=3600)
        print("----nextTime:%s" % liveUtils.utcToLocal(nextCall))
        while not self.__stopped and liveUtils.utcnow() < nextCall:
            time.sleep(0.5)

    def stop(self):
        self.__stopped = True

    def stopped(self):
        return self.__stopped

    def run(self):
        logger.debug("Thread started.")
        ret = True
        while not self.__stopped:
            if ret:
                self.__wait()
            if not self.__stopped:
                ret = False
                try:
                    ret = self.doCall()
                except Exception, e:
                    logger.critical("Unhandled exception", exc_info=e)
        logger.debug("Thread finished.")
Пример #11
0
class PollingThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.__stopped = False

    def __wait(self):
        # Wait until getNextCallDateTime checking for cancelation every 0.5 second.
        nextCall = self.getNextCallDateTime()
        while not self.__stopped and utcnow() < nextCall:
            time.sleep(0.5)

    def stop(self):
        self.__stopped = True

    def stopped(self):
        return self.__stopped

    def run(self):
        logger.debug("Thread started.")
        while not self.__stopped:
            self.__wait()
            if not self.__stopped:
                try:
                    self.doCall()
                except Exception, e:
                    logger.critical("Unhandled exception", exc_info=e)
        logger.debug("Thread finished.")
Пример #12
0
    def doCall(self):
        endDateTime = self.__nextBarClose
        self.__updateNextBarClose()
        barDict = {}

        for indentifier in self.__identifiers:
            try:
                logger.debug("Requesting bars with precision %s and period %s for %s" % (self.__precision, self.__period, indentifier))
                response = api.XigniteGlobalRealTime_GetBar(self.__apiToken, indentifier, "Symbol", endDateTime, self.__precision, self.__period)
                # logger.debug(response)
                barDict[indentifier] = build_bar(response["Bar"], indentifier, self.__frequency)
            except api.XigniteError as e:
                logger.error(e)

        if len(barDict):
            bars = bar.Bars(barDict)
            self.__queue.put((GetBarThread.ON_BARS, bars))
Пример #13
0
    def commitOrderExecution(self, order, dateTime, fillInfo):
        price = fillInfo.getPrice()
        quantity = fillInfo.getQuantity()

        if order.isBuy():
            cost = price * quantity * -1
            assert(cost < 0)
            sharesDelta = quantity
        elif order.isSell():
            cost = price * quantity
            assert(cost > 0)
            sharesDelta = quantity * -1
        else:  # Unknown action
            assert(False)

        commission = self.getCommission().calculate(order, price, quantity)
        cost -= commission
        resultingCash = self.getCash() + cost

        # Check that we're ok on cash after the commission.
        if resultingCash >= 0 or self.__allowNegativeCash:

            # Update the order before updating internal state since addExecutionInfo may raise.
            # addExecutionInfo should switch the order state.
            orderExecutionInfo = broker.OrderExecutionInfo(price, quantity, commission, dateTime)
            order.addExecutionInfo(orderExecutionInfo)

            # Commit the order execution.
            self.__cash = resultingCash
            self.__shares[order.getInstrument()] = self.getShares(order.getInstrument()) + sharesDelta

            # Let the strategy know that the order was filled.
            self.__fillStrategy.onOrderFilled(order)

            # Notify the order update
            if order.isFilled():
                del self.__activeOrders[order.getId()]
                self.notifyOrderEvent(broker.OrderEvent(order, broker.OrderEvent.Type.FILLED, orderExecutionInfo))
            elif order.isPartiallyFilled():
                self.notifyOrderEvent(broker.OrderEvent(order, broker.OrderEvent.Type.PARTIALLY_FILLED, orderExecutionInfo))
            else:
                assert(False)
        else:
            logger.debug("Not enough money to fill order %s" % (order))
Пример #14
0
    def commitOrderExecution(self, order, price, quantity, dateTime):
        if order.getAction() in [
                broker.Order.Action.BUY, broker.Order.Action.BUY_TO_COVER
        ]:
            cost = price * quantity * -1
            assert (cost < 0)
            sharesDelta = quantity
        elif order.getAction() in [
                broker.Order.Action.SELL, broker.Order.Action.SELL_SHORT
        ]:
            cost = price * quantity
            assert (cost > 0)
            sharesDelta = quantity * -1
        else:  # Unknown action
            assert (False)

        ret = False
        commission = self.getCommission().calculate(order, price, quantity)
        cost -= commission
        resultingCash = self.getCash() + cost

        # Check that we're ok on cash after the commission.
        if resultingCash >= 0:
            # Commit the order execution.
            self.setCash(resultingCash)
            self.__shares[order.getInstrument()] = self.getShares(
                order.getInstrument()) + sharesDelta
            ret = True

            # Update the order.
            orderExecutionInfo = broker.OrderExecutionInfo(
                price, quantity, commission, dateTime)
            order.setExecuted(orderExecutionInfo)
        else:
            logger.debug("Not enough money to fill order %s" % (order))

        return ret
Пример #15
0
    def commitOrderExecution(self, order, price, quantity, dateTime):
        if order.getAction() in [broker.Order.Action.BUY, broker.Order.Action.BUY_TO_COVER]:
            cost = price * quantity * -1
            assert(cost < 0)
            sharesDelta = quantity
        elif order.getAction() in [broker.Order.Action.SELL, broker.Order.Action.SELL_SHORT]:
            cost = price * quantity
            assert(cost > 0)
            sharesDelta = quantity * -1
        else: # Unknown action
            assert(False)

        ret = False
        instrument = order.getInstrument()
        commission = self.getCommission().calculate(order, price, quantity)
        cost -= commission
        resultingCash = self.getCash() + cost

        # Check that we're ok on cash after the commission.
        if resultingCash >= 0 or self.__allowNegativeCash:
            # Commit the order execution.
            self.setCash(resultingCash)
            self.__shares[instrument] = self.getShares(instrument) + sharesDelta
            if self.__shares[instrument] == 0:
                self.__totalCost[instrument] = 0
            else:
                self.__totalCost[instrument] = self.getTotalCost(instrument) + cost
            ret = True

            # Update the order.
            orderExecutionInfo = broker.OrderExecutionInfo(price, quantity, commission, dateTime)
            order.setExecuted(orderExecutionInfo)

            logger.debug("%s Order filled: %s" % (instrument, orderExecutionInfo))
            logger.debug("%s shares owned. Total cost: %s" % (self.__shares[instrument], self.__totalCost[instrument]))
        else:
            logger.debug("Not enough cash to fill the order for %s @ %.2f. Avail: %.2f, Req: %.2f" %
                        (instrument, price, self.getCash(), cost * -1))

        return ret
Пример #16
0
 def __threadMain(self):
     logger.debug("Thread started.")
     self.__wsClient.startClient()
     logger.debug("Thread finished.")
Пример #17
0
 def handleResponse(self, msg):
     ret = msg.get("table") == "pong"
     if ret:
         logger.debug("Received pong.")
     return ret
Пример #18
0
    def stop(self):
        self.__stopped = True

    def stopped(self):
        return self.__stopped

    def run(self):
        logger.debug("Thread started.")
        while not self.__stopped:
            self.__wait()
            if not self.__stopped:
                try:
                    self.doCall()
                except Exception, e:
                    logger.critical("Unhandled exception", exc_info=e)
        logger.debug("Thread finished.")

    # Must return a non-naive datetime.
    def getNextCallDateTime(self):
        raise NotImplementedError()

    def doCall(self):
        raise NotImplementedError()


class TushareBarFeedThread(TuSharePollingThread):
    # Events
    ON_BARS = 1

    def __init__(self, queue, identifiers, frequency):
        super(TushareBarFeedThread, self).__init__(identifiers)
Пример #19
0
 def __register_state(self, name, function):
     logger.debug('Registering state [%s]' % name)
     if name in self.__states:
         raise Exception("Duplicate state %s" % name)
     self.__states[name] = function
Пример #20
0
 def __set_initial_state(self, name):
     assert name in self.__states
     logger.debug('Initial state [%s]' % name)
     self.__current_state = name
Пример #21
0
 def handleResponse(self, msg):
     ret = msg.get("event") == "pusher:pong"
     if ret:
         logger.debug("Received pusher:pong.")
     return ret
Пример #22
0
 def sendKeepAlive(self):
     logger.debug("Sending pusher:ping.")
     self.getWSClient().sendPing()
Пример #23
0
 def handleResponse(self, msg):
     ret = msg.get("event") == "pusher:pong"
     if ret:
         logger.debug("Received pusher:pong.")
     return ret
Пример #24
0
 def __on_error(self, ws, error):
     logger.debug("Error : %s" % error)
Пример #25
0
    def stop(self):
        self.__stopped = True

    def stopped(self):
        return self.__stopped

    def run(self):
        logger.debug("Thread started.")
        while not self.__stopped:
            self.__wait()
            if not self.__stopped:
                try:
                    self.doCall()
                except Exception, e:
                    logger.critical("Unhandled exception", exc_info=e)
        logger.debug("Thread finished.")

    # Must return a non-naive datetime.
    def getNextCallDateTime(self):
        raise NotImplementedError()

    def doCall(self):
        raise NotImplementedError()


class TushareBarFeedThread(TuSharePollingThread):
    # Events
    ON_BARS = 1

    def __init__(self, queue, identifiers, frequency):
        super(TushareBarFeedThread, self).__init__(identifiers)
Пример #26
0
 def __threadMain(self):
     logger.debug("Thread started.")
     self.__wsClient.startClient()
     logger.debug("Thread finished.")
Пример #27
0
 def sendKeepAlive(self):
     logger.debug("Sending pusher:ping.")
     self.getWSClient().sendPing()