示例#1
0
    def get_listenKey(self):
        url = self.param['api'].get("listenKey", None)
        # uri = "/fapi/v1/listenKey"
        data = {"timestamp": tools.get_cur_timestamp_ms()}

        key = self.request("post", url, body=data, auth=False)
        return key
示例#2
0
    def _get_positions(self, symbol=None):

        uri = "/fapi/v1/positionRisk"
        data = {"timestamp": tools.get_cur_timestamp_ms()}
        data = self.request("get", uri, body=data, auth=True)
        position = {}
        if isinstance(data, list):
            log.info("is list")
            for d in data:
                if float(d['positionAmt']) != 0:
                    p = Position()
                    p.broker = self.name
                    p.symbol = d['symbol']
                    p.qty = float(d['positionAmt'])
                    if d['positionSide'] == "BOTH":
                        p.direction = Direction.LONG if p.qty > 0 else Direction.SHORT
                    else:
                        p.direction = Direction.LONG if d[
                            'positionSide'] == "LONG" else Direction.SHORT
                    p.price = float(d['entryPrice'])
                    p.liquidation_Price = float(d['liquidationPrice'])
                    if p.symbol in position:
                        position[p.symbol].append(p)
                    else:
                        position[p.symbol] = []
                        position[p.symbol].append(p)
                    # log.info("新增加持仓记录")
                    # log.info(p)
            self.positions = position
        else:
            log.info(f"无效持仓 {data}")
        if symbol:
            # log.info(self.positions)
            # log.info(symbol)
            return self.positions.get(symbol, [])
示例#3
0
 def cancel_order(self, symbol, order_id=None):
     # uri = "/fapi/v1/order"
     url = self.param['api'].get("order", None)
     data = {"symbol": symbol, "timestamp": tools.get_cur_timestamp_ms()}
     if order_id:
         data["orderId"] = order_id
     return self.request("delete", url, body=data, auth=True)
示例#4
0
 def get_trades(self, symbol, order_id=None):
     url = self.param['api'].get("order", None)
     # uri = "/fapi/v1/order"
     data = {"symbol": symbol, "timestamp": tools.get_cur_timestamp_ms()}
     if order_id:
         data["orderId"] = order_id
     return self.request("get", url, body=data, auth=True)
示例#5
0
 def get_balnce(self, symbol=None):
     url = self.param['api'].get("balance", None)
     # uri = "/fapi/v1/balance"
     data = {"timestamp": tools.get_cur_timestamp_ms()}
     balance = self.request("get", url, body=data, auth=True)
     for b in balance:
         ba = Balance(b['balance'], b['withdrawAvailable'])
         self.balances[b['asset']] = ba
     return self.balances
示例#6
0
 def get_order_book(self, symbol, limit=500):
     uri = "/fapi/v1/depth"
     data = {
         "symbol": symbol,
         "limit": limit,
         "timestamp": tools.get_cur_timestamp_ms()
     }
     data = self.request("get", uri, body=data, auth=False)
     return data
示例#7
0
 def get_order_book(self, symbol, limit=500):
     url = self.param['api'].get("orderbook", None)
     # uri = "/api/v3/depth"
     data = {
         "symbol": symbol,
         "limit": limit,
         "timestamp": tools.get_cur_timestamp_ms()
     }
     data = self.request("get", url, body=data, auth=False)
     return data
示例#8
0
    def get_user_account(self):
        """Get user account information.

        Returns:
            success: Success results, otherwise it's None.
            error: Error information, otherwise it's None.
        """
        url = "/account"
        ts = tools.get_cur_timestamp_ms()
        params = None
        success, error = self.request("get", url, params, auth=True)
        return success, error
示例#9
0
 def get_open_interest(self, symbol, period, starttime=None, endtime=None):
     url = self.param['api'].get("openinterest", None)
     data = {
         "symbol": symbol,
         "period": period,
         "limit": 500,
         "timestamp": tools.get_cur_timestamp_ms()
     }
     if starttime:
         data["starttime"] = starttime
         data["endTime"] = endtime
     data = self.request("get", url, body=data, auth=False)
     return data
示例#10
0
 def get_fundingrate(self, symbol):
     url = self.param['api'].get("fundingrate", None)
     # uri = "/fapi/v1/openOrders"
     data = {
         "contract_code": symbol,
         "timestamp": tools.get_cur_timestamp_ms()
     }
     rs = self.request("get", url, body=data, auth=False)
     status = rs.get("status", "")
     if status == "ok":
         return rs["data"]
     else:
         return None
示例#11
0
    def get_user_account(self):
        """Get user account information.

        Returns:
            success: Success results, otherwise it's None.
            error: Error information, otherwise it's None.
        """
        url = self.param['api'].get("account", None)
        # uri = "/api/v3/account"
        ts = tools.get_cur_timestamp_ms()
        params = {"timestamp": str(ts)}
        success, error = self.request("get", url, params, auth=True)
        return success, error
示例#12
0
 def close_Longorder(self, symbol, stopprice):
     url = "/fapi/v1/order"
     data = {
         "symbol": symbol,
         "side": SELL,
         "type": OrderType.STOP_MARKET.name,
         "positionSide": Direction.LONG.name,
         "stopprice": stopprice,
         "closePosition": True,
         "timestamp": tools.get_cur_timestamp_ms()
     }
     # log.info(f"{symbol},{action},{quantity},{price}")
     # log.info(data)
     order = self.request("post", url, body=data, auth=True)
     return self.parse_order(order)
示例#13
0
 def get_balnce(self, symbol=None):
     uri = "/fapi/v1/balance"
     if self.balances:
         return self.balances.get(symbol, None)
     else:
         uri = "/fapi/v1/balance"
         data = {
             "symbol": symbol,
             "timestamp": tools.get_cur_timestamp_ms()
         }
         balance = self.request("get", uri, body=data, auth=True)
         for b in balance:
             ba = Balance(b['balance'], b['withdrawAvailable'])
             self.balances[b['asset']] = ba
         if symbol:
             return self.balances.get(symbol, None)
示例#14
0
 def get_positions(self,symbol):
     """"
         {
   "success": true,
   "result": [
     {
       "cost": -31.7906,
       "entryPrice": 138.22,
       "estimatedLiquidationPrice": 152.1,
       "future": "ETH-PERP",
       "initialMarginRequirement": 0.1,
       "longOrderSize": 1744.55,
       "maintenanceMarginRequirement": 0.04,
       "netSize": -0.23,
       "openSize": 1744.32,
       "realizedPnl": 3.39441714,
       "shortOrderSize": 1732.09,
       "side": "sell",
       "size": 0.23,
       "unrealizedPnl": 0
     }
   ]
 }
     """
     url = "/positions"
     ts = tools.get_cur_timestamp_ms()
     params = None
     success, data = self.request("get", url, params, auth=True)
     if success:
         for d in data['result']:
             p = Position()
             p.broker = self.name
             p.symbol = d['future']
             p.qty = d['size']
             p.direction = Direction.LONG if d['side'] =='buy' else Direction.SHORT
             p.price = d['entryPrice']
             p.liquidation_Price = d['estimatedLiquidationPrice']
             self.positions[p.symbol] = p
     if symbol:
         return self.positions[symbol]
     else:
         return self.positions
示例#15
0
    def create_order(self,
                     action,
                     symbol,
                     quantity,
                     price=None,
                     order_type=OrderType.LIMIT,
                     reduceOnly=False,
                     tif=None,
                     position_side="BOTH",
                     client_id=None):
        """Create an order.
        LIMIT_MAKER are LIMIT orders that will be rejected if they would immediately match and trade as a taker.
        STOP_LOSS and TAKE_PROFIT will execute a MARKET order when the stopPrice is reached.
        Any LIMIT or LIMIT_MAKER type order can be made an iceberg order by sending an icebergQty.
        Any order with an icebergQty MUST have timeInForce set to GTC.
        MARKET orders using quantity specifies how much a user wants to buy or sell based on the market price.
        MARKET orders using quoteOrderQty specifies the amount the user wants to spend (when buying) or receive (when selling) of the quote asset; the correct quantity will be determined based on the market liquidity and quoteOrderQty.
        MARKET orders using quoteOrderQty will not break LOT_SIZE filter rules; the order will execute a quantity that will have the notional value as close as possible to quoteOrderQty.
        """
        url = self.param['api'].get("order", None)

        # url = "/fapi/v1/order"
        data = {
            "symbol": symbol,
            "side": action,
            "type": order_type.name.upper(),
            "positionSide": position_side,
            "quantity": quantity,
            "timestamp": tools.get_cur_timestamp_ms()
        }
        if tif != None:
            data["timeInForce"] = tif.name
        if reduceOnly:
            data["reduceOnly"] = reduceOnly
        if price:
            data["price"] = price
        if client_id:
            data["newClientOrderId"] = client_id
        # log.info(f"{symbol},{action},{quantity},{price}")
        log.info(data)
        return self.request("post", url, body=data, auth=True)
示例#16
0
    def _get_positions(self, symbol=None):
        """"
                [
            {
                "entryPrice": "0.00000", // 开仓均价
                "marginType": "isolated", // 逐仓模式或全仓模式
                "isAutoAddMargin": "false",
                "isolatedMargin": "0.00000000", // 逐仓保证金
                "leverage": "10", // 当前杠杆倍数
                "liquidationPrice": "0", // 参考强平价格
                "markPrice": "6679.50671178",   // 当前标记价格
                "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限
                "positionAmt": "0.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空
                "symbol": "BTCUSDT", // 交易对
                "unRealizedProfit": "0.00000000", // 持仓未实现盈亏
                "positionSide": "BOTH", // 持仓方向
            },
            {
                "entryPrice": "6563.66500", // 开仓均价
                "marginType": "isolated", // 逐仓模式或全仓模式
                "isAutoAddMargin": "false",
                "isolatedMargin": "15517.54150468", // 逐仓保证金
                "leverage": "10", // 当前杠杆倍数
                "liquidationPrice": "5930.78", // 参考强平价格
                "markPrice": "6679.50671178",   // 当前标记价格
                "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限
                "positionAmt": "20.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空
                "symbol": "BTCUSDT", // 交易对
                "unRealizedProfit": "2316.83423560" // 持仓未实现盈亏
                "positionSide": "LONG", // 持仓方向
            },
            {
                "entryPrice": "0.00000", // 开仓均价
                "marginType": "isolated", // 逐仓模式或全仓模式
                "isAutoAddMargin": "false",
                "isolatedMargin": "5413.95799991", // 逐仓保证金
                "leverage": "10", // 当前杠杆倍数
                "liquidationPrice": "7189.95", // 参考强平价格
                "markPrice": "6679.50671178",   // 当前标记价格
                "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限
                "positionAmt": "-10.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空
                "symbol": "BTCUSDT", // 交易对
                "unRealizedProfit": "-1156.46711780" // 持仓未实现盈亏
                "positionSide": "SHORT", // 持仓方向
            }

        ]
         """
        uri = "/fapi/v1/positionRisk"
        data = {"timestamp": tools.get_cur_timestamp_ms()}
        data = self.request("get", uri, body=data, auth=True)
        position = {}
        if isinstance(data, list):
            log.info("is list")
            for d in data:
                if float(d['positionAmt']) != 0:
                    p = Position()
                    p.broker = self.name
                    p.symbol = d['symbol']
                    p.qty = float(d['positionAmt'])
                    if d['positionSide'] == "BOTH":
                        p.direction = Direction.LONG if p.qty > 0 else Direction.SHORT
                    else:
                        p.direction = Direction.LONG if d[
                            'positionSide'] == "LONG" else Direction.SHORT
                    p.price = float(d['entryPrice'])
                    p.liquidation_Price = float(d['liquidationPrice'])
                    if p.symbol in position:
                        position[p.symbol].append(p)
                    else:
                        position[p.symbol] = []
                        position[p.symbol].append(p)
                    # log.info("新增加持仓记录")
                    # log.info(p)
            self.positions = position
        else:
            log.info(f"无效持仓 {data}")
        if symbol:
            # log.info(self.positions)
            # log.info(symbol)
            return self.positions.get(symbol, [])
示例#17
0
 def get_open_order(self, symbol, order_id=None):
     uri = "/fapi/v1/openOrder"
     data = {"symbol": symbol, "timestamp": tools.get_cur_timestamp_ms()}
     if order_id:
         data["orderId"] = order_id
     return self.request("get", uri, body=data, auth=True)
示例#18
0
 def put_listenKey(self):
     if self.API_KEY:
         uri = "/fapi/v1/listenKey"
         data = {"timestamp": tools.get_cur_timestamp_ms()}
         return self.request("put", uri, body=data, auth=False)
示例#19
0
    def get_listenKey(self):
        uri = "/fapi/v1/listenKey"
        data = {"timestamp": tools.get_cur_timestamp_ms()}

        key = self.request("post", uri, body=data, auth=False)
        return key
示例#20
0
 def put_listenKey(self):
     if self.API_KEY:
         url = self.param['api'].get("listenKey", None)
         data = {"timestamp": tools.get_cur_timestamp_ms()}
         return self.request("put", url, body=data, auth=False)
示例#21
0
 def cancel_all_order(self, symbol):
     uri = "/fapi/v1/allOpenOrders"
     data = {"symbol": symbol, "timestamp": tools.get_cur_timestamp_ms()}
     return self.request("delete", uri, body=data, auth=True)
示例#22
0
 def get_open_orders(self, symbol):
     url = self.param['api'].get("open_orders", None)
     # uri = "/fapi/v1/openOrders"
     data = {"symbol": symbol, "timestamp": tools.get_cur_timestamp_ms()}
     return self.request("get", url, body=data, auth=True)