Răsfoiți Sursa

[-] 策略中使用緩存好的交易所數據
[-] 將區塊信息也緩存了

skyfffire 5 luni în urmă
părinte
comite
77af72f0d2
4 a modificat fișierele cu 63 adăugiri și 41 ștergeri
  1. 5 1
      as.py
  2. 51 38
      erc20_to_mexc.py
  3. 1 1
      submit_process_demo.py
  4. 6 1
      toto.readme

+ 5 - 1
as.py

@@ -59,6 +59,7 @@ core_data = {
     "eth_balance": Decimal(0),                      # 全局 eth餘額
     "eth_balance": Decimal(0),                      # 全局 eth餘額
     "eth_price": 0,                                 # 全局 eth價格
     "eth_price": 0,                                 # 全局 eth價格
     "block_number": 0,                              # 全局 區塊號
     "block_number": 0,                              # 全局 區塊號
+    "block": None,                                  # 全局 最后一個區塊的信息
 }
 }
 core_lock = threading.Lock()                        # 核心數據的锁
 core_lock = threading.Lock()                        # 核心數據的锁
 
 
@@ -219,6 +220,7 @@ def update_core_data_periodically():
             new_eth_balance = None
             new_eth_balance = None
             new_nonce = None
             new_nonce = None
             new_block_number = None
             new_block_number = None
+            new_block = None
 
 
             # 1. 从 Binance 获取 ETH 价格
             # 1. 从 Binance 获取 ETH 价格
             if binance_client:
             if binance_client:
@@ -234,7 +236,8 @@ def update_core_data_periodically():
             # 确保 w3 已初始化且 USER_WALLET 已配置
             # 确保 w3 已初始化且 USER_WALLET 已配置
             if w3 and w3.is_connected() and USER_WALLET and USER_WALLET != "你的钱包地址":
             if w3 and w3.is_connected() and USER_WALLET and USER_WALLET != "你的钱包地址":
                 try:
                 try:
-                    new_block_number = w3.eth.block_number
+                    new_block = w3.eth.get_block('latest')
+                    new_block_number = new_block['number']
                     new_nonce = w3.eth.get_transaction_count(USER_WALLET, 'latest')
                     new_nonce = w3.eth.get_transaction_count(USER_WALLET, 'latest')
                     eth_balance_origin = w3.eth.get_balance(USER_WALLET)
                     eth_balance_origin = w3.eth.get_balance(USER_WALLET)
                     new_eth_balance = Decimal(eth_balance_origin / (10 ** 18))
                     new_eth_balance = Decimal(eth_balance_origin / (10 ** 18))
@@ -257,6 +260,7 @@ def update_core_data_periodically():
                 # 判斷block_number是否發生變化(升高)
                 # 判斷block_number是否發生變化(升高)
                 if new_block_number is not None and new_block_number > core_data["block_number"]:
                 if new_block_number is not None and new_block_number > core_data["block_number"]:
                     core_data["block_number"] = new_block_number
                     core_data["block_number"] = new_block_number
+                    core_data["block"] = new_block
                 
                 
                     # 區塊變了才刷新nonce,否則還是要靠本地的緩存維護
                     # 區塊變了才刷新nonce,否則還是要靠本地的緩存維護
                     if new_nonce is not None and core_data["nonce"] != new_nonce:
                     if new_nonce is not None and core_data["nonce"] != new_nonce:

+ 51 - 38
erc20_to_mexc.py

@@ -191,23 +191,30 @@ class ArbitrageProcess:
             pseudo_amount_to_sell = self.exchange_sell_amount.quantize(Decimal('1'), rounding=ROUND_DOWN)
             pseudo_amount_to_sell = self.exchange_sell_amount.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}, 不能触发套保交易。"
-                        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.coin}: {balance['free']}, 交易所准备卖出:{pseudo_amount_to_sell}, 余额校验通过(可以套保)。"
-                        logger.info(msg)
-                        add_state_flow_entry(self.process_item, self.current_state, msg, "success")
-                        break
+            with self.mexc_lock:
+                balances = self.mexc_data['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}, 不能触发套保交易。"
+                            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.coin}: {balance['free']}, 交易所准备卖出:{pseudo_amount_to_sell}, 余额校验通过(可以套保)。"
+                            logger.info(msg)
+                            add_state_flow_entry(self.process_item, self.current_state, msg, "success")
+
+                            balance['free'] = str(Decimal(balance['free']) - pseudo_amount_to_sell)
+
+                            break
 
 
             # step2,估算gas
             # step2,估算gas
-            latest_block = web3.w3.eth.get_block('latest')
+            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['maxPriorityFeePerGas'] = int(int(self.tx['maxPriorityFeePerGas']) * self.gas_price_multiplier)
             self.tx['maxFeePerGas'] = int(int(latest_block['baseFeePerGas']) * 2 + self.tx['maxPriorityFeePerGas'])
             self.tx['maxFeePerGas'] = int(int(latest_block['baseFeePerGas']) * 2 + self.tx['maxPriorityFeePerGas'])
 
 
@@ -215,6 +222,7 @@ class ArbitrageProcess:
             gas_price_gwei = gas_price / Decimal('1e9')
             gas_price_gwei = gas_price / Decimal('1e9')
             gas_price_gwei = gas_price_gwei.quantize(Decimal('1e-9'), rounding=ROUND_DOWN)
             gas_price_gwei = gas_price_gwei.quantize(Decimal('1e-9'), rounding=ROUND_DOWN)
 
 
+            logger.info("鏈上各種校驗")
             estimated_gas_origin = web3.w3.eth.estimate_gas(self.tx)
             estimated_gas_origin = web3.w3.eth.estimate_gas(self.tx)
             estimated_gas = int(estimated_gas_origin * self.gas_limit_multiplier)
             estimated_gas = int(estimated_gas_origin * self.gas_limit_multiplier)
             estimated_wei = Decimal(estimated_gas) * gas_price
             estimated_wei = Decimal(estimated_gas) * gas_price
@@ -600,22 +608,23 @@ class ArbitrageProcess:
             pseudo_amount_to_buy = pseudo_amount_to_buy.quantize(Decimal('1'), rounding=ROUND_DOWN)
             pseudo_amount_to_buy = pseudo_amount_to_buy.quantize(Decimal('1'), rounding=ROUND_DOWN)
 
 
             # 交易所U余额判断
             # 交易所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, 不能触发回滚交易。"
-                        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.base_coin}: {balance['free']}, 交易所准备使用:{pseudo_amount_to_buy}, 余额校验通过(可以回滚)。"
-                        logger.info(msg)
-                        add_state_flow_entry(self.process_item, self.current_state, msg, "success")
-                        break
+            with self.mexc_lock:
+                balances = self.mexc_data['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, 不能触发回滚交易。"
+                            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.base_coin}: {balance['free']}, 交易所准备使用:{pseudo_amount_to_buy}, 余额校验通过(可以回滚)。"
+                            logger.info(msg)
+                            add_state_flow_entry(self.process_item, self.current_state, msg, "success")
+                            break
             
             
             order_params = {
             order_params = {
                 "symbol": self.symbol.replace('_', ''),
                 "symbol": self.symbol.replace('_', ''),
@@ -702,7 +711,8 @@ class ArbitrageProcess:
             last_deposit_state = None
             last_deposit_state = None
             while waiting_times > 0:
             while waiting_times > 0:
                 time.sleep(60)
                 time.sleep(60)
-                deposit_list = mexc.wallet.get_deposit_list()
+                with mexc_lock:
+                    deposit_list = copy.deepcopy(self.mexc_data['deposit_list'])
 
 
                 # 是否已經在列表中了,抹茶識別充值會稍微有點慢,所以要耐心等
                 # 是否已經在列表中了,抹茶識別充值會稍微有點慢,所以要耐心等
                 is_list = False
                 is_list = False
@@ -726,7 +736,8 @@ class ArbitrageProcess:
                 # 檢查是否滿足快速提現的條件
                 # 檢查是否滿足快速提現的條件
                 if is_list:
                 if is_list:
                     # 交易所代幣余额判断
                     # 交易所代幣余额判断
-                    balances = mexc.trade.get_account_info()['balances']
+                    with mexc_lock:
+                        balances = copy.deepcopy(self.mexc_data['account_info']['balances'])
                     asset_balance = 0
                     asset_balance = 0
                     for balance in balances:
                     for balance in balances:
                         if balance['asset'] == self.coin:
                         if balance['asset'] == self.coin:
@@ -755,7 +766,8 @@ class ArbitrageProcess:
             last_deposit_state = None
             last_deposit_state = None
             last_deposit_state_formated = None
             last_deposit_state_formated = None
             while waiting_times > 0:
             while waiting_times > 0:
-                deposit_list = mexc.wallet.get_deposit_list()
+                with mexc_lock:
+                    deposit_list = copy.deepcopy(self.mexc_data['deposit_list'])
                 for deposit in deposit_list:
                 for deposit in deposit_list:
                     if deposit['transHash'] != self.chain_tx_hash:
                     if deposit['transHash'] != self.chain_tx_hash:
                         continue
                         continue
@@ -852,17 +864,18 @@ class ArbitrageProcess:
             last_deposit_state = None
             last_deposit_state = None
             last_deposit_state_formated = None
             last_deposit_state_formated = None
             while waiting_times > 0:
             while waiting_times > 0:
-                withdrawal_list = mexc.wallet.get_withdraw_list()
+                with mexc_lock:
+                    withdraw_list = copy.deepcopy(self.mexc_data['withdraw_list'])
 
 
-                if not isinstance(withdrawal_list, list):
-                    msg = f"查询交易所提现状态时发生错误:{withdrawal_list}"
+                if not isinstance(withdraw_list, list):
+                    msg = f"查询交易所提现状态时发生错误:{withdraw_list}"
                     logger.error(msg)
                     logger.error(msg)
                     add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
                     add_state_flow_entry(self.process_item, self.current_state, msg, "fail")
 
 
                     self._set_state("FAILED")
                     self._set_state("FAILED")
                     return
                     return
 
 
-                for withdrawal in withdrawal_list:
+                for withdrawal in withdraw_list:
                     if withdrawal['id'] != exchange_withdrawal_id:
                     if withdrawal['id'] != exchange_withdrawal_id:
                         continue
                         continue
 
 

+ 1 - 1
submit_process_demo.py

@@ -19,7 +19,7 @@ def create_mock_arbitrage_data():
     CHAIN_ID = 1
     CHAIN_ID = 1
     IN_TOKEN_ADDRESS = '0xdAC17F958D2ee523a2206206994597C13D831ec7' # USDT on Ethereum
     IN_TOKEN_ADDRESS = '0xdAC17F958D2ee523a2206206994597C13D831ec7' # USDT on Ethereum
     IN_TOKEN_DECIMALS = 6
     IN_TOKEN_DECIMALS = 6
-    EXCHANGE_OUT_AMOUNT = Decimal(2200000)
+    EXCHANGE_OUT_AMOUNT = Decimal(2100000)
     IN_AMOUNT_TO_QUERY = Decimal(12)
     IN_AMOUNT_TO_QUERY = Decimal(12)
     OUT_TOKEN_ADDRESS = '0xf816507E690f5Aa4E29d164885EB5fa7a5627860' # RATO on Ethereum
     OUT_TOKEN_ADDRESS = '0xf816507E690f5Aa4E29d164885EB5fa7a5627860' # RATO on Ethereum
     USER_WALLET = '0xb1f33026Db86a86372493a3B124d7123e9045Bb4'
     USER_WALLET = '0xb1f33026Db86a86372493a3B124d7123e9045Bb4'

+ 6 - 1
toto.readme

@@ -13,8 +13,13 @@
 [-] 解密HASH進行鑒權
 [-] 解密HASH進行鑒權
 [-] json用pprint美化后輸出
 [-] json用pprint美化后輸出
 [-] ETH餘額緩存
 [-] ETH餘額緩存
-[ ] 交易所數據緩存
+[-] 交易所數據緩存
 
 
 2025-06-07
 2025-06-07
+[-] 策略中使用緩存好的交易所數據
+[-] 將區塊信息也緩存了
+[ ] Mexc的提現手續費等信息維護
+
+2025-06-10
 [ ] 做另一個方向之前,需要先整理策略層架構,當前架構如何兼容多策略
 [ ] 做另一個方向之前,需要先整理策略層架構,當前架構如何兼容多策略
 [ ] 另一個方向
 [ ] 另一個方向