def makeOrder(self, order):
        """
        Makes the order happen, and when called in the future checks the status.

        :param order: The order dict, specified in strategy

        """
        tryMaxCount = 7
        tries = 0
        while tries < tryMaxCount:
            try:
                if not order.get('initialized'):
                    #TODO: Allow option to not reach equilibrium
                    self.initializeLimitOrder(order)

                if order.get('completed'):
                    # logger.logDuplicateOrder(order)
                    return None

                order['orderQuantity'] = min(
                    abs(
                        self.quantityLeftInOrder(order.get('orderID'),
                                                 math.inf)),
                    abs(order.get('orderQuantity', math.inf)))

                if self.isInRange(
                        order['currentAction'], order['initialPrice'],
                        self.getCurrentPrice(order['currency'],
                                             order['asset']),
                        self.maximumDeviationFromPrice, order['equilibrium']
                ) and order.get('orderQuantity') != 0:
                    res = self.sendLimitOrder(
                        order['currentAction'],
                        order['asset'],
                        order['currency'],
                        order['orderQuantity'],
                        order.get('orderID'),
                        order.get('note'),
                        currentLimitPrice=order.get('currentLimitPrice'))
                    if hasattr(res, 'orderID'):
                        order['orderID'] = res.orderID
                        order['currentLimitPrice'] = res.limitPrice
                    else:
                        order['orderQuantity'] = self.quantityLeftInOrder(
                            order['orderID'], order['orderQuantity'])
                        orderID = order['orderID']
                        order['orderID'] = None
                        self.closeLimitOrder(orderID)
                else:
                    if self.orderOpen(order['orderID']):
                        self.closeLimitOrder(order['orderID'])
                    self.finishOrderStep(order)

                break
            except:
                tries = tries + 1
                tb = traceback.format_exc()
                logger.logError(tb)
                sleep(self.delayBetweenAttempts)
                self.connect()
    def limitOrderStatus(self, orderID, triesLeft=None):
        """

        :param orderID: 
        :param triesLeft:  (Default value = None)

        """
        if triesLeft == None:
            triesLeft = 1
        if orderID == None:
            return False
        filter = '{"orderID": "' + orderID + '"}'
        res = self.market.Order.Order_getOrders(filter=filter).result()

        try:
            res = res[0][0]
            status = res['ordStatus']
        except:
            if triesLeft != 0:
                sleep(1)
                return self.limitOrderStatus(orderID)
            triesLeft = triesLeft - 1
            logger.logError('--- ORDER LIST ERROR ---')

        return res
예제 #3
0
def readJsonFile(file):
    try:
        with open(file, 'r') as log_json:
            data = json.load(log_json)
    except Exception as error:
        data = []
        logger.logError(error)
    return data
    def limitBuy(self,
                 price,
                 asset,
                 currency,
                 orderQuantity,
                 orderId=None,
                 note=None):
        """

        :param price: 
        :param asset: 
        :param currency: 
        :param orderQuantity: 
        :param orderId:  (Default value = None)
        :param note:  (Default value = None)

        """
        result = None

        openOrder = self.orderOpen(orderId)
        if openOrder and orderQuantity != 0:
            try:
                result = self.market.Order.Order_amend(orderID=orderId,
                                                       price=price).result()
                logger.logOrder(
                    self.marketName, 'Limit', price, asset, currency,
                    orderQuantity,
                    str(note) + ' amend for order: ' + str(orderId))
            except Exception as e:

                if e.response.status_code == 400:
                    logger.logError('LIMIT AMEND ERROR')
                    orderQuantity = self.quantityLeftInOrder(
                        orderId, orderQuantity)
                    if orderQuantity != 0:
                        openOrder = False
                else:
                    logger.logError('UNKNOWN LIMIT ERROR: ' + str(e))
                    raise e

        if not openOrder and orderQuantity != 0:
            result = self.market.Order.Order_new(
                symbol=currency + asset,
                orderQty=orderQuantity,
                ordType="Limit",
                price=price,
                execInst='ParticipateDoNotInitiate').result()
            logger.logOrder(self.marketName, 'Limit', price, asset, currency,
                            orderQuantity, note)
        if result is not None:
            tradeInfo = result[0]
            for key, value in tradeInfo.items():
                if key == "orderID":
                    newOrderId = (key + ": {0}".format(value))
                    return newOrderId[9:]
        else:
            return None
    def makeOrder(self, order):
        """
        Handles the boilerplate operations for creating a market order. For contractural exchanges with shorts, sends out an order to equilibriumize the balance.

        :param order: The order dict

        """
        tries = 0
        maxTries = 7
        while tries < maxTries:

            try:
                currentAmount = self.getAmountOfItem(order['currency'],
                                                     order['asset'])
                text = "current amount of %s%s: %f \n " % (
                    order['currency'], order['asset'], currentAmount)
                print(text)

                if currentAmount > 0 and order[
                        'action'] == self.sellText or currentAmount < 0 and order[
                            'action'] == self.buyText:
                    self.marketBuy(-currentAmount,
                                   order['currency'],
                                   order['asset'],
                                   note='Resetting to equilibrium')
                    self.logOrderInBank(order,
                                        action=self.buyText if
                                        -currentAmount > 0 else self.sellText,
                                        orderAmount=abs(currentAmount),
                                        orderPrice=self.getCurrentPrice(
                                            order['currency'], order['asset']))

                orderSize = order['orderQuantity']

                if order['action'] == self.buyText:
                    result = self.marketBuy(orderSize,
                                            order['currency'],
                                            order['asset'],
                                            note='Going long')
                    self.logOrderInBank(order,
                                        action=self.buyText,
                                        orderAmount=self.getAmountOfItem(
                                            order['currency'], order['asset']),
                                        orderPrice=self.getCurrentPrice(
                                            order['currency'], order['asset']))
                else:
                    if order['action'] == self.sellText:
                        result = self.marketSell(orderSize,
                                                 order['currency'],
                                                 order['asset'],
                                                 note='Going short')
                        self.logOrderInBank(order,
                                            action=self.sellText,
                                            orderAmount=self.getAmountOfItem(
                                                order['currency'],
                                                order['asset']),
                                            orderPrice=self.getCurrentPrice(
                                                order['currency'],
                                                order['asset']))
                order['result'] = '0'
                break
            except:
                tries = tries + 1
                tb = traceback.format_exc()
                logger.logError(tb)
                sleep(4)
                self.connect()
        if order.get('result') is None:
            order['result'] = 'Failure'