Example #1
0
 async def get_open_orders(self) -> List[OpenOrder]:
     ret_val = []
     for trading_pair in self._trading_pairs:
         query_params = {
             "market_id": trading_pair
         }
         result = await self._api_request(
             method="GET",
             path_url=CONSTANTS.OPEN_ORDER_URL,
             params=query_params,
             is_auth_required=True
         )
         if "data" not in result:
             self.logger().info(f"Unexpected response from GET {CONSTANTS.OPEN_ORDER_URL}. "
                                f"Params: {query_params} "
                                f"Response: {result} ")
         for order in result["data"]:
             if order["type"] != "limit":
                 raise Exception(f"Unsupported order type {order['type']}")
             ret_val.append(
                 OpenOrder(
                     client_order_id=order["client_order_id"],
                     trading_pair=order["market_id"],
                     price=Decimal(str(order["limit_price"])),
                     amount=Decimal(str(order["quantity"])),
                     executed_amount=Decimal(str(order["quantity"])) - Decimal(str(order["filled_quantity"])),
                     status=order["status"],
                     order_type=OrderType.LIMIT,
                     is_buy=True if order["side"].lower() == "buy" else False,
                     time=int(probit_utils.convert_iso_to_epoch(order["time"])),
                     exchange_order_id=order["id"]
                 )
             )
     return ret_val
Example #2
0
    async def _update_order_status(self):
        """
        Calls REST API to get status update for each in-flight order.
        """
        last_tick = int(self._last_poll_timestamp / self.UPDATE_ORDER_STATUS_MIN_INTERVAL)
        current_tick = int(self.current_timestamp / self.UPDATE_ORDER_STATUS_MIN_INTERVAL)

        if current_tick > last_tick and len(self._in_flight_orders) > 0:
            tracked_orders = list(self._in_flight_orders.values())

            tasks = []
            for tracked_order in tracked_orders:
                ex_order_id = await tracked_order.get_exchange_order_id()

                query_params = {
                    "market_id": tracked_order.trading_pair,
                    "order_id": ex_order_id
                }

                tasks.append(self._api_request(method="GET",
                                               path_url=CONSTANTS.ORDER_URL,
                                               params=query_params,
                                               is_auth_required=True)
                             )
            self.logger().debug(f"Polling for order status updates of {len(tasks)} orders.")
            order_results: List[Dict[str, Any]] = await safe_gather(*tasks, return_exceptions=True)

            # Retrieve start_time and end_time of the earliest and last order.
            # Retrieves all trades between this order creations.
            min_order_ts: str = ""

            min_ts: float = float("inf")
            for order_update in order_results:
                if isinstance(order_update, Exception):
                    raise order_update

                # Order Creation Time
                for update in order_update["data"]:
                    order_ts: float = probit_utils.convert_iso_to_epoch(update["time"])
                    if order_ts < min_ts:
                        min_order_ts = update["time"]
                        min_ts = order_ts

            trade_history_tasks = []
            for trading_pair in self._trading_pairs:
                query_params = {
                    "start_time": min_order_ts,
                    "end_time": probit_utils.get_iso_time_now(),
                    "limit": 1000,
                    "market_id": trading_pair
                }
                trade_history_tasks.append(self._api_request(
                    method="GET",
                    path_url=CONSTANTS.TRADE_HISTORY_URL,
                    params=query_params,
                    is_auth_required=True
                ))
            trade_history_results: List[Dict[str, Any]] = await safe_gather(*trade_history_tasks, return_exceptions=True)

            for t_pair_history in trade_history_results:
                if isinstance(t_pair_history, Exception):
                    raise t_pair_history
                if "data" not in t_pair_history:
                    self.logger().info(f"Unexpected response from GET /trade_history. 'data' field not in resp: {t_pair_history}")
                    continue

                trade_details: List[Dict[str, Any]] = t_pair_history["data"]
                for trade in trade_details:
                    self._process_trade_message(trade)

            for order_update in order_results:
                if isinstance(order_update, Exception):
                    raise order_update
                if "data" not in order_update:
                    self.logger().info(f"Unexpected response from GET /order. 'data' field not in resp: {order_update}")
                    continue

                for order in order_update["data"]:
                    self._process_order_message(order)