| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816 |
- import time
- import logging
- import datetime
- from web3_py_client import EthClient
- from mexc_client import MexcClient
- from decimal import Decimal, ROUND_DOWN
- web3 = EthClient()
- mexc = MexcClient()
- # 配置日志
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
- def get_formatted_timestamp():
- """
- 获取指定格式的时间戳: YYYY-MM-DD HH:MM:SS,ms
- 例如: 2025-05-16 14:44:09,324
- """
- now = datetime.datetime.now()
- # 格式化日期和时间部分
- timestamp_str = now.strftime("%Y-%m-%d %H:%M:%S")
- # 获取毫秒部分,并格式化为3位数字
- milliseconds = now.microsecond // 1000
- milliseconds_str = f"{milliseconds:03d}"
- # 组合最终格式
- return f"{timestamp_str},{milliseconds_str}"
- def add_state_flow_entry(process_item, state_name, msg, status_val="pending"):
- """辅助函数,用于向 stateFlow 列表添加条目。"""
- entry = {
- "stateName": state_name, # 状态名称
- "timestamp": get_formatted_timestamp(), # 时间戳
- "msg": msg, # 消息
- "status": status_val # 状态值: "pending", "success", "fail", "skipped"
- }
- process_item["stateFlow"].append(entry)
- process_item["currentState"] = state_name # 更新整体状态
- # logging.info(f"[流程 {process_item.get('id', 'N/A')}][{state_name}]: {msg} (状态: {status_val})")
- class ArbitrageProcess:
- def __init__(self, tx, gas_limit_multiplier, gas_price_multiplier,
- from_token, to_token,
- from_token_amount_human, exchange_out_amount,
- user_exchange_wallet, user_wallet,
- symbol, process_item):
- """
- 初始化套利流程
- Args:
- tx: 在链上要发送交易的tx
- gas_limit_multiplier: gas limit倍数, 一般都不加倍
- gas_price_multiplier: gas price倍数, 可以提高交易成功率
- """
- tx.pop('gasPrice', None)
- tx.pop('value', None)
- tx.pop('minReceiveAmount', None)
- tx.pop('slippage', None)
- tx.pop('maxSpendAmount', None)
- tx.pop('signatureData', None)
- self.tx = tx
- self.gas_limit_multiplier = gas_limit_multiplier
- self.gas_price_multiplier = gas_price_multiplier
- self.from_token_addr = from_token
- self.to_token_addr = to_token
- self.user_exchange_wallet = user_exchange_wallet
- self.user_wallet = user_wallet
- self.symbol = symbol
- self.coin = symbol.split('_')[0]
- self.base_coin = symbol.split('_')[1]
- self.process_item = process_item
- self.sell_price = Decimal(0)
- self.buy_price = Decimal(0)
- # 存储当前套利交易的细节信息,例如买入数量、价格等
- self.arbitrage_details = {
- "chain_buy_tx_hash": None, # 链上买入的tx hash
- "chain_usdt_use": Decimal(from_token_amount_human), # 链上usdt减少量(使用量), todo, 暂用固定值代替
- "chain_amount_before_trade": 0,
- "chain_amount_after_trade": 0,
- "chain_buy_amount": Decimal('0'), # 链上币增加量(购入量), todo, 暂用即时余额代替
- "chain_buy_price": None, # 链上购入价, todo
- "chain_withdrawal_tx_hash": None, # 链上转入交易所的tx
- "exchange_out_amount": Decimal(exchange_out_amount), # 交易所卖出量
- "exchange_sell_order_id": None, # 交易所卖出id
- "exchange_withdraw_id": None, # 交易所提现id
- "exchange_withdraw_amount": None, # 交易所提现数量
- }
- # 定义可能的状态
- self.STATES = [
- "CHECK", # 检查余额、估算gas等
- "SELLING_ON_EXCHANGE", # 正在中心化交易所卖出现货
- "WAITING_SELL_CONFIRM", # 等待现货卖出订单确认
- "BUYING_ON_CHAIN", # 正在链上买入
- "WAITING_CHAIN_CONFIRM", # 等待链上交易确认
- "WAITING_EXCHANGE_ROLLBACK", # 等待交易所回滚
- # "HEDGING_ON_EXCHANGE", # 正在中心化交易所套保
- # "WAITING_HEDGE_CONFIRM", # 等待套保订单确认
- # "TRANSFERRING_TO_EXCHANGE", # 正在向交易所转账
- # "CLOSING_HEDGE", # 正在平掉套保单
- # "WAITING_CLOSE_HEDGE_CONFIRM", # 等待平掉套保单确认
- "WAITING_TRANSFER_ARRIVE", # 等待交易所充值到账
- "TRANSFERRING_TO_CHAIN", # 正在向链上转账
- "WAITING_WITHDRAWAL_CONFIRM", # 等待链上提现确认
- "COMPLETED", # 套利流程完成
- "REJECT", # 套利被程序拒绝
- "FAILED" # 套利流程失败
- ]
- self.STATE_IDLE = "IDLE"
- self.STATE_CHECK = "CHECK"
- self.STATE_SELLING_ON_EXCHANGE = "SELLING_ON_EXCHANGE"
- self.STATE_WAITING_SELL_CONFIRM = "WAITING_SELL_CONFIRM"
- self.STATE_BUYING_ON_CHAIN = "BUYING_ON_CHAIN"
- self.STATE_WAITING_CHAIN_CONFIRM = "WAITING_CHAIN_CONFIRM"
- self.STATE_WAITING_EXCHANGE_ROLLBACK = "WAITING_EXCHANGE_ROLLBACK"
- # self.STATE_TRANSFERRING_TO_EXCHANGE = "TRANSFERRING_TO_EXCHANGE"
- self.STATE_WAITING_TRANSFER_ARRIVE = "WAITING_TRANSFER_ARRIVE"
- self.STATE_TRANSFERRING_TO_CHAIN = "TRANSFERRING_TO_CHAIN"
- self.STATE_WAITING_WITHDRAWAL_CONFIRM = "WAITING_WITHDRAWAL_CONFIRM"
- self.STATE_COMPLETED = "COMPLETED"
- self.STATE_REJECT = "REJECT"
- self.STATE_FAILED = "FAILED"
- self.current_state = "IDLE"
- def _set_state(self, state):
- """
- 设置系统状态,并打印日志
- """
- if state in self.STATES:
- logging.info(f"状态变更:{self.current_state} -> {state}")
- logging.info('')
- self.current_state = state
- else:
- logging.error(f"尝试设置无效状态:{state}")
- def run_arbitrage_step(self):
- """
- 根据当前状态执行套利流程的下一步
- 这是一个周期性调用的函数,例如在主循环中调用
- """
- if self.current_state == self.STATE_CHECK:
- self._execute_check()
- elif self.current_state == self.STATE_SELLING_ON_EXCHANGE:
- self._execute_sell_on_exchange()
- elif self.current_state == self.STATE_WAITING_SELL_CONFIRM:
- self._wait_sell_confirm()
- elif self.current_state == self.STATE_BUYING_ON_CHAIN:
- self._execute_buy_on_chain()
- elif self.current_state == self.STATE_WAITING_CHAIN_CONFIRM:
- self._wait_chain_confirm()
- elif self.current_state == self.STATE_WAITING_EXCHANGE_ROLLBACK:
- self._wait_exchange_rollback()
- # elif self.current_state == "TRANSFERRING_TO_EXCHANGE":
- # self._execute_transfer_to_exchange()
- elif self.current_state == self.STATE_WAITING_TRANSFER_ARRIVE:
- self._wait_transfer_arrive()
- elif self.current_state == self.STATE_TRANSFERRING_TO_CHAIN:
- self._execute_transfer_to_chain()
- elif self.current_state == self.STATE_WAITING_WITHDRAWAL_CONFIRM:
- self._wait_withdrawal_confirm()
- elif self.current_state == self.STATE_COMPLETED:
- msg = "套利流程成功完成!"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- elif self.current_state == self.STATE_REJECT:
- msg = "套利流程被程序拒绝"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- elif self.current_state == self.STATE_FAILED:
- msg = "套利流程失败!"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- def _execute_check(self):
- """
- 前置检查,防止低能错误
- """
- try:
- # step1,檢查交易所的餘額是否夠用
- pseudo_amount_to_sell = self.arbitrage_details["exchange_out_amount"]
- # 处理精度
- pseudo_amount_to_sell = pseudo_amount_to_sell.quantize(Decimal('1'), rounding=ROUND_DOWN)
- # 交易所套保余额判断
- balances = mexc.trade.get_account_info()['balances']
- for balance in balances:
- if balance['asset'] == self.coin:
- if Decimal(balance['free']) < pseudo_amount_to_sell:
- msg = f"交易所剩余{self.coin}: {balance['free']}, 交易所准备卖出:{pseudo_amount_to_sell}, 不能触发套保交易。"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_REJECT)
- return
- else:
- msg = f"交易所剩余{self.coin}: {balance['free']}, 交易所准备卖出:{pseudo_amount_to_sell}, 余额校验通过(可以套保)。"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- break
- # step2,估算gas
- latest_block = web3.w3.eth.get_block('latest')
- self.tx['maxPriorityFeePerGas'] = int(int(self.tx['maxPriorityFeePerGas']) * self.gas_price_multiplier)
- self.tx['maxFeePerGas'] = int(int(latest_block['baseFeePerGas']) * 2 + self.tx['maxPriorityFeePerGas'])
- estimated_gas_origin = web3.w3.eth.estimate_gas(self.tx)
- estimated_gas = int(estimated_gas_origin * self.gas_limit_multiplier)
- estimated_wei = estimated_gas * (self.tx['maxPriorityFeePerGas'] + self.tx['maxFeePerGas'])
- estimated_eth = estimated_wei / (10 ** 18)
- msg = f"估算的燃气量: {estimated_gas}, eth消耗: {estimated_eth},gas估算通過"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # step3, 費用與利潤比較
- LIMIT = 0.005
- if estimated_eth > LIMIT:
- msg = f"TODO: 費用判斷不通過,費用還是固定值,建議改成與ETH價格挂鈎的值,方便設定利潤!LIMIT:{LIMIT}, estimated_eth: {estimated_eth}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_REJECT)
- return
- msg = f"TODO: 費用判斷通過,費用還是固定值,建議改成與ETH價格挂鈎的值,方便設定利潤!LIMIT:{LIMIT}, estimated_eth: {estimated_eth}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # step4, 與賬戶eth餘額比對(至少留0.001,不然沒gas了)
- MARGIN = 0.001
- eth_balance_origin = web3.w3.eth.get_balance(self.user_wallet)
- eth_balance = eth_balance_origin / (10 ** 18)
- if eth_balance - estimated_eth < MARGIN:
- msg = f"gas餘額判斷不通過! MARGIN:{MARGIN}, estimated_eth: {estimated_eth}, eth_balance: {eth_balance}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_REJECT)
- return
- msg = f"gas餘額判斷通過! MARGIN:{MARGIN}, estimated_eth: {estimated_eth}, eth_balance: {eth_balance}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # final, 設定交易狀態,開始交易
- self._set_state(self.STATE_SELLING_ON_EXCHANGE)
- except Exception as e:
- msg = f"前置檢查未通過:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_REJECT)
- # 以下是每个状态对应的具体执行函数
- def _execute_sell_on_exchange(self):
- """
- 在中心化交易所卖出现货
- """
- msg = "执行:中心化交易所卖出现货..."
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- # 第一步直接卖出,这个数量用固定数量
- pseudo_amount_to_sell = self.arbitrage_details["exchange_out_amount"]
- # 处理精度
- pseudo_amount_to_sell = pseudo_amount_to_sell.quantize(Decimal('1'), rounding=ROUND_DOWN)
-
- # # 链上余额判断
- # from_token_balance = web3.get_erc20_balance(self.from_token_addr, self.user_wallet)
-
- # if from_token_balance < self.arbitrage_details["chain_usdt_use"]:
- # msg = f"链上剩余{self.base_coin}: {from_token_balance}, 需要使用:{self.arbitrage_details["chain_usdt_use"]}, 余额不足,不能触发交易。"
- # logging.info(msg)
- # add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- # self._set_state(self.STATE_FAILED)
- # return
- # msg = f"链上剩余{self.base_coin}: {from_token_balance}, 需要使用:{self.arbitrage_details["chain_usdt_use"]}, 余额充足。"
- # logging.info(msg)
- # add_state_flow_entry(self.process_item, self.current_state, msg, "success")
-
- order_params = {
- "symbol": self.symbol.replace('_', ''),
- "side": "SELL",
- "type": "MARKET",
- "quantity": int(pseudo_amount_to_sell),
- }
- logging.info(order_params)
- exchange_sell_order = mexc.trade.post_order(order_params)
- if 'orderId' not in exchange_sell_order:
- msg = f"交易所现货卖出下单失败:{exchange_sell_order}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- return
- exchange_sell_order_id = exchange_sell_order['orderId']
-
- msg = f"交易所现货卖出订单已发送, 订单ID: {exchange_sell_order_id}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self.arbitrage_details["exchange_sell_order_id"] = exchange_sell_order_id
- self._set_state(self.STATE_WAITING_SELL_CONFIRM)
- except Exception as e:
- msg = f"交易所现货卖出下单失败:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- def _wait_sell_confirm(self):
- """
- 等待交易所现货卖出订单确认(完全成交)
- """
- exchange_sell_order_id = self.arbitrage_details["exchange_sell_order_id"]
- msg = f"等待交易所现货卖出订单确认:{exchange_sell_order_id}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- last_order = None
- try:
- # 查询交易所订单状态
- waiting_times = 30
- while waiting_times > 0:
- params = {
- "symbol": self.symbol.replace('_', ''),
- "orderId": exchange_sell_order_id
- }
- order = mexc.trade.get_order(params)
- last_order = order
- if order['status'] in ["FILLED", "PARTIALLY_CANCELED"]:
- money = Decimal(order['cummulativeQuoteQty'])
- amount = self.arbitrage_details["exchange_out_amount"]
- self.sell_price = money / amount
- self.sell_price = self.sell_price.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
- msg = f"交易所现货卖出订单已完成, 价格:{self.sell_price}。{order}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self.arbitrage_details["exchange_withdraw_amount"] = order['cummulativeQuoteQty']
- self._set_state(self.STATE_BUYING_ON_CHAIN)
- return
- else:
- time.sleep(1)
- waiting_times = waiting_times - 1
- msg = f"交易所现货卖出订单失敗, 最後狀態:{last_order}。"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.FAILED)
- except Exception as e:
- msg = f"查询交易所现货卖出订单状态时发生错误:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- def _execute_buy_on_chain(self):
- """
- 在链上执行买入操作
- """
- msg = "执行:链上买入操作..."
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- self.arbitrage_details["chain_amount_before_trade"] = web3.get_erc20_balance(self.to_token_addr, self.user_exchange_wallet)
- # 调用链上客户端执行买入交易
- chain_buy_tx_hash = web3._sign_and_send_transaction(
- self.tx,
- self.gas_limit_multiplier
- )
- # 交易成功
- msg = f"链上买入交易已发送,交易哈希:{chain_buy_tx_hash}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self.arbitrage_details["chain_buy_tx_hash"] = chain_buy_tx_hash
- self._set_state(self.STATE_WAITING_CHAIN_CONFIRM)
- except Exception as e:
- msg = f"链上买入失败:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
- def _wait_chain_confirm(self):
- """
- 等待链上交易确认
- """
- hash = self.arbitrage_details["chain_buy_tx_hash"]
- msg = f"等待链上交易确认:{hash}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- # 查询链上交易确认状态
- receipt = web3.wait_for_transaction_receipt(hash, timeout=300)
- if receipt.status == 1:
- # 在这里根据实际链上交易结果更新实际买入数量,用于后续流程
- # 这里要用确认后数量减去确认前数量,才知道具体买入了多少
- # TODO 卡這裏了 這個方案不太好啊,要不直接獲取交易所充值信息得了
- actual_buy_amount = Decimal(0)
- while True:
- self.arbitrage_details["chain_amount_after_trade"] = web3.get_erc20_balance(self.to_token_addr, self.user_exchange_wallet)
-
- actual_buy_amount = self.arbitrage_details["chain_amount_after_trade"] - self.arbitrage_details["chain_amount_before_trade"]
- if actual_buy_amount > Decimal(0):
- break
-
- time.sleep(1)
- buy_amount_human = actual_buy_amount.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
- sell_amount_human = self.arbitrage_details["chain_usdt_use"]
- self.arbitrage_details["chain_buy_amount"] = buy_amount_human # 存储实际买入数量
- self.buy_price = sell_amount_human / buy_amount_human
- self.buy_price = self.buy_price.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
- rate = self.sell_price / self.buy_price
- rate = rate.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
- msg = f"【比率{rate}】。链上交易已确认。用{sell_amount_human}买入{buy_amount_human},价格{self.buy_price}。"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_WAITING_TRANSFER_ARRIVE)
- else:
- msg = f"链上交易确认失败:{hash}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
- except Exception as e:
- msg = f"查询链上确认状态时发生错误:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
- def _wait_exchange_rollback(self):
- """
- 市价进行交易所交易回滚
- """
- msg = "执行:中心化交易所买入现货回滚..."
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- # 使用预提现数量进行回滚
- pseudo_amount_to_buy = Decimal(self.arbitrage_details["exchange_withdraw_amount"])
- # 处理精度
- pseudo_amount_to_buy = pseudo_amount_to_buy.quantize(Decimal('1'), rounding=ROUND_DOWN)
- # 交易所U余额判断
- balances = mexc.trade.get_account_info()['balances']
- for balance in balances:
- if balance['asset'] == self.base_coin:
- pseudo_amount_to_buy = min(Decimal(balance['free']), pseudo_amount_to_buy)
- if pseudo_amount_to_buy < Decimal('10'):
- msg = f"交易所剩余{self.base_coin}: {balance['free']}, 小于10, 不能触发回滚交易。"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- return
- else:
- msg = f"交易所剩余{self.base_coin}: {balance['free']}, 交易所准备使用:{pseudo_amount_to_buy}, 余额校验通过(可以回滚)。"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- break
-
- order_params = {
- "symbol": self.symbol.replace('_', ''),
- "side": "BUY",
- "type": "MARKET",
- "quoteOrderQty": int(pseudo_amount_to_buy),
- }
- logging.info(order_params)
- exchange_buy_order = mexc.trade.post_order(order_params)
- if 'orderId' not in exchange_buy_order:
- msg = f"【回滚】交易所现货买入下单失败:{exchange_buy_order}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- return
- exchange_buy_order_id = exchange_buy_order['orderId']
-
- msg = f"【回滚】交易所现货买入订单已发送, 订单ID: {exchange_buy_order_id}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # 查询交易所订单状态
- waiting_times = 30
- last_query_rst = None
- while True:
- params = {
- "symbol": self.symbol.replace('_', ''),
- "orderId": exchange_buy_order_id
- }
- order = mexc.trade.get_order(params)
- last_query_rst = order
- if order['status'] == "FILLED":
- money = Decimal(order['cummulativeQuoteQty'])
- amount = self.arbitrage_details["exchange_out_amount"]
- price = money / amount
- price = price.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
- msg = f"【回滚】交易所现货买入订单已完全成交, 价格:{price}。{order}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_FAILED)
- return
- else:
- # 继续等待成交
- pass
- time.sleep(1)
- waiting_times = waiting_times - 1
-
- msg = f"【回滚】回滚交易订单查询超时, 订单ID: {exchange_buy_order_id},最终状态:{last_query_rst}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- except Exception as e:
- msg = f"【回滚】交易所回滚交易失败:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- def _wait_transfer_arrive(self):
- """
- 等待资产在交易所内到账
- """
- msg = f"等待资产在交易所到账..."
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- is_arrived = False
- # 先進行快速提現判斷,如果不滿足條件就走後面的等待充值模式,雙模,這個步驟最多等待10分鐘
- waiting_times = 10
- last_deposit_state = None
- while waiting_times > 0:
- time.sleep(60)
- deposit_list = mexc.wallet.get_deposit_list()
- # 是否已經在列表中了,抹茶識別充值會稍微有點慢,所以要耐心等
- is_list = False
- # pending中的數量
- pending_amount = Decimal(0)
- for deposit in deposit_list:
- # 不屬于該路徑需要監聽的代幣
- if deposit['coin'] != self.coin:
- continue
- # 處理pending數量
- if Decimal(deposit['confirmTimes']) < Decimal(deposit['unlockConfirm']):
- pending_amount = pending_amount + Decimal(deposit['amount'])
- # 檢查到沒到列表中
- if deposit['transHash'] != self.arbitrage_details['chain_buy_tx_hash']:
- continue
- last_deposit_state = deposit
- is_list = True
-
- # 檢查是否滿足快速提現的條件
- if is_list:
- # 交易所代幣余额判断
- balances = mexc.trade.get_account_info()['balances']
- asset_balance = 0
- for balance in balances:
- if balance['asset'] == self.coin:
- asset_balance = Decimal(balance['free'])
-
- # 最終判斷
- if asset_balance > pending_amount:
- msg = f"【flash】资产可以進行快速提現。{last_deposit_state}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_TRANSFERRING_TO_CHAIN)
- return
-
- logging.info(f"正在檢查快速提現條件...({waiting_times}/10)")
- waiting_times = waiting_times - 1
- # 最多等待30分钟
- waiting_times = 30
- last_deposit_state = None
- while waiting_times > 0:
- deposit_list = mexc.wallet.get_deposit_list()
- for deposit in deposit_list:
- if deposit['transHash'] != self.arbitrage_details['chain_buy_tx_hash']:
- continue
- last_deposit_state = deposit
- logging.info(f"等待资产在交易所到账...({deposit['confirmTimes']}/{deposit['unlockConfirm']})")
- if Decimal(deposit['confirmTimes']) >= Decimal(deposit['unlockConfirm']):
- is_arrived = True
- if is_arrived:
- msg = f"资产已在交易所到账。{last_deposit_state}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_TRANSFERRING_TO_CHAIN)
- return
-
- time.sleep(60)
- waiting_times = waiting_times - 1
- msg = f"等待充值到账超时(超过30分钟): {last_deposit_state}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- except Exception as e:
- msg = f"查询交易所到账状态时发生错误:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- def _execute_transfer_to_chain(self):
- """
- 将交易后获得的计价资产(例如USDT)转账回链上
- """
- msg = "执行:交易所计价资产转账回链上..."
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- # times = 10
- # while times > 0:
- # balances = mexc.trade.get_account_info()['balances']
- # for balance in balances:
- # if balance['asset'] == 'USDT':
- pseudo_withdraw_amount = str(int(float(self.arbitrage_details["exchange_withdraw_amount"])))
- withdraw_params = {
- 'coin': 'USDT',
- 'netWork': 'ETH',
- 'address': self.user_wallet,
- 'amount': pseudo_withdraw_amount
- }
- withdraw_rst = mexc.wallet.post_withdraw(withdraw_params)
- if "id" not in withdraw_rst:
- logging.error(f"提现失败")
- logging.error(withdraw_params)
- logging.error(withdraw_rst)
- exchange_withdrawal_id = withdraw_rst["id"]
- msg = f"交易所提现已发送, 提现ID: {exchange_withdrawal_id}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self.arbitrage_details["exchange_withdrawl_id"] = withdraw_rst["id"]
- self._set_state(self.STATE_WAITING_WITHDRAWAL_CONFIRM)
- except Exception as e:
- msg = f"转账回链上失败:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- def _wait_withdrawal_confirm(self):
- """
- 等待交易所提现到链上确认
- """
- exchange_withdrawl_id = self.arbitrage_details['exchange_withdrawl_id']
- msg = f"等待交易所提现确认:{exchange_withdrawl_id}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- is_arrived = False
- # 最多等待30分钟
- waiting_times = 60
- last_deposit_state = None
- while waiting_times > 0:
- withdraw_list = mexc.wallet.get_withdraw_list()
- if not isinstance(withdraw_list, list):
- msg = f"查询交易所提现状态时发生错误:{withdraw_list}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- return
- for withdraw in withdraw_list:
- if withdraw['id'] != exchange_withdrawl_id:
- continue
- last_deposit_state = withdraw
- if withdraw['status'] == 7:
- is_arrived = True
- if is_arrived:
- msg = f"提现请求已上链: {last_deposit_state}"
- logging.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_COMPLETED)
- return
-
- time.sleep(30)
- waiting_times = waiting_times - 1
- msg = f"等待提现到账超时(超过30分钟): {last_deposit_state}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- except Exception as e:
- msg = f"查询交易所提现状态时发生错误:{e}"
- logging.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
-
- self._set_state("FAILED")
- # 伪代码示例:如何使用这个类
- if __name__ == "__main__":
- import ok_chain_client
- import decimal
- import pprint
- CHAIN_ID = 1
- FROM_TOKEN = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
- FROM_TOKEN_AMOUNT_HUMAM = Decimal('20')
- FROM_TOKEN_DECIMAL = 6
- TO_TOKEN = '0xf816507E690f5Aa4E29d164885EB5fa7a5627860'
- USER_WALLET = '0xb1f33026Db86a86372493a3B124d7123e9045Bb4'
- USER_EXCHANGE_WALLET = '0xc71835a042F4d870B0F4296cc89cAeb921a9f3DA'
- SYMBOL = "RATO_USDT"
- # 询价,注意!!!这里直接把交易所地址当收款方,省去transfer的流程
- data = ok_chain_client.swap(CHAIN_ID,
- FROM_TOKEN_AMOUNT_HUMAM * (10 ** FROM_TOKEN_DECIMAL),
- FROM_TOKEN,
- TO_TOKEN,
- 1,
- USER_WALLET,
- USER_EXCHANGE_WALLET, # 这里直接把交易所地址当收款方,省去transfer的流程!!!
- )
- if data.get('code') != '0' or not data.get('data'):
- pprint.pprint(data)
- pprint.pprint({
- "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 '格式错误'}"})
- raise Exception("")
- d = data['data'][0]
- tx = d['tx']
- router_result = d['routerResult']
- in_dec, out_dec = int(router_result['fromToken']['decimal']), int(router_result['toToken']['decimal'])
- atomic_in_base, atomic_out_target = Decimal(router_result['fromTokenAmount']), Decimal(router_result['toTokenAmount'])
- human_in_base = atomic_in_base / (10 ** in_dec)
- human_out_target = atomic_out_target / (10 ** out_dec)
- FROM_TOKEN_AMOUNT_HUMAM = human_in_base
- TO_TOKEN_AMOUNT_HUMAM = human_out_target
- pprint.pprint(tx)
- # 套利流程执行
- process_item = {
- "stateFlow": [], # 状态流转记录
- }
- ap = ArbitrageProcess(tx, 2, 1.2,
- FROM_TOKEN, TO_TOKEN,
- FROM_TOKEN_AMOUNT_HUMAM, TO_TOKEN_AMOUNT_HUMAM,
- USER_EXCHANGE_WALLET, USER_WALLET,
- SYMBOL, process_item)
- # 一般都是从这个流程开始,测试时可以稍作修改、测试后续流程
- ap._set_state(ap.SELLING_ON_EXCHANGE)
- # 在主循环中周期性调用 run_arbitrage_step
- while ap.current_state != "COMPLETED" and ap.current_state != "FAILED":
- ap.run_arbitrage_step()
- if ap.current_state == ap.STATE_WAITING_TRANSFER_ARRIVE or ap.current_state == ap.STATE_WAITING_WITHDRAWAL_CONFIRM:
- time.sleep(10)
- # else:
- # time.sleep(1)
- logging.info(process_item)
- if ap.current_state == "COMPLETED":
- logging.info("套利流程执行成功!")
- else:
- logging.info("套利流程执行失败!")
|