binance_usdt_swap_ws.py 22 KB

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