erc20_to_mexc.py 43 KB

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