Browse Source

做另一個方向之前,需要先整理策略層架構,當前架構如何兼容多策略

skyfffire 4 months ago
parent
commit
0c7dd56e8b
4 changed files with 37 additions and 50 deletions
  1. 31 46
      as.py
  2. 2 1
      checker/erc20_to_mexc_checker.py
  3. 3 2
      erc20_to_mexc.py
  4. 1 1
      toto.readme

+ 31 - 46
as.py

@@ -146,33 +146,21 @@ def move_completed_process_to_history(process_id_to_move: str) -> bool:
             
     return moved_successfully
 
-# 實際套利邏輯
-def arbitrage_process_flow(process_item):
-    """
-    在单独线程中执行的实际套利逻辑。
-    会直接修改 'process_item' 字典。
-    """
+
+# 策略構建器
+def strategy_builder(process_item):
     process_id = process_item['id']
-    SYMBOL = process_item['symbol']
-    tx = process_item['tx'] # 预期包含 'rawTransaction' (原始交易)
-    FROM_TOKEN = process_item['fromToken']
-    TO_TOKEN = process_item['toToken']
-    FROM_TOKEN_AMOUNT_HUMAM = process_item['fromTokenAmountHuman']
-    TO_TOKEN_AMOUNT_HUMAM = process_item['toTokenAmountHuman']
     profit = Decimal(process_item['profit'])
     profitLimit = Decimal(process_item['profitLimit'])
-    USER_EXCHANGE_WALLET = process_item['userExchangeWallet']
-    USER_WALLET = process_item['userWallet']
-    SYMBOL = process_item['symbol']
-    EXCHANGE_OUT_AMOUNT = process_item['exchangeOutAmount']
-
+    strategy = process_item['strategy']
 
+    # 對於高利潤交易,進行適當加速
     gas_limit_multiplier = 1
     gas_price_multiplier = 1.5
     if profit > Decimal(5) * profitLimit:
-        gas_price_multiplier = 2
+        gas_price_multiplier = 5
     elif profit > Decimal(10) * profitLimit:
-        gas_price_multiplier = 3
+        gas_price_multiplier = 10
 
     global core_data
     global core_lock
@@ -181,11 +169,24 @@ def arbitrage_process_flow(process_item):
     global mexc_data
     global mexc_lock
 
-    ap = erc20_to_mexc.ArbitrageProcess(tx, gas_limit_multiplier, gas_price_multiplier, process_item, 
+    if strategy == 'erc20_to_mexc':
+        return erc20_to_mexc.ArbitrageProcess(gas_limit_multiplier, gas_price_multiplier, process_item, 
         core_data, core_lock,
         pending_data, pending_lock,
         mexc_data, mexc_lock
-    )
+        )
+    else:
+        process_item_formated = pformat(process_item, indent=2)
+        logger.error(f'不存在的策略:{strategy}\n{process_item_formated}')
+
+# 實際套利邏輯
+def arbitrage_process_flow(process_item):
+    """
+    在单独线程中执行的实际套利逻辑。
+    会直接修改 'process_item' 字典。
+    """
+    
+    ap = strategy_builder(process_item)
 
     # 一般都是从这个流程开始,测试时可以稍作修改、测试后续流程
     ap._set_state(ap.STATE_CHECK)
@@ -553,7 +554,7 @@ def handle_submit_process():
     if not data:
         return jsonify({"error": "无效的 JSON 请求体"}), 400
 
-    required_fields = ['tx', 'profit', 'profitLimit', 'symbol', 'fromToken', 'fromTokenAmountHuman', 'fromTokenDecimal', 'toToken', 'toTokenAmountHuman', 'exchangeOutAmount']
+    required_fields = ['tx', 'profit', 'profitLimit', 'symbol', 'strategy']
     for field in required_fields:
         if field not in data:
             return jsonify({"error": f"缺少字段: {field}"}), 400
@@ -561,11 +562,6 @@ def handle_submit_process():
     try:
         profit = Decimal(str(data['profit']))                                   # 利润
         profit_limit = Decimal(str(data['profitLimit']))                        # 利润阈值
-        from_token_amount_human = Decimal(str(data['fromTokenAmountHuman']))    # fromToken 的人类可读数量
-        from_token_decimal = Decimal(str(data['fromTokenDecimal']))             # fromToken 的小数位数
-        to_token_amount_human = Decimal(str(data['toTokenAmountHuman']))        # toToken 的人类可读数量
-        to_token_decimal = Decimal(str(data['toTokenDecimal']))             # fromToken 的小数位数
-        exchange_out_amount = Decimal(str(data['exchangeOutAmount']))           # 交易所需要卖出的数量
     except (decimal.InvalidOperation, ValueError) as e:
         return jsonify({"error": f"请求体中包含无效的小数/整数值: {e}"}), 400
 
@@ -581,25 +577,14 @@ def handle_submit_process():
 
     if profit >= profit_limit:
         process_id = str(uuid.uuid4()) # 生成唯一流程ID
-        process_item = {
-            "id": process_id,
-            "creationTime": get_formatted_timestamp(), # 创建时间
-            "tx": data['tx'], # 交易详情,应包含 rawTransaction
-            "profit": str(profit), # 利润 (字符串存储)
-            "profitLimit": str(profit_limit), # 利润阈值 (字符串存储)
-            "symbol": symbol, # 交易对
-            "userWallet": USER_WALLET,
-            "userExchangeWallet": USER_EXCHANGE_WALLET,
-            "fromToken": data['fromToken'], # 起始代币
-            "fromTokenAmountHuman": str(from_token_amount_human), # 起始代币数量 (人类可读, 字符串存储)
-            "fromTokenDecimal": str(from_token_decimal), # 起始代币小数位数
-            "toTokenAmountHuman": str(to_token_amount_human),
-            "toTokenDecimal": str(to_token_decimal),
-            "exchangeOutAmount": str(exchange_out_amount),
-            "toToken": data['toToken'], # 目标代币
-            "stateFlow": [], # 状态流转记录
-            "currentState": "PENDING_START", # 当前状态
-        }
+        process_item = copy.deepcopy(data)
+        process_item['id'] = process_id
+        process_item['creationTime'] = get_formatted_timestamp(), # 创建时间
+        process_item['userWallet'] = USER_WALLET
+        process_item['userExchangeWallet'] = USER_EXCHANGE_WALLET
+        process_item['stateFlow'] = [] # 状态流转记录
+        process_item['currentState'] = "PENDING_START"
+
         # 初始状态更新
         add_state_flow_entry(process_item, "RECEIVED", f"流程已接收。利润 {profit} >= 利润阈值 {profit_limit}。开始套利。", "success")
 

+ 2 - 1
checker/erc20_to_mexc_checker.py

@@ -430,7 +430,8 @@ def send_arb_msg(profit_amount, chain_swap_data, mexc_price_usdt_per_target, in_
         "toToken": OUT_TOKEN_ADDRESS,
         "toTokenAmountHuman": str(human_out_target.quantize(Decimal(f'1e-{out_dec}'))),
         "toTokenDecimal": str(out_dec),
-        "exchangeOutAmount": str(EXCHANGE_OUT_AMOUNT.quantize(Decimal(f'1e-{out_dec}'))) # CEX上期望卖出的目标币数量
+        "exchangeOutAmount": str(EXCHANGE_OUT_AMOUNT.quantize(Decimal(f'1e-{out_dec}'))), # CEX上期望卖出的目标币数量
+        "strategy": "erc20_to_mexc",
     }
 
     logger.info(f"正在提交套利数据到 {ARB_EXECUTOR_URL}, profit {arbitrage_data["profit"]}, profitLimit {arbitrage_data["profitLimit"]}")

+ 3 - 2
erc20_to_mexc.py

@@ -15,7 +15,7 @@ mexc = MexcClient()
 logger = get_logger('as')
 
 class ArbitrageProcess:
-    def __init__(self, tx, gas_limit_multiplier, gas_price_multiplier, process_item, 
+    def __init__(self, gas_limit_multiplier, gas_price_multiplier, process_item, 
         core_data, core_lock,
         pending_data, pending_lock,
         mexc_data, mexc_lock,
@@ -24,12 +24,13 @@ class ArbitrageProcess:
         初始化套利流程
 
         Args:
-            tx: 在链上要发送交易的tx
             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)

+ 1 - 1
toto.readme

@@ -32,7 +32,7 @@
 2025-06-13
 [-] 抹茶餘額大於20才做提現
 [-] 修復ws部分的in_amount問題
-[ ] 做另一個方向之前,需要先整理策略層架構,當前架構如何兼容多策略
+[-] 做另一個方向之前,需要先整理策略層架構,當前架構如何兼容多策略
 
 2025-06-18
 [ ] approve自動