Exemple #1
0
    async def create_order(self, action, price, quantity, *args, **kwargs):
        """ Create an order.

        Args:
            action: Trade direction, BUY or SELL.
            price: Price of each contract.
            quantity: The buying or selling quantity.

        Returns:
            order_no: Order ID if created successfully, otherwise it's None.
            error: Error information, otherwise it's None.
        """
        if float(quantity) > 0:
            if action == ORDER_ACTION_BUY:
                trade_type = TRADE_TYPE_BUY_OPEN
            else:
                trade_type = TRADE_TYPE_SELL_CLOSE
        else:
            if action == ORDER_ACTION_BUY:
                trade_type = TRADE_TYPE_BUY_CLOSE
            else:
                trade_type = TRADE_TYPE_SELL_OPEN
        quantity = abs(float(quantity))
        price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)
        client_order_id = tools.get_uuid1().replace("-",
                                                    "")[:21] + str(trade_type)
        result, error = await self._rest_api.create_order(
            action, self._raw_symbol, price, quantity, client_order_id)
        if error:
            return None, error
        order_no = "{}_{}".format(result["orderId"], result["clientOrderId"])
        return order_no, None
Exemple #2
0
    async def create_order(self,
                           action,
                           price,
                           quantity,
                           order_type=ORDER_TYPE_LIMIT):
        """ Create an order.

        Args:
            action: Trade direction, BUY or SELL.
            price: Price of each contract.
            quantity: The buying or selling quantity.
            order_type: Limit order or market order, LIMIT or MARKET.

        Returns:
            order_no: Order ID if created successfully, otherwise it's None.
            error: Error information, otherwise it's None.
        """
        price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)
        result, error = await self._rest_api.create_order(
            action, self._raw_symbol, price, quantity)
        if error:
            return None, error
        order_no = "{}_{}".format(result["orderId"], result["clientOrderId"])
        return order_no, None
Exemple #3
0
    async def on_event_orderbook_update(self, orderbook: Orderbook):
        """ 订单薄更新
        """
        logger.debug("orderbook:", orderbook, caller=self)
        ask1_price = float(orderbook.asks[0][0])  # 卖一价格
        bid1_price = float(orderbook.bids[0][0])  # 买一价格
        price = (ask1_price + bid1_price) / 2  # 为了方便,这里假设盘口价格为 卖一 和 买一 的平均值

        # 判断是否需要撤单
        if self.order_no:
            if (self.create_order_price + 10 > price - 1) and (self.create_order_price + 10 < price + 1):
                return
            _, error = await self.trader.revoke_order(self.order_no)
            if error:
                logger.error("revoke order error! error:", error, caller=self)
                return
            self.order_no = None
            logger.info("revoke order:", self.order_no, caller=self)

        # 创建新订单
        new_price = price + 10
        quantity = "1"  # 委托数量为1
        action = ORDER_ACTION_BUY
        new_price = tools.float_to_str(new_price)  # 将价格转换为字符串,保持精度
        quantity = tools.float_to_str(quantity)  # 将数量转换为字符串,保持精度
        order_no, error = await self.trader.create_order(action, new_price, quantity)
        if error:
            logger.error("create order error! error:", error, caller=self)
            return
        self.order_no = order_no
        self.create_order_price = float(new_price)
        logger.info("create new order:", order_no, caller=self)
Exemple #4
0
 async def create_order(self, action, price, quantity, order_type=ORDER_TYPE_LIMIT):
     """ 创建订单
     @param action 交易方向 BUY / SELL
     @param price 委托价格
     @param quantity 委托数量
     @param order_type 委托类型 LIMIT / MARKET
     """
     if action == ORDER_ACTION_BUY:
         if order_type == ORDER_TYPE_LIMIT:
             t = "buy-limit"
         elif order_type == ORDER_TYPE_MARKET:
             t = "buy-market"
         else:
             logger.error("order_type error! order_type:", order_type, caller=self)
             return None, "order type error"
     elif action == ORDER_ACTION_SELL:
         if order_type == ORDER_TYPE_LIMIT:
             t = "sell-limit"
         elif order_type == ORDER_TYPE_MARKET:
             t = "sell-market"
         else:
             logger.error("order_type error! order_type:", order_type, caller=self)
             return None, "order type error"
     else:
         logger.error("action error! action:", action, caller=self)
         return None, "action error"
     price = tools.float_to_str(price)
     quantity = tools.float_to_str(quantity)
     result, error = await self._rest_api.create_order(self._raw_symbol, price, quantity, t)
     return result, error
    async def create_order(self, action, price, quantity, *args, **kwargs):
        """ Create an order.

        Args:
            action: Trade direction, BUY or SELL.
            price: Price of each contract.
            quantity: The buying or selling quantity.

        Returns:
            order_no: Order ID if created successfully, otherwise it's None.
            error: Error information, otherwise it's None.
        """
        price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)
        client_order_id = kwargs.get("client_order_id")
        result, error = await self._rest_api.create_order(
            action,
            self._raw_symbol,
            price,
            quantity,
            client_order_id=client_order_id)
        if error:
            return None, error
        order_no = "{}_{}".format(result["orderId"], result["clientOrderId"])
        return order_no, None
Exemple #6
0
    async def create_order(self, action, price, quantity, order_type=ORDER_TYPE_LIMIT, *args, **kwargs):
        """ 创建订单
        @param action 交易方向 BUY/SELL
        @param price 委托价格
        @param quantity 委托数量
        @param order_type 委托类型 LIMIT / MARKET
        """
        if action not in [ORDER_ACTION_BUY, ORDER_ACTION_SELL]:
            return None, "action error"
        if order_type not in [ORDER_TYPE_MARKET, ORDER_TYPE_LIMIT]:
            return None, "order_type error"

        # 创建订单
        price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)
        success, error = await self._rest_api.create_order(action, self._raw_symbol, price, quantity, order_type)
        if error:
            return None, error
        order_no = str(success["orderNo"])
        infos = {
            "account": self._account,
            "platform": self._platform,
            "strategy": self._strategy,
            "order_no": order_no,
            "symbol": self._symbol,
            "action": action,
            "price": price,
            "quantity": quantity,
            "order_type": order_type
        }
        order = Order(**infos)
        self._orders[order_no] = order
        if self._order_update_callback:
            SingleTask.run(self._order_update_callback, copy.copy(order))
        return order_no, None
Exemple #7
0
    async def on_event_orderbook_update(self, orderbook: Orderbook):
        """ 订单薄更新
        """
        logger.debug("orderbook:", orderbook, caller=self)
        bid3_price = orderbook.bids[2][0]  # 买三价格
        bid4_price = orderbook.bids[3][0]  # 买四价格

        # 判断是否需要撤单
        if self.order_no:
            if float(self.create_order_price) < float(bid3_price) or float(
                    self.create_order_price) > float(bid4_price):
                return
            _, error = await self.trader.revoke_order(self.order_no)
            if error:
                logger.error("revoke order error! error:", error, caller=self)
                return
            self.order_no = None
            logger.info("revoke order:", self.order_no, caller=self)

        # 创建新订单
        new_price = (float(bid3_price) + float(bid4_price)) / 2
        quantity = "0.1"  # 假设委托数量为0.1
        action = ORDER_ACTION_BUY
        price = tools.float_to_str(new_price)
        quantity = tools.float_to_str(quantity)
        order_no, error = await self.trader.create_order(
            action, price, quantity)
        if error:
            logger.error("create order error! error:", error, caller=self)
            return
        self.order_no = order_no
        self.create_order_price = price
        logger.info("create new order:", order_no, caller=self)
Exemple #8
0
    async def create_order(self,
                           symbol,
                           action,
                           price,
                           quantity,
                           order_type=ORDER_TYPE_LIMIT,
                           *args,
                           **kwargs):
        """ Create an order.

        Args:
            symbol: Trade target
            action: Trade direction, `BUY` or `SELL`.
            price: Price of each contract.
            quantity: The buying or selling quantity.
            order_type: Order type, `MARKET` or `LIMIT`.

        Returns:
            order_no: Order ID if created successfully, otherwise it's None.
            error: Error information, otherwise it's None.
        """
        price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)
        result, error = await self._rest_api.create_order(
            action, symbol, price, quantity, order_type)
        if error:
            return None, error
        if not result["result"]:
            return None, result
        return result["order_id"], None
Exemple #9
0
    async def on_event_orderbook_update(self, orderbook: Orderbook):
        """ 订单薄更新
        """
        #logger.debug("orderbook:", orderbook, caller=self)
        ask1_price = float(orderbook.asks[0][0])  # 卖一价格
        bid1_price = float(orderbook.bids[0][0])  # 买一价格
        logger.debug("btc/busd :",
                     ask1_price,
                     bid1_price,
                     self.bsud_usdt_price,
                     caller=self)

        if self.bsud_usdt_price == 0:
            logger.debug("on_event_orderbook_update busd/usdt not get now")
            return

        self.highest_price = max(self.highest_price, ask1_price)
        self.lowest_price = min(self.lowest_price, bid1_price)

        if ask1_price < self.btc_busd_relative[
                'bid0_relative'] and not self.buy_open_order_no:
            logger.info("on_event_orderbook_update: Buy signal", bid1_price,
                        orderbook.bids[0][1])
            self.buy_open_price = float(orderbook.asks[0][0])
            quantity = self.buy_open_quantity
            action = ORDER_ACTION_BUY
            new_price = tools.float_to_str(self.buy_open_price)
            logger.info('check :', action)
            order_no, error = await self.trader.create_order(
                action, new_price, quantity)
            s = "buy bitcoin" + new_price
            os.system('say ' + s)
            if error:
                logger.error("create order error! error:", error, caller=self)
                return
            self.buy_open_order_no = order_no
            logger.info("create buy open order:", order_no, caller=self)
        elif self.buy_open_order_no and not self.sell_close_order_no:
            #止损
            if ask1_price < self.buy_open_price * (1 - self.threshold) or \
                (ask1_price < self.highest_price *  (1 - self.threshold) and ask1_price > self.buy_open_price * (1 + self.threshold)):
                price = bid1_price  # 当前盘口价格,
                new_price = tools.float_to_str(price)  # 将价格转换为字符串,保持精度
                order_no, error = await self.trader.create_order(
                    ORDER_ACTION_SELL, new_price, self.buy_open_quantity)
                if error:
                    logger.error("create order error! error:",
                                 error,
                                 caller=self)
                    return
                self.sell_close_order_no = order_no
                logger.info("create sell close order:", order_no, caller=self)

        elif self.sell_close_order_no:
            logger.info("wait for sell close")
        else:
            logger.info("wait for better price")
Exemple #10
0
    async def create_order(self,
                           action,
                           price,
                           quantity,
                           order_type=ORDER_TYPE_LIMIT,
                           *args,
                           **kwargs):
        """ Create an order.

        Args:
            action: Trade direction, BUY or SELL.
            price: Price of order.
            quantity: The buying or selling quantity.
            order_type: order type, MARKET or LIMIT.

        Returns:
            order_no: Order ID if created successfully, otherwise it's None.
            error: Error information, otherwise it's None.
        """
        if action == ORDER_ACTION_BUY:
            action_type = "buy"
        elif action == ORDER_ACTION_SELL:
            action_type = "sell"
        else:
            return None, "action error"
        if order_type == ORDER_TYPE_MARKET:
            order_type_2 = "market"
        elif order_type == ORDER_TYPE_LIMIT:
            order_type_2 = "limit"
        else:
            return None, "order_type error"

        client_id = tools.get_uuid1()
        price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)
        success, error = await self._rest_api.create_order(
            client_id, action_type, self._raw_symbol, order_type_2, price,
            quantity)
        if error:
            return None, error
        order_no = success["orderId"]
        infos = {
            "account": self._account,
            "platform": self._platform,
            "strategy": self._strategy,
            "order_no": order_no,
            "symbol": self._symbol,
            "action": action,
            "price": price,
            "quantity": quantity,
            "order_type": order_type
        }
        order = Order(**infos)
        self._orders[order_no] = order
        if self._order_update_callback:
            SingleTask.run(self._order_update_callback, copy.copy(order))
        return order_no, None
Exemple #11
0
 async def create_order(self, action, price, quantity, order_type=ORDER_TYPE_LIMIT):
     """ 创建订单
     @param action 交易方向 BUY/SELL
     @param price 委托价格
     @param quantity 委托数量
     @param order_type 委托类型 LIMIT / MARKET
     """
     price = tools.float_to_str(price)
     quantity = tools.float_to_str(quantity)
     result, error = await self._rest_api.create_order(action, self._raw_symbol, price, quantity, order_type)
     if error:
         return None, error
     if not result["result"]:
         return None, result
     return result["order_id"], None
    async def create_order(self,
                           action,
                           price,
                           quantity,
                           order_type=ORDER_TYPE_LIMIT,
                           *args,
                           **kwargs):
        """ Create an order.

        Args:
            action: Trade direction, BUY or SELL.
            price: Price of order.
            quantity: The buying or selling quantity.
            order_type: Order type, MARKET or LIMIT.

        Returns:
            order_no: Order ID if created successfully, otherwise it's None.
            error: Error information, otherwise it's None.
        """
        if action not in [ORDER_ACTION_BUY, ORDER_ACTION_SELL]:
            return None, "action error"
        if order_type not in [ORDER_TYPE_MARKET, ORDER_TYPE_LIMIT]:
            return None, "order_type error"

        price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)
        success, error = await self._rest_api.create_order(
            action, self._raw_symbol, price, quantity, order_type)
        if error:
            return None, error
        order_no = str(success["orderNo"])
        infos = {
            "account": self._account,
            "platform": self._platform,
            "strategy": self._strategy,
            "order_no": order_no,
            "symbol": self._symbol,
            "action": action,
            "price": price,
            "quantity": quantity,
            "order_type": order_type
        }
        order = Order(**infos)
        self._orders[order_no] = order
        if self._order_update_callback:
            SingleTask.run(self._order_update_callback, copy.copy(order))
        return order_no, None
    async def create_order(self,
                           action,
                           price,
                           quantity,
                           order_type=ORDER_TYPE_LIMIT,
                           account_type='margin',
                           exchange='main'):
        """ 创建订单
        @param action 交易方向 BUY/SELL
        @param price 委托价格
        @param quantity 委托数量
        @param order_type 委托类型 LIMIT / MARKET
        """
        if order_type == ORDER_TYPE_LIMIT and price:
            price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)

        result, error = await self._rest_api.create_order(
            action, self._raw_symbol, price, quantity, order_type,
            account_type, exchange)
        if error:
            return None, error
        if result['status'] != 0:
            return None, result
        order_id = result["data"]

        # 创建订单成功后,将订单存下来
        info = {
            "platform": self._platform,
            "account": self._account,
            "strategy": self._strategy,
            "order_no": order_id,
            "action": action,
            "symbol": self._symbol,
            "price": price,  # 字符串
            "quantity": quantity,
            "remain": quantity,
            "status": ORDER_STATUS_SUBMITTED,
            "avg_price": price,
            'order_type': order_type
        }
        order = Order(**info)
        self._orders[order_id] = order

        return order_id, None
Exemple #14
0
 async def create_order(self,
                        action,
                        price,
                        quantity,
                        order_type=ORDER_TYPE_LIMIT):
     """ 创建订单
     @param action 交易方向 BUY/SELL
     @param price 委托价格
     @param quantity 委托数量
     @param order_type 委托类型 LIMIT / MARKET
     """
     price = tools.float_to_str(price)
     quantity = tools.float_to_str(quantity)
     result, error = await self._rest_api.create_order(
         action, self._raw_symbol, price, quantity)
     if error:
         return None, error
     order_no = "{}_{}".format(result["orderId"], result["clientOrderId"])
     return order_no, None
Exemple #15
0
 async def on_ticker(self, *args, **kwargs):
     """ 系统循环回调,每秒钟执行一次
     """
     logger.info("do ticker ...", caller=self)
     if self.sell_close_time_down > 0:
         self.sell_close_time_down -= 1
         if self.sell_close_time_down <= 0:
             price = self.current_price - 2  # 当前盘口价格再减去2,尽量保证可以快速成交
             new_price = tools.float_to_str(price)  # 将价格转换为字符串,保持精度
             order_no, error = await self.trader.create_order(ORDER_ACTION_SELL, new_price, self.buy_open_quantity)
             if error:
                 logger.error("create order error! error:", error, caller=self)
                 return
             logger.info("create sell close order:", order_no, caller=self)
Exemple #16
0
    async def on_event_orderbook_update(self, orderbook: Orderbook):
        """ 订单薄更新
        """
        logger.debug("orderbook:", orderbook, caller=self)
        ask1_price = float(orderbook.asks[0][0])  # 卖一价格
        bid1_price = float(orderbook.bids[0][0])  # 买一价格
        self.current_price = (ask1_price + bid1_price) / 2  # 为了方便,这里假设盘口价格为 卖一 和 买一 的平均值

        # 如果没有挂单,那么执行挂单
        if not self.buy_open_order_no:
            price = self.current_price - 10
            quantity = self.buy_open_quantity
            action = ORDER_ACTION_BUY
            new_price = tools.float_to_str(price)  # 将价格转换为字符串,保持精度
            order_no, error = await self.trader.create_order(action, new_price, quantity)
            if error:
                logger.error("create order error! error:", error, caller=self)
                return
            self.buy_open_order_no = order_no
            logger.info("create buy open order:", order_no, caller=self)
Exemple #17
0
    async def start_orders(self, actions, callback):
        logger.info('start orders...', actions)
        # self.actions = [['BTC/BUSD', 'Buy', self.six_price[4], amount_usdt / self.six_price[2] / self.six_price[1]],
        #                 ['BTC/USDT', 'Sell', self.six_price[3], amount_usdt / self.six_price[3]],
        #                 ['BUSD/USDT', 'Buy', self.six_price[0], amount_usdt / self.six_price[1]]]

        # 先交易第个

        for action in actions:
            symbol = action[0]
            side = action[1]
            new_price = tools.float_to_str(action[2])
            decimal_places = 2 if symbol == "BUSD/USDT" else 6
            quantity = tools.round2(action[3], decimal_places)
            logger.info('order: ', symbol, new_price, quantity)
            order_no, error = await self.trader[symbol].create_order(side, new_price, quantity)
            if error:
                logger.error("create order error! error:", error, caller=self)
                break
            logger.info("create sell close order:", order_no, caller=self)
            await asyncio.sleep(0.01)
            if callback:
                SingleTask.run(callback, order_no)
Exemple #18
0
    async def create_order(self,
                           action,
                           price,
                           quantity,
                           order_type=ORDER_TYPE_LMT):
        """ 创建委托单
        @param action 操作类型 BUY买/SELL卖
        @param price 委托价格
        @param quantity 委托数量
        @param order_type 委托单类型 LMT限价单/MKT市价单
        """
        if action not in [ORDER_ACTION_BUY, ORDER_ACTION_SELL]:
            logger.error('action error! action:', action, caller=self)
            return
        if order_type not in [ORDER_TYPE_MKT, ORDER_TYPE_LMT]:
            logger.error('order_type error! order_type:',
                         order_type,
                         caller=self)
            return

        # 创建订单
        price = tools.float_to_str(price)
        quantity = tools.float_to_str(quantity)
        params = {
            "symbol": self._raw_symbol,
            "action": action,
            "price": price,
            "quantity": quantity,
            "order_type": order_type
        }
        success, result = await self._request.do_request(
            Request.CREATE_ORDER, params)
        if not success:
            logger.error('create order error! strategy:',
                         self._strategy,
                         'symbol:',
                         self._symbol,
                         'action:',
                         action,
                         'price:',
                         price,
                         'quantity:',
                         quantity,
                         'order_type:',
                         order_type,
                         caller=self)
            return None

        order_no = result["order_no"]
        infos = {
            'platform': self._platform,
            'account': self._account,
            'strategy': self._strategy,
            'order_no': order_no,
            'symbol': self._symbol,
            'action': action,
            'price': price,
            'quantity': quantity,
            'order_type': order_type
        }
        order = Order(**infos)

        # 增加订单到订单列表
        self._add_order(order)

        # 数据库里创建新订单记录
        # await self._order_db.create_new_order(order)

        logger.info('order:', order, caller=self)
        return order_no