| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690 |
- # -*- coding: utf-8 -*-
- from checker.logger_config import get_logger
- logger = get_logger('as')
- logger.info('\n\n----------------------------------------------as啓動--------------------------------------------')
- import threading
- import uuid # 用于生成唯一的流程ID
- import time
- import logging
- import s_erc20_to_mexc
- import s_mexc_to_erc20
- import web3_py_client
- import traceback
- import copy
- import sys
- from decimal import Decimal, ROUND_DOWN
- from flask import Flask, request, jsonify
- from flask_cors import CORS # 导入
- from as_utils import get_formatted_timestamp
- from as_utils import add_state_flow_entry
- from config import wallet
- from config import withdraw
- from binance.client import Client # 用于获取ETH价格
- from checker import ok_chain_client
- from mexc_client import MexcClient
- from pprint import pprint
- from pprint import pformat
- ok_chain_client.api_config = {
- "api_key": 'a05643ab-fb17-402b-94a8-a886bd343301', # 请替换为您的真实 API Key
- "secret_key": '9D59B53EB1E60B1B5F290D3698A8C9DA', # 请替换为您的真实 Secret Key
- "passphrase": 'Qwe123123.', # 请替换为您的真实 Passphrase
- }
- # 配置日志
- log = logging.getLogger('werkzeug')
- log.setLevel(logging.ERROR)
- web3 = web3_py_client.EthClient()
- w3 = web3.w3
- mexc = MexcClient()
- USER_WALLET = wallet["user_wallet"]
- USER_EXCHANGE_WALLET = wallet["user_exchange_wallet"]
- # 该代币最后一次执行套利的区块信息 (如果需要防止过于频繁的同类套利,不然变成砸盘、拉盘的了)
- last_process_info = {} # 示例: {"RATO_USDT": 0}
- MIN_BLOCKS_BETWEEN_ARB = Decimal(5) # 在重试相同交易对之前等待几个区块
- # --- 全局状态和锁 ---
- processing_list = [] # 正在处理的任务列表
- history_process_list = [] # 已完成的任务历史列表
- list_lock = threading.Lock() # 用于修改 processing_list 和 history_process_list 结构的锁
- # --- 一些核心數據和鎖 ---
- core_data = {
- "nonce": 0, # 全局 Nonce
- "eth_balance": Decimal(0), # 全局 eth餘額
- "eth_price": 0, # 全局 eth價格
- "block_number": 0, # 全局 區塊號
- "block": None, # 全局 最后一個區塊的信息
- }
- core_lock = threading.Lock() # 核心數據的锁
- # --- pending數據和鎖 ---
- pending_data = {
- # # 數據結構的demo
- # "0xaf181bbbf5bf56d9204bd18cd25abd90e51890e848525e7788b410689c0c26a4": {
- # "block_number": 22570370, # 提交pending時的區塊,隔幾個區塊去獲取數據會更準確
- # "tx_details": None, # okapi解析的數據, None就是還沒有獲取到
- # "reponse": None, # okapi最後一次獲取到的數據
- # },
- }
- pending_lock = threading.Lock()
- PENDING_CONFIRM_BLOCK = 3 # 需要幾個區塊才進行確認
- # --- mexc相關數據和鎖 ---
- mexc_data = {
- "account_info": {},
- "deposit_list": [],
- "withdraw_list": [],
- "coin_info_map": {}, # 處理過的幣種信息,coin_info_map[coin][network]
- }
- mexc_lock = threading.Lock()
- CHAIN_ID = -1
- try:
- if w3.provider:
- CHAIN_ID = w3.eth.chain_id
- logger.info(f"Web3 已连接。chain_id={CHAIN_ID}")
- else:
- logger.info("Web3 未连接。")
- except Exception as e:
- logger.info(f"初始化 {USER_WALLET} 的全局 nonce 时出错: {e}")
- # Binance 客户端 (无需API Key/Secret即可获取公开行情数据)
- try:
- binance_client = Client()
- # 测试连接 (可选,但建议)
- binance_client.ping()
- logger.info("成功连接到 Binance API。")
- except Exception as e:
- logger.error(f"初始化 Binance Client 时发生错误: {e}")
- binance_client = None
- # --- Flask 应用 ---
- app = Flask(__name__)
- CORS(app) # 在创建 app 实例后启用 CORS
- WITHDRAWAL_COOLDOWN = 180 # 秒,成功提现后冷却60秒
- def move_completed_process_to_history(process_id_to_move: str) -> bool:
- """
- 将一个完成的 process_item 从 processing_list 移动到 history_process_list。
- 此操作是线程安全的。
- Args:
- process_id_to_move (str): 要移动的 process_item 的 ID。
- Returns:
- bool: 如果成功找到并移动了 item,则返回 True,否则返回 False。
- """
- global processing_list, history_process_list # 因为我们要修改这两个列表
-
- item_to_move = None
- moved_successfully = False
- with list_lock:
- # 查找并从 processing_list 中移除
- found_index = -1
- for i, item in enumerate(processing_list):
- if item.get('id') == process_id_to_move:
- found_index = i
- break
-
- if found_index != -1:
- item_to_move = processing_list.pop(found_index) # 从 processing_list 中移除并获取它
-
- # 假设在 item_to_move 中,其 currentState 已经被 arbitrage_process_flow 更新为 COMPLETED 或 FAILED
- # arbitrage_process.add_state_flow_entry(item_to_move, "MOVED_TO_HISTORY", f"流程处理完毕,移至历史记录。最终状态: {item_to_move.get('currentState', 'N/A')}", "info")
-
- history_process_list.append(item_to_move) # 添加到 history_process_list
- logger.info(f"已将 process_id: {process_id_to_move} 从 processing_list 移动到 history_process_list。")
- moved_successfully = True
- else:
- logger.warning(f"尝试移动到 history_list 时,在 processing_list 中未找到 process_id: {process_id_to_move}")
-
- return moved_successfully
- # 策略構建器
- def strategy_builder(process_item):
- profit = Decimal(process_item['profit'])
- profitLimit = Decimal(process_item['profitLimit'])
- strategy = process_item['strategy']
- # 對於高利潤交易,進行適當加速
- gas_limit_multiplier = 1
- gas_price_multiplier = 1
- # if profit > Decimal(5) * profitLimit:
- # gas_price_multiplier = 5
- # elif profit > Decimal(10) * profitLimit:
- # gas_price_multiplier = 10
- global core_data
- global core_lock
- global pending_data
- global pending_lock
- global mexc_data
- global mexc_lock
- process_item_formated = pformat(process_item, indent=2)
- logger.info(f'策略原始参数:\n{process_item_formated}')
- if strategy == 'erc20_to_mexc':
- return s_erc20_to_mexc.ArbitrageProcess(gas_limit_multiplier, gas_price_multiplier, process_item,
- core_data, core_lock,
- pending_data, pending_lock,
- mexc_data, mexc_lock
- )
- elif strategy == 'mexc_to_erc20':
- return s_mexc_to_erc20.ArbitrageProcess(gas_limit_multiplier, gas_price_multiplier, process_item,
- core_data, core_lock,
- pending_data, pending_lock,
- mexc_data, mexc_lock
- )
- else:
- logger.error(f'不存在的策略:{strategy}')
- # 實際套利邏輯
- def arbitrage_process_flow(process_item):
- """
- 在单独线程中执行的实际套利逻辑。
- 会直接修改 'process_item' 字典。
- """
- process_id = process_item['id']
-
- ap = strategy_builder(process_item)
- # 一般都是从这个流程开始,测试时可以稍作修改、测试后续流程
- ap._set_state(ap.STATE_CHECK)
- # 在主循环中周期性调用 run_arbitrage_step
- while ap.current_state != ap.STATE_COMPLETED and ap.current_state != ap.STATE_FAILED and ap.current_state != ap.STATE_REJECT:
- ap.run_arbitrage_step()
- ap.run_arbitrage_step()
- move_completed_process_to_history(process_id)
-
- # --- 核心數據更新綫程函數 ---
- def update_core_data_periodically():
- """
- 周期性更新 nonce 和 ETH 价格的线程函数。
- """
- global core_data # 明确表示我们要修改全局的 core_data
- if not USER_WALLET or USER_WALLET == "你的钱包地址":
- logger.error("USER_WALLET 未正确配置。nonce 更新将无法进行。")
- # 如果 USER_WALLET 未配置,可以考虑让线程不执行 nonce 更新,或者直接退出
- # 这里我们选择继续运行,但 nonce 不会被更新
- while True:
- try:
- new_eth_price = None
- new_eth_balance = None
- new_nonce = None
- new_block_number = None
- new_block = None
- # 1. 从 Binance 获取 ETH 价格
- if binance_client:
- try:
- ticker = binance_client.get_symbol_ticker(symbol="ETHUSDT")
- new_eth_price = float(ticker['price'])
- except Exception as e:
- logger.error(f"从 Binance 获取 ETH 价格失败: {e}")
- else:
- logger.warning("Binance client 未初始化, 无法获取 ETH 价格。")
- # 2. 获取最新的 Nonce 和 最新的block_number 以及 最新的賬戶eth餘額
- # 确保 w3 已初始化且 USER_WALLET 已配置
- if w3 and w3.is_connected() and USER_WALLET and USER_WALLET != "你的钱包地址":
- try:
- new_block = w3.eth.get_block('latest')
- new_block_number = new_block['number']
- new_nonce = w3.eth.get_transaction_count(USER_WALLET, 'latest')
- eth_balance_origin = w3.eth.get_balance(USER_WALLET)
- new_eth_balance = Decimal(eth_balance_origin / (10 ** 18))
- new_eth_balance = new_eth_balance.quantize(Decimal('1e-6'), rounding=ROUND_DOWN)
- except Exception as e:
- logger.error(f"为 {USER_WALLET} 获取 Nonce、BlockNumber、EthBalances 失败: {e}")
- elif not (w3 and w3.is_connected()):
- logger.warning("Web3 未连接, 无法获取 nonce。")
- elif not (USER_WALLET and USER_WALLET != "你的钱包地址"):
- logger.warning("USER_WALLET 配置不正确, 无法获取 nonce。")
- # 3. 更新共享数据 core_data (使用锁)
- # 只有当获取到新数据时才更新,避免不必要的写操作和日志
- with core_lock:
- if new_eth_price is not None and core_data["eth_price"] != new_eth_price:
- eth_price = Decimal(new_eth_price)
- eth_price = eth_price.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
- core_data["eth_price"] = eth_price
-
- # 判斷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"] = new_block
-
- # 區塊變了才刷新nonce,否則還是要靠本地的緩存維護
- if new_nonce is not None and core_data["nonce"] != new_nonce:
- core_data["nonce"] = new_nonce
- # 餘額也同理
- if new_eth_balance is not None and core_data["eth_balance"] != new_eth_balance:
- core_data["eth_balance"] = new_eth_balance
-
- # logger.info(f"核心数据已更新: ETH Price = {core_data['eth_price']}, Nonce ({USER_WALLET}) = {core_data['nonce']}, EthBalance={core_data['eth_balance']}, BlockNumber = {core_data['block_number']}")
- except Exception as e:
- # 捕获线程循环中的其他潜在错误
- exc_traceback = traceback.format_exc()
- logger.error(f"数据更新线程发生未知错误\n{exc_traceback}")
- # traceback.print_exc()
-
- # 等待 500ms
- time.sleep(0.5)
- # --- mexc數據更新綫程函數 ---
- def update_mexc_data_periodically():
- """
- 周期性更新 mexc的相關數據 的线程函数。
- """
- global mexc_data
- # 每60秒獲取一次coin_info
- coin_info_get_delay = 60
- while True:
- try:
- new_account_info = None
- new_withdraw_list = None
- new_deposit_list = None
- new_coin_info_list = None
- # 1. new_account_info
- try:
- new_account_info = mexc.trade.get_account_info()
- if 'balances' not in new_account_info:
- raise Exception("未找到balances")
- with mexc_lock:
- mexc_data['account_info'] = new_account_info
- # logger.info(f'account_info: {new_account_info['balances']}')
- except Exception as e:
- logger.error(f"从 Mexc 获取 Balance 失败: {e}, {new_account_info}")
- # 2. new_deposit_list
- try:
- new_deposit_list = mexc.wallet.get_deposit_list()
- if not isinstance(new_deposit_list, list):
- raise Exception("充值信息獲取錯誤")
- with mexc_lock:
- mexc_data['deposit_list'] = new_deposit_list
- # logger.info(f'deposit_list: {new_deposit_list[0]}')
- except Exception as e:
- logger.error(f"从 Mexc 获取 deposit_list 失败: {e}, {new_deposit_list}")
- # 3. new_withdraw_list
- try:
- new_withdraw_list = mexc.wallet.get_withdraw_list()
- if not isinstance(new_withdraw_list, list):
- raise Exception("提現信息獲取錯誤")
- with mexc_lock:
- mexc_data['withdraw_list'] = new_withdraw_list
- # logger.info(f'withdraw_list: {new_withdraw_list[0]}')
- except Exception as e:
- logger.error(f"从 Mexc 获取 withdraw_list 失败: {e}, {new_withdraw_list}")
- # 4. new_coin_info list
- try:
- if coin_info_get_delay >= 60:
- coin_info_get_delay = 0
- new_coin_info_list = mexc.wallet.get_coinlist()
- if not isinstance(new_coin_info_list, list):
- raise Exception("幣種信息獲取錯誤")
- # 處理幣種信息
- new_coin_info_map = {}
- for coin_info in new_coin_info_list:
- new_coin_info_map[coin_info['coin']] = {}
- for network in coin_info['networkList']:
- new_coin_info_map[coin_info['coin']][network['netWork']] = network
- with mexc_lock:
- mexc_data['coin_info_map'] = new_coin_info_map
- # logger.info(f'coin_info_map: {new_coin_info_map['USDT']}')
- except Exception as e:
- logger.error(f"从 Mexc 获取 withdraw_list 失败: {e}, {new_withdraw_list}")
- except Exception as e:
- # 捕获线程循环中的其他潜在错误
- exc_traceback = traceback.format_exc()
- logger.error(f"数据更新线程发生未知错误\n{exc_traceback}")
- # traceback.print_exc()
-
- # 幣種信息處理的delay
- coin_info_get_delay = coin_info_get_delay + 1
- # 等待 1s
- time.sleep(1)
- # --- tx pending數據獲取綫程函數 ---
- def update_tx_data_periodically():
- """
- 每一秒獲取一條tx數據
- """
- global pending_data # 明确表示我们要修改全局的 pending_data
- while True:
- # 等待1s
- time.sleep(1)
- try:
- # 使用拷貝后的數據,否則可能會出現綫程問題
- with pending_lock:
- pending_data_copy = copy.deepcopy(pending_data)
- # 核心數據同理
- with core_lock:
- core_data_copy = copy.deepcopy(core_data)
- block_number = core_data_copy['block_number']
- for tx in pending_data_copy:
- try:
- # 已獲取的就不要再獲取了
- if pending_data_copy[tx]['tx_details'] is not None:
- continue
- # PENDING_CONFIRM_BLOCK個區塊之後的才進行確認,防止回滾頻繁觸發
- if block_number < pending_data_copy[tx]['block_number'] + PENDING_CONFIRM_BLOCK:
- continue
- # 調用ok的api,直接獲取詳細交易
- ok_rst = ok_chain_client.history(CHAIN_ID, tx)
- # 存儲最後一次獲取的細節
- with pending_lock:
- pending_data[tx]['response'] = ok_rst
- # 錯誤響應
- if ok_rst['code'] != '0':
- raise RuntimeError("API 返回错误响应", ok_rst)
-
- # ok不一定那麽快獲取到
- if ok_rst['data'] is None:
- # 每一個之間等待1s
- time.sleep(1)
- continue
-
- details = ok_rst['data']
- status = details['status']
- if status != 'fail':
- # 有時候不會馬上識別出成交數量
- if 'fromTokenDetails' not in details or 'toTokenDetails' not in details:
- # 每一個之間等待1s
- time.sleep(1)
- continue
-
- # 有時候不會馬上識別出成交數量 判斷2
- if details['fromTokenDetails'] is None or details['toTokenDetails'] is None:
- # 每一個之間等待1s
- time.sleep(1)
- continue
-
- # 有時候不會馬上識別出gas信息之類的
- fileds = ['gasLimit', 'gasPrice', 'gasUsed', 'height']
- insufficient = False
- for filed in fileds:
- if details[filed] == '':
- insufficient = True
- break
- if insufficient:
- # 每一個之間等待1s
- time.sleep(1)
- continue
- # 成功獲取之後直接調用更新
- with pending_lock:
- pending_data[tx]['tx_details'] = details
- formated_data = pformat(ok_rst['data'], indent=2) # indent=2 让格式更整齐
- logger.info(f"獲取成功: \n{formated_data}")
- except Exception as e:
- exc_traceback = traceback.format_exc()
- logger.error(f"tx數據獲取失敗\n{exc_traceback}")
- # traceback.print_exc()
-
- # 每一個之間等待1s
- time.sleep(1)
- except Exception as e:
- exc_traceback = traceback.format_exc()
- logger.error(f"pending更新线程发生未知错误\n{exc_traceback}")
- # traceback.print_exc()
- # --- 餘額平衡綫程 ---
- def balance_available_funds_periodically():
- """
- 每10秒嘗試平衡一次餘額
- """
- PROPORTION_LIMIT = Decimal(withdraw['proportion_limit']) # 鏈上資金比例低於這個值就會觸發平衡
- PROPORTION_TARGET = Decimal(withdraw['proportion_target']) # 鏈上資金占比目標,1表示100%是鏈上資金
- BASE_COIN = 'USDT'
- BASE_COIN_ADDR = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
- CANT_WITHDRAW_STATE_LIST = ['IDLE',
- 'CHECK',
- 'SELLING_ON_EXCHANGE',
- 'WAITING_SELL_CONFIRM',
- "BUYING_ON_CHAIN",
- "WAITING_CHAIN_CONFIRM",
- "WAITING_EXCHANGE_ROLLBACK"
- ]
- global processing_list
- while True:
- time.sleep(10)
- try:
- mexc_available = Decimal(0)
- # 交易所餘額讀取
- new_account_info = mexc.trade.get_account_info()
- balances = new_account_info['balances']
- for balance in balances:
- if balance['asset'].upper() == BASE_COIN:
- mexc_available = Decimal(balance['free'])
- mexc_available = mexc_available.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
-
- # 鏈上餘額讀取
- chain_available = web3.get_erc20_balance(BASE_COIN_ADDR)
- chain_available = chain_available.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
- # 縂可用餘額(不包括lock的)
- total_available = mexc_available + chain_available
- # 小於20都懶得做平衡,手續費都不夠
- if total_available < Decimal(20):
- continue
- # 抹茶餘額也要大於20
- if mexc_available < Decimal(20):
- continue
- # 計算鏈上資金佔總體的比例
- proportion = chain_available / total_available
- proportion = proportion.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
- # 判斷比例是否滿足limit,不滿足則先不提現
- if proportion > PROPORTION_LIMIT:
- continue
- # 鏈上應該具備的資金量
- chain_available_target = total_available * PROPORTION_TARGET
- mexc_should_be_withdrawal_founds = chain_available_target - chain_available
- mexc_should_be_withdrawal_founds = mexc_should_be_withdrawal_founds.quantize(Decimal(1), rounding=ROUND_DOWN)
- # 如若當前綫程中有未執行完的,先不執行提現
- with list_lock:
- cant_withdraw = False
- for processing in processing_list:
- if processing['currentState'] in CANT_WITHDRAW_STATE_LIST:
- cant_withdraw = True
- break
- # 不執行提現判斷
- if cant_withdraw:
- # formated_processing = pformat(processing_list, indent=2)
- # logger.info(f"不執行提現, 因爲: \n{formated_processing}")
- continue
-
- if mexc_should_be_withdrawal_founds > 0:
- withdrawal_params = {
- 'coin': 'USDT',
- 'netWork': 'ETH',
- 'address': USER_WALLET,
- 'amount': mexc_should_be_withdrawal_founds,
- }
- withdrawal_params_formated = pformat(withdrawal_params, indent=2)
- withdrawal_rst = mexc.wallet.post_withdraw(withdrawal_params)
- withdrawal_rst_formated = pformat(withdrawal_rst, indent=2)
- logger.info(f"[withdrawal]mexc_available={mexc_available}, chain_available={chain_available},proportion={proportion}, mexc_withdrawal={mexc_should_be_withdrawal_founds}")
- if "id" not in withdrawal_rst:
- msg = f"[withdrawal]交易所提现失败\n參數: {withdrawal_params_formated}\n響應: {withdrawal_rst_formated}"
- logger.error(msg)
- else:
- msg = f"[withdrawal]交易所提现已发送, 进入 {WITHDRAWAL_COOLDOWN} 秒冷却期。\n參數: {withdrawal_params_formated}\n響應: {withdrawal_rst_formated}"
- logger.info(msg)
- time.sleep(WITHDRAWAL_COOLDOWN)
- else:
- # TODO 這是另一個方向,需要從鏈上往交易所劃轉
- pass
- except Exception as e:
- exc_traceback = traceback.format_exc()
- logger.error(f"可用資金平衡綫程发生未知错误\n{exc_traceback}")
- # traceback.print_exc()
- @app.route('/submit_process', methods=['POST'])
- def handle_submit_process():
- data = request.get_json()
- if not data:
- return jsonify({"error": "无效的 JSON 请求体"}), 400
- required_fields = ['tx', 'profit', 'profitLimit', 'symbol', 'strategy']
- for field in required_fields:
- if field not in data:
- return jsonify({"error": f"缺少字段: {field}, keys: {data.keys()}"}), 400
- try:
- profit = Decimal(str(data['profit'])) # 利润
- profit_limit = Decimal(str(data['profitLimit'])) # 利润阈值
- except (decimal.InvalidOperation, ValueError) as e:
- return jsonify({"error": f"请求体中包含无效的小数/整数值: {e}"}), 400
- symbol = data['symbol'] # 交易对符号
- # 检查此交易对此区块是否处理过
- last_trade_block = last_process_info.get(symbol)
- with core_lock:
- current_block = core_data['block_number']
- if last_trade_block:
- if current_block - last_trade_block < MIN_BLOCKS_BETWEEN_ARB:
- return jsonify({"message": f"已跳过: {symbol} 最近已处理 (区块 {last_trade_block}). 当前区块 {current_block}."}), 200
- if profit >= profit_limit:
- process_id = str(uuid.uuid4()) # 生成唯一流程ID
- 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")
- with list_lock:
- processing_list.append(process_item)
- last_process_info[symbol] = current_block
- logger.info(f"已更新 {symbol} 的最后处理信息至区块 {current_block}")
- # 在新线程中开始套利过程
- arb_thread = threading.Thread(target=arbitrage_process_flow, args=(process_item,), daemon=True)
- arb_thread.start()
- return jsonify({"message": "套利过程已启动", "process_id": process_id}), 201
- else:
- return jsonify({"message": f"利润 {profit} 小于利润阈值 {profit_limit}。不处理。"}), 200
- @app.route('/processing', methods=['GET'])
- def get_processing_list():
- """获取正在处理的任务列表"""
- with list_lock:
- # 返回一个副本,以避免在迭代生成 JSON 响应时列表被修改的问题
- return jsonify(list(processing_list))
- @app.route('/history', methods=['GET'])
- def get_history_list():
- """获取已完成的任务历史列表"""
- with list_lock:
- return jsonify(list(history_process_list))
- @app.route('/status', methods=['GET'])
- def get_status():
- """获取系统状态概览"""
- with list_lock:
- return jsonify({
- "processing_count": len(processing_list), # 正在处理的任务数量
- "history_count": len(history_process_list), # 历史任务数量
- # "current_nonce_USER_WALLET_if_managed_here": global_nonce_USER_WALLET, # 示例:如果服务器管理此nonce
- "last_process_info": last_process_info # 最后处理信息 (如果使用)
- })
- if __name__ == "__main__":
- logger.info("启动核心数据更新线程...")
- updater_thread = threading.Thread(target=update_core_data_periodically, daemon=True)
- updater_thread.start()
- logger.info("启动抹茶数据更新线程...")
- updater_thread = threading.Thread(target=update_mexc_data_periodically, daemon=True)
- updater_thread.start()
- logger.info("启动pending信息獲取线程...")
- pending_thread = threading.Thread(target=update_tx_data_periodically, daemon=True)
- pending_thread.start()
- logger.info("启动餘額平衡线程...")
- pending_thread = threading.Thread(target=balance_available_funds_periodically, daemon=True)
- pending_thread.start()
- logger.info("主线程继续执行,可以执行其他任务或保持运行以观察数据更新。")
- logger.info("启动 Flask 套利执行服务器...")
- app.run(host='0.0.0.0', port=188, debug=False) # 使用与 price_checker 不同的端口
|