async def cancel(self): self.check() result = await self.api.future_cancel(order_id=self.order_id, symbol=self.symbol, contract_type=self.contract_type) logger.debug(result) return result
async def sell_market_price(self, symbol='XBTM18', amount=100): if amount > 0: amount = -amount result = self.rest_api.Order.Order_new(symbol=symbol, orderQty=amount).result() logger.debug(result) return None
async def get_order_info(self, order_id=None): result = self.rest_api.Order.Order_getOrders( filter=json.dumps({'orderID': order_id})).result() logger.debug(result[0]) if result[0]: return result[0][0] else: raise EmptyResultError("Empty Result")
async def get_all_my_new_orders(self, symbol='XBTM18'): result = self.rest_api.Order.Order_getOrders( filter=json.dumps({ 'symbol': symbol, 'ordStatus': 'New' })).result() logger.debug(result[0]) return result[0]
async def get_order_info_by_status(self, status="2"): result = await self.rest_api.future_order_info(symbol="btc_usd", contract_type="quarter", order_id="-1", status=status, current_page="1", page_length="50") logger.debug(result) return result
async def sub_channels(self, *channels): if self._connect_status_flag != 1: await asyncio.sleep(2) await self.sub_channels(*channels) return self.current_sub_channels.update(set(channels)) for channel in channels: logger.debug("{{'op':'subscribe','args':['{0}']}}".format(channel)) await self.session.send_str( '{{"op":"subscribe","args":["{0}"]}}'.format(channel))
async def update_order(self, order_id, price): try: result = self.rest_api.Order.Order_amend(orderID=order_id, price=price).result() logger.debug(result[0]) return result[0] except Exception as e: if isinstance(e, HTTPBadRequest): pass else: raise e
async def reconnect(self): logger.debug("重新连接websocket") self.ping_pong_task.cancel() async def sub_all_channel(): await asyncio.sleep(20) logger.debug("重新 加载已经定义的频道:{}".format(self.current_sub_channels)) await self.sub_channels(*self.current_sub_channels) self._loop.create_task(self.create_session()) self._loop.create_task(sub_all_channel())
async def info(self): self.check() result = await self.api.future_order_info( symbol=self.symbol, contract_type=self.contract_type, order_id=self.order_id) logger.debug(result) self.status = result["orders"][0]["status"] self.amount = result["orders"][0]["amount"] self.lever_rate = result["orders"][0]["lever_rate"] self.deal_amount = result["orders"][0]["deal_amount"] self.contract_name = result["orders"][0]["contract_name"] return result
async def buy(self, price, symbol, amount): result = self.rest_api.Order.Order_new(symbol=symbol, orderQty=amount, price=price).result() logger.debug(result) if result[0]: order = Order() order.id = result[0]["orderID"] order.symbol = symbol order.host = 'bitmex' order.result = result[0] order_manager.set_buy_order(order) return order else: return None
async def list(self, **filter): """ okex的这个api需要传入 filter = {"order_ids"=[123,321],"symbol":"btc_usd","contract_type":"quarter"} :param filter: :return: """ order_ids = filter["order_ids"] symbol = filter["symbol"] contract_type = filter["contract_type"] self.check() result = await self.api.future_orders_info( symbol=symbol, contract_type=contract_type, order_id=",".join(order_ids)) logger.debug(result) return result
async def sell(self, price, amount, type=2, match_price="0"): try: result = await self.rest_api.future_trade(symbol="btc_usd", contract_type="quarter", price=str(price), amount=str(amount), type=str(type), match_price=match_price, lever_rate="10") logger.debug(result) if result["result"]: order = Order() order.id = result["order_id"] order.host = 'okex' order.type = type order.amount = amount order.price = price order_manager.set_sell_order(order) except Exception as e: logger.exception("异常")
async def begin_trade(build_type="buy_long", price=None): if build_type == "buy_long": self.current_flag = "买多建仓" if build_type == "buy_short": self.current_flag = "买空平仓" if build_type == "sell_long": self.current_flag = "卖多平仓" if build_type == "sell_short": self.current_flag = "卖空建仓" logger.info(f"当前的交易标志:{self.current_flag}") # 预设交易信息 trade = self.okex_market.api.trade().lever_rate(10).symbol( "btc_usd").contract_type("quarter") # 开仓或者平仓,以市价成交 aa = build_type.split("_") # 采用定价方式,使用这种方式即可 # trade.start(aa[0], aa[1]).amount(1).price(price) trade.start(aa[0], aa[1]).amount(1).as_market_price() result = await trade.go() # 创建order order = self.okex_market.api.order(result["order_id"], symbol="btc_usd", contract_type="quarter") # 更新order信息 # 0等待成交 1部分成交 2全部成交 -1撤单 4撤单处理中 5撤单中 # 等待单全部完成 while True: await order.info() if order.status == 2: break else: await asyncio.sleep(30) # 如果当前是平仓的操作,则重置交易标志位 if "平仓" in self.current_flag: logger.debug("平仓成功,重置标志位,进行下一轮") self.current_flag = None
async def _execute_request(self, method, request_type, kwargs): try: if request_type == "post": payload = self.base_payload.copy() payload.update(kwargs) from MaxValue.utils.sign import okex_build_sign payload.update({"sign": okex_build_sign(self.secret_key, payload)}) logger.debug(payload) async with self.session.post(f"{self.base_url}/{method}.do", proxy=self.proxy, data=payload, timeout=10) as resp: response = await resp.json() return response else: payload = {} payload.update(kwargs) logger.debug(payload) async with self.session.get(f"{self.base_url}/{method}.do", proxy=self.proxy, params=payload, timeout=10) as resp: response = await resp.json() return response except Exception as e: logger.error(e)
async def list(self, start_time=None, end_time=None, **filter): """ :param start_time: 开始时间 :param end_time: 结束时间 :param filter: 选择器 具体支持的选项 :return: """ if start_time and end_time: if isinstance(start_time, datetime) and isinstance( end_time, datetime): pass else: raise Exception("start_time,end_time 必须是datetime类型") elif start_time is None and end_time is None: start_time = arrow.get().shift(days=-10).datetime end_time = arrow.get().datetime elif start_time is None: start_time = arrow.get(end_time).shift(days=-10).datetime elif end_time is None: end_time = arrow.get().datetime _ = {} self.check() for i in ["symbol", "order_id", "side", "status"]: if i in filter: _.update({"symbol": filter["symbol"]}) if i == "symbol" else 1 _.update({"orderID": filter["order_id"] }) if i == "order_id" else 1 _.update({"side": filter["side"]}) if i == "side" else 1 _.update({"ordStatus": filter["status"] }) if i == "status" else 1 result = await self.api.future_orders_info(filter=_, startTime=start_time, endTime=end_time) logger.debug(result) return result
async def create_session(self, auto_reconnect=True): logger.debug("连接websocket") client_session = aiohttp.ClientSession() try: ws = await client_session.ws_connect(self.base_url, proxy=proxy, timeout=10, autoping=True) self._connect_status_flag = 1 self.session = ws self.ping_pong_task = self._loop.create_task(self.send_ping()) while True: msg = await ws.receive() if msg.type == aiohttp.WSMsgType.TEXT: if msg.data == 'close cmd': await ws.close() break else: await self._msg_hander._on_message(json.loads(msg.data) ) elif msg.type == aiohttp.WSMsgType.CLOSED: logger.debug(msg.type) self._connect_status_flag = 2 break elif msg.type == aiohttp.WSMsgType.ERROR: logger.debug(msg.type) self._connect_status_flag = 3 break except Exception as e: logger.warn(e) finally: logger.debug("退出后重试重试") if client_session and not client_session.closed: await client_session.close() self.session = None if auto_reconnect: await asyncio.sleep(10) await self.reconnect()
async def get_future_ticker(self): result = await self.rest_api.future_ticker(symbol="btc_usd", contract_type="quarter") logger.debug(result) return result
async def pong(): logger.debug("获取到服务器的pong回复")
async def addChannel(data_item): logger.debug(f"频道{data_item['data']['channel']}订阅成功")
async def get_order_info(self, symbol, contract_type, order_id): result = await self.rest_api.future_order_info( symbol=symbol, contract_type=contract_type, order_id=order_id) logger.debug(result) return result
async def get_order_info_by_id(self, order_id): result = await self.rest_api.future_order_info(symbol="btc_usd", contract_type="quarter", order_id=order_id) logger.debug(result) return result["orders"][0]
async def cancel_future(self, order_id, symbol, contract_type): result = await self.rest_api.future_cancel(order_id=order_id, symbol=symbol, contract_type=contract_type) logger.debug(result) return result
async def get_position(self, symbol='XBTM18'): logger.debug("执行get_position") result = self.rest_api.Position.Position_get( filter=json.dumps({'symbol': symbol})).result() return result
async def get_trades_history(self): result = await self.rest_api.future_trades_history(symbol="btc_usd", date="2018-06-29", since=111111111111) logger.debug(result) return result
async def info(self): self.check() result = await self.api.get_order_info(order_id=self.order_id) logger.debug(result) return result
async def get_userinfo(self): result = await self.rest_api.future_userinfo_4fix() logger.debug(result) return result
async def get_position(self): result = await self.rest_api.future_position_4fix( symbol="btc_usd", contract_type="quarter") logger.debug(result)
async def get_all_my_trades(self, symbol='XBTM18'): result = self.rest_api.Trade.Trade_get( filter=json.dumps({'symbol': symbol})).result() logger.debug(result)
async def get(self, symbol, contract_type): result = await self.api.future_position_4fix( symbol=symbol, contract_type=contract_type) logger.debug(result) return result
async def order(data_item): logger.debug(data_item)