s_mexc_to_erc20.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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. with self.core_lock:
  48. self.eth_price = self.core_data['eth_price']
  49. with self.mexc_lock:
  50. self.withdraw_info = copy.deepcopy(self.mexc_data['coin_info_map'][self.coin][self.NETWORK])
  51. self.WITHDRAW_FEE = Decimal(self.withdraw_info['withdrawFee']) # 提現手續費
  52. self.WITHDRAW_ENABLE = self.withdraw_info['withdrawEnable'] # 是否启用提现
  53. withdraw_info_formated = pformat(self.withdraw_info, indent=2)
  54. logger.info(f'提現信息識別, 手續費:{self.WITHDRAW_FEE}\n{withdraw_info_formated}')
  55. self.tx = tx
  56. self.mexc_price = Decimal(process_item['cexPrice'])
  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.sell_value = Decimal(0)
  71. self.buy_price = Decimal(0)
  72. self.buy_value = Decimal(0)
  73. self.chain_tx_hash = None # 链上卖出的tx hash
  74. self.exchange_buy_amount = Decimal(process_item['fromTokenAmountHuman']) # 交易所买入量
  75. self.exchange_buy_amount = self.exchange_buy_amount + self.WITHDRAW_FEE # 买入量考虑提现手续费
  76. self.already_bought_amount = Decimal(0)
  77. self.exchange_withdrawal_id = None # 交易所提现id
  78. self.exchange_withdrawal_amount = None # 交易所提现数量
  79. self.actual_profit = Decimal(0) # 實際利潤
  80. # 定义可能的状态
  81. self.STATES = [
  82. "CHECK", # 检查余额、估算gas等
  83. "BUYING_ON_EXCHANGE", # 正在中心化交易所买入现货
  84. "WAITING_BUY_CONFIRM", # 等待现货买入订单确认
  85. "SELLING_ON_CHAIN", # 正在链上卖出
  86. "WAITING_CHAIN_CONFIRM", # 等待链上交易确认
  87. "WAITING_EXCHANGE_ROLLBACK", # 等待交易所回滚
  88. "TRANSFERRING_TO_CHAIN", # 正在向链上转账
  89. "WAITING_WITHDRAWAL_CONFIRM", # 等待链上提现确认
  90. "COMPLETED", # 套利流程完成
  91. "REJECT", # 套利被程序拒绝
  92. "FAILED" # 套利流程失败
  93. ]
  94. self.STATE_IDLE = "IDLE"
  95. self.STATE_CHECK = "CHECK"
  96. self.STATE_BUYING_ON_EXCHANGE = "BUYING_ON_EXCHANGE"
  97. # self.STATE_WAITING_BUY_CONFIRM = "WAITING_BUY_CONFIRM"
  98. self.STATE_SELLING_ON_CHAIN = "SELLING_ON_CHAIN"
  99. self.STATE_WAITING_CHAIN_CONFIRM = "WAITING_CHAIN_CONFIRM"
  100. self.STATE_WAITING_EXCHANGE_ROLLBACK = "WAITING_EXCHANGE_ROLLBACK"
  101. self.STATE_WAITING_TRANSFER_ARRIVE = "WAITING_TRANSFER_ARRIVE"
  102. self.STATE_TRANSFERRING_TO_CHAIN = "TRANSFERRING_TO_CHAIN"
  103. self.STATE_WAITING_WITHDRAWAL_CONFIRM = "WAITING_WITHDRAWAL_CONFIRM"
  104. self.STATE_COMPLETED = "COMPLETED"
  105. self.STATE_REJECT = "REJECT"
  106. self.STATE_FAILED = "FAILED"
  107. self.current_state = "IDLE"
  108. def _set_state(self, state):
  109. """
  110. 设置系统状态,并打印日志
  111. """
  112. if state in self.STATES:
  113. logger.info(f"状态变更:{self.current_state} -> {state}")
  114. logger.info('')
  115. self.current_state = state
  116. else:
  117. logger.error(f"尝试设置无效状态:{state}")
  118. def run_arbitrage_step(self):
  119. """
  120. 根据当前状态执行套利流程的下一步
  121. 这是一个周期性调用的函数,例如在主循环中调用
  122. """
  123. if self.current_state == self.STATE_CHECK:
  124. self._execute_check()
  125. elif self.current_state == self.STATE_BUYING_ON_EXCHANGE:
  126. self._execute_buy_on_exchange()
  127. elif self.current_state == self.STATE_SELLING_ON_CHAIN:
  128. self._selling_on_chain()
  129. elif self.current_state == self.STATE_WAITING_CHAIN_CONFIRM:
  130. self._wait_chain_confirm()
  131. elif self.current_state == self.STATE_WAITING_EXCHANGE_ROLLBACK:
  132. self._wait_exchange_rollback()
  133. elif self.current_state == self.STATE_WAITING_TRANSFER_ARRIVE:
  134. self._wait_transfer_arrive()
  135. elif self.current_state == self.STATE_TRANSFERRING_TO_CHAIN:
  136. self._execute_transfer_to_chain()
  137. elif self.current_state == self.STATE_WAITING_WITHDRAWAL_CONFIRM:
  138. self._wait_withdrawal_confirm()
  139. elif self.current_state == self.STATE_COMPLETED:
  140. msg = "套利流程成功完成!"
  141. logger.info(msg)
  142. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  143. elif self.current_state == self.STATE_REJECT:
  144. msg = "套利流程被程序拒绝"
  145. logger.error(msg)
  146. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  147. elif self.current_state == self.STATE_FAILED:
  148. msg = "套利流程失败!"
  149. logger.error(msg)
  150. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  151. def _execute_check(self):
  152. """
  153. 前置检查,防止低能错误
  154. """
  155. try:
  156. # step1,檢查交易所的餘額是否夠用,给2%的余量
  157. pseudo_value_to_buy = (self.exchange_buy_amount * self.mexc_price) * Decimal(1.02)
  158. pseudo_value_to_buy = pseudo_value_to_buy.quantize(Decimal('1'), rounding=ROUND_DOWN)
  159. # 交易所套保余额判断
  160. with self.mexc_lock:
  161. balances = self.mexc_data['account_info']['balances']
  162. for balance in balances:
  163. if balance['asset'] == self.base_coin:
  164. if Decimal(balance['free']) < pseudo_value_to_buy:
  165. msg = f"交易所剩余{self.base_coin}: {balance['free']}, 买入要使用:{pseudo_value_to_buy}, 不能触发交易。"
  166. logger.info(msg)
  167. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  168. self._set_state(self.STATE_REJECT)
  169. return
  170. else:
  171. msg = f"交易所剩余{self.base_coin}: {balance['free']}, 买入要使用:{pseudo_value_to_buy}, 余额校验通过。"
  172. logger.info(msg)
  173. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  174. break
  175. # 检查该币对是否有提现权限
  176. if not self.WITHDRAW_ENABLE:
  177. coin_info_formated = pformat(self.withdraw_info, indent=2)
  178. msg = f"{self.coin}不允许提现。\n{coin_info_formated}"
  179. logger.info(msg)
  180. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  181. self._set_state(self.STATE_REJECT)
  182. return
  183. # step2,估算gas
  184. logger.info("獲取區塊信息")
  185. with self.core_lock:
  186. latest_block = copy.deepcopy(self.core_data['block'])
  187. self.tx['maxPriorityFeePerGas'] = int(int(self.tx['maxPriorityFeePerGas']) * self.gas_price_multiplier)
  188. self.tx['maxFeePerGas'] = int(int(latest_block['baseFeePerGas']) * 2 + self.tx['maxPriorityFeePerGas'])
  189. gas_price = Decimal(self.tx['maxPriorityFeePerGas'] + self.tx['maxFeePerGas'])
  190. gas_price_gwei = gas_price / Decimal('1e9')
  191. gas_price_gwei = gas_price_gwei.quantize(Decimal('1e-9'), rounding=ROUND_DOWN)
  192. tx_formated = pformat(self.tx, indent=2)
  193. logger.info(f"鏈上各種校驗\n{tx_formated}")
  194. estimated_gas_origin = web3.w3.eth.estimate_gas(self.tx)
  195. estimated_gas = int(estimated_gas_origin * self.gas_limit_multiplier)
  196. estimated_wei = Decimal(estimated_gas) * gas_price
  197. estimated_eth = Decimal(estimated_wei / Decimal('1e18')) / Decimal(2) # 除以2才是比較接近正常消耗的gas費,否則會過於高估
  198. estimated_eth = estimated_eth.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
  199. msg = f"估算的燃气量: {estimated_gas}, eth消耗: {estimated_eth}, gas price: {gas_price_gwei} gwei, gas估算通過"
  200. logger.info(msg)
  201. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  202. # step3, 費用與利潤比較
  203. estimated_eth_value = estimated_eth * self.eth_price
  204. estimated_eth_value = estimated_eth_value.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
  205. cost = estimated_eth_value + self.WITHDRAW_FEE * self.mexc_price # 成本
  206. if self.profit < cost:
  207. msg = f"費用判斷不通過! profit: {self.profit}, eth_value:{estimated_eth_value}, eth: {estimated_eth}, eth_price: {self.eth_price}"
  208. logger.info(msg)
  209. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  210. self._set_state(self.STATE_REJECT)
  211. return
  212. msg = f"費用判斷通過! profit: {self.profit}, eth_value:{estimated_eth_value}, eth: {estimated_eth}, eth_price: {self.eth_price}"
  213. logger.info(msg)
  214. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  215. # step4, 與賬戶eth餘額比對(至少留0.002,不然沒gas了)
  216. MARGIN = Decimal(0.002)
  217. # 暫時鎖住core_data
  218. with self.core_lock:
  219. eth_balance = self.core_data['eth_balance']
  220. if eth_balance - estimated_eth < MARGIN:
  221. msg = f"gas餘額判斷不通過! MARGIN:{MARGIN}, estimated_eth: {estimated_eth}, eth_balance: {eth_balance}"
  222. logger.info(msg)
  223. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  224. self._set_state(self.STATE_REJECT)
  225. return
  226. # 餘額判斷通過后預扣除balance,防止綫程更新不及時導致其他綫程誤發送tx
  227. self.core_data['eth_balance'] = self.core_data['eth_balance'] - estimated_eth
  228. msg = f"gas餘額判斷通過! MARGIN:{MARGIN}, estimated_eth: {estimated_eth}, eth_balance: {eth_balance}"
  229. logger.info(msg)
  230. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  231. # final, 設定交易狀態,開始交易
  232. self._set_state(self.STATE_BUYING_ON_EXCHANGE)
  233. except Exception as e:
  234. exc_traceback = traceback.format_exc()
  235. msg = f"前置檢查未通過\n{exc_traceback}"
  236. logger.error(msg)
  237. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  238. self._set_state(self.STATE_REJECT)
  239. # traceback.print_exc()
  240. # 以下是每个状态对应的具体执行函数
  241. def _execute_buy_on_exchange(self):
  242. """
  243. 在中心化交易所买入现货
  244. """
  245. msg = "执行:中心化交易所买入现货..."
  246. logger.info(msg)
  247. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  248. try:
  249. order_times = 0
  250. self.already_bought_amount = Decimal(0)
  251. while self.already_bought_amount < self.exchange_buy_amount and order_times < 5:
  252. order_times = order_times + 1
  253. # 第一步直接买入,这个数量用固定数量
  254. pseudo_amount_to_buy = self.exchange_buy_amount - self.already_bought_amount
  255. # 处理精度
  256. pseudo_amount_to_buy = pseudo_amount_to_buy.quantize(Decimal('1'), rounding=ROUND_DOWN)
  257. order_params = {
  258. "symbol": self.symbol.replace('_', ''),
  259. "side": "BUY",
  260. "type": "MARKET",
  261. "quantity": int(pseudo_amount_to_buy), # 以【幣】的數量進行買入
  262. }
  263. order_params_formated = pformat(order_params, indent=2)
  264. exchange_buy_order = mexc.trade.post_order(order_params)
  265. exchange_buy_order_formated = pformat(exchange_buy_order, indent=2)
  266. msg = f"[{order_times}]交易所现货买入订单已发送 \n params:{order_params_formated} \n rst: {exchange_buy_order_formated}"
  267. if 'orderId' not in exchange_buy_order:
  268. logger.error(msg)
  269. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  270. continue
  271. exchange_buy_order_id = exchange_buy_order['orderId']
  272. # 查询交易所订单状态
  273. waiting_times = 5
  274. last_order = None
  275. while waiting_times > 0:
  276. params = {
  277. "symbol": self.symbol.replace('_', ''),
  278. "orderId": exchange_buy_order_id
  279. }
  280. order = mexc.trade.get_order(params)
  281. last_order = order
  282. if order['status'] in ["FILLED", "PARTIALLY_CANCELED"]:
  283. # 以实际成交数量为准
  284. money = Decimal(order['cummulativeQuoteQty'])
  285. self.already_bought_amount = self.already_bought_amount + Decimal(order['executedQty'])
  286. self.buy_value = self.buy_value + money
  287. self.buy_price = self.buy_value / self.already_bought_amount
  288. self.buy_price = self.buy_price.quantize(Decimal('1e-16'), rounding=ROUND_DOWN)
  289. order_formated = pformat(order, indent=2)
  290. msg = f"交易所现货买入订单已完成, 价格:{self.buy_price}, money: {money}\n order: {order_formated}"
  291. logger.info(msg)
  292. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  293. self.exchange_withdrawal_amount = self.already_bought_amount
  294. break
  295. else:
  296. time.sleep(1)
  297. waiting_times = waiting_times - 1
  298. if order_times < 5:
  299. msg = 'mexc现货买入流程完成'
  300. logger.info(msg)
  301. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  302. self._set_state(self.STATE_SELLING_ON_CHAIN)
  303. else:
  304. msg = 'mexc现货买入流程失败, 重试次数大于5'
  305. logger.info(msg)
  306. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  307. self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
  308. except Exception as e:
  309. exc_traceback = traceback.format_exc()
  310. msg = f"交易所现货买入下单失败\n{exc_traceback}"
  311. logger.error(msg)
  312. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  313. self._set_state(self.STATE_FAILED)
  314. # traceback.print_exc()
  315. def _selling_on_chain(self):
  316. """
  317. 在链上执行卖出操作
  318. """
  319. msg = "执行:链上卖出操作..."
  320. logger.info(msg)
  321. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  322. try:
  323. # 交易前nonce
  324. with self.core_lock:
  325. self.tx['nonce'] = self.core_data['nonce']
  326. # 调用链上客户端执行卖出交易
  327. signed_tx = web3._sign(self.tx, self.gas_limit_multiplier)
  328. self.chain_tx_hash = web3.w3.to_hex(signed_tx.hash)
  329. try:
  330. # 主要节点先发交易
  331. web3.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
  332. # 使用备用节点再发一次交易
  333. web3_backup.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
  334. except Exception as e:
  335. msg = f"据反饋說链上卖出失败:{e}, 交易哈希:{self.chain_tx_hash}"
  336. logger.error(msg)
  337. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  338. # 交易成功后刷新全局nonce
  339. with self.core_lock:
  340. self.core_data['nonce'] = self.core_data['nonce'] + 1
  341. block_number = self.core_data['block_number']
  342. # 將hash放入pending裏,等待確認
  343. with self.pending_lock:
  344. self.pending_data[self.chain_tx_hash] = {
  345. "block_number": block_number,
  346. "tx_details": None,
  347. "reponse": None,
  348. }
  349. # 交易成功
  350. msg = f"再次確認交易是否上鏈:{self.chain_tx_hash}"
  351. logger.info(msg)
  352. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  353. self._set_state(self.STATE_WAITING_CHAIN_CONFIRM)
  354. except Exception as e:
  355. exc_traceback = traceback.format_exc()
  356. msg = f"鏈上買入未處理的錯誤, 交易哈希:{self.chain_tx_hash}\n{exc_traceback}"
  357. logger.error(msg)
  358. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  359. self._set_state(self.STATE_WAITING_CHAIN_CONFIRM)
  360. # traceback.print_exc()
  361. def _wait_chain_confirm(self):
  362. """
  363. 等待链上交易确认
  364. """
  365. chain_tx_hash = self.chain_tx_hash
  366. msg = f"等待链上交易确认:{chain_tx_hash}"
  367. logger.info(msg)
  368. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  369. try:
  370. # 給120秒時間進行確認
  371. waiting_times = 120
  372. while waiting_times > 0:
  373. with self.pending_lock:
  374. tx_details = copy.deepcopy(self.pending_data[chain_tx_hash]['tx_details'])
  375. if tx_details is None:
  376. waiting_times = waiting_times - 1
  377. time.sleep(1)
  378. continue
  379. # # 交易確認后,移除出pending列表
  380. # with self.pending_lock:
  381. # del self.pending_data[chain_tx_hash]
  382. # 交易失敗的邏輯處理,直接進行回滾
  383. if 'fromTokenDetails' not in tx_details \
  384. or 'toTokenDetails' not in tx_details:
  385. msg = f"链上交易失敗。{tx_details}"
  386. logger.info(msg)
  387. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  388. self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
  389. break
  390. tx_details_formated = pformat(tx_details, indent=2)
  391. msg = f"链上交易已确认。\n details: {tx_details_formated}"
  392. logger.info(msg)
  393. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  394. # 獲取交易信息
  395. from_token_details = tx_details['fromTokenDetails']
  396. to_token_details = tx_details['toTokenDetails']
  397. from_token_amount = Decimal(from_token_details['amount'])
  398. from_token_amount_human = from_token_amount / (Decimal(10) ** self.from_token_decimal)
  399. from_token_amount_human = from_token_amount_human.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
  400. to_token_amount = Decimal(to_token_details['amount'])
  401. to_token_amount_human = to_token_amount / (Decimal(10) ** self.to_token_decimal)
  402. self.sell_value = to_token_amount_human
  403. self.sell_price = to_token_amount_human / from_token_amount_human
  404. self.sell_price = self.sell_price.quantize(Decimal('1e-16'), rounding=ROUND_DOWN)
  405. # 交易預估利潤百分比計算
  406. rate = self.sell_price / self.buy_price
  407. rate = rate.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
  408. msg = f"【比率{rate}】。用{from_token_amount_human}卖出{to_token_amount_human},价格{self.sell_price}。"
  409. logger.info(msg)
  410. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  411. # 計算實際利潤
  412. value = self.sell_value - self.buy_value
  413. actual_gas_price = Decimal(tx_details['gasPrice'])
  414. actual_gas_price_gwei = actual_gas_price / Decimal('1e9')
  415. actual_gas_price_gwei = actual_gas_price_gwei.quantize(Decimal('1e-9'), rounding=ROUND_DOWN)
  416. actual_gas_used = Decimal(tx_details['gasUsed'])
  417. actual_wei = actual_gas_price * actual_gas_used
  418. actual_eth = actual_wei / Decimal('1e18')
  419. actual_eth = actual_eth.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
  420. actual_fee_used = actual_eth * self.eth_price
  421. actual_fee_used = actual_fee_used.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
  422. actual_profit = value - actual_fee_used - self.WITHDRAW_FEE * self.mexc_price
  423. msg = f"【最終利潤】{actual_profit}{self.base_coin}(已扣除所有手續費、滑點)\
  424. \n鏈上ETH使用: {actual_eth}({actual_fee_used} USD), gas_price: {actual_gas_price_gwei} GWEI, gas_used: {actual_gas_used}\
  425. \n交易所出售代幣利潤: {value}, 提現手續費: {self.WITHDRAW_FEE}\
  426. "
  427. logger.info(msg)
  428. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  429. self._set_state(self.STATE_WAITING_TRANSFER_ARRIVE)
  430. break
  431. # 如果120秒都沒確認成功,該交易大概率沒有上鏈
  432. if waiting_times <= 0:
  433. with self.pending_lock:
  434. response = copy.deepcopy(self.pending_data[chain_tx_hash]['response'])
  435. response_formated = pformat(response, indent=2)
  436. msg = f"链上交易确认失败:{chain_tx_hash}\n{response_formated}"
  437. logger.error(msg)
  438. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  439. self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
  440. except Exception as e:
  441. exc_traceback = traceback.format_exc()
  442. msg = f"查询链上确认状态时发生错误\n{exc_traceback}"
  443. logger.error(msg)
  444. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  445. self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
  446. # traceback.print_exc()
  447. def _wait_exchange_rollback(self):
  448. """
  449. 市价进行交易所交易回滚
  450. """
  451. msg = "执行:中心化交易所卖出现货回滚..."
  452. logger.info(msg)
  453. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  454. try:
  455. # 使用预提现数量进行回滚
  456. pseudo_amount_to_sell = Decimal(self.already_bought_amount)
  457. # 处理精度
  458. pseudo_amount_to_sell = pseudo_amount_to_sell.quantize(Decimal('1'), rounding=ROUND_DOWN)
  459. # 交易所币余额判断
  460. with self.mexc_lock:
  461. balances = self.mexc_data['account_info']['balances']
  462. for balance in balances:
  463. if balance['asset'] == self.coin:
  464. pseudo_amount_to_sell = min(Decimal(balance['free']), pseudo_amount_to_sell)
  465. if pseudo_amount_to_sell * self.mexc_price < Decimal('10'):
  466. msg = f"交易所剩余{self.coin}: {balance['free']}, 小于10, 不能触发回滚交易。"
  467. logger.info(msg)
  468. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  469. self._set_state(self.STATE_FAILED)
  470. return
  471. else:
  472. msg = f"交易所剩余{self.coin}: {balance['free']}, 交易所准备使用:{pseudo_amount_to_sell}, 余额校验通过(可以回滚)。"
  473. logger.info(msg)
  474. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  475. break
  476. order_params = {
  477. "symbol": self.symbol.replace('_', ''),
  478. "side": "SELL",
  479. "type": "MARKET",
  480. "quantity": int(pseudo_amount_to_sell),
  481. }
  482. order_params_formated = pformat(order_params, indent=2)
  483. exchange_sell_order = mexc.trade.post_order(order_params)
  484. exchange_sell_order_formated = pformat(exchange_sell_order, indent=2)
  485. if 'orderId' not in exchange_sell_order:
  486. msg = f"【回滚】交易所现货卖出下单失败\n params:{order_params_formated}\norder: {exchange_sell_order_formated}"
  487. logger.error(msg)
  488. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  489. self._set_state("FAILED")
  490. return
  491. exchange_sell_order_id = exchange_sell_order['orderId']
  492. msg = f"【回滚】交易所现货卖出订单已发送, 订单ID: {exchange_sell_order_id}"
  493. logger.info(msg)
  494. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  495. # 查询交易所订单状态
  496. waiting_times = 30
  497. last_query_rst = None
  498. while True:
  499. params = {
  500. "symbol": self.symbol.replace('_', ''),
  501. "orderId": exchange_sell_order_id
  502. }
  503. order = mexc.trade.get_order(params)
  504. order_formated = pformat(order, indent=2)
  505. last_query_rst = order
  506. if order['status'] == "FILLED":
  507. money = Decimal(order['cummulativeQuoteQty'])
  508. amount = self.exchange_buy_amount
  509. price = money / amount
  510. price = price.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
  511. msg = f"【回滚】交易所现货卖出订单已完全成交, 价格:{price}。\norder: {order_formated}"
  512. logger.info(msg)
  513. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  514. self._set_state(self.STATE_FAILED)
  515. return
  516. else:
  517. # 继续等待成交
  518. pass
  519. time.sleep(1)
  520. waiting_times = waiting_times - 1
  521. last_query_rst_formated = pformat(last_query_rst, indent=2)
  522. msg = f"【回滚】回滚交易订单查询超时, 订单ID: {exchange_sell_order_id}\n最终状态:{last_query_rst_formated}"
  523. logger.info(msg)
  524. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  525. self._set_state(self.STATE_FAILED)
  526. except Exception as e:
  527. exc_traceback = traceback.format_exc()
  528. msg = f"【回滚】交易所回滚交易失败\n{exc_traceback}"
  529. logger.error(msg)
  530. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  531. self._set_state(self.STATE_FAILED)
  532. # traceback.print_exc()
  533. def _wait_transfer_arrive(self):
  534. """
  535. 等待资产在交易所内到账
  536. """
  537. msg = f"等待资产在交易所到账..."
  538. logger.info(msg)
  539. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  540. try:
  541. is_arrived = False
  542. # 先進行快速提現判斷,如果不滿足條件就走後面的等待充值模式,雙模,這個步驟最多等待10分鐘
  543. waiting_times = 10
  544. last_deposit_state = None
  545. while waiting_times > 0:
  546. time.sleep(60)
  547. with self.mexc_lock:
  548. deposit_list = copy.deepcopy(self.mexc_data['deposit_list'])
  549. # 是否已經在列表中了,抹茶識別充值會稍微有點慢,所以要耐心等
  550. is_list = False
  551. # pending中的數量
  552. pending_amount = Decimal(0)
  553. for deposit in deposit_list:
  554. # 不屬于該路徑需要監聽的代幣
  555. if deposit['coin'] != self.base_coin:
  556. continue
  557. # 處理pending數量
  558. if Decimal(deposit['confirmTimes']) < Decimal(deposit['unlockConfirm']):
  559. pending_amount = pending_amount + Decimal(deposit['amount'])
  560. # 檢查到沒到列表中
  561. if deposit['transHash'] != self.chain_tx_hash:
  562. continue
  563. last_deposit_state = deposit
  564. is_list = True
  565. # 檢查是否滿足快速提現的條件
  566. if is_list:
  567. # 交易所代幣余额判断
  568. with self.mexc_lock:
  569. balances = copy.deepcopy(self.mexc_data['account_info']['balances'])
  570. asset_balance = 0
  571. for balance in balances:
  572. if balance['asset'] == self.base_coin:
  573. asset_balance = Decimal(balance['free'])
  574. # 交易所賣出餘額
  575. buy_value = self.buy_value
  576. # 最終判斷
  577. if buy_value + asset_balance > pending_amount:
  578. last_deposit_state_formated = pformat(last_deposit_state, indent=2)
  579. msg = f"【flash】资产可以進行快速提現。\n{last_deposit_state_formated}"
  580. logger.info(msg)
  581. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  582. self._set_state(self.STATE_TRANSFERRING_TO_CHAIN)
  583. return
  584. else:
  585. logger.info(f"buy_value{buy_value}, asset_balance{asset_balance}, pending_amount{pending_amount}")
  586. logger.info(f"正在檢查快速提現條件...({waiting_times}/10)")
  587. waiting_times = waiting_times - 1
  588. # 最多等待30分钟
  589. waiting_times = 30
  590. last_deposit_state = None
  591. last_deposit_state_formated = None
  592. while waiting_times > 0:
  593. with self.mexc_lock:
  594. deposit_list = copy.deepcopy(self.mexc_data['deposit_list'])
  595. for deposit in deposit_list:
  596. if deposit['transHash'] != self.chain_tx_hash:
  597. continue
  598. last_deposit_state = deposit
  599. last_deposit_state_formated = pformat(last_deposit_state, indent=2)
  600. logger.info(f"等待资产在交易所到账...({deposit['confirmTimes']}/{deposit['unlockConfirm']})")
  601. if Decimal(deposit['confirmTimes']) >= Decimal(deposit['unlockConfirm']):
  602. is_arrived = True
  603. if is_arrived:
  604. msg = f"资产已在交易所到账。\n{last_deposit_state_formated}"
  605. logger.info(msg)
  606. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  607. self._set_state(self.STATE_TRANSFERRING_TO_CHAIN)
  608. return
  609. time.sleep(60)
  610. waiting_times = waiting_times - 1
  611. msg = f"等待充值到账超时(超过30分钟)。\n{last_deposit_state_formated}"
  612. logger.error(msg)
  613. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  614. self._set_state(self.STATE_FAILED)
  615. except Exception as e:
  616. msg = f"查询交易所到账状态时发生错误:{e}"
  617. logger.error(msg)
  618. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  619. self._set_state(self.STATE_FAILED)
  620. traceback.print_exc()
  621. def _execute_transfer_to_chain(self):
  622. """
  623. 将交易后获得的计价资产(例如USDT)转账回链上
  624. """
  625. msg = "执行:交易所计价资产转账回链上..."
  626. logger.info(msg)
  627. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  628. try:
  629. pseudo_withdrawal_amount = str(int(float(self.exchange_buy_amount)))
  630. withdrawal_params = {
  631. 'coin': self.coin,
  632. 'netWork': 'ETH',
  633. 'address': self.user_wallet,
  634. 'amount': pseudo_withdrawal_amount
  635. }
  636. withdrawal_params_formated = pformat(withdrawal_params, indent=2)
  637. withdrawal_rst = mexc.wallet.post_withdraw(withdrawal_params)
  638. withdrawal_rst_formated = pformat(withdrawal_rst, indent=2)
  639. if "id" not in withdrawal_rst:
  640. msg = f"交易所提现失败\n參數: {withdrawal_params_formated}\n響應: {withdrawal_rst_formated}"
  641. logger.error(msg)
  642. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  643. self._set_state(self.STATE_FAILED)
  644. else:
  645. self.exchange_withdrawal_id = withdrawal_rst["id"]
  646. msg = f"交易所提现已发送\n{withdrawal_rst_formated}"
  647. logger.info(msg)
  648. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  649. self._set_state(self.STATE_WAITING_WITHDRAWAL_CONFIRM)
  650. except Exception as e:
  651. msg = f"转账回链上失败: {e}"
  652. logger.error(msg)
  653. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  654. self._set_state(self.STATE_FAILED)
  655. traceback.print_exc()
  656. def _wait_withdrawal_confirm(self):
  657. """
  658. 等待交易所提现到链上确认
  659. """
  660. exchange_withdrawal_id = self.exchange_withdrawal_id
  661. msg = f"等待交易所提现确认:{exchange_withdrawal_id}"
  662. logger.info(msg)
  663. add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
  664. try:
  665. is_arrived = False
  666. # 最多等待30分钟
  667. waiting_times = 60
  668. last_deposit_state = None
  669. last_deposit_state_formated = None
  670. while waiting_times > 0:
  671. with self.mexc_lock:
  672. withdraw_list = copy.deepcopy(self.mexc_data['withdraw_list'])
  673. if not isinstance(withdraw_list, list):
  674. msg = f"查询交易所提现状态时发生错误:{withdraw_list}"
  675. logger.error(msg)
  676. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  677. self._set_state("FAILED")
  678. return
  679. for withdrawal in withdraw_list:
  680. if withdrawal['id'] != exchange_withdrawal_id:
  681. continue
  682. last_deposit_state = withdrawal
  683. last_deposit_state_formated = pformat(last_deposit_state, indent=2)
  684. if withdrawal['status'] == 7:
  685. is_arrived = True
  686. if is_arrived:
  687. msg = f"提现请求已上链:\n{last_deposit_state_formated}"
  688. logger.info(msg)
  689. add_state_flow_entry(self.process_item, self.current_state, msg, "success")
  690. self._set_state(self.STATE_COMPLETED)
  691. return
  692. time.sleep(30)
  693. waiting_times = waiting_times - 1
  694. msg = f"等待提现到账超时(超过30分钟):\n{last_deposit_state_formated}"
  695. logger.error(msg)
  696. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  697. self._set_state(self.STATE_FAILED)
  698. except Exception as e:
  699. msg = f"查询交易所提现状态时发生错误:{e}"
  700. logger.error(msg)
  701. add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
  702. self._set_state(self.STATE_FAILED)
  703. traceback.print_exc()