s_erc20_to_mexc.py 34 KB

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