erc20_to_mexc.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. import time
  2. import traceback
  3. import copy
  4. from web3_py_client import EthClient
  5. from mexc_client import MexcClient
  6. from decimal import Decimal, ROUND_DOWN
  7. from as_utils import add_state_flow_entry
  8. from checker.logger_config import get_logger
  9. from pprint import pformat
  10. web3 = EthClient()
  11. mexc = MexcClient()
  12. # 配置日志
  13. logger = get_logger('as')
  14. class ArbitrageProcess:
  15. def __init__(self, gas_limit_multiplier, gas_price_multiplier, process_item,
  16. core_data, core_lock,
  17. pending_data, pending_lock,
  18. mexc_data, mexc_lock,
  19. ):
  20. """
  21. 初始化套利流程
  22. Args:
  23. gas_limit_multiplier: gas limit倍数, 一般都不加倍
  24. gas_price_multiplier: gas price倍数, 可以提高交易成功率
  25. process_item: 信號發送端傳入的原始參數
  26. """
  27. self.NETWORK = 'ETH'
  28. tx = process_item['tx']
  29. tx.pop('gasPrice', None)
  30. tx.pop('value', None)
  31. tx.pop('minReceiveAmount', None)
  32. tx.pop('slippage', None)
  33. tx.pop('maxSpendAmount', None)
  34. tx.pop('signatureData', None)
  35. self.core_data = core_data
  36. self.core_lock = core_lock
  37. self.pending_data = pending_data
  38. self.pending_lock = pending_lock
  39. self.mexc_data = mexc_data
  40. self.mexc_lock = mexc_lock
  41. # symbol轉大寫
  42. self.symbol = process_item['symbol'].upper()
  43. self.coin = self.symbol.split('_')[0]
  44. self.base_coin = self.symbol.split('_')[1]
  45. with self.core_lock:
  46. self.eth_price = self.core_data['eth_price']
  47. with self.mexc_lock:
  48. self.withdraw_info = copy.deepcopy(self.mexc_data['coin_info_map'][self.base_coin][self.NETWORK])
  49. self.WITHDRAW_FEE = Decimal(self.withdraw_info['withdrawFee']) # 提現手續費
  50. withdraw_info_formated = pformat(self.withdraw_info, indent=2)
  51. logger.info(f'提現信息識別, 手續費:{self.WITHDRAW_FEE}\n{withdraw_info_formated}')
  52. self.tx = tx
  53. self.profit = Decimal(process_item['profit']) # 這個利潤是實際到手利潤
  54. self.profit_limit = Decimal(process_item['profitLimit']) # 這個利潤是實際到手利潤的limit
  55. self.gas_limit_multiplier = gas_limit_multiplier
  56. self.gas_price_multiplier = gas_price_multiplier
  57. self.from_token_addr = process_item['fromToken']
  58. self.from_token_decimal = Decimal(process_item['fromTokenDecimal'])
  59. self.to_token_addr = process_item['toToken']
  60. self.to_token_decimal = Decimal(process_item['toTokenDecimal'])
  61. self.user_exchange_wallet = process_item['userExchangeWallet']
  62. self.user_wallet = process_item['userWallet']
  63. self.process_item = process_item
  64. # 存储当前套利交易的细节信息,例如买入数量、价格等
  65. self.sell_price = Decimal(0)
  66. self.buy_price = Decimal(0)
  67. self.chain_tx_hash = None # 链上买入的tx hash
  68. self.chain_usdt_use = Decimal(process_item['fromTokenAmountHuman']) # 链上usdt减少量(使用量)
  69. self.chain_buy_amount = Decimal(0) # 链上币增加量(购入量), todo, 暂用即时余额代替
  70. self.exchange_sell_amount = Decimal(process_item['exchangeOutAmount']) # 交易所卖出量
  71. self.exchange_sell_order_id = None # 交易所卖出id
  72. self.exchange_withdrawal_id = None # 交易所提现id
  73. self.exchange_withdrawal_amount = None # 交易所提现数量
  74. self.actual_profit = Decimal(0) # 實際利潤
  75. # 定义可能的状态
  76. self.STATES = [
  77. "CHECK", # 检查余额、估算gas等
  78. "SELLING_ON_EXCHANGE", # 正在中心化交易所卖出现货
  79. "WAITING_SELL_CONFIRM", # 等待现货卖出订单确认
  80. "BUYING_ON_CHAIN", # 正在链上买入
  81. "WAITING_CHAIN_CONFIRM", # 等待链上交易确认
  82. "WAITING_EXCHANGE_ROLLBACK", # 等待交易所回滚
  83. # "HEDGING_ON_EXCHANGE", # 正在中心化交易所套保
  84. # "WAITING_HEDGE_CONFIRM", # 等待套保订单确认
  85. # "TRANSFERRING_TO_EXCHANGE", # 正在向交易所转账
  86. # "CLOSING_HEDGE", # 正在平掉套保单
  87. # "WAITING_CLOSE_HEDGE_CONFIRM", # 等待平掉套保单确认
  88. "WAITING_TRANSFER_ARRIVE", # 等待交易所充值到账
  89. "TRANSFERRING_TO_CHAIN", # 正在向链上转账
  90. "WAITING_WITHDRAWAL_CONFIRM", # 等待链上提现确认
  91. "COMPLETED", # 套利流程完成
  92. "REJECT", # 套利被程序拒绝
  93. "FAILED" # 套利流程失败
  94. ]
  95. self.STATE_IDLE = "IDLE"
  96. self.STATE_CHECK = "CHECK"
  97. self.STATE_SELLING_ON_EXCHANGE = "SELLING_ON_EXCHANGE"
  98. self.STATE_WAITING_SELL_CONFIRM = "WAITING_SELL_CONFIRM"
  99. self.STATE_BUYING_ON_CHAIN = "BUYING_ON_CHAIN"
  100. self.STATE_WAITING_CHAIN_CONFIRM = "WAITING_CHAIN_CONFIRM"
  101. self.STATE_WAITING_EXCHANGE_ROLLBACK = "WAITING_EXCHANGE_ROLLBACK"
  102. # self.STATE_TRANSFERRING_TO_EXCHANGE = "TRANSFERRING_TO_EXCHANGE"
  103. self.STATE_WAITING_TRANSFER_ARRIVE = "WAITING_TRANSFER_ARRIVE"
  104. self.STATE_TRANSFERRING_TO_CHAIN = "TRANSFERRING_TO_CHAIN"
  105. self.STATE_WAITING_WITHDRAWAL_CONFIRM = "WAITING_WITHDRAWAL_CONFIRM"
  106. self.STATE_COMPLETED = "COMPLETED"
  107. self.STATE_REJECT = "REJECT"
  108. self.STATE_FAILED = "FAILED"
  109. self.current_state = "IDLE"
  110. def _set_state(self, state):
  111. """
  112. 设置系统状态,并打印日志
  113. """
  114. if state in self.STATES:
  115. logger.info(f"状态变更:{self.current_state} -> {state}")
  116. logger.info('')
  117. self.current_state = state
  118. else:
  119. logger.error(f"尝试设置无效状态:{state}")
  120. def run_arbitrage_step(self):
  121. """
  122. 根据当前状态执行套利流程的下一步
  123. 这是一个周期性调用的函数,例如在主循环中调用
  124. """
  125. if self.current_state == self.STATE_CHECK:
  126. self._execute_check()
  127. elif self.current_state == self.STATE_SELLING_ON_EXCHANGE:
  128. self._execute_sell_on_exchange()
  129. elif self.current_state == self.STATE_WAITING_SELL_CONFIRM:
  130. self._wait_sell_confirm()
  131. elif self.current_state == self.STATE_BUYING_ON_CHAIN:
  132. self._execute_buy_on_chain()
  133. elif self.current_state == self.STATE_WAITING_CHAIN_CONFIRM:
  134. self._wait_chain_confirm()
  135. elif self.current_state == self.STATE_WAITING_EXCHANGE_ROLLBACK:
  136. self._wait_exchange_rollback()
  137. # elif self.current_state == "TRANSFERRING_TO_EXCHANGE":
  138. # self._execute_transfer_to_exchange()
  139. elif self.current_state == self.STATE_WAITING_TRANSFER_ARRIVE:
  140. self._wait_transfer_arrive()
  141. elif self.current_state == self.STATE_TRANSFERRING_TO_CHAIN:
  142. self._execute_transfer_to_chain()
  143. elif self.current_state == self.STATE_WAITING_WITHDRAWAL_CONFIRM:
  144. self._wait_withdrawal_confirm()
  145. elif self.current_state == self.STATE_COMPLETED:
  146. msg = "套利流程成功完成!"
  147. logger.info(msg)
  148. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  149. elif self.current_state == self.STATE_REJECT:
  150. msg = "套利流程被程序拒绝"
  151. logger.error(msg)
  152. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  153. elif self.current_state == self.STATE_FAILED:
  154. msg = "套利流程失败!"
  155. logger.error(msg)
  156. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  157. def _execute_check(self):
  158. """
  159. 前置检查,防止低能错误
  160. """
  161. try:
  162. # step1,檢查交易所的餘額是否夠用
  163. # 处理精度
  164. pseudo_amount_to_sell = self.exchange_sell_amount.quantize(Decimal('1'), rounding=ROUND_DOWN)
  165. # 交易所套保余额判断
  166. with self.mexc_lock:
  167. balances = self.mexc_data['account_info']['balances']
  168. for balance in balances:
  169. if balance['asset'] == self.coin:
  170. if Decimal(balance['free']) < pseudo_amount_to_sell:
  171. msg = f"交易所剩余{self.coin}: {balance['free']}, 交易所准备卖出:{pseudo_amount_to_sell}, 不能触发套保交易。"
  172. logger.info(msg)
  173. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  174. self._set_state(self.STATE_REJECT)
  175. return
  176. else:
  177. msg = f"交易所剩余{self.coin}: {balance['free']}, 交易所准备卖出:{pseudo_amount_to_sell}, 余额校验通过(可以套保)。"
  178. logger.info(msg)
  179. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  180. break
  181. # step2,估算gas
  182. logger.info("獲取區塊信息")
  183. with self.core_lock:
  184. latest_block = copy.deepcopy(self.core_data['block'])
  185. self.tx['maxPriorityFeePerGas'] = int(int(self.tx['maxPriorityFeePerGas']) * self.gas_price_multiplier)
  186. self.tx['maxFeePerGas'] = int(int(latest_block['baseFeePerGas']) * 2 + self.tx['maxPriorityFeePerGas'])
  187. gas_price = Decimal(self.tx['maxPriorityFeePerGas'] + self.tx['maxFeePerGas'])
  188. gas_price_gwei = gas_price / Decimal('1e9')
  189. gas_price_gwei = gas_price_gwei.quantize(Decimal('1e-9'), rounding=ROUND_DOWN)
  190. tx_formated = pformat(self.tx, indent=2)
  191. logger.info(f"鏈上各種校驗\n{tx_formated}")
  192. estimated_gas_origin = web3.w3.eth.estimate_gas(self.tx)
  193. estimated_gas = int(estimated_gas_origin * self.gas_limit_multiplier)
  194. estimated_wei = Decimal(estimated_gas) * gas_price
  195. estimated_eth = Decimal(estimated_wei / Decimal('1e18')) / Decimal(2) # 除以2才是比較接近正常消耗的gas費,否則會過於高估
  196. estimated_eth = estimated_eth.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
  197. msg = f"估算的燃气量: {estimated_gas}, eth消耗: {estimated_eth}, gas price: {gas_price_gwei} gwei, gas估算通過"
  198. logger.info(msg)
  199. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  200. # step3, 費用與利潤比較
  201. estimated_eth_value = estimated_eth * self.eth_price
  202. estimated_eth_value = estimated_eth_value.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
  203. cost = estimated_eth_value + self.WITHDRAW_FEE # 成本
  204. if self.profit < cost:
  205. msg = f"費用判斷不通過! profit: {self.profit}, eth_value:{estimated_eth_value}, eth: {estimated_eth}, eth_price: {self.eth_price}"
  206. logger.info(msg)
  207. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  208. self._set_state(self.STATE_REJECT)
  209. return
  210. msg = f"費用判斷通過! profit: {self.profit}, eth_value:{estimated_eth_value}, eth: {estimated_eth}, eth_price: {self.eth_price}"
  211. logger.info(msg)
  212. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  213. # step4, 與賬戶eth餘額比對(至少留0.001,不然沒gas了)
  214. MARGIN = Decimal(0.001)
  215. # 暫時鎖住core_data
  216. with self.core_lock:
  217. eth_balance = self.core_data['eth_balance']
  218. if eth_balance - estimated_eth < MARGIN:
  219. msg = f"gas餘額判斷不通過! MARGIN:{MARGIN}, estimated_eth: {estimated_eth}, eth_balance: {eth_balance}"
  220. logger.info(msg)
  221. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  222. self._set_state(self.STATE_REJECT)
  223. return
  224. # 餘額判斷通過后預扣除balance,防止綫程更新不及時導致其他綫程誤發送tx
  225. self.core_data['eth_balance'] = self.core_data['eth_balance'] - estimated_eth
  226. msg = f"gas餘額判斷通過! MARGIN:{MARGIN}, estimated_eth: {estimated_eth}, eth_balance: {eth_balance}"
  227. logger.info(msg)
  228. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  229. # final, 設定交易狀態,開始交易
  230. self._set_state(self.STATE_SELLING_ON_EXCHANGE)
  231. except Exception as e:
  232. exc_traceback = traceback.format_exc()
  233. msg = f"前置檢查未通過\n{exc_traceback}"
  234. logger.error(msg)
  235. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  236. self._set_state(self.STATE_REJECT)
  237. # traceback.print_exc()
  238. # 以下是每个状态对应的具体执行函数
  239. def _execute_sell_on_exchange(self):
  240. """
  241. 在中心化交易所卖出现货
  242. """
  243. msg = "执行:中心化交易所卖出现货..."
  244. logger.info(msg)
  245. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  246. try:
  247. # 第一步直接卖出,这个数量用固定数量
  248. pseudo_amount_to_sell = self.exchange_sell_amount
  249. # 处理精度
  250. pseudo_amount_to_sell = pseudo_amount_to_sell.quantize(Decimal('1'), rounding=ROUND_DOWN)
  251. order_params = {
  252. "symbol": self.symbol.replace('_', ''),
  253. "side": "SELL",
  254. "type": "MARKET",
  255. "quantity": int(pseudo_amount_to_sell),
  256. }
  257. order_params_formated = pformat(order_params, indent=2)
  258. exchange_sell_order = mexc.trade.post_order(order_params)
  259. exchange_sell_order_formated = pformat(exchange_sell_order, indent=2)
  260. msg = f"交易所现货卖出订单已发送 \n params:{order_params_formated} \n rst: {exchange_sell_order_formated}"
  261. if 'orderId' not in exchange_sell_order:
  262. logger.error(msg)
  263. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  264. self._set_state(self.STATE_FAILED)
  265. return
  266. self.exchange_sell_order_id = exchange_sell_order['orderId']
  267. logger.info(msg)
  268. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  269. self._set_state(self.STATE_WAITING_SELL_CONFIRM)
  270. except Exception as e:
  271. exc_traceback = traceback.format_exc()
  272. msg = f"交易所现货卖出下单失败\n{exc_traceback}"
  273. logger.error(msg)
  274. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  275. self._set_state(self.STATE_FAILED)
  276. # traceback.print_exc()
  277. def _wait_sell_confirm(self):
  278. """
  279. 等待交易所现货卖出订单确认(完全成交)
  280. """
  281. exchange_sell_order_id = self.exchange_sell_order_id
  282. msg = f"等待交易所现货卖出订单确认:{exchange_sell_order_id}"
  283. logger.info(msg)
  284. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  285. try:
  286. # 查询交易所订单状态
  287. waiting_times = 30
  288. last_order = None
  289. while waiting_times > 0:
  290. params = {
  291. "symbol": self.symbol.replace('_', ''),
  292. "orderId": exchange_sell_order_id
  293. }
  294. order = mexc.trade.get_order(params)
  295. last_order = order
  296. if order['status'] in ["FILLED", "PARTIALLY_CANCELED"]:
  297. money = Decimal(order['cummulativeQuoteQty'])
  298. amount = self.exchange_sell_amount
  299. self.sell_price = money / amount
  300. self.sell_price = self.sell_price.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
  301. order_formated = pformat(order, indent=2)
  302. msg = f"交易所现货卖出订单已完成, 价格:{self.sell_price}, money: {money}\n order: {order_formated}"
  303. logger.info(msg)
  304. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  305. self.exchange_withdrawal_amount = money
  306. self._set_state(self.STATE_BUYING_ON_CHAIN)
  307. return
  308. else:
  309. time.sleep(1)
  310. waiting_times = waiting_times - 1
  311. last_order_formated = pformat(last_order, indent=2)
  312. msg = f"交易所现货卖出订单失敗, 最後狀態:\n{last_order_formated}。"
  313. logger.info(msg)
  314. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  315. self._set_state(self.STATE_FAILED)
  316. except Exception as e:
  317. exc_traceback = traceback.format_exc()
  318. msg = f"查询交易所现货卖出订单状态时发生错误\n{exc_traceback}"
  319. logger.error(msg)
  320. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  321. self._set_state(self.STATE_FAILED)
  322. # traceback.print_exc()
  323. def _execute_buy_on_chain(self):
  324. """
  325. 在链上执行买入操作
  326. """
  327. msg = "执行:链上买入操作..."
  328. logger.info(msg)
  329. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  330. try:
  331. # 交易前nonce
  332. with self.core_lock:
  333. self.tx['nonce'] = self.core_data['nonce']
  334. # 调用链上客户端执行买入交易
  335. signed_tx = web3._sign(self.tx, self.gas_limit_multiplier)
  336. self.chain_tx_hash = web3.w3.to_hex(signed_tx.hash)
  337. try:
  338. web3.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
  339. except Exception as e:
  340. msg = f"据反饋說链上买入失败:{e}, 交易哈希:{self.chain_tx_hash}"
  341. logger.error(msg)
  342. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  343. # 交易成功后刷新全局nonce
  344. with self.core_lock:
  345. self.core_data['nonce'] = self.core_data['nonce'] + 1
  346. block_number = self.core_data['block_number']
  347. # 將hash放入pending裏,等待確認
  348. with self.pending_lock:
  349. self.pending_data[self.chain_tx_hash] = {
  350. "block_number": block_number,
  351. "tx_details": None,
  352. "reponse": None,
  353. }
  354. # 交易成功
  355. msg = f"再次確認交易是否上鏈:{self.chain_tx_hash}"
  356. logger.info(msg)
  357. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  358. self._set_state(self.STATE_WAITING_CHAIN_CONFIRM)
  359. except Exception as e:
  360. exc_traceback = traceback.format_exc()
  361. msg = f"鏈上買入未處理的錯誤, 交易哈希:{self.chain_tx_hash}\n{exc_traceback}"
  362. logger.error(msg)
  363. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  364. self._set_state(self.STATE_WAITING_CHAIN_CONFIRM)
  365. # traceback.print_exc()
  366. def _wait_chain_confirm(self):
  367. """
  368. 等待链上交易确认
  369. """
  370. chain_tx_hash = self.chain_tx_hash
  371. msg = f"等待链上交易确认:{chain_tx_hash}"
  372. logger.info(msg)
  373. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  374. try:
  375. # 給300秒時間進行確認
  376. waiting_times = 300
  377. while waiting_times > 0:
  378. with self.pending_lock:
  379. tx_details = copy.deepcopy(self.pending_data[chain_tx_hash]['tx_details'])
  380. if tx_details is None:
  381. waiting_times = waiting_times - 1
  382. time.sleep(1)
  383. continue
  384. # # 交易確認后,移除出pending列表
  385. # with self.pending_lock:
  386. # del self.pending_data[chain_tx_hash]
  387. # 交易失敗的邏輯處理,直接進行回滾
  388. if 'fromTokenDetails' not in tx_details \
  389. or 'toTokenDetails' not in tx_details:
  390. msg = f"链上交易失敗。{tx_details}"
  391. logger.info(msg)
  392. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  393. self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
  394. break
  395. tx_details_formated = pformat(tx_details, indent=2)
  396. msg = f"链上交易已确认。\n details: {tx_details_formated}"
  397. logger.info(msg)
  398. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  399. # 獲取交易信息
  400. from_token_details = tx_details['fromTokenDetails']
  401. to_token_details = tx_details['toTokenDetails']
  402. from_token_amount = Decimal(from_token_details['amount'])
  403. from_token_amount_human = from_token_amount / (Decimal(10) ** self.from_token_decimal)
  404. from_token_amount_human = from_token_amount_human.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
  405. self.chain_buy_amount = from_token_amount_human # 存储实际买入数量
  406. to_token_amount = Decimal(to_token_details['amount'])
  407. to_token_amount_human = to_token_amount / (Decimal(10) ** self.to_token_decimal)
  408. self.buy_price = from_token_amount_human / to_token_amount_human
  409. self.buy_price = self.buy_price.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
  410. # 交易預估利潤百分比計算
  411. rate = self.sell_price / self.buy_price
  412. rate = rate.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
  413. msg = f"【比率{rate}】。用{from_token_amount_human}买入{to_token_amount_human},价格{self.buy_price}。"
  414. logger.info(msg)
  415. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  416. # 判斷快速二賣條件
  417. diff = int(to_token_amount_human - self.exchange_sell_amount)
  418. value = diff * self.sell_price
  419. value = value.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
  420. if value > 2:
  421. msg = f"滿足二賣條件,{diff}*{self.sell_price} = {value}"
  422. logger.info(msg)
  423. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  424. order_params = {
  425. "symbol": self.symbol.replace('_', ''),
  426. "side": "SELL",
  427. "type": "MARKET",
  428. "quantity": int(diff),
  429. }
  430. order_params_formated = pformat(order_params, indent=2)
  431. exchange_sell_order = mexc.trade.post_order(order_params)
  432. exchange_sell_order_formated = pformat(exchange_sell_order, indent=2)
  433. if 'orderId' not in exchange_sell_order:
  434. msg = f"交易所现货二卖下单失败 \n params:{order_params_formated} \n rst: {exchange_sell_order_formated}"
  435. logger.error(msg)
  436. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  437. else:
  438. oid = exchange_sell_order['orderId']
  439. # 查询交易所订单状态
  440. waiting_times_inner = 30
  441. last_order = None
  442. while waiting_times_inner > 0:
  443. params = {
  444. "symbol": self.symbol.replace('_', ''),
  445. "orderId": oid
  446. }
  447. order = mexc.trade.get_order(params)
  448. order_formated = pformat(order, indent=2)
  449. last_order = order
  450. if order['status'] in ["FILLED", "PARTIALLY_CANCELED"]:
  451. money = Decimal(order['cummulativeQuoteQty'])
  452. msg = f"交易所现货二卖订单已完成, money: {money}。\n order: {order_formated}"
  453. logger.info(msg)
  454. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  455. self.exchange_withdrawal_amount = self.exchange_withdrawal_amount + money
  456. break
  457. else:
  458. time.sleep(1)
  459. waiting_times_inner = waiting_times_inner - 1
  460. if waiting_times_inner <= 0:
  461. last_order_formated = pformat(last_order, indent=2)
  462. msg = f"交易所现货二卖订单失敗, 最後狀態:{last_order_formated}。"
  463. logger.info(msg)
  464. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  465. else:
  466. msg = f"不滿足二賣條件,{diff}*{self.sell_price} = {value}"
  467. logger.info(msg)
  468. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  469. # 計算實際利潤
  470. actual_profit = value
  471. actual_gas_price = Decimal(tx_details['gasPrice'])
  472. actual_gas_price_gwei = actual_gas_price / Decimal('1e9')
  473. actual_gas_price_gwei = actual_gas_price_gwei.quantize(Decimal('1e-9'), rounding=ROUND_DOWN)
  474. actual_gas_used = Decimal(tx_details['gasUsed'])
  475. actual_wei = actual_gas_price * actual_gas_used
  476. actual_eth = actual_wei / Decimal('1e18')
  477. actual_eth = actual_eth.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
  478. actual_fee_used = actual_eth * self.eth_price
  479. actual_fee_used = actual_fee_used.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
  480. actual_profit = value - actual_fee_used - self.WITHDRAW_FEE
  481. msg = f"【最終利潤】{actual_profit}{self.base_coin}(已扣除所有手續費、滑點)\
  482. \n鏈上ETH使用: {actual_eth}({actual_fee_used} USD), gas_price: {actual_gas_price_gwei} GWEI, gas_used: {actual_gas_used}\
  483. \n交易所出售代幣利潤: {value}, 提現手續費: {self.WITHDRAW_FEE}\
  484. "
  485. logger.info(msg)
  486. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  487. self._set_state(self.STATE_COMPLETED)
  488. break
  489. # 如果300秒都沒確認成功,該交易大概率沒有上鏈
  490. if waiting_times <= 0:
  491. with self.pending_lock:
  492. response = copy.deepcopy(self.pending_data[chain_tx_hash]['response'])
  493. response_formated = pformat(response, indent=2)
  494. msg = f"链上交易确认失败:{chain_tx_hash}\n{response_formated}"
  495. logger.error(msg)
  496. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  497. self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
  498. except Exception as e:
  499. exc_traceback = traceback.format_exc()
  500. msg = f"查询链上确认状态时发生错误\n{exc_traceback}"
  501. logger.error(msg)
  502. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  503. self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
  504. # traceback.print_exc()
  505. def _wait_exchange_rollback(self):
  506. """
  507. 市价进行交易所交易回滚
  508. """
  509. msg = "执行:中心化交易所买入现货回滚..."
  510. logger.info(msg)
  511. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  512. try:
  513. # 使用预提现数量进行回滚
  514. pseudo_amount_to_buy = Decimal(self.exchange_withdrawal_amount)
  515. # 处理精度
  516. pseudo_amount_to_buy = pseudo_amount_to_buy.quantize(Decimal('1'), rounding=ROUND_DOWN)
  517. # 交易所U余额判断
  518. with self.mexc_lock:
  519. balances = self.mexc_data['account_info']['balances']
  520. for balance in balances:
  521. if balance['asset'] == self.base_coin:
  522. pseudo_amount_to_buy = min(Decimal(balance['free']), pseudo_amount_to_buy)
  523. if pseudo_amount_to_buy < Decimal('10'):
  524. msg = f"交易所剩余{self.base_coin}: {balance['free']}, 小于10, 不能触发回滚交易。"
  525. logger.info(msg)
  526. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  527. self._set_state(self.STATE_FAILED)
  528. return
  529. else:
  530. msg = f"交易所剩余{self.base_coin}: {balance['free']}, 交易所准备使用:{pseudo_amount_to_buy}, 余额校验通过(可以回滚)。"
  531. logger.info(msg)
  532. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  533. break
  534. order_params = {
  535. "symbol": self.symbol.replace('_', ''),
  536. "side": "BUY",
  537. "type": "MARKET",
  538. "quoteOrderQty": int(pseudo_amount_to_buy),
  539. }
  540. order_params_formated = pformat(order_params, indent=2)
  541. exchange_buy_order = mexc.trade.post_order(order_params)
  542. exchange_buy_order_formated = pformat(exchange_buy_order, indent=2)
  543. if 'orderId' not in exchange_buy_order:
  544. msg = f"【回滚】交易所现货买入下单失败\n params:{order_params_formated}\norder: {exchange_buy_order_formated}"
  545. logger.error(msg)
  546. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  547. self._set_state("FAILED")
  548. return
  549. exchange_buy_order_id = exchange_buy_order['orderId']
  550. msg = f"【回滚】交易所现货买入订单已发送, 订单ID: {exchange_buy_order_id}"
  551. logger.info(msg)
  552. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  553. # 查询交易所订单状态
  554. waiting_times = 30
  555. last_query_rst = None
  556. while True:
  557. params = {
  558. "symbol": self.symbol.replace('_', ''),
  559. "orderId": exchange_buy_order_id
  560. }
  561. order = mexc.trade.get_order(params)
  562. order_formated = pformat(order, indent=2)
  563. last_query_rst = order
  564. if order['status'] == "FILLED":
  565. money = Decimal(order['cummulativeQuoteQty'])
  566. amount = self.exchange_sell_amount
  567. price = money / amount
  568. price = price.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
  569. msg = f"【回滚】交易所现货买入订单已完全成交, 价格:{price}。\norder: {order_formated}"
  570. logger.info(msg)
  571. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  572. self._set_state(self.STATE_FAILED)
  573. return
  574. else:
  575. # 继续等待成交
  576. pass
  577. time.sleep(1)
  578. waiting_times = waiting_times - 1
  579. last_query_rst_formated = pformat(last_query_rst, indent=2)
  580. msg = f"【回滚】回滚交易订单查询超时, 订单ID: {exchange_buy_order_id}\n最终状态:{last_query_rst_formated}"
  581. logger.info(msg)
  582. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  583. self._set_state(self.STATE_FAILED)
  584. except Exception as e:
  585. exc_traceback = traceback.format_exc()
  586. msg = f"【回滚】交易所回滚交易失败\n{exc_traceback}"
  587. logger.error(msg)
  588. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  589. self._set_state(self.STATE_FAILED)
  590. # traceback.print_exc()
  591. # 伪代码示例:如何使用这个类
  592. if __name__ == "__main__":
  593. import ok_chain_client
  594. import decimal
  595. import pprint
  596. CHAIN_ID = 1
  597. FROM_TOKEN = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
  598. FROM_TOKEN_AMOUNT_HUMAM = Decimal('20')
  599. FROM_TOKEN_DECIMAL = 6
  600. TO_TOKEN = '0xf816507E690f5Aa4E29d164885EB5fa7a5627860'
  601. USER_WALLET = ''
  602. USER_EXCHANGE_WALLET = '0xc71835a042F4d870B0F4296cc89cAeb921a9f3DA'
  603. SYMBOL = "RATO_USDT"
  604. # 询价,注意!!!这里直接把交易所地址当收款方,省去transfer的流程
  605. data = ok_chain_client.swap(CHAIN_ID,
  606. FROM_TOKEN_AMOUNT_HUMAM * (10 ** FROM_TOKEN_DECIMAL),
  607. FROM_TOKEN,
  608. TO_TOKEN,
  609. 1,
  610. USER_WALLET,
  611. USER_EXCHANGE_WALLET, # 这里直接把交易所地址当收款方,省去transfer的流程!!!
  612. )
  613. if data.get('code') != '0' or not data.get('data'):
  614. pprint.pprint(data)
  615. pprint.pprint({
  616. "error": f"OK API错误({1}) - Code:{data.get('code', 'N/A')}, Msg:{data.get('msg', data.get('message', 'N/A')) if isinstance(data, dict) else '格式错误'}"})
  617. raise Exception("")
  618. d = data['data'][0]
  619. tx = d['tx']
  620. router_result = d['routerResult']
  621. in_dec, out_dec = int(router_result['fromToken']['decimal']), int(router_result['toToken']['decimal'])
  622. atomic_in_base, atomic_out_target = Decimal(router_result['fromTokenAmount']), Decimal(router_result['toTokenAmount'])
  623. human_in_base = atomic_in_base / (10 ** in_dec)
  624. human_out_target = atomic_out_target / (10 ** out_dec)
  625. FROM_TOKEN_AMOUNT_HUMAM = human_in_base
  626. TO_TOKEN_AMOUNT_HUMAM = human_out_target
  627. pprint.pprint(tx)
  628. # 套利流程执行
  629. process_item = {
  630. "stateFlow": [], # 状态流转记录
  631. }
  632. ap = ArbitrageProcess(tx, 2, 1.2,
  633. FROM_TOKEN, TO_TOKEN,
  634. FROM_TOKEN_AMOUNT_HUMAM, TO_TOKEN_AMOUNT_HUMAM,
  635. USER_EXCHANGE_WALLET, USER_WALLET,
  636. SYMBOL, process_item)
  637. # 一般都是从这个流程开始,测试时可以稍作修改、测试后续流程
  638. ap._set_state(ap.SELLING_ON_EXCHANGE)
  639. # 在主循环中周期性调用 run_arbitrage_step
  640. while ap.current_state != "COMPLETED" and ap.current_state != "FAILED":
  641. ap.run_arbitrage_step()
  642. if ap.current_state == ap.STATE_WAITING_TRANSFER_ARRIVE or ap.current_state == ap.STATE_WAITING_WITHDRAWAL_CONFIRM:
  643. time.sleep(10)
  644. # else:
  645. # time.sleep(1)
  646. logger.info(process_item)
  647. if ap.current_state == "COMPLETED":
  648. logger.info("套利流程执行成功!")
  649. else:
  650. logger.info("套利流程执行失败!")