Ejemplo n.º 1
0
    async def execute_cancellation(self, order: dict) -> dict:
        cancellation = None
        try:
            cancellation = await self.private_delete(
                self.endpoints["cancel_order"],
                {
                    "symbol": self.symbol,
                    "orderId": order["order_id"]
                },
            )

            return {
                "symbol":
                self.symbol,
                "side":
                cancellation["side"].lower(),
                "order_id":
                int(cancellation["orderId"]),
                "position_side":
                cancellation["positionSide"].lower().replace("short", "short"),
                "qty":
                float(cancellation["origQty"]),
                "price":
                float(cancellation["price"]),
            }
        except Exception as e:
            print(f"error cancelling order {order} {e}")
            print_async_exception(cancellation)
            traceback.print_exc()
            self.ts_released["force_update"] = 0.0
            return {}
Ejemplo n.º 2
0
 async def execute_order(self, order: dict) -> dict:
     o = None
     try:
         params = {'symbol': self.symbol,
                   'side': order['side'].upper(),
                   'positionSide': order['position_side'].replace('shrt', 'short').upper(),
                   'type': order['type'].upper(),
                   'quantity': str(order['qty'])}
         if params['type'] == 'LIMIT':
             params['timeInForce'] = 'GTX'
             params['price'] = order['price']
         if 'custom_id' in order:
             params['newClientOrderId'] = \
                 f"{order['custom_id']}_{str(int(time() * 1000))[8:]}_{int(np.random.random() * 1000)}"
         o = await self.private_post(self.endpoints['create_order'], params)
         return {'symbol': self.symbol,
                 'side': o['side'].lower(),
                 'position_side': o['positionSide'].lower().replace('short', 'shrt'),
                 'type': o['type'].lower(),
                 'qty': float(o['origQty']),
                 'order_id': int(o['orderId']),
                 'price': float(o['price'])}
     except Exception as e:
         print(f'error executing order {order} {e}')
         print_async_exception(o)
         traceback.print_exc()
         return {}
Ejemplo n.º 3
0
 async def execute_order(self, order: dict) -> dict:
     o = None
     try:
         params = {
             'symbol':
             self.symbol,
             'side':
             first_capitalized(order['side']),
             'order_type':
             first_capitalized(order['type']),
             'qty':
             float(order['qty']) if 'linear_perpetual' in self.market_type
             else int(order['qty']),
             'close_on_trigger':
             False
         }
         if self.hedge_mode:
             params['position_idx'] = 1 if order[
                 'position_side'] == 'long' else 2
             if 'linear_perpetual' in self.market_type:
                 params['reduce_only'] = 'close' in order['custom_id']
         else:
             params['position_idx'] = 0
             params['reduce_only'] = 'close' in order['custom_id']
         if params['order_type'] == 'Limit':
             params['time_in_force'] = 'PostOnly'
             params['price'] = str(order['price'])
         else:
             params['time_in_force'] = 'GoodTillCancel'
         params['order_link_id'] = \
             f"{order['custom_id']}_{str(int(time() * 1000))[8:]}_{int(np.random.random() * 1000)}"
         o = await self.private_post(self.endpoints['create_order'], params)
         if o['result']:
             return {
                 'symbol': o['result']['symbol'],
                 'side': o['result']['side'].lower(),
                 'order_id': o['result']['order_id'],
                 'position_side': order['position_side'],
                 'type': o['result']['order_type'].lower(),
                 'qty': o['result']['qty'],
                 'price': o['result']['price']
             }
         else:
             return o, order
     except Exception as e:
         print(f'error executing order {order} {e}')
         print_async_exception(o)
         traceback.print_exc()
         return {}
Ejemplo n.º 4
0
 async def execute_order(self, order: dict) -> dict:
     o = None
     try:
         params = {
             "symbol":
             self.symbol,
             "side":
             first_capitalized(order["side"]),
             "order_type":
             first_capitalized(order["type"]),
             "qty":
             float(order["qty"]) if "linear_perpetual" in self.market_type
             else int(order["qty"]),
             "close_on_trigger":
             False,
         }
         if self.hedge_mode:
             params["position_idx"] = 1 if order[
                 "position_side"] == "long" else 2
             if "linear_perpetual" in self.market_type:
                 params["reduce_only"] = "close" in order["custom_id"]
         else:
             params["position_idx"] = 0
             params["reduce_only"] = "close" in order["custom_id"]
         if params["order_type"] == "Limit":
             params["time_in_force"] = "PostOnly"
             params["price"] = str(order["price"])
         else:
             params["time_in_force"] = "GoodTillCancel"
         params[
             "order_link_id"] = f"{order['custom_id']}_{str(int(time() * 1000))[8:]}_{int(np.random.random() * 1000)}"
         o = await self.private_post(self.endpoints["create_order"], params)
         if o["result"]:
             return {
                 "symbol": o["result"]["symbol"],
                 "side": o["result"]["side"].lower(),
                 "order_id": o["result"]["order_id"],
                 "position_side": order["position_side"],
                 "type": o["result"]["order_type"].lower(),
                 "qty": o["result"]["qty"],
                 "price": o["result"]["price"],
             }
         else:
             return o, order
     except Exception as e:
         print(f"error executing order {order} {e}")
         print_async_exception(o)
         traceback.print_exc()
         return {}
Ejemplo n.º 5
0
    async def execute_cancellation(self, order: dict) -> dict:
        cancellation = None
        try:
            cancellation = await self.private_delete(self.endpoints['cancel_order'],
                                                     {'symbol': self.symbol, 'orderId': order['order_id']})

            return {'symbol': self.symbol, 'side': cancellation['side'].lower(), 'order_id': int(cancellation['orderId']),
                    'position_side': cancellation['positionSide'].lower().replace('short', 'shrt'),
                    'qty': float(cancellation['origQty']), 'price': float(cancellation['price'])}
        except Exception as e:
            print(f'error cancelling order {order} {e}')
            print_async_exception(cancellation)
            traceback.print_exc()
            self.ts_released['force_update'] = 0.0
            return {}
Ejemplo n.º 6
0
 async def fetch_income(
     self,
     symbol: str = None,
     income_type: str = None,
     limit: int = 50,
     start_time: int = None,
     end_time: int = None,
     page=None,
 ):
     params = {
         "limit": limit,
         "symbol": self.symbol if symbol is None else symbol
     }
     if start_time is not None:
         params["start_time"] = int(start_time / 1000)
     if end_time is not None:
         params["end_time"] = int(end_time / 1000)
     if income_type is not None:
         params["exec_type"] = first_capitalized(income_type)
     if page is not None:
         params["page"] = page
     fetched = None
     try:
         fetched = await self.private_get(self.endpoints["income"], params)
         if fetched["result"]["data"] is None:
             return []
         return sorted(
             [{
                 "symbol": e["symbol"],
                 "income_type": e["exec_type"].lower(),
                 "income": float(e["closed_pnl"]),
                 "token": self.margin_coin,
                 "timestamp": float(e["created_at"]) * 1000,
                 "info": {
                     "page": fetched["result"]["current_page"]
                 },
                 "transaction_id": float(e["id"]),
                 "trade_id": e["order_id"],
             } for e in fetched["result"]["data"]],
             key=lambda x: x["timestamp"],
         )
     except Exception as e:
         print("error fetching income: ", e)
         traceback.print_exc()
         print_async_exception(fetched)
         return []
Ejemplo n.º 7
0
 async def execute_order(self, order: dict) -> dict:
     o = None
     try:
         params = {
             "symbol":
             self.symbol,
             "side":
             order["side"].upper(),
             "positionSide":
             order["position_side"].replace("short", "short").upper(),
             "type":
             order["type"].upper(),
             "quantity":
             str(order["qty"]),
         }
         if params["type"] == "LIMIT":
             params["timeInForce"] = "GTX"
             params["price"] = order["price"]
         if "custom_id" in order:
             params[
                 "newClientOrderId"] = f"{order['custom_id']}_{str(int(time() * 1000))[8:]}_{int(np.random.random() * 1000)}"
         o = await self.private_post(self.endpoints["create_order"], params)
         return {
             "symbol":
             self.symbol,
             "side":
             o["side"].lower(),
             "position_side":
             o["positionSide"].lower().replace("short", "short"),
             "type":
             o["type"].lower(),
             "qty":
             float(o["origQty"]),
             "order_id":
             int(o["orderId"]),
             "price":
             float(o["price"]),
         }
     except Exception as e:
         print(f"error executing order {order} {e}")
         print_async_exception(o)
         traceback.print_exc()
         return {}
Ejemplo n.º 8
0
 async def fetch_income(self,
                        symbol: str = None,
                        income_type: str = None,
                        limit: int = 50,
                        start_time: int = None,
                        end_time: int = None,
                        page=None):
     params = {
         'limit': limit,
         'symbol': self.symbol if symbol is None else symbol
     }
     if start_time is not None:
         params['start_time'] = int(start_time / 1000)
     if end_time is not None:
         params['end_time'] = int(end_time / 1000)
     if income_type is not None:
         params['exec_type'] = first_capitalized(income_type)
     if page is not None:
         params['page'] = page
     fetched = None
     try:
         fetched = await self.private_get(self.endpoints['income'], params)
         if fetched['result']['data'] is None:
             return []
         return sorted([{
             'symbol': e['symbol'],
             'income_type': e['exec_type'].lower(),
             'income': float(e['closed_pnl']),
             'token': self.margin_coin,
             'timestamp': float(e['created_at']) * 1000,
             'info': {
                 'page': fetched['result']['current_page']
             },
             'transaction_id': float(e['id']),
             'trade_id': e['order_id']
         } for e in fetched['result']['data']],
                       key=lambda x: x['timestamp'])
     except Exception as e:
         print('error fetching income: ', e)
         traceback.print_exc()
         print_async_exception(fetched)
         return []
Ejemplo n.º 9
0
 async def execute_cancellation(self, order: dict) -> dict:
     cancellation = None
     try:
         cancellation = await self.private_post(
             self.endpoints['cancel_order'], {
                 'symbol': self.symbol,
                 'order_id': order['order_id']
             })
         return {
             'symbol': self.symbol,
             'side': order['side'],
             'order_id': cancellation['result']['order_id'],
             'position_side': order['position_side'],
             'qty': order['qty'],
             'price': order['price']
         }
     except Exception as e:
         print(f'error cancelling order {order} {e}')
         print_async_exception(cancellation)
         traceback.print_exc()
         self.ts_released['force_update'] = 0.0
         return {}
Ejemplo n.º 10
0
 async def execute_cancellation(self, order: dict) -> dict:
     cancellation = None
     try:
         cancellation = await self.private_post(
             self.endpoints["cancel_order"],
             {
                 "symbol": self.symbol,
                 "order_id": order["order_id"]
             },
         )
         return {
             "symbol": self.symbol,
             "side": order["side"],
             "order_id": cancellation["result"]["order_id"],
             "position_side": order["position_side"],
             "qty": order["qty"],
             "price": order["price"],
         }
     except Exception as e:
         print(f"error cancelling order {order} {e}")
         print_async_exception(cancellation)
         traceback.print_exc()
         self.ts_released["force_update"] = 0.0
         return {}