erc20_to_mexc_first_sell.py 40 KB

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