binance_usdt_swap_ws.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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, csv, sys, utils
  12. import logging, logging.handlers
  13. import model
  14. from loguru import logger
  15. def empty_call(msg):
  16. pass
  17. def timeit(func):
  18. def wrapper(*args, **kwargs):
  19. nowTime = time.time()
  20. res = func(*args, **kwargs)
  21. spend_time = time.time() - nowTime
  22. spend_time = round(spend_time * 1000, 5)
  23. print(f'{func.__name__} 耗时 {spend_time} ms')
  24. return res
  25. return wrapper
  26. def inflate(data):
  27. '''
  28. 解压缩数据
  29. '''
  30. decompress = zlib.decompressobj(-zlib.MAX_WBITS)
  31. inflated = decompress.decompress(data)
  32. inflated += decompress.flush()
  33. return inflated
  34. class BinanceUsdtSwapWs:
  35. def __init__(self, params:model.ClientParams, colo=0, is_print=0):
  36. if colo:
  37. print('不支持colo高速线路')
  38. self.URL = 'wss://fstream.binance.com/ws/'
  39. else:
  40. self.URL = 'wss://fstream.binance.com/ws/'
  41. self.params = params
  42. self.name = self.params.name
  43. self.base = params.pair.split('_')[0].upper()
  44. self.quote = params.pair.split('_')[1].upper()
  45. self.symbol = self.base + self.quote
  46. if len(self.params.pair.split('_')) > 2:
  47. self.delivery = self.params.pair.split('_')[2] # 210924
  48. self.symbol += f"_{self.delivery}"
  49. self.callback = {
  50. "onMarket":self.save_market,
  51. "onPosition":empty_call,
  52. "onEquity":empty_call,
  53. "onOrder":empty_call,
  54. "onTicker":empty_call,
  55. "onDepth":empty_call,
  56. "onExit":empty_call,
  57. }
  58. self.is_print = is_print
  59. self.proxy = None
  60. if 'win' in sys.platform:
  61. self.proxy = self.params.proxy
  62. self.logger = self.get_logger()
  63. self.ticker_info = {"name":self.name,'bp':0.0,'ap':0.0}
  64. self.stop_flag = 0
  65. self.public_update_time = time.time()
  66. self.private_update_time = time.time()
  67. self.expired_time = 300
  68. ### 更新id
  69. self.update_flag_u = 0
  70. self.max_buy = 0.0
  71. self.min_sell = 0.0
  72. self.buy_v = 0.0
  73. self.buy_q = 0.0
  74. self.sell_v = 0.0
  75. self.sell_q = 0.0
  76. self.depth = []
  77. ####
  78. self.depth_update = []
  79. self.need_flash = 1
  80. self.lastUpdateId = None # 就是小写u
  81. self.depth_full = dict()
  82. self.depth_full['bids'] = dict()
  83. self.depth_full['asks'] = dict()
  84. self.decimal = 99
  85. #### 指定发包ip
  86. iplist = utils.get_local_ip_list()
  87. self.ip = iplist[int(self.params.ip)]
  88. def get_logger(self):
  89. logger = logging.getLogger(__name__)
  90. logger.setLevel(logging.DEBUG)
  91. # log to txt
  92. formatter = logging.Formatter('[%(asctime)s] - %(levelname)s - %(message)s')
  93. handler = logging.handlers.RotatingFileHandler(f"log.log",maxBytes=1024*1024)
  94. handler.setLevel(logging.DEBUG)
  95. handler.setFormatter(formatter)
  96. logger.addHandler(handler)
  97. return logger
  98. def save_market(self, msg):
  99. date = time.strftime('%Y-%m-%d',time.localtime())
  100. interval = self.params.interval
  101. if msg:
  102. exchange = msg['name']
  103. if len(msg['data']) > 1:
  104. with open(f'./history/{exchange}_{self.symbol}_{interval}_{date}.csv',
  105. 'a',
  106. newline='',
  107. encoding='utf-8') as f:
  108. writer = csv.writer(f, delimiter=',')
  109. writer.writerow(msg['data'])
  110. if self.is_print:print(f'写入行情 {self.symbol}')
  111. async def get_sign(self):
  112. headers = {}
  113. headers['Content-Type'] = 'application/json'
  114. headers['X-MBX-APIKEY'] = self.params.access_key
  115. params = {
  116. 'timestamp':int(time.time())*1000,
  117. 'recvWindow':5000,
  118. }
  119. query_string = "&".join(["{}={}".format(k, params[k]) for k in sorted(params.keys())])
  120. signature = hmac.new(self.params.secret_key.encode(), msg=query_string.encode(), digestmod=hashlib.sha256).hexdigest()
  121. params['signature']=signature
  122. url = 'https://fapi.binance.com/fapi/v1/listenKey'
  123. session = aiohttp.ClientSession()
  124. response = await session.post(
  125. url,
  126. params=params,
  127. headers=headers,
  128. timeout=5,
  129. proxy=self.proxy
  130. )
  131. self.logger.debug("申请key")
  132. login_str = await response.text()
  133. print(login_str)
  134. self.logger.debug(login_str)
  135. await session.close()
  136. try:
  137. return ujson.loads(login_str)['listenKey']
  138. except:
  139. self.logger.error('登录失败')
  140. return 'qqlh'
  141. async def long_key(self):
  142. headers = {}
  143. headers['Content-Type'] = 'application/json'
  144. headers['X-MBX-APIKEY'] = self.params.access_key
  145. params = {
  146. 'timestamp':int(time.time())*1000,
  147. 'recvWindow':5000,
  148. }
  149. query_string = "&".join(["{}={}".format(k, params[k]) for k in sorted(params.keys())])
  150. signature = hmac.new(self.params.secret_key.encode(), msg=query_string.encode(), digestmod=hashlib.sha256).hexdigest()
  151. params['signature']=signature
  152. url = 'https://fapi.binance.com/fapi/v1/listenKey'
  153. session = aiohttp.ClientSession()
  154. response = await session.put(
  155. url,
  156. params=params,
  157. headers=headers,
  158. timeout=5,
  159. proxy=self.proxy
  160. )
  161. self.logger.debug("续期key")
  162. login_str = await response.text()
  163. self.logger.debug(login_str)
  164. await session.close()
  165. return ujson.loads(login_str)
  166. def _check_update_u(self, id):
  167. if id > self.update_flag_u:
  168. self.update_flag_u = id
  169. return 0
  170. else:
  171. return 1
  172. def _update_ticker(self, msg):
  173. self.public_update_time = time.time()
  174. msg = ujson.loads(msg)
  175. if self._check_update_u(msg['u']):
  176. return
  177. else:
  178. bp = float(msg['b'])
  179. bq = float(msg['B'])
  180. ap = float(msg['a'])
  181. aq = float(msg['A'])
  182. self.ticker_info["bp"] = bp
  183. self.ticker_info["ap"] = ap
  184. self.callback['onTicker'](self.ticker_info)
  185. ### 标准化深度
  186. self.depth = [bp,bq,ap,aq]
  187. self.callback['onDepth']({'name':self.name,'data':self.depth})
  188. # @timeit
  189. def _update_depth20(self, msg):
  190. logger.info(msg)
  191. self.public_update_time = time.time()
  192. msg = ujson.loads(msg)
  193. if self._check_update_u(msg['u']):
  194. return
  195. else:
  196. # 更新ticker信息但不触发
  197. self.ticker_info["bp"] = float(msg['b'][0][0])
  198. self.ticker_info["ap"] = float(msg['a'][0][0])
  199. self.callback['onTicker'](self.ticker_info)
  200. if self.decimal == 99:self.decimal = utils.num_to_decimal(msg['b'][0][0])
  201. ##### 标准化深度
  202. mp = (self.ticker_info["bp"] + self.ticker_info["ap"])*0.5
  203. step = round(mp * utils.EFF_RANGE / utils.LEVEL, self.decimal)
  204. bp = []
  205. ap = []
  206. bv = [0 for _ in range(utils.LEVEL)]
  207. av = [0 for _ in range(utils.LEVEL)]
  208. for i in range(utils.LEVEL):
  209. bp.append(round(self.ticker_info["bp"]-step*i, self.decimal))
  210. for i in range(utils.LEVEL):
  211. ap.append(round(self.ticker_info["ap"]+step*i, self.decimal))
  212. ###############################################
  213. price_thre = self.ticker_info["bp"] - step
  214. index = 0
  215. for i in msg['b']:
  216. price = float(i[0])
  217. amount = float(i[1])
  218. if price > price_thre:
  219. bv[index] += amount
  220. else:
  221. price_thre -= step
  222. index += 1
  223. if index == utils.LEVEL:
  224. break
  225. bv[index] += amount
  226. price_thre = self.ticker_info["ap"] + step
  227. index = 0
  228. for i in msg['a']:
  229. price = float(i[0])
  230. amount = float(i[1])
  231. if price < price_thre:
  232. av[index] += amount
  233. else:
  234. price_thre += step
  235. index += 1
  236. if index == utils.LEVEL:
  237. break
  238. av[index] += amount
  239. self.depth = bp + bv + ap + av
  240. self.callback['onDepth']({'name':self.name,'data':self.depth})
  241. # @timeit
  242. def _update_depth(self, msg):
  243. self.public_update_time = time.time()
  244. msg = ujson.loads(msg)
  245. self.depth_update.append(msg)
  246. ### 检查是否有遗漏
  247. for i in range(1,len(self.depth_update)):
  248. if self.depth_update[i]['pu'] != self.depth_update[i]['u']:
  249. self.need_flash = 1
  250. self.logger.error('发现遗漏增量深度推送 重置绝对深度')
  251. return
  252. # print(len(self.depth_update))
  253. if self.need_flash == 0: # 可以更新深度
  254. for i in self.depth_update[:]:
  255. u = i['u']
  256. U = i['U']
  257. pu = i['pu']
  258. # print(f'处理 {u}')
  259. if u < self.lastUpdateId: # 丢弃过旧的信息
  260. self.depth_update.remove(i)
  261. else:
  262. if u >= self.lastUpdateId: # 后续更新本地副本
  263. # print(f'符合要求 {u}')
  264. # 开始更新深度
  265. for j in i['b']:
  266. price = float(j[0])
  267. amount = float(j[1])
  268. if amount > 0:
  269. self.depth_full['bids'][price] = amount
  270. else:
  271. if price in self.depth_full['bids']:del(self.depth_full['bids'][price])
  272. for j in i['a']:
  273. price = float(j[0])
  274. amount = float(j[1])
  275. if amount > 0:
  276. self.depth_full['asks'][price] = amount
  277. else:
  278. if price in self.depth_full['asks']:del(self.depth_full['asks'][price])
  279. self.depth_update.remove(i)
  280. self.lastUpdateId = u
  281. else:
  282. self.logger.error('增量深度不满足文档要求的条件')
  283. buyP = list(self.depth_full['bids'].keys())
  284. buyP.sort(reverse=True) # 从大到小
  285. sellP = list(self.depth_full['asks'].keys())
  286. sellP.sort(reverse=False) # 从小到大
  287. # update ticker
  288. self.ticker_info["bp"] = float(buyP[0])
  289. self.ticker_info["ap"] = float(sellP[0])
  290. self.callback['onTicker'](self.ticker_info)
  291. if self.ticker_info["bp"] > self.ticker_info["ap"]:
  292. self.need_flash = 1
  293. ##### 标准化深度
  294. mp = (self.ticker_info["bp"] + self.ticker_info["ap"])*0.5
  295. step = mp * utils.EFF_RANGE / utils.LEVEL
  296. bp = []
  297. ap = []
  298. bv = [0 for _ in range(utils.LEVEL)]
  299. av = [0 for _ in range(utils.LEVEL)]
  300. for i in range(utils.LEVEL):
  301. bp.append(self.ticker_info["bp"]-step*i)
  302. for i in range(utils.LEVEL):
  303. ap.append(self.ticker_info["ap"]+step*i)
  304. #
  305. price_thre = self.ticker_info["bp"] - step
  306. index = 0
  307. for price in buyP:
  308. if price > price_thre:
  309. bv[index] += self.depth_full['bids'][price]
  310. else:
  311. price_thre -= step
  312. index += 1
  313. if index == utils.LEVEL:
  314. break
  315. bv[index] += self.depth_full['bids'][price]
  316. price_thre = self.ticker_info["ap"] + step
  317. index = 0
  318. for price in sellP:
  319. if price < price_thre:
  320. av[index] += self.depth_full['asks'][price]
  321. else:
  322. price_thre += step
  323. index += 1
  324. if index == utils.LEVEL:
  325. break
  326. av[index] += self.depth_full['asks'][price]
  327. self.depth = bp + bv + ap + av
  328. self.callback['onDepth']({'name':self.name,'data':self.depth})
  329. def _update_trade(self, msg):
  330. '''
  331. 根据trade修正depth对性能消耗很大
  332. '''
  333. self.public_update_time = time.time()
  334. msg = ujson.loads(msg)
  335. price = float(msg['p'])
  336. if self.decimal == 99:self.decimal=utils.num_to_decimal(price)
  337. amount = float(msg['q'])
  338. side = 'sell' if msg['m'] else 'buy'
  339. if price > self.max_buy or self.max_buy == 0.0:
  340. self.max_buy = price
  341. if price < self.min_sell or self.min_sell == 0.0:
  342. self.min_sell = price
  343. if side == 'buy':
  344. self.buy_q += amount
  345. self.buy_v += amount*price
  346. elif side == 'sell':
  347. self.sell_q += amount
  348. self.sell_v += amount*price
  349. #### 修正ticker ####
  350. # side = 'sell' if msg['m'] else 'buy'
  351. # if side == 'buy' and price > self.ticker_info['ap']:
  352. # self.ticker_info['ap'] = price
  353. # self.callback['onTicker'](self.ticker_info)
  354. # if side == 'sell' and price < self.ticker_info['bp']:
  355. # self.ticker_info['bp'] = price
  356. # self.callback['onTicker'](self.ticker_info)
  357. def _update_account(self, msg):
  358. self.private_update_time = time.time()
  359. msg = ujson.loads(msg)
  360. for i in msg['a']['B']:
  361. if i['a'] == self.quote:
  362. self.callback['onEquity']({self.quote:float(i['wb'])})
  363. def _update_order(self, msg):
  364. '''将ws收到的订单信息触发quant'''
  365. msg = ujson.loads(msg)
  366. self.logger.debug(f"ws订单推送 {msg}")
  367. data = msg['o']
  368. if self.symbol in data['s']:
  369. order_event = dict()
  370. status = data['X']
  371. if status == "NEW": # 新增
  372. local_status = "NEW"
  373. elif status in ["CANCELED", "FILLED", "EXPIRED"]: # 删除
  374. local_status = "REMOVE"
  375. elif status in ["PARTIALLY_FILLED"]: # 忽略
  376. return
  377. else:
  378. print("未知订单状态",data)
  379. return
  380. order_event['status'] = local_status
  381. order_event['filled_price'] = float(data['ap'])
  382. order_event['filled'] = float(data['z'])
  383. order_event['client_id'] = data['c']
  384. order_event['order_id'] = data['i']
  385. self.callback['onOrder'](order_event)
  386. self.private_update_time = time.time()
  387. def _update_position(self, msg):
  388. long_pos, short_pos = 0, 0
  389. long_avg, short_avg = 0, 0
  390. msg = ujson.loads(msg)
  391. is_update = 0
  392. for i in msg['a']['P']:
  393. if i['s'] == self.symbol:
  394. is_update = 1
  395. if i['ps'] == 'LONG':
  396. long_pos += abs(float(i['pa']))
  397. long_avg = abs(float(i['ep']))
  398. if i['ps'] == 'SHORT':
  399. short_pos += abs(float(i['pa']))
  400. short_avg = abs(float(i['ep']))
  401. if is_update:
  402. pos = model.Position()
  403. pos.longPos = long_pos
  404. pos.longAvg = long_avg
  405. pos.shortPos = short_pos
  406. pos.shortAvg = short_avg
  407. self.callback['onPosition'](pos)
  408. self.private_update_time = time.time()
  409. def _get_data(self):
  410. market_data = self.depth + [self.max_buy, self.min_sell]
  411. self.max_buy = 0.0
  412. self.min_sell = 0.0
  413. self.buy_v = 0.0
  414. self.buy_q = 0.0
  415. self.sell_v = 0.0
  416. self.sell_q = 0.0
  417. return {'name': self.name,'data':market_data}
  418. async def get_depth_flash(self):
  419. headers = {}
  420. headers['Content-Type'] = 'application/json'
  421. url = f'https://fapi.binance.com/fapi/v1/depth?symbol={self.symbol}&limit=1000'
  422. session = aiohttp.ClientSession()
  423. response = await session.get(
  424. url,
  425. headers=headers,
  426. timeout=5,
  427. proxy=self.proxy
  428. )
  429. depth_flash = await response.text()
  430. await session.close()
  431. return ujson.loads(depth_flash)
  432. async def go(self):
  433. interval = float(self.params.interval)
  434. if self.is_print:print(f'Ws循环器启动 interval {interval}')
  435. ### onTrade
  436. while 1:
  437. try:
  438. # 更新市场信息
  439. market_data = self._get_data()
  440. self.callback['onMarket'](market_data)
  441. except:
  442. traceback.print_exc()
  443. await asyncio.sleep(interval)
  444. async def run(self, is_auth=0, sub_trade=0, sub_fast=0):
  445. while True:
  446. try:
  447. # 重置更新时间
  448. self.public_update_time = time.time()
  449. self.private_update_time = time.time()
  450. # 尝试连接
  451. print(f'{self.name} 尝试连接ws')
  452. # 登陆
  453. if is_auth:
  454. listenKey = await self.get_sign()
  455. listenKeyTime = time.time()
  456. else:
  457. listenKey = 'qqlh'
  458. ws_url = self.URL+listenKey
  459. async with aiohttp.ClientSession(
  460. connector = aiohttp.TCPConnector(
  461. limit=50,
  462. keepalive_timeout=120,
  463. verify_ssl=False,
  464. local_addr=(self.ip,0)
  465. )
  466. ).ws_connect(
  467. ws_url,
  468. proxy=self.proxy,
  469. timeout=30,
  470. receive_timeout=30,
  471. ) as _ws:
  472. print(f'{self.name} ws连接成功')
  473. self.logger.debug(f'{self.name} ws连接成功')
  474. # 订阅
  475. symbol = self.symbol.lower()
  476. if sub_fast:
  477. channels=[
  478. f"{symbol}@bookTicker",
  479. ]
  480. else:
  481. channels=[
  482. # f"{symbol}@depth@100ms",
  483. f"{symbol}@depth20@100ms",
  484. ]
  485. if sub_trade:
  486. channels.append(f"{symbol}@aggTrade")
  487. sub_str = ujson.dumps({"method": "SUBSCRIBE", "params": channels, "id":random.randint(1,1000)})
  488. await _ws.send_str(sub_str)
  489. self.need_flash = 1
  490. while True:
  491. # 停机信号
  492. if self.stop_flag:
  493. await _ws.close()
  494. return
  495. # 接受消息
  496. try:
  497. msg = await _ws.receive(timeout=30)
  498. except:
  499. print(f'{self.name} ws长时间没有收到消息 准备重连...')
  500. self.logger.error(f'{self.name} ws长时间没有收到消息 准备重连...')
  501. break
  502. msg = msg.data
  503. # 处理消息
  504. # if 'depthUpdate' in msg:self._update_depth(msg)
  505. if 'depthUpdate' in msg:self._update_depth20(msg)
  506. elif 'bookTicker' in msg:self._update_ticker(msg)
  507. elif 'aggTrade' in msg:self._update_trade(msg)
  508. elif 'ACCOUNT_UPDATE' in msg:
  509. self._update_position(msg)
  510. self._update_account(msg)
  511. elif 'ORDER_TRADE_UPDATE' in msg:self._update_order(msg)
  512. elif 'ping' in msg:await _ws.send_str('pong')
  513. elif 'listenKeyExpired' in msg:raise Exception('key过期重连')
  514. # 续期listenkey
  515. if is_auth:
  516. if time.time() - listenKeyTime > 60*15: # 每15分钟续一次
  517. print('续期listenKey')
  518. listenKeyTime = time.time()
  519. await self.long_key()
  520. if time.time() - self.private_update_time > self.expired_time*5:
  521. raise Exception('长期未更新私有信息重连')
  522. if time.time() - self.public_update_time > self.expired_time:
  523. raise Exception('长期未更新公有信息重连')
  524. # if self.need_flash:
  525. # depth_flash = await self.get_depth_flash()
  526. # self.lastUpdateId = depth_flash['lastUpdateId']
  527. # print(f'更新绝对深度 {self.lastUpdateId}')
  528. # # 检查已有更新中是否包含
  529. # self.depth_full['bids'] = dict()
  530. # self.depth_full['asks'] = dict()
  531. # for i in depth_flash['bids']:self.depth_full['bids'][float(i[0])] = float(i[1])
  532. # for i in depth_flash['asks']:self.depth_full['asks'][float(i[0])] = float(i[1])
  533. # self.need_flash = 0
  534. except:
  535. traceback.print_exc()
  536. print(f'{self.name} ws连接失败 开始重连...')
  537. self.logger.error(f'{self.name} ws连接失败 开始重连...')
  538. self.logger.error(traceback.format_exc())
  539. await asyncio.sleep(1)