kucoin_usdt_swap_ws.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import aiohttp
  2. import time
  3. import asyncio
  4. import zlib
  5. import json, ujson
  6. import zlib
  7. import hashlib
  8. import hmac
  9. import base64
  10. import traceback
  11. import random
  12. import gzip, csv, sys
  13. from uuid import uuid4
  14. import logging, logging.handlers
  15. import utils
  16. import model
  17. from decimal import Decimal
  18. def empty_call(msg):
  19. # print(msg)
  20. pass
  21. class KucoinUsdtSwapWs:
  22. def __init__(self, params: model.ClientParams, colo=0, is_print=0):
  23. if colo:
  24. print('不支持colo高速线路')
  25. self.BaseURL = "https://api-futures.kucoin.com"
  26. else:
  27. self.BaseURL = "https://api-futures.kucoin.com"
  28. self.params = params
  29. self.name = self.params.name
  30. self.base = self.params.pair.split('_')[0].upper()
  31. self.quote = self.params.pair.split('_')[1].upper()
  32. self.symbol = self.base + self.quote + "M"
  33. # 处理特殊情况
  34. if self.symbol == 'BTCUSDTM':
  35. self.symbol = 'XBTUSDTM'
  36. self.callback = {
  37. "onMarket":self.save_market,
  38. "onPosition":empty_call,
  39. "onEquity":empty_call,
  40. "onOrder":empty_call,
  41. "onTicker":empty_call,
  42. "onDepth":empty_call,
  43. "onExit":empty_call,
  44. }
  45. self.is_print = is_print
  46. self.proxy = None
  47. if 'win' in sys.platform:
  48. self.proxy = self.params.proxy
  49. self.logger = self.get_logger()
  50. self.ticker_info = {"name":self.name,'bp':0.0,'ap':0.0}
  51. self.multiplier = None
  52. self.max_buy = 0.0
  53. self.min_sell = 0.0
  54. self.buy_v = 0.0
  55. self.buy_q = 0.0
  56. self.sell_v = 0.0
  57. self.sell_q = 0.0
  58. self.update_t = 0.0
  59. self.depth = []
  60. #### 指定发包ip
  61. iplist = utils.get_local_ip_list()
  62. self.ip = iplist[int(self.params.ip)]
  63. def get_logger(self):
  64. logger = logging.getLogger(__name__)
  65. logger.setLevel(logging.DEBUG)
  66. # log to txt
  67. formatter = logging.Formatter('[%(asctime)s] - %(levelname)s - %(message)s')
  68. handler = logging.handlers.RotatingFileHandler(f"log.log",maxBytes=1024*1024)
  69. handler.setLevel(logging.DEBUG)
  70. handler.setFormatter(formatter)
  71. logger.addHandler(handler)
  72. return logger
  73. def save_market(self, msg):
  74. date = time.strftime('%Y-%m-%d',time.localtime())
  75. interval = float(self.params.interval)
  76. if msg:
  77. exchange = msg['name']
  78. if len(msg['data']) > 1:
  79. with open(f'./history/{exchange}_{self.symbol}_{interval}_{date}.csv',
  80. 'a',
  81. newline='',
  82. encoding='utf-8') as f:
  83. writer = csv.writer(f, delimiter=',')
  84. writer.writerow(msg['data'])
  85. if self.is_print:print(f'写入行情 {self.symbol}')
  86. async def get_sign(self):
  87. headers = {}
  88. headers['Content-Type'] = 'application/json'
  89. headers['X-MBX-APIKEY'] = self.params.access_key
  90. params = {
  91. 'timestamp':int(time.time())*1000,
  92. 'recvWindow':5000,
  93. }
  94. query_string = "&".join(["{}={}".format(k, params[k]) for k in sorted(params.keys())])
  95. signature = hmac.new(self.params.secret_key.encode(), msg=query_string.encode(), digestmod=hashlib.sha256).hexdigest()
  96. params['signature']=signature
  97. url = 'https://fapi.binance.com/fapi/v1/listenKey'
  98. session = aiohttp.ClientSession()
  99. response = await session.post(
  100. url,
  101. params=params,
  102. headers=headers,
  103. timeout=5,
  104. proxy=self.proxy
  105. )
  106. login_str = await response.text()
  107. await session.close()
  108. return ujson.loads(login_str)['listenKey']
  109. def _update_depth(self, msg):
  110. if msg['data']['sequence'] > self.update_t:
  111. self.update_t = msg['data']['sequence']
  112. self.ticker_info['bp'] = float(msg['data']['bids'][0][0])
  113. self.ticker_info['ap'] = float(msg['data']['asks'][0][0])
  114. self.callback['onTicker'](self.ticker_info)
  115. ##### 标准化深度
  116. mp = (self.ticker_info["bp"] + self.ticker_info["ap"])*0.5
  117. step = mp * utils.EFF_RANGE / utils.LEVEL
  118. bp = []
  119. ap = []
  120. bv = [0 for _ in range(utils.LEVEL)]
  121. av = [0 for _ in range(utils.LEVEL)]
  122. for i in range(utils.LEVEL):
  123. bp.append(self.ticker_info["bp"]-step*i)
  124. for i in range(utils.LEVEL):
  125. ap.append(self.ticker_info["ap"]+step*i)
  126. #
  127. price_thre = self.ticker_info["bp"] - step
  128. index = 0
  129. for bid in msg['data']['bids']:
  130. price = float(bid[0])
  131. amount = float(bid[1])
  132. if price > price_thre:
  133. bv[index] += amount
  134. else:
  135. price_thre -= step
  136. index += 1
  137. if index == utils.LEVEL:
  138. break
  139. bv[index] += amount
  140. price_thre = self.ticker_info["ap"] + step
  141. index = 0
  142. for ask in msg['data']['asks']:
  143. price = float(ask[0])
  144. amount = float(ask[1])
  145. if price < price_thre:
  146. av[index] += amount
  147. else:
  148. price_thre += step
  149. index += 1
  150. if index == utils.LEVEL:
  151. break
  152. av[index] += amount
  153. self.depth = bp + bv + ap + av
  154. self.callback['onDepth']({'name':self.name,'data':self.depth})
  155. def _update_ticker(self, msg):
  156. if msg['data']['sequence'] > self.update_t:
  157. self.update_t = msg['data']['sequence']
  158. self.ticker_info['bp'] = float(msg['data']['bestBidPrice'])
  159. self.ticker_info['ap'] = float(msg['data']['bestAskPrice'])
  160. self.callback['onTicker'](self.ticker_info)
  161. def _update_trade(self, msg):
  162. price = float(msg["data"]['price'])
  163. side = msg["data"]['side']
  164. amount = float(msg["data"]['size'])*self.multiplier
  165. if price > self.max_buy or self.max_buy == 0.0:
  166. self.max_buy = price
  167. if price < self.min_sell or self.min_sell == 0.0:
  168. self.min_sell = price
  169. if side == 'buy':
  170. self.buy_q += amount
  171. self.buy_v += amount*price
  172. elif side == 'sell':
  173. self.sell_q += amount
  174. self.sell_v += amount*price
  175. def _update_position(self, msg):
  176. pos = model.Position()
  177. if "currentQty" in msg['data']:
  178. amt = float(msg["data"]["currentQty"]) * self.multiplier
  179. ep = float(msg["data"]["avgEntryPrice"])
  180. if amt == 0:
  181. self.callback["onPosition"](pos)
  182. elif amt > 0:
  183. pos.longPos = amt
  184. pos.longAvg = ep
  185. self.callback["onPosition"](pos)
  186. elif amt < 0:
  187. pos.shortPos = -amt
  188. pos.shortAvg = ep
  189. self.callback["onPosition"](pos)
  190. def _update_account(self, msg):
  191. pass
  192. # if msg['data']['currency'] == 'USDT' and msg['subject'] == "availableBalance.change":
  193. # cash = float(msg['data']['availableBalance']) + float(msg['data']['holdBalance'])
  194. # self.callback['onEquity'] = {self.quote:cash}
  195. def _update_order(self, msg):
  196. self.logger.debug(f"ws订单推送 {msg}")
  197. if '/contractMarket/tradeOrders' in msg['topic']:
  198. if msg["data"]["symbol"] == self.symbol:
  199. if msg["data"]["status"] == 'open': # 新增订单
  200. order_event = dict()
  201. order_event['status'] = "NEW"
  202. order_event['filled'] = 0
  203. order_event['filled_price'] = 0
  204. order_event['client_id'] = msg["data"]["clientOid"] if "clientOid" in msg["data"] else ""
  205. order_event['order_id'] = msg["data"]['orderId']
  206. self.callback["onOrder"](order_event)
  207. elif msg["data"]["type"] in ['filled','canceled']: # 删除订单
  208. order_event = dict()
  209. order_event['status'] = "REMOVE"
  210. order_event['client_id'] = msg["data"]["clientOid"] if "clientOid" in msg["data"] else ""
  211. order_event['order_id'] = msg["data"]['orderId']
  212. order_event['filled'] = float(Decimal(msg["data"]["filledSize"])*Decimal(str(self.multiplier)))
  213. if 'price' in msg["data"]:
  214. if msg['data']['price'] != '':
  215. order_event['filled_price'] = float(msg["data"]["price"])
  216. else:
  217. order_event['filled_price'] = 0
  218. else:
  219. order_event['filled_price'] = 0
  220. self.callback["onOrder"](order_event)
  221. def _get_data(self):
  222. market_data = self.depth + [self.max_buy, self.min_sell]
  223. self.max_buy = 0.0
  224. self.min_sell = 0.0
  225. self.buy_v = 0.0
  226. self.buy_q = 0.0
  227. self.sell_v = 0.0
  228. self.sell_q = 0.0
  229. return {'name': self.name,'data':market_data}
  230. async def go(self):
  231. interval = float(self.params.interval)
  232. if self.is_print:print(f'Ws循环器启动 interval {interval}')
  233. ### onTrade
  234. while 1:
  235. try:
  236. # 更新市场信息
  237. market_data = self._get_data()
  238. self.callback['onMarket']({'name': self.name,'data':market_data})
  239. except:
  240. traceback.print_exc()
  241. await asyncio.sleep(interval)
  242. async def get_token(self, is_auth):
  243. # 获取 合约系数
  244. session = aiohttp.ClientSession()
  245. response = await session.get(
  246. "https://api-futures.kucoin.com/api/v1/contracts/active",
  247. proxy=self.proxy
  248. )
  249. res = await response.json()
  250. for i in res['data']:
  251. if i['symbol'] == self.symbol:
  252. self.multiplier = float(i["multiplier"])
  253. print(f"合约乘数为 {self.multiplier}")
  254. self.logger.debug(f"合约乘数为 {self.multiplier}")
  255. await session.close()
  256. # 获取 token
  257. if is_auth:
  258. uri = "/api/v1/bullet-private"
  259. else:
  260. uri = "/api/v1/bullet-public"
  261. headers = {}
  262. if is_auth:
  263. now_time = int(time.time()) * 1000
  264. str_to_sign = str(now_time) + "POST" + uri
  265. sign = base64.b64encode(hmac.new(self.params.secret_key.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
  266. passphrase = base64.b64encode(hmac.new(self.params.secret_key.encode('utf-8'), self.params.pass_key.encode('utf-8'), hashlib.sha256).digest())
  267. headers = {
  268. "KC-API-SIGN": sign.decode(),
  269. "KC-API-TIMESTAMP": str(now_time),
  270. "KC-API-KEY": self.params.access_key,
  271. "KC-API-PASSPHRASE": passphrase.decode(),
  272. "Content-Type": "application/json",
  273. "KC-API-KEY-VERSION": "2"
  274. }
  275. headers["User-Agent"] = "kucoin-python-sdk/v1.0"
  276. session = aiohttp.ClientSession()
  277. response = await session.post(
  278. self.BaseURL+uri,
  279. timeout=5,
  280. headers=headers,
  281. proxy=self.proxy
  282. )
  283. res = await response.text()
  284. res = ujson.loads(res)
  285. await session.close()
  286. if res["code"] == "200000":
  287. token = res["data"]["token"]
  288. ws_connect_id = str(uuid4()).replace('-', '')
  289. endpoint = res["data"]['instanceServers'][0]['endpoint']
  290. ws_endpoint = f"{endpoint}?token={token}&connectId={ws_connect_id}"
  291. encrypt = res["data"]['instanceServers'][0]['encrypt']
  292. if is_auth:
  293. ws_endpoint += '&acceptUserMessage=true'
  294. return ws_endpoint, encrypt
  295. else:
  296. raise Exception("kucoin usdt swap 获取token错误")
  297. async def run(self, is_auth=0, sub_trade=0, sub_fast=0):
  298. while True:
  299. try:
  300. ping_time = time.time()
  301. # 尝试连接
  302. print(f'{self.name} 尝试连接ws')
  303. # 获取token
  304. ws_endpoint, encrypt = await self.get_token(is_auth)
  305. # 登陆
  306. ws_url = ws_endpoint
  307. async with aiohttp.ClientSession(
  308. connector = aiohttp.TCPConnector(
  309. limit=50,
  310. keepalive_timeout=120,
  311. verify_ssl=False,
  312. local_addr=(self.ip,0)
  313. )
  314. ).ws_connect(
  315. ws_url,
  316. proxy=self.proxy,
  317. timeout=30,
  318. receive_timeout=30,
  319. ) as _ws:
  320. print(f'{self.name} ws连接成功')
  321. self.logger.info(f'{self.name} ws连接成功')
  322. # 订阅
  323. channels=[
  324. # f"/contractMarket/tickerV2:{self.symbol}",
  325. f"/contractMarket/level2Depth50:{self.symbol}",
  326. ]
  327. if sub_trade:
  328. channels += [f"/contractMarket/execution:{self.symbol}"]
  329. if is_auth:
  330. channels += [
  331. f"/contractAccount/wallet",
  332. f"/contract/position:{self.symbol}",
  333. f"/contractMarket/tradeOrders:{self.symbol}",
  334. ]
  335. for i in channels:
  336. sub_str = ujson.dumps({"topic": i, "type":"subscribe"})
  337. await _ws.send_str(sub_str)
  338. while True:
  339. # 接受消息
  340. try:
  341. msg = await _ws.receive(timeout=30)
  342. except:
  343. print(f'{self.name} ws长时间没有收到消息 准备重连...')
  344. self.logger.error(f'{self.name} ws长时间没有收到消息 准备重连...')
  345. break
  346. msg = ujson.loads(msg.data)
  347. # print(msg)
  348. # 处理消息
  349. if 'data' in msg:
  350. if 'level2' in msg['subject']:self._update_depth(msg)
  351. elif "tickerV2" in msg["subject"]:self._update_ticker(msg)
  352. elif 'match' in msg['subject']:self._update_trade(msg)
  353. elif 'orderMargin.change' in msg['subject']:self._update_account(msg)
  354. elif 'symbolOrderChange' in msg['subject']:self._update_order(msg)
  355. elif 'position.change' in msg['subject']:self._update_position(msg)
  356. # heartbeat
  357. if time.time() - ping_time > 30:
  358. msg = {
  359. 'id': str(int(time.time() * 1000)),
  360. 'type': 'ping'
  361. }
  362. await _ws.send_str(ujson.dumps(msg))
  363. ping_time = time.time()
  364. except:
  365. traceback.print_exc()
  366. print(f'{self.name} ws连接失败 开始重连...')
  367. self.logger.error(f'{self.name} ws连接失败 开始重连...')
  368. # await asyncio.sleep(1)