binance_usdt_swap_ws.py 22 KB

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