| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902 |
- import time
- import traceback
- import copy
- import os
- from web3_py_client import EthClient
- from mexc_client import MexcClient
- from decimal import Decimal, ROUND_DOWN
- from as_utils import add_state_flow_entry
- from checker.logger_config import get_logger
- from pprint import pformat
- web3 = EthClient()
- web3_backup = EthClient(os.getenv("RPC_URL_2"))
- mexc = MexcClient()
- # 配置日志
- logger = get_logger('as')
- class ArbitrageProcess:
- def __init__(self, gas_limit_multiplier, gas_price_multiplier, process_item,
- core_data, core_lock,
- pending_data, pending_lock,
- mexc_data, mexc_lock,
- ):
- """
- 初始化套利流程
- Args:
- gas_limit_multiplier: gas limit倍数, 一般都不加倍
- gas_price_multiplier: gas price倍数, 可以提高交易成功率
- process_item: 信號發送端傳入的原始參數
- """
- self.NETWORK = 'ETH'
- tx = process_item['tx']
- 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.core_data = core_data
- self.core_lock = core_lock
- self.pending_data = pending_data
- self.pending_lock = pending_lock
- self.mexc_data = mexc_data
- self.mexc_lock = mexc_lock
- # symbol轉大寫
- self.symbol = process_item['symbol'].upper()
- self.coin = self.symbol.split('_')[0]
- self.base_coin = self.symbol.split('_')[1]
- with self.core_lock:
- self.eth_price = self.core_data['eth_price']
-
- with self.mexc_lock:
- self.withdraw_info = copy.deepcopy(self.mexc_data['coin_info_map'][self.coin][self.NETWORK])
- self.WITHDRAW_FEE = Decimal(self.withdraw_info['withdrawFee']) # 提現手續費
- self.WITHDRAW_ENABLE = self.withdraw_info['withdrawEnable'] # 是否启用提现
- withdraw_info_formated = pformat(self.withdraw_info, indent=2)
- logger.info(f'提現信息識別, 手續費:{self.WITHDRAW_FEE}\n{withdraw_info_formated}')
- self.tx = tx
-
- self.mexc_price = Decimal(process_item['cexPrice'])
- self.profit = Decimal(process_item['profit']) # 這個利潤是實際到手利潤
- self.profit_limit = Decimal(process_item['profitLimit']) # 這個利潤是實際到手利潤的limit
- self.gas_limit_multiplier = gas_limit_multiplier
- self.gas_price_multiplier = gas_price_multiplier
- self.from_token_addr = process_item['fromToken']
- self.from_token_decimal = Decimal(process_item['fromTokenDecimal'])
- self.to_token_addr = process_item['toToken']
- self.to_token_decimal = Decimal(process_item['toTokenDecimal'])
- self.user_exchange_wallet = process_item['userExchangeWallet']
- self.user_wallet = process_item['userWallet']
- self.process_item = process_item
- # 存储当前套利交易的细节信息,例如买入数量、价格等
- self.sell_price = Decimal(0)
- self.sell_value = Decimal(0)
- self.buy_price = Decimal(0)
- self.buy_value = Decimal(0)
- self.chain_tx_hash = None # 链上卖出的tx hash
- self.exchange_buy_amount = Decimal(process_item['fromTokenAmountHuman']) # 交易所买入量
- self.exchange_buy_amount = self.exchange_buy_amount + self.WITHDRAW_FEE # 买入量考虑提现手续费
- self.already_bought_amount = Decimal(0)
- self.exchange_withdrawal_id = None # 交易所提现id
- self.exchange_withdrawal_amount = None # 交易所提现数量
- self.actual_profit = Decimal(0) # 實際利潤
- # 定义可能的状态
- self.STATES = [
- "CHECK", # 检查余额、估算gas等
- "BUYING_ON_EXCHANGE", # 正在中心化交易所买入现货
- "WAITING_BUY_CONFIRM", # 等待现货买入订单确认
- "SELLING_ON_CHAIN", # 正在链上卖出
- "WAITING_CHAIN_CONFIRM", # 等待链上交易确认
- "WAITING_EXCHANGE_ROLLBACK", # 等待交易所回滚
- "WAITING_TRANSFER_ARRIVE", # 等待交易所到账
- "TRANSFERRING_TO_CHAIN", # 正在向链上转账
- "WAITING_WITHDRAWAL_CONFIRM", # 等待链上提现确认
- "COMPLETED", # 套利流程完成
- "REJECT", # 套利被程序拒绝
- "FAILED" # 套利流程失败
- ]
- self.STATE_IDLE = "IDLE"
- self.STATE_CHECK = "CHECK"
- self.STATE_BUYING_ON_EXCHANGE = "BUYING_ON_EXCHANGE"
- # self.STATE_WAITING_BUY_CONFIRM = "WAITING_BUY_CONFIRM"
- self.STATE_SELLING_ON_CHAIN = "SELLING_ON_CHAIN"
- self.STATE_WAITING_CHAIN_CONFIRM = "WAITING_CHAIN_CONFIRM"
- self.STATE_WAITING_EXCHANGE_ROLLBACK = "WAITING_EXCHANGE_ROLLBACK"
- 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 = self.STATE_IDLE
- exchange_info_params = {
- "symbols": self.symbol.replace('_', '')
- }
- exchange_info_rst = mexc.market.get_exchangeInfo(exchange_info_params)
- # 返回值检查
- if 'symbols' not in exchange_info_rst or len(exchange_info_rst['symbols']) != 1:
- params_formated = pformat(exchange_info_params, indent=2)
- info_formated = pformat(exchange_info_rst, indent=2)
- msg = f'获取交易规则时出现错误\n{exchange_info_params}\n{info_formated}'
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self.current_state = self.STATE_FAILED
- return
- # 返回的交易对信息核对]
- exchange_info = exchange_info_rst['symbols'][0]
- if exchange_info['symbol'].upper() != self.symbol.replace('_', ''):
- info_formated = pformat(exchange_info, indent=2)
- msg = f'获取到的交易规则与交易币对无关\n{info_formated}'
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self.current_state = self.STATE_FAILED
- return
-
- # 精度取得, 假如是RATOUSDT这个交易对的话:
- self.coin_asset_precision = Decimal(f'1e-{exchange_info['baseAssetPrecision']}') # 这是RATO的精度
- self.base_coin_asset_precision = Decimal(f'1e-{exchange_info['quoteAssetPrecision']}') # 这是USDT的精度
- self.price_precision = Decimal(f'1e-{exchange_info['quotePrecision']}') # 这是价格的精度
- def _set_state(self, state):
- """
- 设置系统状态,并打印日志
- """
- if state in self.STATES:
- logger.info(f"状态变更:{self.current_state} -> {state}")
- logger.info('')
- self.current_state = state
- else:
- logger.error(f"尝试设置无效状态:{state}")
- def run_arbitrage_step(self):
- """
- 根据当前状态执行套利流程的下一步
- 这是一个周期性调用的函数,例如在主循环中调用
- """
- if self.current_state == self.STATE_CHECK:
- self._execute_check()
- elif self.current_state == self.STATE_BUYING_ON_EXCHANGE:
- self._execute_buy_on_exchange()
- elif self.current_state == self.STATE_SELLING_ON_CHAIN:
- self._selling_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 == 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 = "套利流程成功完成!"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- elif self.current_state == self.STATE_REJECT:
- msg = "套利流程被程序拒绝"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- elif self.current_state == self.STATE_FAILED:
- msg = "套利流程失败!"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- def _execute_check(self):
- """
- 前置检查,防止低能错误
- """
- try:
- # step1,檢查交易所的餘額是否夠用,给2%的余量
- pseudo_value_to_buy = (self.exchange_buy_amount * self.mexc_price) * Decimal(1.02)
- pseudo_value_to_buy = pseudo_value_to_buy.quantize(self.coin_asset_precision, rounding=ROUND_DOWN)
-
- # 交易所套保余额判断
- with self.mexc_lock:
- balances = self.mexc_data['account_info']['balances']
- for balance in balances:
- if balance['asset'] == self.base_coin:
- if Decimal(balance['free']) < pseudo_value_to_buy:
- msg = f"交易所剩余{self.base_coin}: {balance['free']}, 买入要使用:{pseudo_value_to_buy}, 不能触发交易。"
- logger.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.base_coin}: {balance['free']}, 买入要使用:{pseudo_value_to_buy}, 余额校验通过。"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- break
- # 检查该币对是否有提现权限
- if not self.WITHDRAW_ENABLE:
- coin_info_formated = pformat(self.withdraw_info, indent=2)
- msg = f"{self.coin}不允许提现。\n{coin_info_formated}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_REJECT)
- return
- # step2,估算gas
- logger.info("獲取區塊信息")
- with self.core_lock:
- latest_block = copy.deepcopy(self.core_data['block'])
- self.tx['maxPriorityFeePerGas'] = int(int(self.tx['maxPriorityFeePerGas']) * self.gas_price_multiplier)
- self.tx['maxFeePerGas'] = int(int(latest_block['baseFeePerGas']) * 2 + self.tx['maxPriorityFeePerGas'])
- gas_price = Decimal(self.tx['maxPriorityFeePerGas'] + self.tx['maxFeePerGas'])
- gas_price_gwei = gas_price / Decimal('1e9')
- gas_price_gwei = gas_price_gwei.quantize(Decimal('1e-9'), rounding=ROUND_DOWN)
- tx_formated = pformat(self.tx, indent=2)
- logger.info(f"鏈上各種校驗\n{tx_formated}")
- estimated_gas_origin = web3.w3.eth.estimate_gas(self.tx)
- estimated_gas = int(estimated_gas_origin * self.gas_limit_multiplier)
- estimated_wei = Decimal(estimated_gas) * gas_price
- estimated_eth = Decimal(estimated_wei / Decimal('1e18')) / Decimal(2) # 除以2才是比較接近正常消耗的gas費,否則會過於高估
- estimated_eth = estimated_eth.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
- msg = f"估算的燃气量: {estimated_gas}, eth消耗: {estimated_eth}, gas price: {gas_price_gwei} gwei, gas估算通過"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # step3, 費用與利潤比較
- estimated_eth_value = estimated_eth * self.eth_price
- estimated_eth_value = estimated_eth_value.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
- cost = estimated_eth_value + self.WITHDRAW_FEE * self.mexc_price # 成本
- if self.profit < cost:
- msg = f"費用判斷不通過! profit: {self.profit}, eth_value:{estimated_eth_value}, eth: {estimated_eth}, eth_price: {self.eth_price}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_REJECT)
- return
- msg = f"費用判斷通過! profit: {self.profit}, eth_value:{estimated_eth_value}, eth: {estimated_eth}, eth_price: {self.eth_price}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # step4, 與賬戶eth餘額比對(至少留0.002,不然沒gas了)
- MARGIN = Decimal(0.002)
- # 暫時鎖住core_data
- with self.core_lock:
- eth_balance = self.core_data['eth_balance']
- if eth_balance - estimated_eth < MARGIN:
- msg = f"gas餘額判斷不通過! MARGIN:{MARGIN}, estimated_eth: {estimated_eth}, eth_balance: {eth_balance}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_REJECT)
- return
-
- # 餘額判斷通過后預扣除balance,防止綫程更新不及時導致其他綫程誤發送tx
- self.core_data['eth_balance'] = self.core_data['eth_balance'] - estimated_eth
- msg = f"gas餘額判斷通過! MARGIN:{MARGIN}, estimated_eth: {estimated_eth}, eth_balance: {eth_balance}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # final, 設定交易狀態,開始交易
- self._set_state(self.STATE_BUYING_ON_EXCHANGE)
- except Exception as e:
- exc_traceback = traceback.format_exc()
- msg = f"前置檢查未通過\n{exc_traceback}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_REJECT)
- # traceback.print_exc()
- # 以下是每个状态对应的具体执行函数
- def _execute_buy_on_exchange(self):
- """
- 在中心化交易所买入现货
- """
- msg = "执行:中心化交易所买入现货..."
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- order_times = 0
- self.already_bought_amount = Decimal(0)
- while self.already_bought_amount < self.exchange_buy_amount and order_times < 5:
- order_times = order_times + 1
- # 第一步直接买入,这个数量用固定数量
- pseudo_amount_to_buy = self.exchange_buy_amount - self.already_bought_amount
- # 处理精度
- pseudo_amount_to_buy = pseudo_amount_to_buy.quantize(self.coin_asset_precision, rounding=ROUND_DOWN)
- # 初始化 quantity 变量
- quantity_for_api = None
- # 用求余法判断是否是整数
- if pseudo_amount_to_buy % 1 == 0:
- # 如果是整数,转换为 int 类型。某些API可能只接受整数交易对的整数数量
- quantity_for_api = int(pseudo_amount_to_buy)
- else:
- # 如果是非整数,转换为 float 类型。这是最常见的API数量类型
- quantity_for_api = float(pseudo_amount_to_buy)
- order_params = {
- "symbol": self.symbol.replace('_', ''),
- "side": "BUY",
- "type": "MARKET",
- "quantity": quantity_for_api, # 以【幣】的數量進行買入
- }
- order_params_formated = pformat(order_params, indent=2)
-
- exchange_buy_order = mexc.trade.post_order(order_params)
- exchange_buy_order_formated = pformat(exchange_buy_order, indent=2)
- msg = f"[{order_times}]交易所现货买入订单已发送 \n params:{order_params_formated} \n rst: {exchange_buy_order_formated}"
- if 'orderId' not in exchange_buy_order:
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- continue
- # 查询交易所订单状态
- exchange_buy_order_id = exchange_buy_order['orderId']
- waiting_times = 5
- while waiting_times > 0:
- params = {
- "symbol": self.symbol.replace('_', ''),
- "orderId": exchange_buy_order_id
- }
- order = mexc.trade.get_order(params)
- if order['status'] in ["FILLED", "PARTIALLY_CANCELED"]:
- # 以实际成交数量为准
- money = Decimal(order['cummulativeQuoteQty'])
- self.already_bought_amount = self.already_bought_amount + Decimal(order['executedQty'])
- self.buy_value = self.buy_value + money
- self.buy_price = self.buy_value / self.already_bought_amount
- self.buy_price = self.buy_price.quantize(self.price_precision, rounding=ROUND_DOWN)
- order_formated = pformat(order, indent=2)
- msg = f"交易所现货买入订单已完成, 价格:{self.buy_price}, money: {money}\n order: {order_formated}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self.exchange_withdrawal_amount = self.already_bought_amount
- break
- else:
- time.sleep(1)
- waiting_times = waiting_times - 1
-
- if order_times < 5:
- msg = 'mexc现货买入流程完成'
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_SELLING_ON_CHAIN)
- else:
- msg = 'mexc现货买入流程失败, 重试次数大于5'
- logger.info(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:
- exc_traceback = traceback.format_exc()
- msg = f"交易所现货买入下单失败\n{exc_traceback}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- # traceback.print_exc()
- def _selling_on_chain(self):
- """
- 在链上执行卖出操作
- """
- msg = "执行:链上卖出操作..."
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- # 交易前nonce
- with self.core_lock:
- self.tx['nonce'] = self.core_data['nonce']
-
- # 调用链上客户端执行卖出交易
- signed_tx = web3._sign(self.tx, self.gas_limit_multiplier)
- self.chain_tx_hash = web3.w3.to_hex(signed_tx.hash)
- try:
- # 主要节点先发交易
- web3.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
- # 使用备用节点再发一次交易
- web3_backup.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
- except Exception as e:
- msg = f"据反饋說链上卖出失败:{e}, 交易哈希:{self.chain_tx_hash}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- # 交易成功后刷新全局nonce
- with self.core_lock:
- self.core_data['nonce'] = self.core_data['nonce'] + 1
- block_number = self.core_data['block_number']
-
- # 將hash放入pending裏,等待確認
- with self.pending_lock:
- self.pending_data[self.chain_tx_hash] = {
- "block_number": block_number,
- "tx_details": None,
- "reponse": None,
- }
- # 交易成功
- msg = f"再次確認交易是否上鏈:{self.chain_tx_hash}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_WAITING_CHAIN_CONFIRM)
- except Exception as e:
- exc_traceback = traceback.format_exc()
- msg = f"鏈上買入未處理的錯誤, 交易哈希:{self.chain_tx_hash}\n{exc_traceback}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_WAITING_CHAIN_CONFIRM)
- # traceback.print_exc()
- def _wait_chain_confirm(self):
- """
- 等待链上交易确认
- """
- chain_tx_hash = self.chain_tx_hash
- msg = f"等待链上交易确认:{chain_tx_hash}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- # 給120秒時間進行確認
- waiting_times = 120
- while waiting_times > 0:
- with self.pending_lock:
- tx_details = copy.deepcopy(self.pending_data[chain_tx_hash]['tx_details'])
- if tx_details is None:
- waiting_times = waiting_times - 1
- time.sleep(1)
- continue
- # # 交易確認后,移除出pending列表
- # with self.pending_lock:
- # del self.pending_data[chain_tx_hash]
- # 交易失敗的邏輯處理,直接進行回滾
- if 'fromTokenDetails' not in tx_details \
- or 'toTokenDetails' not in tx_details:
- msg = f"链上交易失敗。{tx_details}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
- break
- tx_details_formated = pformat(tx_details, indent=2)
- msg = f"链上交易已确认。\n details: {tx_details_formated}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # 獲取交易信息
- from_token_details = tx_details['fromTokenDetails']
- to_token_details = tx_details['toTokenDetails']
- from_token_amount = Decimal(from_token_details['amount'])
- from_token_amount_human = from_token_amount / (Decimal(10) ** self.from_token_decimal)
- from_token_amount_human = from_token_amount_human.quantize(self.coin_asset_precision, rounding=ROUND_DOWN)
- to_token_amount = Decimal(to_token_details['amount'])
- to_token_amount_human = to_token_amount / (Decimal(10) ** self.to_token_decimal)
- to_token_amount_human = to_token_amount_human.quantize(self.base_coin_asset_precision, rounding=ROUND_DOWN)
- self.sell_value = to_token_amount_human
- self.sell_price = to_token_amount_human / from_token_amount_human
- self.sell_price = self.sell_price.quantize(self.price_precision, rounding=ROUND_DOWN)
- # 交易預估利潤百分比計算
- rate = self.sell_price / self.buy_price
- rate = rate.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
- msg = f"【比率{rate}】。用{from_token_amount_human}卖出{to_token_amount_human},价格{self.sell_price}。"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # 計算實際利潤
- value = self.sell_value - self.buy_value
- actual_gas_price = Decimal(tx_details['gasPrice'])
- actual_gas_price_gwei = actual_gas_price / Decimal('1e9')
- actual_gas_price_gwei = actual_gas_price_gwei.quantize(Decimal('1e-9'), rounding=ROUND_DOWN)
- actual_gas_used = Decimal(tx_details['gasUsed'])
- actual_wei = actual_gas_price * actual_gas_used
- actual_eth = actual_wei / Decimal('1e18')
- actual_eth = actual_eth.quantize(Decimal('1e-8'), rounding=ROUND_DOWN)
- actual_fee_used = actual_eth * self.eth_price
- actual_fee_used = actual_fee_used.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
- actual_profit = value - actual_fee_used - self.WITHDRAW_FEE * self.mexc_price
- msg = f"【最終利潤】{actual_profit}{self.base_coin}(已扣除所有手續費、滑點)\
- \n鏈上ETH使用: {actual_eth}({actual_fee_used} USD), gas_price: {actual_gas_price_gwei} GWEI, gas_used: {actual_gas_used}\
- \n交易所出售代幣利潤: {value}, 提現手續費: {self.WITHDRAW_FEE}\
- "
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_WAITING_TRANSFER_ARRIVE)
- break
-
- # 如果120秒都沒確認成功,該交易大概率沒有上鏈
- if waiting_times <= 0:
- with self.pending_lock:
- response = copy.deepcopy(self.pending_data[chain_tx_hash])
- response_formated = pformat(response, indent=2)
- msg = f"链上交易确认失败:{chain_tx_hash}\n{response_formated}"
- logger.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:
- exc_traceback = traceback.format_exc()
- msg = f"查询链上确认状态时发生错误\n{exc_traceback}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_WAITING_EXCHANGE_ROLLBACK)
- # traceback.print_exc()
- def _wait_exchange_rollback(self):
- """
- 市价进行交易所交易回滚
- """
- msg = "执行:中心化交易所卖出现货回滚..."
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- # 使用预提现数量进行回滚
- pseudo_amount_to_sell = Decimal(self.already_bought_amount)
- # 处理精度
- pseudo_amount_to_sell = pseudo_amount_to_sell.quantize(self.coin_asset_precision, rounding=ROUND_DOWN)
- # 交易所币余额判断
- with self.mexc_lock:
- balances = self.mexc_data['account_info']['balances']
- for balance in balances:
- if balance['asset'] == self.coin:
- pseudo_amount_to_sell = min(Decimal(balance['free']), pseudo_amount_to_sell)
- if pseudo_amount_to_sell * self.mexc_price < Decimal('10'):
- msg = f"交易所剩余{self.coin}: {balance['free']}, 小于10, 不能触发回滚交易。"
- logger.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.coin}: {balance['free']}, 交易所准备使用:{pseudo_amount_to_sell}, 余额校验通过(可以回滚)。"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- break
-
- ready_to_sell = pseudo_amount_to_sell
- order_params = {
- "symbol": self.symbol.replace('_', ''),
- "side": "SELL",
- "price": self.buy_price,
- "type": "LIMIT",
- "quantity": float(pseudo_amount_to_sell),
- }
- order_params_formated = pformat(order_params, indent=2)
- exchange_sell_order = mexc.trade.post_order(order_params)
- exchange_sell_order_formated = pformat(exchange_sell_order, indent=2)
- if 'orderId' not in exchange_sell_order:
- msg = f"【回滚】交易所现货卖出下单失败\n params:{order_params_formated}\norder: {exchange_sell_order_formated}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- return
- exchange_sell_order_id = exchange_sell_order['orderId']
-
- msg = f"【回滚】交易所现货卖出订单已发送, 订单ID: {exchange_sell_order_id}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- # 查询交易所订单状态
- last_query_rst = None
- while True:
- params = {
- "symbol": self.symbol.replace('_', ''),
- "orderId": exchange_sell_order_id
- }
- order = mexc.trade.get_order(params)
- order_formated = pformat(order, indent=2)
- last_query_rst = order
- if order['status'] == "FILLED":
- money = Decimal(order['cummulativeQuoteQty'])
- amount = self.exchange_buy_amount
- price = money / amount
- price = price.quantize(self.price_precision, rounding=ROUND_DOWN)
- msg = f"【回滚】交易所现货卖出订单已完全成交, 价格:{price}。\norder: {order_formated}"
- logger.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)
-
- last_query_rst_formated = pformat(last_query_rst, indent=2)
- msg = f"【回滚】回滚交易订单查询超时, 订单ID: {exchange_sell_order_id}\n最终状态:{last_query_rst_formated}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- except Exception as e:
- exc_traceback = traceback.format_exc()
- msg = f"【回滚】交易所回滚交易失败\n{exc_traceback}"
- logger.error(msg)
-
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- # traceback.print_exc()
- def _wait_transfer_arrive(self):
- """
- 等待资产在交易所内到账
- """
- msg = f"等待资产在交易所到账..."
- logger.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)
- with self.mexc_lock:
- deposit_list = copy.deepcopy(self.mexc_data['deposit_list'])
- # 是否已經在列表中了,抹茶識別充值會稍微有點慢,所以要耐心等
- is_list = False
- # pending中的數量
- pending_amount = Decimal(0)
- for deposit in deposit_list:
- # 不屬于該路徑需要監聽的代幣
- if deposit['coin'] != f'{self.base_coin}-{self.NETWORK}':
- continue
- # 處理pending數量
- if Decimal(deposit['confirmTimes']) < Decimal(deposit['unlockConfirm']):
- pending_amount = pending_amount + Decimal(deposit['amount'])
- # 檢查到沒到列表中
- if deposit['transHash'] != self.chain_tx_hash:
- continue
- last_deposit_state = deposit
- is_list = True
-
- # 檢查是否滿足快速提現的條件
- if is_list:
- # 交易所代幣余额判断
- with self.mexc_lock:
- balances = copy.deepcopy(self.mexc_data['account_info']['balances'])
- asset_balance = 0
- for balance in balances:
- if balance['asset'] == self.base_coin:
- asset_balance = Decimal(balance['free'])
- # 交易所賣出餘額
- buy_value = self.buy_value
-
- # 最終判斷
- if buy_value + asset_balance > pending_amount:
- last_deposit_state_formated = pformat(last_deposit_state, indent=2)
- msg = f"【flash】资产可以進行快速提現。\nbuy_value {buy_value}, asset_balance {asset_balance}, pending_amount {pending_amount}\n{last_deposit_state_formated}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_TRANSFERRING_TO_CHAIN)
- return
- else:
- logger.info(f"buy_value{buy_value}, asset_balance{asset_balance}, pending_amount{pending_amount}")
-
- logger.info(f"正在檢查快速提現條件...({waiting_times}/10)")
- waiting_times = waiting_times - 1
- # 最多等待30分钟
- waiting_times = 30
- last_deposit_state = None
- last_deposit_state_formated = None
- while waiting_times > 0:
- with self.mexc_lock:
- deposit_list = copy.deepcopy(self.mexc_data['deposit_list'])
- for deposit in deposit_list:
- if deposit['transHash'] != self.chain_tx_hash:
- continue
- last_deposit_state = deposit
- last_deposit_state_formated = pformat(last_deposit_state, indent=2)
- logger.info(f"等待资产在交易所到账...({deposit['confirmTimes']}/{deposit['unlockConfirm']})")
- if Decimal(deposit['confirmTimes']) >= Decimal(deposit['unlockConfirm']):
- is_arrived = True
- if is_arrived:
-
- msg = f"资产已在交易所到账。\n{last_deposit_state_formated}"
- logger.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分钟)。\n{last_deposit_state_formated}"
- logger.error(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}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- traceback.print_exc()
-
- def _execute_transfer_to_chain(self):
- """
- 将交易后获得的币(例如RATO)转账回链上
- """
- msg = "执行:交易所计价资产转账回链上..."
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "pending")
- try:
- self.exchange_buy_amount = self.exchange_buy_amount.quantize(self.coin_asset_precision, rounding=ROUND_DOWN)
- pseudo_withdrawal_amount = str(self.exchange_buy_amount)
- withdrawal_params = {
- 'coin': self.coin,
- 'netWork': 'ETH',
- 'address': self.user_wallet,
- 'amount': pseudo_withdrawal_amount
- }
- withdrawal_params_formated = pformat(withdrawal_params, indent=2)
- withdrawal_rst = mexc.wallet.post_withdraw(withdrawal_params)
- withdrawal_rst_formated = pformat(withdrawal_rst, indent=2)
- if "id" not in withdrawal_rst:
- msg = f"交易所提现失败\n參數: {withdrawal_params_formated}\n響應: {withdrawal_rst_formated}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- else:
- self.exchange_withdrawal_id = withdrawal_rst["id"]
- msg = f"交易所提现已发送\n{withdrawal_rst_formated}"
- logger.info(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "success")
- self._set_state(self.STATE_WAITING_WITHDRAWAL_CONFIRM)
- except Exception as e:
- msg = f"转账回链上失败: {e}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- traceback.print_exc()
- def _wait_withdrawal_confirm(self):
- """
- 等待交易所提现到链上确认
- """
- exchange_withdrawal_id = self.exchange_withdrawal_id
- msg = f"等待交易所提现确认:{exchange_withdrawal_id}"
- logger.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
- last_deposit_state_formated = None
- while waiting_times > 0:
- with self.mexc_lock:
- withdraw_list = copy.deepcopy(self.mexc_data['withdraw_list'])
- if not isinstance(withdraw_list, list):
- msg = f"查询交易所提现状态时发生错误:{withdraw_list}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state("FAILED")
- return
- for withdrawal in withdraw_list:
- if withdrawal['id'] != exchange_withdrawal_id:
- continue
- last_deposit_state = withdrawal
- last_deposit_state_formated = pformat(last_deposit_state, indent=2)
- if withdrawal['status'] == 7:
- is_arrived = True
- if is_arrived:
- msg = f"提现请求已上链:\n{last_deposit_state_formated}"
- logger.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分钟):\n{last_deposit_state_formated}"
- logger.error(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}"
- logger.error(msg)
- add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
- self._set_state(self.STATE_FAILED)
- traceback.print_exc()
|