c_erc20_to_mexc_simple.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import requests
  2. import decimal
  3. import time
  4. import threading
  5. import json
  6. import logging
  7. import ok_chain_client # 假设这是你的 OKX Chain 客户端库
  8. import pprint
  9. import plotly.graph_objects as go
  10. import argparse
  11. from flask import Flask, render_template, jsonify
  12. from collections import deque
  13. from plotly.utils import PlotlyJSONEncoder
  14. # configs
  15. from config import wallet
  16. from config import okchain_api
  17. from config import arb
  18. # logs
  19. from logger_config import get_logger
  20. logger = get_logger('as')
  21. # lite客户端
  22. from web3_py_client_lite import EthClient
  23. web3_client = EthClient()
  24. # delay区块,有利润后延迟几个区块再发
  25. prev_profit_block_number = 0
  26. send_delay_block = 1
  27. # ok web3的配置
  28. ok_chain_client.api_config = okchain_api # 假设ok_chain_client有此配置方式
  29. # --- 配置 arb_executor.py 的 HTTP 地址和端口 ---
  30. ARB_EXECUTOR_URL = arb["ARB_EXECUTOR_URL"]
  31. # --- 配置部分 ---
  32. # IN_AMOUNT_TO_QUERY 将在循环中动态确定
  33. EXCHANGE_OUT_AMOUNT = decimal.Decimal(str(arb["COIN_TOKEN_TRADE_AMOUNT"])) # 确保是Decimal
  34. PROFIT_LIMIT = decimal.Decimal(str(arb["PROFIT_LIMIT"])) # 确保是Decimal
  35. IN_TOKEN_ADDRESS = arb["BASE_TOKEN_ADDRESS"]
  36. IN_TOKEN_DECIMALS = web3_client.get_erc20_decimals(IN_TOKEN_ADDRESS)
  37. OUT_TOKEN_ADDRESS = arb["COIN_TOKEN_ADDRESS"]
  38. SLIPPAGE = arb["SLIPPAGE"]
  39. MEXC_TARGET_PAIR_USDT = arb["CEX_PAIR"]
  40. CHAIN_ID = arb["CHAIN_ID"]
  41. STRATEGY = arb["STRATEGY"]
  42. # 錢包的配置
  43. USER_WALLET = wallet["user_wallet"]
  44. USER_EXCHANGE_WALLET = wallet["user_exchange_wallet"]
  45. proxies = None # {'http': 'http://proxy_url:port', 'https': 'http://proxy_url:port'}
  46. # 運行模式【trade、view】
  47. mode = None
  48. # oo_price_usdt_per_target = None # 这个全局变量似乎没有被有效使用,价格在循环内获取
  49. # 配置請求的日志等級
  50. app = Flask(__name__)
  51. log = logging.getLogger('werkzeug')
  52. log.setLevel(logging.ERROR)
  53. REFRESH_INTERVAL_SECONDS = 1 # 稍微增加间隔以减少API调用频率
  54. MAX_HISTORY_POINTS_PLOTLY = 21600
  55. historical_data_points = deque(maxlen=MAX_HISTORY_POINTS_PLOTLY)
  56. TARGET_ASSET_SYMBOL = MEXC_TARGET_PAIR_USDT.split('_')[0] # e.g., RATO
  57. BASE_CURRENCY_SYMBOL = MEXC_TARGET_PAIR_USDT.split('_')[1] # e.g., USDT (assumed to be consistent with IN_TOKEN_ADDRESS)
  58. # --- 链上价格获取函数 (Okx) ---
  59. # 返回: price_base_per_target (例如 USDT per RATO)
  60. def get_chain_price_vs_target_currency(chain_id, in_token_addr, out_token_addr, amount_in_base_human, in_token_decimals, slippage, user_wallet_addr):
  61. try:
  62. # amount_in_base_human 已经是 decimal.Decimal 类型的人类可读数量
  63. in_token_amount_atomic = int(amount_in_base_human * (10 ** in_token_decimals)) # 转为原子单位整数
  64. data = ok_chain_client.swap(chain_id, in_token_amount_atomic, in_token_addr, out_token_addr, slippage, user_wallet_addr, None, 'fast')
  65. if data.get('code') == '0' and data.get('data'):
  66. d = data['data'][0]
  67. router_result = d['routerResult']
  68. in_dec, out_dec = int(router_result['fromToken']['decimal']), int(router_result['toToken']['decimal'])
  69. atomic_in_base, atomic_out_target = decimal.Decimal(router_result['fromTokenAmount']), decimal.Decimal(router_result['toTokenAmount'])
  70. human_in_base = atomic_in_base / (10 ** in_dec)
  71. human_out_target = atomic_out_target / (10 ** out_dec)
  72. if human_out_target == 0: return {"error": f"OO输出目标代币为0 ({CHAIN_ID})"}, data # data 也返回
  73. return {"price_base_per_target": human_in_base / human_out_target}, data
  74. else:
  75. pprint.pprint(data)
  76. return {
  77. "error": f"Okx API错误({chain_id}) - Code:{data.get('code', 'N/A')}, Msg:{data.get('msg', data.get('message', 'N/A')) if isinstance(data, dict) else '格式错误'}"}, None
  78. except Exception as e:
  79. logger.error(f"Okx ({chain_id})请求错误详情: ", exc_info=True)
  80. return {"error": f"Okx ({chain_id})请求错误: {e}"}, None
  81. # MEXC 现货 (获取 目标代币/USDT 的 bid 价格)
  82. # 返回: price_target_per_usdt (例如 RATO per USDT)
  83. def get_mexc_spot_price_target_usdt_bid(pair_symbol):
  84. url = "https://api.mexc.com/api/v3/depth"
  85. params = {'symbol': pair_symbol.replace('_', ''), 'limit': 1000} # 减少limit,5000可能过大且非必要
  86. try:
  87. r = requests.get(url, params=params, proxies=proxies, timeout=5) # 减少超时
  88. r.raise_for_status()
  89. data = r.json()
  90. if 'bids' in data and data['bids']: # 确保bids存在且不为空
  91. bids = data['bids']
  92. trade_volume_remaining = EXCHANGE_OUT_AMOUNT # 还需要卖出的数量 (Decimal)
  93. trade_value = decimal.Decimal('0') # 累计的总价值 (Decimal)
  94. accumulated_volume = decimal.Decimal('0') # 累计吃单量
  95. for orderbook in bids:
  96. price = decimal.Decimal(orderbook[0])
  97. volume = decimal.Decimal(orderbook[1])
  98. if trade_volume_remaining <= decimal.Decimal('0'):
  99. break # 已经满足卖出量
  100. can_fill = min(volume, trade_volume_remaining)
  101. trade_value += price * can_fill
  102. accumulated_volume += can_fill
  103. trade_volume_remaining -= can_fill
  104. if accumulated_volume == decimal.Decimal('0'): # 如果一点都没卖出去
  105. # logger.warning(f"MEXC无法以EXCHANGE_OUT_AMOUNT={EXCHANGE_OUT_AMOUNT}获取任何 efectiva 卖出价格,累积量为0")
  106. return {"error": f"MEXC订单簿深度不足以卖出{EXCHANGE_OUT_AMOUNT} {TARGET_ASSET_SYMBOL}"}, decimal.Decimal('0')
  107. # 计算平均卖出价格
  108. # sell_price 代表 1 TARGET_ASSET = X USDT
  109. sell_price = trade_value / accumulated_volume
  110. sell_price = sell_price.quantize(decimal.Decimal('1e-10'), rounding=decimal.ROUND_DOWN)
  111. # trade_value 代表卖出 accumulated_volume 个 TARGET_ASSET 能得到的 USDT 总量
  112. return {
  113. "price_target_per_usdt": sell_price # 这个名字其实是 RATO/USDT,所以可以叫 price_target_per_base
  114. }, trade_value # 返回的是实际能卖出 EXCHANGE_OUT_AMOUNT (或更少,如果深度不足) 所得的 USDT 总额
  115. else:
  116. # logger.warning(f"MEXC现货({pair_symbol}) bids 数据不存在或为空: {data}")
  117. return {"error": f"MEXC现货({pair_symbol}) bids 数据不存在或为空"}, decimal.Decimal('0')
  118. except requests.exceptions.RequestException as e:
  119. # logger.error(f"MEXC现货({pair_symbol})请求错误: {e}")
  120. return {"error": f"MEXC现货({pair_symbol})请求错误: {e}"}, decimal.Decimal('0')
  121. except Exception as e:
  122. # logger.error(f"MEXC现货({pair_symbol})处理错误: {e}", exc_info=True)
  123. return {"error": f"MEXC现货({pair_symbol})处理错误: {e}"}, decimal.Decimal('0')
  124. latest_values_for_table = {
  125. f"oo_price_usdt_per_target": "N/A",
  126. f"mexc_price_target_per_base": "N/A", # MEXC Bid1 (converted to USDT/TARGET)
  127. f"diff_oo_vs_mexc_percentage": "N/A",
  128. "profit_value_for_table": "N/A", # 新增:用于表格的利润值
  129. "oo_error": None, "mexc_error": None,
  130. "last_updated": "N/A",
  131. "mexc_pair_usdt_for_display": MEXC_TARGET_PAIR_USDT,
  132. "target_asset_symbol_for_display": TARGET_ASSET_SYMBOL,
  133. "base_currency_symbol_for_display": BASE_CURRENCY_SYMBOL
  134. }
  135. data_lock = threading.Lock()
  136. def calculate_percentage_diff(price_a_base_per_target, price_b_base_per_target):
  137. # price_a: MEXC卖价 (USDT/TARGET) - 链上买的目标币,拿到CEX卖掉
  138. # price_b: 链上买价 (USDT/TARGET) - 链上用USDT买目标币
  139. # 期望 price_a > price_b
  140. if price_a_base_per_target is not None and price_b_base_per_target is not None and \
  141. isinstance(price_a_base_per_target, decimal.Decimal) and \
  142. isinstance(price_b_base_per_target, decimal.Decimal) and price_b_base_per_target != 0:
  143. # (卖价 - 买价) / 买价
  144. rst = (price_a_base_per_target - price_b_base_per_target) / price_b_base_per_target
  145. rst = rst.quantize(decimal.Decimal('1e-6'), rounding=decimal.ROUND_DOWN) # 提高精度
  146. return rst
  147. return None
  148. def send_arb_msg(profit_amount, chain_swap_data, mexc_price_usdt_per_target, in_amount_to_query_human):
  149. # chain_swap_data 是从 get_chain_price_vs_target_currency 返回的第二个值
  150. if not (chain_swap_data and chain_swap_data.get('data') and chain_swap_data['data']):
  151. logger.error(f"套利消息发送失败:链上交易数据不完整 {chain_swap_data}")
  152. return
  153. d = chain_swap_data['data'][0]
  154. tx = d['tx'] # 这是预签名的交易结构体,不是tx hash
  155. router_result = d['routerResult']
  156. from_token_info = router_result['fromToken']
  157. to_token_info = router_result['toToken']
  158. in_dec, out_dec = int(from_token_info['decimal']), int(to_token_info['decimal'])
  159. # human_in_base 根据实际传入的 IN_AMOUNT_TO_QUERY (trade_value) 确定
  160. # human_out_target 是链上swap的实际输出
  161. atomic_out_target = decimal.Decimal(router_result['toTokenAmount'])
  162. human_out_target = atomic_out_target / (10 ** out_dec)
  163. arbitrage_data = {
  164. "tx": tx, # 预签名交易
  165. "profit": str(profit_amount.quantize(decimal.Decimal('0.001'))),
  166. "profitLimit": str(PROFIT_LIMIT.quantize(decimal.Decimal('0.001'))),
  167. # "mexcPriceUsdtPerTarget": str(mexc_price_usdt_per_target.quantize(decimal.Decimal('1e-8'))),
  168. "symbol": MEXC_TARGET_PAIR_USDT,
  169. "fromToken": IN_TOKEN_ADDRESS,
  170. "fromTokenAmountHuman": str(in_amount_to_query_human.quantize(decimal.Decimal(f'1e-{in_dec}'))),
  171. "fromTokenDecimal": str(in_dec),
  172. "toToken": OUT_TOKEN_ADDRESS,
  173. "toTokenAmountHuman": str(human_out_target.quantize(decimal.Decimal(f'1e-{out_dec}'))),
  174. "toTokenDecimal": str(out_dec),
  175. "exchangeOutAmount": str(EXCHANGE_OUT_AMOUNT.quantize(decimal.Decimal(f'1e-{out_dec}'))), # CEX上期望卖出的目标币数量
  176. "strategy": STRATEGY,
  177. }
  178. logger.info(f"正在提交套利数据到 {ARB_EXECUTOR_URL}, profit {arbitrage_data["profit"]}, profitLimit {arbitrage_data["profitLimit"]}")
  179. try:
  180. response = requests.post(ARB_EXECUTOR_URL, json=arbitrage_data, timeout=10)
  181. logger.info(f"套利执行器响应状态码: {response.status_code}")
  182. try:
  183. response_data = response.json()
  184. logger.info(f"套利执行器响应内容: {response_data}")
  185. except requests.exceptions.JSONDecodeError:
  186. logger.error(f"套利执行器响应无法解析为JSON: {response.text}")
  187. except requests.exceptions.RequestException as e:
  188. logger.error(f"连接套利执行器 {ARB_EXECUTOR_URL} 失败: {e}")
  189. except Exception as e:
  190. logger.error(f"发送套利消息未知错误: {e}", exc_info=True)
  191. def update_data_for_plotly_and_table():
  192. global historical_data_points, latest_values_for_table # IN_AMOUNT_TO_QUERY
  193. logger.info(f"数据更新线程 ({TARGET_ASSET_SYMBOL}/{BASE_CURRENCY_SYMBOL})...")
  194. # local_in_amount_to_query = decimal.Decimal(str(arb["IN_AMOUNT_TO_QUERY"])) # 从配置初始化,后续动态调整
  195. while True:
  196. fetch_time_full = time.strftime("%Y-%m-%d %H:%M:%S")
  197. fetch_time_chart = time.strftime("%H:%M:%S")
  198. # 1. MEXC: 获取 price_target_per_usdt (例如 RATO/USDT) 和相应的 trade_value_usdt
  199. # trade_value_usdt 是指如果以 EXCHANGE_OUT_AMOUNT 的目标代币在MEXC上砸盘卖出,能获得的USDT估值
  200. mexc_data, trade_value_usdt = get_mexc_spot_price_target_usdt_bid(MEXC_TARGET_PAIR_USDT)
  201. mexc_price_target_per_usdt = mexc_data.get("price_target_per_usdt") # TARGET/USDT
  202. mexc_err = mexc_data.get("error")
  203. # price_target_per_usdt: 这是1个目标币能卖多少USDT, 即 USDT/TARGET
  204. # 所以可以直接用,不需要转换,变量名应为 mexc_price_target_per_base
  205. mexc_price_target_per_base = None
  206. if mexc_price_target_per_usdt is not None and mexc_price_target_per_usdt > 0:
  207. mexc_price_target_per_base = mexc_price_target_per_usdt # RATO/USDT => USDT/TARGET (命名约定)
  208. elif not mexc_err and mexc_price_target_per_usdt is not None:
  209. mexc_err = mexc_err or "MEXC价格为0或无效"
  210. if mexc_err or trade_value_usdt == decimal.Decimal('0'): # 如果MEXC有问题或无法确定砸盘价值,则跳过本次循环
  211. logger.warning(f"MEXC数据获取问题: {mexc_err}, trade_value_usdt: {trade_value_usdt}. 跳过本次循环。")
  212. with data_lock: # 依然更新错误信息
  213. latest_values_for_table["mexc_error"] = mexc_err
  214. latest_values_for_table["oo_error"] = latest_values_for_table.get("oo_error") # 保持上次的oo_error
  215. latest_values_for_table["last_updated"] = fetch_time_full
  216. time.sleep(REFRESH_INTERVAL_SECONDS)
  217. continue
  218. # 2. 确定链上查询的输入金额 (USDT)
  219. # 使用 MEXC 卖出 EXCHANGE_OUT_AMOUNT 个目标币能得到的USDT数量 (trade_value_usdt)
  220. # 作为链上购买目标币时花费的USDT数量 (in_amount_to_query_human)
  221. in_amount_to_query_human = trade_value_usdt.quantize(decimal.Decimal('1.00'), rounding=decimal.ROUND_DOWN) # 保留两位小数,向下取整
  222. if in_amount_to_query_human <= decimal.Decimal('0'):
  223. logger.warning(f"计算出的链上查询金额为0或负数 ({in_amount_to_query_human} USDT),跳过。trade_value_usdt: {trade_value_usdt}")
  224. time.sleep(REFRESH_INTERVAL_SECONDS)
  225. continue
  226. # 3. 获取链上价格:用 in_amount_to_query_human 这么多的USDT去买目标币,能买到多少,以及价格 (USDT/TARGET)
  227. oo_data, chain_swap_full_response = get_chain_price_vs_target_currency(
  228. CHAIN_ID,
  229. IN_TOKEN_ADDRESS, # USDT
  230. OUT_TOKEN_ADDRESS, # TARGET
  231. in_amount_to_query_human, # 花费的USDT数量
  232. IN_TOKEN_DECIMALS, # USDT的精度
  233. SLIPPAGE,
  234. USER_WALLET
  235. )
  236. oo_price_usdt_per_target = oo_data.get("price_base_per_target") # USDT/TARGET
  237. oo_err = oo_data.get("error")
  238. # 4. 计算百分比差异
  239. # diff = (MEXC卖价 - 链上买价) / 链上买价
  240. diff_oo_vs_mexc_pct = calculate_percentage_diff(
  241. mexc_price_target_per_base, # MEXC卖价 (USDT/TARGET)
  242. oo_price_usdt_per_target # 链上买价 (USDT/TARGET)
  243. )
  244. # 5. 计算实际利润额 (以USDT计价)
  245. # 利润 = (MEXC每目标币卖价 - 链上每目标币买价) * 链上买入的目标币数量
  246. # 链上买入的目标币数量 = in_amount_to_query_human / oo_price_usdt_per_target
  247. # 简化:利润百分比 * 投入的USDT金额
  248. actual_profit_usdt = None
  249. if diff_oo_vs_mexc_pct is not None and oo_price_usdt_per_target is not None and oo_price_usdt_per_target > 0:
  250. # 方案A: 基于百分比和投入金额
  251. actual_profit_usdt = diff_oo_vs_mexc_pct * in_amount_to_query_human
  252. # # 方案B: 基于单价差和数量 (更精确,如果chain_swap_full_response可用)
  253. # if chain_swap_full_response and chain_swap_full_response.get('data'):
  254. # router_result = chain_swap_full_response['data'][0]['routerResult']
  255. # atomic_out_target = decimal.Decimal(router_result['toTokenAmount'])
  256. # out_dec = int(router_result['toToken']['decimal'])
  257. # human_out_target_onchain = atomic_out_target / (10 ** out_dec) # 链上实际换到的目标币
  258. # # 能在CEX卖出的目标币数量,取链上换到的数量和CEX预设卖出量的较小值,因为CEX订单深度是按EXCHANGE_OUT_AMOUNT查的
  259. # effective_target_to_sell_on_mexc = min(human_out_target_onchain, EXCHANGE_OUT_AMOUNT)
  260. # revenue_on_mexc = effective_target_to_sell_on_mexc * mexc_price_target_per_base
  261. # cost_on_chain = in_amount_to_query_human # 这是我们实际在链上花的USDT
  262. # actual_profit_usdt_v2 = revenue_on_mexc - cost_on_chain
  263. # actual_profit_usdt = actual_profit_usdt_v2 # 使用更精确的V2版本
  264. # block_number = web3_client.w3.eth.block_number
  265. block_number = 0
  266. # 6. 满足利润条件,发送套利消息, PROFIT_LIMIT + 3的3是提前計算的成本,否則一直提交
  267. global mode
  268. global prev_profit_block_number
  269. if actual_profit_usdt is not None and actual_profit_usdt > PROFIT_LIMIT + 3 and mode == 'trade':
  270. # 确保有完整的链上数据
  271. if chain_swap_full_response:
  272. # and block_number == prev_profit_block_number + send_delay_block:
  273. send_arb_msg(actual_profit_usdt, chain_swap_full_response, mexc_price_target_per_base, in_amount_to_query_human)
  274. else:
  275. logger.warning("利润满足但链上数据不完整,无法发送套利消息。")
  276. prev_profit_block_number = block_number
  277. current_point = {
  278. "time": fetch_time_chart,
  279. "oo_price_usdt_per_target": float(oo_price_usdt_per_target) if oo_price_usdt_per_target else None,
  280. "mexc_price_target_per_base": float(mexc_price_target_per_base) if mexc_price_target_per_base else None,
  281. "diff_oo_vs_mexc": float(diff_oo_vs_mexc_pct) if diff_oo_vs_mexc_pct is not None else None,
  282. "profit_value": float(actual_profit_usdt) if actual_profit_usdt is not None else None, # 新增:用于图表的实际利润额
  283. }
  284. with data_lock:
  285. historical_data_points.append(current_point)
  286. latest_values_for_table["oo_price_usdt_per_target"] = f"{oo_price_usdt_per_target:.8f}" if oo_price_usdt_per_target else "N/A"
  287. latest_values_for_table["mexc_price_target_per_base"] = f"{mexc_price_target_per_base:.8f}" if mexc_price_target_per_base else "N/A"
  288. latest_values_for_table["diff_oo_vs_mexc_percentage"] = f"{diff_oo_vs_mexc_pct:+.4%}" if diff_oo_vs_mexc_pct is not None else "N/A" # 显示为百分比
  289. latest_values_for_table["profit_value_for_table"] = f"{actual_profit_usdt:.2f} {BASE_CURRENCY_SYMBOL}" if actual_profit_usdt is not None else "N/A" # 新增
  290. latest_values_for_table["oo_error"] = oo_err
  291. latest_values_for_table["mexc_error"] = mexc_err
  292. latest_values_for_table["last_updated"] = fetch_time_full
  293. latest_values_for_table["in_amount_for_query_display"] = f"{in_amount_to_query_human:.2f} {BASE_CURRENCY_SYMBOL}" if in_amount_to_query_human > 0 else "N/A"
  294. # logger.info(f"{fetch_time_chart} Price Query: Chain Input {in_amount_to_query_human:.2f} {BASE_CURRENCY_SYMBOL} | OKX Price: {oo_price_usdt_per_target_display} | MEXC Price: {mexc_price_target_per_base_display} | Diff: {diff_display} | Profit: {profit_display}")
  295. if oo_err or mexc_err :
  296. logger.warning(f"{fetch_time_chart} Errors: OO:{oo_err}, MEXC:{mexc_err}")
  297. time.sleep(REFRESH_INTERVAL_SECONDS)
  298. @app.route('/')
  299. def index_plotly():
  300. return render_template('index_plotly_dynamic_ok.html',
  301. target_asset=TARGET_ASSET_SYMBOL,
  302. base_asset=BASE_CURRENCY_SYMBOL,
  303. mexc_pair_usdt=MEXC_TARGET_PAIR_USDT,
  304. refresh_interval_ms=REFRESH_INTERVAL_SECONDS * 1000)
  305. @app.route('/table-data')
  306. def get_table_data():
  307. with data_lock:
  308. # logger.info(f"Table data requested: {latest_values_for_table}")
  309. return jsonify(latest_values_for_table)
  310. @app.route('/plotly-chart-data')
  311. def get_plotly_chart_data():
  312. with data_lock:
  313. points = list(historical_data_points)
  314. # logger.info(f"Chart data requested, {len(points)} points.")
  315. if not points:
  316. fig = go.Figure() # Create an empty figure
  317. fig.update_layout(title_text="暂无数据")
  318. empty_json = json.loads(json.dumps(fig, cls=PlotlyJSONEncoder))
  319. return jsonify({
  320. "price_chart": empty_json,
  321. "diff_chart": empty_json,
  322. "profit_chart": empty_json # 新增:空利润图表
  323. })
  324. times = [p['time'] for p in points]
  325. display_target_asset = latest_values_for_table["target_asset_symbol_for_display"]
  326. display_base_asset = latest_values_for_table["base_currency_symbol_for_display"]
  327. common_xaxis_config = dict(title='时间')
  328. common_legend_config = dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
  329. # if len(times) > 1: # Plotly handles autorange for single point ok
  330. # common_xaxis_config['range'] = [times[0], times[-1]]
  331. # else:
  332. common_xaxis_config['autorange'] = True
  333. # Price Chart
  334. fig_prices = go.Figure()
  335. fig_prices.add_trace(go.Scatter(x=times, y=[p['oo_price_usdt_per_target'] for p in points], mode='lines',
  336. name=f'Okx ({display_base_asset}/{display_target_asset})',
  337. line=dict(color='rgb(75, 192, 192)'),
  338. hovertemplate=f'<b>Okx链上价</b><br>价格: %{{y:.8f}} {display_base_asset}<extra></extra>',
  339. connectgaps=True)) # 处理None值不画线
  340. fig_prices.add_trace(go.Scatter(x=times, y=[p['mexc_price_target_per_base'] for p in points], mode='lines',
  341. name=f'MEXC卖1价 ({display_base_asset}/{display_target_asset})',
  342. line=dict(color='rgb(255, 99, 132)', dash='dash'),
  343. hovertemplate=f'<b>MEXC卖出价</b><br>价格: %{{y:.8f}} {display_base_asset}<extra></extra>',
  344. connectgaps=True))
  345. fig_prices.update_layout(title_text=f'{display_base_asset}/{display_target_asset} 价格历史',
  346. xaxis=common_xaxis_config.copy(),
  347. yaxis_title=f'价格 (1 {display_target_asset} = X {display_base_asset})',
  348. legend_title_text='平台',
  349. legend=common_legend_config.copy(), hovermode='x unified',
  350. margin=dict(l=70, r=30, t=80, b=50))
  351. # Percentage Difference Chart
  352. fig_diffs = go.Figure()
  353. fig_diffs.add_trace(
  354. go.Scatter(x=times, y=[p['diff_oo_vs_mexc'] for p in points], mode='lines', name=f'价差百分比 (MEXC卖价 vs Okx买价)',
  355. line=dict(color='rgb(255, 159, 64)'),
  356. hovertemplate=f'<b>(MEXC卖价-Okx买价)/Okx买价</b><br>百分比: %{{y:+.4%}}<extra></extra>', # 显示为百分比
  357. connectgaps=True))
  358. fig_diffs.update_layout(title_text=f'价差百分比历史曲线',
  359. xaxis=common_xaxis_config.copy(),
  360. yaxis_title='价差百分比', legend_title_text='对比', legend=common_legend_config.copy(),
  361. yaxis_zeroline=True, hovermode='x unified', margin=dict(l=70, r=30, t=80, b=50),
  362. yaxis_tickformat=".4%") # y轴也显示为百分比
  363. # --- 新增 Profit Chart ---
  364. fig_profit = go.Figure()
  365. fig_profit.add_trace(
  366. go.Scatter(x=times, y=[p['profit_value'] for p in points], mode='lines', name=f'预估利润 ({display_base_asset})',
  367. line=dict(color='rgb(153, 102, 255)'), # 紫色
  368. hovertemplate=f'<b>预估利润</b><br>金额: %{{y:,.2f}} {display_base_asset}<extra></extra>', # 利润金额,保留2位小数
  369. connectgaps=True))
  370. fig_profit.update_layout(title_text=f'预估利润历史 ({display_base_asset})',
  371. xaxis=common_xaxis_config.copy(),
  372. yaxis_title=f'利润 ({display_base_asset})',
  373. legend_title_text='利润额',
  374. legend=common_legend_config.copy(),
  375. yaxis_zeroline=True, hovermode='x unified',
  376. margin=dict(l=70, r=30, t=80, b=50),
  377. yaxis_tickformat="$,.2f") # y轴格式化为货币
  378. combined_figure_data = {
  379. "price_chart": json.loads(json.dumps(fig_prices, cls=PlotlyJSONEncoder)),
  380. "diff_chart": json.loads(json.dumps(fig_diffs, cls=PlotlyJSONEncoder)),
  381. "profit_chart": json.loads(json.dumps(fig_profit, cls=PlotlyJSONEncoder)) # 新增
  382. }
  383. return jsonify(combined_figure_data)
  384. if __name__ == "__main__":
  385. parser = argparse.ArgumentParser(description='套利监控和交易脚本。')
  386. parser.add_argument('--mode',
  387. required=True,
  388. choices=['trade', 'view'], # 限制可选值
  389. help='运行模式: "trade" (执行交易) 或 "view" (仅观察)')
  390. except_strategy = 'erc20_to_mexc'
  391. if STRATEGY != except_strategy:
  392. raise Exception(f"策略不匹配! 期待{except_strategy}, 实际{STRATEGY}")
  393. try:
  394. args = parser.parse_args()
  395. mode = args.mode
  396. logger.info(f"脚本运行模式为: {mode}")
  397. logger.info("应用启动...")
  398. logger.info(f"目标资产: {TARGET_ASSET_SYMBOL}, 计价货币: {BASE_CURRENCY_SYMBOL}, 获取到的Decimal: {IN_TOKEN_DECIMALS}")
  399. # IN_AMOUNT_TO_QUERY 会动态变化,初始值从配置读取,但循环中会基于MEXC的trade_value更新
  400. # logger.info(f"链上查询初始金额: {arb['IN_AMOUNT_TO_QUERY']} {BASE_CURRENCY_SYMBOL} -> {TARGET_ASSET_SYMBOL}")
  401. logger.info(f"MEXC期望卖出量 (用于计算深度和价值): {EXCHANGE_OUT_AMOUNT} {TARGET_ASSET_SYMBOL}")
  402. logger.info(f"利润阈值: {PROFIT_LIMIT} {BASE_CURRENCY_SYMBOL}")
  403. logger.info(f"MEXC现货交易对: {MEXC_TARGET_PAIR_USDT}")
  404. data_thread = threading.Thread(target=update_data_for_plotly_and_table, daemon=True)
  405. data_thread.start()
  406. port = arb.get("PORT", 5001) # 从配置获取端口,如果没有则默认5001
  407. logger.info(f"Flask 服务将在 http://0.0.0.0:{port} 上运行 (刷新间隔: {REFRESH_INTERVAL_SECONDS}s)")
  408. app.run(debug=False, host='0.0.0.0', port=port, use_reloader=False)
  409. except SystemExit: # argparse 在参数错误时会引发 SystemExit
  410. # parser.print_help() # argparse 默认会打印帮助信息
  411. logger.info("脚本因参数错误而退出。请提供 '--mode' 参数 ('trade' 或 'view')。")
  412. except Exception as e:
  413. logger.critical(f"主程序发生严重错误: {e}", exc_info=True)