Advertisement
den4ik2003

Untitled

Mar 10th, 2025
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.13 KB | None | 0 0
  1. from threading import Thread
  2. import numpy as np
  3. import time
  4. from binance.spot import Spot
  5.  
  6. class Volume:
  7. def __init__(self, group):
  8. self.threads = []
  9. self.binance = Spot('', '')
  10. self.pwr = 0
  11. self.volumes = []
  12. self.bgt = int(time.time())
  13. self.target_f = open(f"/mnt/pt_telemetry/{group}", "r")
  14. self.price = 0
  15.  
  16. def target(self):
  17. lines = self.target_f.readlines()
  18. for line in lines:
  19. if 'price' in line:
  20. self.price = float(eval(line.split(' price ')[1])['price'])
  21. return self.price
  22.  
  23. def _process(self, market, daily_volume, left_bound, right_bound, history_mode, threshold, tight_spread, smart, smart_spread):
  24. book = market.get_info()['book']
  25. self.price = (book['ask_price'] + book['bid_price']) / 2
  26. bal_f = open(f"/mnt/volume_telemetry/{market.symbol[1].upper()}_{market.symbol[2].upper()}_{market.market}", "a")
  27. flush = lambda _: bal_f.flush()
  28. log = lambda name, obj: flush(bal_f.write(f'{int(time.time() * 1000)} {name} {obj}\n'))
  29. log("alert", {'op': 'start'})
  30. price = (book['ask_price'] + book['bid_price']) / 2
  31. counter = 0
  32. self.step = 0.1 ** market.symbol[3]
  33. last_price = None
  34. last_day = 0
  35. last_5m = 0
  36. iter_len = [0]
  37. while True:
  38. bg = time.time()
  39. print(bg, flush=True)
  40. coef = 1
  41. cd = 10
  42. try:
  43. info = market.get_info()
  44. log('book', info['book'])
  45. log('balance', info['balance'])
  46. public_trades = market.get_new_public_trades()
  47. private_trades = market.get_new_private_trades()
  48. log('public_trades', public_trades)
  49. log('private_trades', private_trades)
  50.  
  51. try:
  52. fees_res = market.get_fees()
  53. if type(fees_res) == tuple:
  54. taker_fees, maker_fees = fees_res[0], fees_res[1]
  55. log('fees', {'taker': taker_fees, 'maker': maker_fees})
  56. else:
  57. print('not tuple fees result', fees_res)
  58.  
  59. except Exception as e:
  60. print(f'exception: {e} ({market.market})')
  61. log('alert', {'op': 'stop', 'type':'fees', 'msg':f'{e}'})
  62. return
  63.  
  64. book = market.get_info()['book']
  65. bal = market.get_info()['balance']
  66. spread = book['ask_price'] / book['bid_price'] - 1
  67. if spread >= 0.1:
  68. counter += 1
  69. if counter >= 10:
  70. log('alert', {'op': 'stop', 'type':'spread'})
  71. return
  72. time.sleep(10)
  73. continue
  74. else:
  75. counter = 0
  76. print(f'balances: {bal['base']} {bal['quote']}')
  77. print(f'spread: {spread} {market.market}')
  78. if history_mode:
  79. cur_5m = (int(time.time()) % 86400) // 288
  80. cur_day = int(time.time()) // 86400
  81. if cur_day > last_day:
  82. kline_history = self.binance.klines(symbol='BTCUSDT', interval='5m', limit=289, endTime = cur_day * 86400000)[:-1]
  83. volume_1d = np.sum(float(kline[7]) for kline in kline_history)
  84. last_day = cur_day
  85. kline_5m = kline_history[:cur_5m + 1]
  86. else:
  87. volume_1d = float(self.binance.ticker_24hr(symbol='BTCUSDT')['quoteVolume'])
  88. kline_5m = self.binance.klines(symbol='BTCUSDT', interval='5m', limit=60)
  89.  
  90. print(f'len: {len(kline_5m)}')
  91. pmn = np.min([float(z[4]) for z in kline_5m])
  92. pmx = np.max([float(z[4]) for z in kline_5m])
  93.  
  94. V = daily_volume / float(volume_1d) * float(kline_5m[-2][7])
  95. if V >= 100:
  96. mean_cd = 5
  97. elif V >= 50:
  98. mean_cd = 10
  99. elif V >= 25:
  100. mean_cd = 60
  101. elif V >= 10:
  102. mean_cd = 120
  103. else:
  104. mean_cd = 180
  105. mean_vol = V * ((mean_cd + np.mean(iter_len)) / 300)
  106. print(np.mean(iter_len))
  107. cd = min(120, max(1, np.random.uniform(mean_cd / 10, mean_cd * 1.9)))
  108. norm_price = (float(kline_5m[-1][4]) - pmn) / (pmx - pmn) * (right_bound - left_bound) + left_bound
  109. step_size = 0.1 ** market.symbol[3]
  110. cur_price = (book['bid_price'] + step_size) + (book['ask_price'] - book['bid_price'] - 2 * step_size) * norm_price
  111. target_price = self.target()
  112. try:
  113. print(target_price)
  114. print(f'target: {target_price} (clip inside ({target_price * (1 - threshold / 100)}; {target_price * (1 + threshold / 100)}))')
  115. cur_price = np.clip(cur_price, target_price * (1 - threshold / 100), target_price * (1 + threshold / 100))
  116. except Exception as e:
  117. print(e)
  118. print(mean_vol)
  119. qty = min((bal['base'] * cur_price + bal['quote']) / 3, 3.5 + max(1.6, np.random.normal(mean_vol, mean_vol / 3))) / cur_price
  120. cur_price = float(f'%.{market.symbol[3]}f' % cur_price)
  121. print(f"iteration: {qty}, {cur_price}, {norm_price}")
  122. if last_price != None:
  123. if abs(cur_price / last_price - 1) >= 0.08:
  124. log('alert', {'op': 'stop'})
  125. break
  126.  
  127. cur_5m = (int(time.time()) % 86400) // 288
  128. if cur_5m > last_5m:
  129. cur_price = last_price
  130. last_5m = cur_5m
  131.  
  132. book = market.get_info()['book']
  133. print(f'{cur_price} {book['bid_price'] + step_size} {book['ask_price'] - step_size}')
  134. print(f'{market.market} {book}')
  135. if bal['base'] < qty:
  136. if last_price == None or abs(book['ask_price'] / last_price - 1) <= 0.01:
  137. market.new_limit(book['ask_price'], qty, True)
  138. elif bal['quote'] < qty * cur_price:
  139. if last_price == None or abs(book['bid_price'] / last_price - 1) <= 0.01:
  140. market.new_limit(book['bid_price'], qty, False)
  141. else:
  142. if smart:
  143. print('doing smart')
  144. if book['ask_price'] / book['bid_price'] - 1 <= smart_spread:
  145. print('spread is ok')
  146. threads = []
  147. threads.append(Thread(target=market.new_limit, args=(book['ask_price'], qty, True)))
  148. threads[-1].start()
  149. threads.append(Thread(target=market.new_limit, args=(book['bid_price'], qty, False)))
  150. threads[-1].start()
  151. for t in threads:
  152. t.join()
  153. elif cur_price <= book['ask_price'] - step_size / 2 and cur_price >= book['bid_price'] + step_size / 2:
  154. last_price = cur_price
  155. print(f"proceeding {type(market)}")
  156. # log('info', f'{{"price": {cur_price}, "quantity": {qty}, "book": {book}}}')
  157. threads = []
  158. if np.random.randint(0, 2):
  159. threads.append(Thread(target=market.new_limit, args=(cur_price, qty, False)))
  160. threads[-1].start()
  161. threads.append(Thread(target=market.new_limit, args=(cur_price, qty, True)))
  162. threads[-1].start()
  163. else:
  164. threads.append(Thread(target=market.new_limit, args=(cur_price, qty, True)))
  165. threads[-1].start()
  166. threads.append(Thread(target=market.new_limit, args=(cur_price, qty, False)))
  167. threads[-1].start()
  168. for t in threads:
  169. t.join()
  170. elif tight_spread:
  171. print(f"tight {type(market)}")
  172. qty /= 2
  173. qty = max(qty, 6 / cur_price)
  174. # log('info', f'{{"price": {cur_price}, "quantity": {qty}, "book": {book}}}')
  175. threads = []
  176. if last_price != None and last_price > book['ask_price']:
  177. is_buy = True
  178. else:
  179. is_buy = False
  180. tp = self.target()
  181. print(qty)
  182. print(book['ask_price'])
  183. is_buy = (tp >= book['ask_price'])
  184. if is_buy:
  185. print('buying in tight')
  186. threads.append(Thread(target=market.new_limit, args=(book['ask_price'], qty, True)))
  187. threads[-1].start()
  188. else:
  189. print('selling in tight')
  190. threads.append(Thread(target=market.new_limit, args=(book['bid_price'], qty, False)))
  191. threads[-1].start()
  192. for t in threads:
  193. t.join()
  194. last_price = cur_price
  195.  
  196. except Exception as e:
  197. print(f'exception: {e} ({market.market})')
  198. try:
  199. market.cancel_open_orders()
  200. except Exception as e:
  201. print(f'exception cancel: {e} ({market.market})')
  202. finally:
  203. if len(iter_len) == 100:
  204. iter_len = iter_len[1:]
  205. iter_len.append(time.time() - bg)
  206. time.sleep(cd)
  207.  
  208. def add_market(self, market, daily_volume, left_bound=1/4, right_bound=3/4, history_mode=False, threshold=1.5, tight_spread=False, smart_daily_volume=0, smart_spread_size=2):
  209. daily_volume = float(daily_volume)
  210. left_bound = float(left_bound)
  211. right_bound = float(right_bound)
  212. threshold = float(threshold)
  213. if threshold < 0:
  214. threshold = None
  215. if smart_daily_volume:
  216. self.threads.append(Thread(target=self._process, args=(market, smart_daily_volume / 2, left_bound, right_bound, history_mode, threshold, tight_spread, True, smart_spread_size)))
  217. self.threads.append(Thread(target=self._process, args=(market, daily_volume, left_bound, right_bound, history_mode, threshold, tight_spread, False, 0)))
  218.  
  219. def run_event_loop(self):
  220. for thread in self.threads:
  221. thread.start()
  222. for thread in self.threads:
  223. thread.join()
  224.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement