as.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. # -*- coding: utf-8 -*-
  2. from checker.logger_config import get_logger
  3. logger = get_logger('as')
  4. logger.info('\n\n----------------------------------------------as啓動--------------------------------------------')
  5. import threading
  6. import uuid # 用于生成唯一的流程ID
  7. import time
  8. import logging
  9. import erc20_to_mexc
  10. import web3_py_client
  11. import traceback
  12. import copy
  13. import sys
  14. from decimal import Decimal, ROUND_DOWN
  15. from flask import Flask, request, jsonify
  16. from flask_cors import CORS # 导入
  17. from as_utils import get_formatted_timestamp
  18. from as_utils import add_state_flow_entry
  19. from config import wallet
  20. from binance.client import Client # 用于获取ETH价格
  21. from checker import ok_chain_client
  22. from mexc_client import MexcClient
  23. from pprint import pprint
  24. from pprint import pformat
  25. ok_chain_client.api_config = {
  26. "api_key": 'a05643ab-fb17-402b-94a8-a886bd343301', # 请替换为您的真实 API Key
  27. "secret_key": '9D59B53EB1E60B1B5F290D3698A8C9DA', # 请替换为您的真实 Secret Key
  28. "passphrase": 'Qwe123123.', # 请替换为您的真实 Passphrase
  29. }
  30. # 配置日志
  31. log = logging.getLogger('werkzeug')
  32. log.setLevel(logging.ERROR)
  33. web3 = web3_py_client.EthClient()
  34. w3 = web3.w3
  35. mexc = MexcClient()
  36. USER_WALLET = wallet["user_wallet"]
  37. USER_EXCHANGE_WALLET = wallet["user_exchange_wallet"]
  38. # 该代币最后一次执行套利的区块信息 (如果需要防止过于频繁的同类套利,不然变成砸盘、拉盘的了)
  39. last_process_info = {} # 示例: {"RATO_USDT": 0}
  40. MIN_BLOCKS_BETWEEN_ARB = Decimal(2) # 在重试相同交易对之前等待几个区块
  41. # --- 全局状态和锁 ---
  42. processing_list = [] # 正在处理的任务列表
  43. history_process_list = [] # 已完成的任务历史列表
  44. list_lock = threading.Lock() # 用于修改 processing_list 和 history_process_list 结构的锁
  45. # --- 一些核心數據和鎖 ---
  46. core_data = {
  47. "nonce": 0, # 全局 Nonce
  48. "eth_balance": Decimal(0), # 全局 eth餘額
  49. "eth_price": 0, # 全局 eth價格
  50. "block_number": 0, # 全局 區塊號
  51. "block": None, # 全局 最后一個區塊的信息
  52. }
  53. core_lock = threading.Lock() # 核心數據的锁
  54. # --- pending數據和鎖 ---
  55. pending_data = {
  56. # # 數據結構的demo
  57. # "0xaf181bbbf5bf56d9204bd18cd25abd90e51890e848525e7788b410689c0c26a4": {
  58. # "block_number": 22570370, # 提交pending時的區塊,隔幾個區塊去獲取數據會更準確
  59. # "tx_details": None, # okapi解析的數據, None就是還沒有獲取到
  60. # "reponse": None, # okapi最後一次獲取到的數據
  61. # },
  62. }
  63. pending_lock = threading.Lock()
  64. PENDING_CONFIRM_BLOCK = 3 # 需要幾個區塊才進行確認
  65. # --- mexc相關數據和鎖 ---
  66. mexc_data = {
  67. "account_info": {},
  68. "deposit_list": [],
  69. "withdraw_list": [],
  70. "coin_info_map": {}, # 處理過的幣種信息,coin_info_map[coin][network]
  71. }
  72. mexc_lock = threading.Lock()
  73. CHAIN_ID = -1
  74. try:
  75. if w3.provider:
  76. CHAIN_ID = w3.eth.chain_id
  77. logger.info(f"Web3 已连接。chain_id={CHAIN_ID}")
  78. else:
  79. logger.info("Web3 未连接。")
  80. except Exception as e:
  81. logger.info(f"初始化 {USER_WALLET} 的全局 nonce 时出错: {e}")
  82. # Binance 客户端 (无需API Key/Secret即可获取公开行情数据)
  83. try:
  84. binance_client = Client()
  85. # 测试连接 (可选,但建议)
  86. binance_client.ping()
  87. logger.info("成功连接到 Binance API。")
  88. except Exception as e:
  89. logger.error(f"初始化 Binance Client 时发生错误: {e}")
  90. binance_client = None
  91. # --- Flask 应用 ---
  92. app = Flask(__name__)
  93. CORS(app) # 在创建 app 实例后启用 CORS
  94. def move_completed_process_to_history(process_id_to_move: str) -> bool:
  95. """
  96. 将一个完成的 process_item 从 processing_list 移动到 history_process_list。
  97. 此操作是线程安全的。
  98. Args:
  99. process_id_to_move (str): 要移动的 process_item 的 ID。
  100. Returns:
  101. bool: 如果成功找到并移动了 item,则返回 True,否则返回 False。
  102. """
  103. global processing_list, history_process_list # 因为我们要修改这两个列表
  104. item_to_move = None
  105. moved_successfully = False
  106. with list_lock:
  107. # 查找并从 processing_list 中移除
  108. found_index = -1
  109. for i, item in enumerate(processing_list):
  110. if item.get('id') == process_id_to_move:
  111. found_index = i
  112. break
  113. if found_index != -1:
  114. item_to_move = processing_list.pop(found_index) # 从 processing_list 中移除并获取它
  115. # 假设在 item_to_move 中,其 currentState 已经被 arbitrage_process_flow 更新为 COMPLETED 或 FAILED
  116. # arbitrage_process.add_state_flow_entry(item_to_move, "MOVED_TO_HISTORY", f"流程处理完毕,移至历史记录。最终状态: {item_to_move.get('currentState', 'N/A')}", "info")
  117. history_process_list.append(item_to_move) # 添加到 history_process_list
  118. logger.info(f"已将 process_id: {process_id_to_move} 从 processing_list 移动到 history_process_list。")
  119. moved_successfully = True
  120. else:
  121. logger.warning(f"尝试移动到 history_list 时,在 processing_list 中未找到 process_id: {process_id_to_move}")
  122. return moved_successfully
  123. # 策略構建器
  124. def strategy_builder(process_item):
  125. profit = Decimal(process_item['profit'])
  126. profitLimit = Decimal(process_item['profitLimit'])
  127. strategy = process_item['strategy']
  128. # 對於高利潤交易,進行適當加速
  129. gas_limit_multiplier = 1
  130. gas_price_multiplier = 1
  131. # if profit > Decimal(5) * profitLimit:
  132. # gas_price_multiplier = 5
  133. # elif profit > Decimal(10) * profitLimit:
  134. # gas_price_multiplier = 10
  135. global core_data
  136. global core_lock
  137. global pending_data
  138. global pending_lock
  139. global mexc_data
  140. global mexc_lock
  141. if strategy == 'erc20_to_mexc':
  142. return erc20_to_mexc.ArbitrageProcess(gas_limit_multiplier, gas_price_multiplier, process_item,
  143. core_data, core_lock,
  144. pending_data, pending_lock,
  145. mexc_data, mexc_lock
  146. )
  147. else:
  148. process_item_formated = pformat(process_item, indent=2)
  149. logger.error(f'不存在的策略:{strategy}\n{process_item_formated}')
  150. # 實際套利邏輯
  151. def arbitrage_process_flow(process_item):
  152. """
  153. 在单独线程中执行的实际套利逻辑。
  154. 会直接修改 'process_item' 字典。
  155. """
  156. process_id = process_item['id']
  157. ap = strategy_builder(process_item)
  158. # 一般都是从这个流程开始,测试时可以稍作修改、测试后续流程
  159. ap._set_state(ap.STATE_CHECK)
  160. # 在主循环中周期性调用 run_arbitrage_step
  161. while ap.current_state != ap.STATE_COMPLETED and ap.current_state != ap.STATE_FAILED and ap.current_state != ap.STATE_REJECT:
  162. ap.run_arbitrage_step()
  163. if ap.current_state == ap.STATE_WAITING_TRANSFER_ARRIVE or ap.current_state == ap.STATE_WAITING_WITHDRAWAL_CONFIRM:
  164. time.sleep(10)
  165. ap.run_arbitrage_step()
  166. move_completed_process_to_history(process_id)
  167. # --- 核心數據更新綫程函數 ---
  168. def update_core_data_periodically():
  169. """
  170. 周期性更新 nonce 和 ETH 价格的线程函数。
  171. """
  172. global core_data # 明确表示我们要修改全局的 core_data
  173. if not USER_WALLET or USER_WALLET == "你的钱包地址":
  174. logger.error("USER_WALLET 未正确配置。nonce 更新将无法进行。")
  175. # 如果 USER_WALLET 未配置,可以考虑让线程不执行 nonce 更新,或者直接退出
  176. # 这里我们选择继续运行,但 nonce 不会被更新
  177. while True:
  178. try:
  179. new_eth_price = None
  180. new_eth_balance = None
  181. new_nonce = None
  182. new_block_number = None
  183. new_block = None
  184. # 1. 从 Binance 获取 ETH 价格
  185. if binance_client:
  186. try:
  187. ticker = binance_client.get_symbol_ticker(symbol="ETHUSDT")
  188. new_eth_price = float(ticker['price'])
  189. except Exception as e:
  190. logger.error(f"从 Binance 获取 ETH 价格失败: {e}")
  191. else:
  192. logger.warning("Binance client 未初始化, 无法获取 ETH 价格。")
  193. # 2. 获取最新的 Nonce 和 最新的block_number 以及 最新的賬戶eth餘額
  194. # 确保 w3 已初始化且 USER_WALLET 已配置
  195. if w3 and w3.is_connected() and USER_WALLET and USER_WALLET != "你的钱包地址":
  196. try:
  197. new_block = w3.eth.get_block('latest')
  198. new_block_number = new_block['number']
  199. new_nonce = w3.eth.get_transaction_count(USER_WALLET, 'latest')
  200. eth_balance_origin = w3.eth.get_balance(USER_WALLET)
  201. new_eth_balance = Decimal(eth_balance_origin / (10 ** 18))
  202. new_eth_balance = new_eth_balance.quantize(Decimal('1e-6'), rounding=ROUND_DOWN)
  203. except Exception as e:
  204. logger.error(f"为 {USER_WALLET} 获取 Nonce、BlockNumber、EthBalances 失败: {e}")
  205. elif not (w3 and w3.is_connected()):
  206. logger.warning("Web3 未连接, 无法获取 nonce。")
  207. elif not (USER_WALLET and USER_WALLET != "你的钱包地址"):
  208. logger.warning("USER_WALLET 配置不正确, 无法获取 nonce。")
  209. # 3. 更新共享数据 core_data (使用锁)
  210. # 只有当获取到新数据时才更新,避免不必要的写操作和日志
  211. with core_lock:
  212. if new_eth_price is not None and core_data["eth_price"] != new_eth_price:
  213. eth_price = Decimal(new_eth_price)
  214. eth_price = eth_price.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
  215. core_data["eth_price"] = eth_price
  216. # 判斷block_number是否發生變化(升高)
  217. if new_block_number is not None and new_block_number > core_data["block_number"]:
  218. core_data["block_number"] = new_block_number
  219. core_data["block"] = new_block
  220. # 區塊變了才刷新nonce,否則還是要靠本地的緩存維護
  221. if new_nonce is not None and core_data["nonce"] != new_nonce:
  222. core_data["nonce"] = new_nonce
  223. # 餘額也同理
  224. if new_eth_balance is not None and core_data["eth_balance"] != new_eth_balance:
  225. core_data["eth_balance"] = new_eth_balance
  226. # 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']}")
  227. except Exception as e:
  228. # 捕获线程循环中的其他潜在错误
  229. exc_traceback = traceback.format_exc()
  230. logger.error(f"数据更新线程发生未知错误\n{exc_traceback}")
  231. # traceback.print_exc()
  232. # 等待 500ms
  233. time.sleep(0.5)
  234. # --- mexc數據更新綫程函數 ---
  235. def update_mexc_data_periodically():
  236. """
  237. 周期性更新 mexc的相關數據 的线程函数。
  238. """
  239. global mexc_data
  240. # 每60秒獲取一次coin_info
  241. coin_info_get_delay = 60
  242. while True:
  243. try:
  244. new_account_info = None
  245. new_withdraw_list = None
  246. new_deposit_list = None
  247. new_coin_info_list = None
  248. # 1. new_account_info
  249. try:
  250. new_account_info = mexc.trade.get_account_info()
  251. if 'balances' not in new_account_info:
  252. raise Exception("未找到balances")
  253. with mexc_lock:
  254. mexc_data['account_info'] = new_account_info
  255. # logger.info(f'account_info: {new_account_info['balances']}')
  256. except Exception as e:
  257. logger.error(f"从 Mexc 获取 Balance 失败: {e}, {new_account_info}")
  258. # 2. new_deposit_list
  259. try:
  260. new_deposit_list = mexc.wallet.get_deposit_list()
  261. if not isinstance(new_deposit_list, list):
  262. raise Exception("充值信息獲取錯誤")
  263. with mexc_lock:
  264. mexc_data['deposit_list'] = new_deposit_list
  265. # logger.info(f'deposit_list: {new_deposit_list[0]}')
  266. except Exception as e:
  267. logger.error(f"从 Mexc 获取 deposit_list 失败: {e}, {new_deposit_list}")
  268. # 3. new_withdraw_list
  269. try:
  270. new_withdraw_list = mexc.wallet.get_withdraw_list()
  271. if not isinstance(new_withdraw_list, list):
  272. raise Exception("提現信息獲取錯誤")
  273. with mexc_lock:
  274. mexc_data['withdraw_list'] = new_withdraw_list
  275. # logger.info(f'withdraw_list: {new_withdraw_list[0]}')
  276. except Exception as e:
  277. logger.error(f"从 Mexc 获取 withdraw_list 失败: {e}, {new_withdraw_list}")
  278. # 4. new_coin_info list
  279. try:
  280. if coin_info_get_delay >= 60:
  281. coin_info_get_delay = 0
  282. new_coin_info_list = mexc.wallet.get_coinlist()
  283. if not isinstance(new_coin_info_list, list):
  284. raise Exception("幣種信息獲取錯誤")
  285. # 處理幣種信息
  286. new_coin_info_map = {}
  287. for coin_info in new_coin_info_list:
  288. new_coin_info_map[coin_info['coin']] = {}
  289. for network in coin_info['networkList']:
  290. new_coin_info_map[coin_info['coin']][network['netWork']] = network
  291. with mexc_lock:
  292. mexc_data['coin_info_map'] = new_coin_info_map
  293. # logger.info(f'coin_info_map: {new_coin_info_map['USDT']}')
  294. except Exception as e:
  295. logger.error(f"从 Mexc 获取 withdraw_list 失败: {e}, {new_withdraw_list}")
  296. except Exception as e:
  297. # 捕获线程循环中的其他潜在错误
  298. exc_traceback = traceback.format_exc()
  299. logger.error(f"数据更新线程发生未知错误\n{exc_traceback}")
  300. # traceback.print_exc()
  301. # 幣種信息處理的delay
  302. coin_info_get_delay = coin_info_get_delay + 1
  303. # 等待 1s
  304. time.sleep(1)
  305. # --- tx pending數據獲取綫程函數 ---
  306. def update_tx_data_periodically():
  307. """
  308. 每一秒獲取一條tx數據
  309. """
  310. global pending_data # 明确表示我们要修改全局的 pending_data
  311. while True:
  312. # 等待1s
  313. time.sleep(1)
  314. try:
  315. # 使用拷貝后的數據,否則可能會出現綫程問題
  316. with pending_lock:
  317. pending_data_copy = copy.deepcopy(pending_data)
  318. # 核心數據同理
  319. with core_lock:
  320. core_data_copy = copy.deepcopy(core_data)
  321. block_number = core_data_copy['block_number']
  322. for tx in pending_data_copy:
  323. try:
  324. # 已獲取的就不要再獲取了
  325. if pending_data_copy[tx]['tx_details'] is not None:
  326. continue
  327. # PENDING_CONFIRM_BLOCK個區塊之後的才進行確認,防止回滾頻繁觸發
  328. if block_number < pending_data_copy[tx]['block_number'] + PENDING_CONFIRM_BLOCK:
  329. continue
  330. # 調用ok的api,直接獲取詳細交易
  331. ok_rst = ok_chain_client.history(CHAIN_ID, tx)
  332. # 存儲最後一次獲取的細節
  333. with pending_lock:
  334. pending_data[tx]['response'] = ok_rst
  335. # 錯誤響應
  336. if ok_rst['code'] != '0':
  337. raise RuntimeError("API 返回错误响应", ok_rst)
  338. # ok不一定那麽快獲取到
  339. if ok_rst['data'] is None:
  340. # 每一個之間等待1s
  341. time.sleep(1)
  342. continue
  343. details = ok_rst['data']
  344. status = details['status']
  345. if status != 'fail':
  346. # 有時候不會馬上識別出成交數量
  347. if 'fromTokenDetails' not in details or 'toTokenDetails' not in details:
  348. # 每一個之間等待1s
  349. time.sleep(1)
  350. continue
  351. # 有時候不會馬上識別出成交數量 判斷2
  352. if details['fromTokenDetails'] is None or details['toTokenDetails'] is None:
  353. # 每一個之間等待1s
  354. time.sleep(1)
  355. continue
  356. # 有時候不會馬上識別出gas信息之類的
  357. fileds = ['gasLimit', 'gasPrice', 'gasUsed', 'height']
  358. insufficient = False
  359. for filed in fileds:
  360. if details[filed] == '':
  361. insufficient = True
  362. break
  363. if insufficient:
  364. # 每一個之間等待1s
  365. time.sleep(1)
  366. continue
  367. # 成功獲取之後直接調用更新
  368. with pending_lock:
  369. pending_data[tx]['tx_details'] = details
  370. formated_data = pformat(ok_rst['data'], indent=2) # indent=2 让格式更整齐
  371. logger.info(f"獲取成功: \n{formated_data}")
  372. except Exception as e:
  373. exc_traceback = traceback.format_exc()
  374. logger.error(f"tx數據獲取失敗\n{exc_traceback}")
  375. # traceback.print_exc()
  376. # 每一個之間等待1s
  377. time.sleep(1)
  378. except Exception as e:
  379. exc_traceback = traceback.format_exc()
  380. logger.error(f"pending更新线程发生未知错误\n{exc_traceback}")
  381. # traceback.print_exc()
  382. # --- 餘額平衡綫程 ---
  383. def balance_available_funds_periodically():
  384. """
  385. 每10秒嘗試平衡一次餘額
  386. """
  387. PROPORTION_LIMIT = Decimal(0.37) # 鏈上資金比例低於這個值就會觸發平衡
  388. PROPORTION_TARGET = Decimal(1) # 鏈上資金占比目標,1表示100%是鏈上資金
  389. BASE_COIN = 'USDT'
  390. BASE_COIN_ADDR = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
  391. CANT_WITHDRAW_STATE_LIST = ['IDLE',
  392. 'CHECK',
  393. 'SELLING_ON_EXCHANGE',
  394. 'WAITING_SELL_CONFIRM',
  395. "BUYING_ON_CHAIN",
  396. "WAITING_CHAIN_CONFIRM",
  397. "WAITING_EXCHANGE_ROLLBACK"
  398. ]
  399. global processing_list
  400. while True:
  401. time.sleep(10)
  402. try:
  403. mexc_available = Decimal(0)
  404. # 交易所餘額讀取
  405. with mexc_lock:
  406. balances = mexc_data['account_info']['balances']
  407. for balance in balances:
  408. if balance['asset'].upper() == BASE_COIN:
  409. mexc_available = Decimal(balance['free'])
  410. mexc_available = mexc_available.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
  411. # 鏈上餘額讀取
  412. chain_available = web3.get_erc20_balance(BASE_COIN_ADDR)
  413. chain_available = chain_available.quantize(Decimal('1e-2'), rounding=ROUND_DOWN)
  414. # 縂可用餘額(不包括lock的)
  415. total_available = mexc_available + chain_available
  416. # 小於20都懶得做平衡,手續費都不夠
  417. if total_available < Decimal(20):
  418. continue
  419. # 抹茶餘額也要大於20
  420. if mexc_available < Decimal(20):
  421. continue
  422. # 計算鏈上資金佔總體的比例
  423. proportion = chain_available / total_available
  424. proportion = proportion.quantize(Decimal('1e-4'), rounding=ROUND_DOWN)
  425. # 判斷比例是否滿足limit,不滿足則先不提現(或者鏈上資產小於500也提現,測試服專用)
  426. if proportion > PROPORTION_LIMIT and chain_available > Decimal(500):
  427. continue
  428. # 鏈上應該具備的資金量
  429. chain_available_target = total_available * PROPORTION_TARGET
  430. mexc_should_be_withdrawal_founds = chain_available_target - chain_available
  431. mexc_should_be_withdrawal_founds = mexc_should_be_withdrawal_founds.quantize(Decimal(1), rounding=ROUND_DOWN)
  432. # 如若當前綫程中有未執行完的,先不執行提現
  433. with list_lock:
  434. cant_withdraw = False
  435. for processing in processing_list:
  436. if processing['currentState'] in CANT_WITHDRAW_STATE_LIST:
  437. cant_withdraw = True
  438. break
  439. # 不執行提現判斷
  440. if cant_withdraw:
  441. # formated_processing = pformat(processing_list, indent=2)
  442. # logger.info(f"不執行提現, 因爲: \n{formated_processing}")
  443. continue
  444. if mexc_should_be_withdrawal_founds > 0:
  445. withdrawal_params = {
  446. 'coin': 'USDT',
  447. 'netWork': 'ETH',
  448. 'address': USER_WALLET,
  449. 'amount': mexc_should_be_withdrawal_founds,
  450. }
  451. withdrawal_params_formated = pformat(withdrawal_params, indent=2)
  452. withdrawal_rst = mexc.wallet.post_withdraw(withdrawal_params)
  453. withdrawal_rst_formated = pformat(withdrawal_rst, indent=2)
  454. logger.info(f"[withdrawal]mexc_available={mexc_available}, chain_available={chain_available},proportion={proportion}, mexc_withdrawal={mexc_should_be_withdrawal_founds}")
  455. if "id" not in withdrawal_rst:
  456. msg = f"[withdrawal]交易所提现失败\n參數: {withdrawal_params_formated}\n響應: {withdrawal_rst_formated}"
  457. logger.error(msg)
  458. else:
  459. msg = f"[withdrawal]交易所提现已发送\n參數: {withdrawal_params_formated}\n響應: {withdrawal_rst_formated}"
  460. logger.info(msg)
  461. else:
  462. # TODO 這是另一個方向,需要從鏈上往交易所劃轉
  463. pass
  464. except Exception as e:
  465. exc_traceback = traceback.format_exc()
  466. logger.error(f"可用資金平衡綫程发生未知错误\n{exc_traceback}")
  467. # traceback.print_exc()
  468. @app.route('/submit_process', methods=['POST'])
  469. def handle_submit_process():
  470. data = request.get_json()
  471. if not data:
  472. return jsonify({"error": "无效的 JSON 请求体"}), 400
  473. required_fields = ['tx', 'profit', 'profitLimit', 'symbol', 'strategy']
  474. for field in required_fields:
  475. if field not in data:
  476. return jsonify({"error": f"缺少字段: {field}, keys: {data.keys()}"}), 400
  477. try:
  478. profit = Decimal(str(data['profit'])) # 利润
  479. profit_limit = Decimal(str(data['profitLimit'])) # 利润阈值
  480. except (decimal.InvalidOperation, ValueError) as e:
  481. return jsonify({"error": f"请求体中包含无效的小数/整数值: {e}"}), 400
  482. symbol = data['symbol'] # 交易对符号
  483. # 检查此交易对此区块是否处理过
  484. last_trade_block = last_process_info.get(symbol)
  485. with core_lock:
  486. current_block = core_data['block_number']
  487. if last_trade_block:
  488. if current_block - last_trade_block < MIN_BLOCKS_BETWEEN_ARB:
  489. return jsonify({"message": f"已跳过: {symbol} 最近已处理 (区块 {last_trade_block}). 当前区块 {current_block}."}), 200
  490. if profit >= profit_limit:
  491. process_id = str(uuid.uuid4()) # 生成唯一流程ID
  492. process_item = copy.deepcopy(data)
  493. process_item['id'] = process_id
  494. process_item['creationTime'] = get_formatted_timestamp(), # 创建时间
  495. process_item['userWallet'] = USER_WALLET
  496. process_item['userExchangeWallet'] = USER_EXCHANGE_WALLET
  497. process_item['stateFlow'] = [] # 状态流转记录
  498. process_item['currentState'] = "PENDING_START"
  499. # 初始状态更新
  500. add_state_flow_entry(process_item, "RECEIVED", f"流程已接收。利润 {profit} >= 利润阈值 {profit_limit}。开始套利。", "success")
  501. with list_lock:
  502. processing_list.append(process_item)
  503. last_process_info[symbol] = current_block
  504. logger.info(f"已更新 {symbol} 的最后处理信息至区块 {current_block}")
  505. # 在新线程中开始套利过程
  506. arb_thread = threading.Thread(target=arbitrage_process_flow, args=(process_item,), daemon=True)
  507. arb_thread.start()
  508. return jsonify({"message": "套利过程已启动", "process_id": process_id}), 201
  509. else:
  510. return jsonify({"message": f"利润 {profit} 小于利润阈值 {profit_limit}。不处理。"}), 200
  511. @app.route('/processing', methods=['GET'])
  512. def get_processing_list():
  513. """获取正在处理的任务列表"""
  514. with list_lock:
  515. # 返回一个副本,以避免在迭代生成 JSON 响应时列表被修改的问题
  516. return jsonify(list(processing_list))
  517. @app.route('/history', methods=['GET'])
  518. def get_history_list():
  519. """获取已完成的任务历史列表"""
  520. with list_lock:
  521. return jsonify(list(history_process_list))
  522. @app.route('/status', methods=['GET'])
  523. def get_status():
  524. """获取系统状态概览"""
  525. with list_lock:
  526. return jsonify({
  527. "processing_count": len(processing_list), # 正在处理的任务数量
  528. "history_count": len(history_process_list), # 历史任务数量
  529. # "current_nonce_USER_WALLET_if_managed_here": global_nonce_USER_WALLET, # 示例:如果服务器管理此nonce
  530. "last_process_info": last_process_info # 最后处理信息 (如果使用)
  531. })
  532. if __name__ == "__main__":
  533. logger.info("启动核心数据更新线程...")
  534. updater_thread = threading.Thread(target=update_core_data_periodically, daemon=True)
  535. updater_thread.start()
  536. logger.info("启动抹茶数据更新线程...")
  537. updater_thread = threading.Thread(target=update_mexc_data_periodically, daemon=True)
  538. updater_thread.start()
  539. logger.info("启动pending信息獲取线程...")
  540. pending_thread = threading.Thread(target=update_tx_data_periodically, daemon=True)
  541. pending_thread.start()
  542. logger.info("启动餘額平衡线程...")
  543. pending_thread = threading.Thread(target=balance_available_funds_periodically, daemon=True)
  544. pending_thread.start()
  545. logger.info("主线程继续执行,可以执行其他任务或保持运行以观察数据更新。")
  546. logger.info("启动 Flask 套利执行服务器...")
  547. app.run(host='0.0.0.0', port=188, debug=False) # 使用与 price_checker 不同的端口