|
|
@@ -40,7 +40,7 @@ ARB_EXECUTOR_URL = arb["ARB_EXECUTOR_URL"]
|
|
|
|
|
|
# --- 配置部分 ---
|
|
|
# IN_AMOUNT_TO_QUERY 将在循环中动态确定
|
|
|
-DEX_QUERY_AMOUNT = decimal.Decimal(str(arb["COIN_TOKEN_QUERY_AMOUNT"])) # 确保是Decimal
|
|
|
+BASE_TOKEN_TRADE_AMOUNT = decimal.Decimal(str(arb["BASE_TOKEN_TRADE_AMOUNT"])) # 确保是Decimal
|
|
|
CEX_TRADE_AMOUNT = decimal.Decimal(str(arb["COIN_TOKEN_TRADE_AMOUNT"])) # 确保是Decimal
|
|
|
OPEN_LIMIT = decimal.Decimal(str(arb["OPEN_LIMIT"])) # 确保是Decimal
|
|
|
CLOSE_LIMIT = decimal.Decimal(str(arb["CLOSE_LIMIT"])) # 确保是Decimal
|
|
|
@@ -48,7 +48,7 @@ IN_TOKEN_ADDRESS = arb["BASE_TOKEN_ADDRESS"]
|
|
|
IN_TOKEN_DECIMALS = web3_client.get_erc20_decimals(IN_TOKEN_ADDRESS)
|
|
|
OUT_TOKEN_ADDRESS = arb["COIN_TOKEN_ADDRESS"]
|
|
|
SLIPPAGE = arb["SLIPPAGE"]
|
|
|
-MEXC_TARGET_PAIR_USDT = arb["CEX_PAIR"]
|
|
|
+CEX_TARGET_PAIR_USDT = arb["CEX_PAIR"]
|
|
|
CHAIN_ID = arb["CHAIN_ID"]
|
|
|
STRATEGY = arb["STRATEGY"]
|
|
|
|
|
|
@@ -74,8 +74,8 @@ REFRESH_INTERVAL_SECONDS = 1 # 稍微增加间隔以减少API调用频率
|
|
|
MAX_HISTORY_POINTS_PLOTLY = 21600
|
|
|
historical_data_points = deque(maxlen=MAX_HISTORY_POINTS_PLOTLY)
|
|
|
|
|
|
-TARGET_ASSET_SYMBOL = MEXC_TARGET_PAIR_USDT.split('_')[0] # e.g., RATO
|
|
|
-BASE_CURRENCY_SYMBOL = MEXC_TARGET_PAIR_USDT.split('_')[1] # e.g., USDT (assumed to be consistent with IN_TOKEN_ADDRESS)
|
|
|
+TARGET_ASSET_SYMBOL = CEX_TARGET_PAIR_USDT.split('_')[0] # e.g., RATO
|
|
|
+BASE_CURRENCY_SYMBOL = CEX_TARGET_PAIR_USDT.split('_')[1] # e.g., USDT (assumed to be consistent with IN_TOKEN_ADDRESS)
|
|
|
|
|
|
# --- 链上价格获取函数 (Okx) ---
|
|
|
# 返回: price_base_per_target (例如 USDT per RATO)
|
|
|
@@ -103,9 +103,9 @@ def get_chain_price_vs_target_currency(chain_id, in_token_addr, out_token_addr,
|
|
|
logger.error(f"Okx ({chain_id})请求错误详情: ", exc_info=True)
|
|
|
return {"error": f"Okx ({chain_id})请求错误: {e}"}, None
|
|
|
|
|
|
-# MEXC 现货 (获取 目标代币/USDT 的 bid 价格)
|
|
|
+# CEX 现货 (获取 目标代币/USDT 的 bid 价格)
|
|
|
# 返回: price_target_per_usdt (例如 RATO per USDT)
|
|
|
-def get_mexc_spot_price_target_usdt_bid(pair_symbol):
|
|
|
+def get_cex_spot_price_target_usdt_bid(pair_symbol):
|
|
|
url = "https://api.mexc.com/api/v3/depth"
|
|
|
params = {'symbol': pair_symbol.replace('_', ''), 'limit': 1000} # 减少limit,5000可能过大且非必要
|
|
|
try:
|
|
|
@@ -131,8 +131,8 @@ def get_mexc_spot_price_target_usdt_bid(pair_symbol):
|
|
|
trade_volume_remaining -= can_fill
|
|
|
|
|
|
if accumulated_volume == decimal.Decimal('0'): # 如果一点都没卖出去
|
|
|
- # logger.warning(f"MEXC无法以CEX_TRADE_AMOUNT={CEX_TRADE_AMOUNT}获取任何 efectiva 卖出价格,累积量为0")
|
|
|
- return {"error": f"MEXC订单簿深度不足以卖出{CEX_TRADE_AMOUNT} {TARGET_ASSET_SYMBOL}"}, decimal.Decimal('0')
|
|
|
+ # logger.warning(f"CEX无法以CEX_TRADE_AMOUNT={CEX_TRADE_AMOUNT}获取任何 efectiva 卖出价格,累积量为0")
|
|
|
+ return {"error": f"CEX订单簿深度不足以卖出{CEX_TRADE_AMOUNT} {TARGET_ASSET_SYMBOL}"}, decimal.Decimal('0')
|
|
|
|
|
|
# 计算平均卖出价格
|
|
|
# sell_price 代表 1 TARGET_ASSET = X USDT
|
|
|
@@ -144,30 +144,30 @@ def get_mexc_spot_price_target_usdt_bid(pair_symbol):
|
|
|
"price_target_per_usdt": sell_price # 这个名字其实是 RATO/USDT,所以可以叫 price_target_per_base
|
|
|
}, trade_value # 返回的是实际能卖出 CEX_TRADE_AMOUNT (或更少,如果深度不足) 所得的 USDT 总额
|
|
|
else:
|
|
|
- # logger.warning(f"MEXC现货({pair_symbol}) bids 数据不存在或为空: {data}")
|
|
|
- return {"error": f"MEXC现货({pair_symbol}) bids 数据不存在或为空"}, decimal.Decimal('0')
|
|
|
+ # logger.warning(f"CEX现货({pair_symbol}) bids 数据不存在或为空: {data}")
|
|
|
+ return {"error": f"CEX现货({pair_symbol}) bids 数据不存在或为空"}, decimal.Decimal('0')
|
|
|
except requests.exceptions.RequestException as e:
|
|
|
- # logger.error(f"MEXC现货({pair_symbol})请求错误: {e}")
|
|
|
- return {"error": f"MEXC现货({pair_symbol})请求错误: {e}"}, decimal.Decimal('0')
|
|
|
+ # logger.error(f"CEX现货({pair_symbol})请求错误: {e}")
|
|
|
+ return {"error": f"CEX现货({pair_symbol})请求错误: {e}"}, decimal.Decimal('0')
|
|
|
except Exception as e:
|
|
|
- # logger.error(f"MEXC现货({pair_symbol})处理错误: {e}", exc_info=True)
|
|
|
- return {"error": f"MEXC现货({pair_symbol})处理错误: {e}"}, decimal.Decimal('0')
|
|
|
+ # logger.error(f"CEX现货({pair_symbol})处理错误: {e}", exc_info=True)
|
|
|
+ return {"error": f"CEX现货({pair_symbol})处理错误: {e}"}, decimal.Decimal('0')
|
|
|
|
|
|
latest_values_for_table = {
|
|
|
f"dex_price": "N/A",
|
|
|
- f"cex_price": "N/A", # MEXC Bid1 (converted to USDT/TARGET)
|
|
|
+ f"cex_price": "N/A", # CEX Bid1 (converted to USDT/TARGET)
|
|
|
f"diff_dex_vs_cex_percentage": "N/A",
|
|
|
"profit_value_for_table": "N/A", # 新增:用于表格的利润值
|
|
|
"dex_error": None, "cex_error": None,
|
|
|
"last_updated": "N/A",
|
|
|
- "mexc_pair_usdt_for_display": MEXC_TARGET_PAIR_USDT,
|
|
|
+ "pair_usdt_for_display": CEX_TARGET_PAIR_USDT,
|
|
|
"target_asset_symbol_for_display": TARGET_ASSET_SYMBOL,
|
|
|
"base_currency_symbol_for_display": BASE_CURRENCY_SYMBOL
|
|
|
}
|
|
|
data_lock = threading.Lock()
|
|
|
|
|
|
def calculate_percentage_diff(price_a_base_per_target, price_b_base_per_target):
|
|
|
- # price_a: MEXC卖价 (USDT/TARGET) - 链上买的目标币,拿到CEX卖掉
|
|
|
+ # price_a: CEX卖价 (USDT/TARGET) - 链上买的目标币,拿到CEX卖掉
|
|
|
# price_b: 链上买价 (USDT/TARGET) - 链上用USDT买目标币
|
|
|
# 期望 price_a > price_b
|
|
|
if price_a_base_per_target is not None and price_b_base_per_target is not None and \
|
|
|
@@ -224,7 +224,7 @@ def send_arb_msg(pct, chain_swap_data, cex_price, dex_price):
|
|
|
"closeLimit": str(CLOSE_LIMIT.quantize(decimal.Decimal('0.00001'))),
|
|
|
"cexPrice": str(cex_price),
|
|
|
"dexPrice": str(dex_price),
|
|
|
- "symbol": MEXC_TARGET_PAIR_USDT,
|
|
|
+ "symbol": CEX_TARGET_PAIR_USDT,
|
|
|
"exchangeOutAmount": str(CEX_TRADE_AMOUNT.quantize(decimal.Decimal(f'1e-{out_dec}'))), # CEX上期望卖出的目标币数量
|
|
|
"strategy": STRATEGY,
|
|
|
"queryPriceUrl": query_price_endpoint,
|
|
|
@@ -255,26 +255,26 @@ def update_data_for_plotly_and_table():
|
|
|
fetch_time_full = time.strftime("%Y-%m-%d %H:%M:%S")
|
|
|
fetch_time_chart = time.strftime("%H:%M:%S")
|
|
|
|
|
|
- # 1. MEXC: 获取 price_target_per_usdt (例如 RATO/USDT) 和相应的 trade_value_usdt
|
|
|
- # trade_value_usdt 是指如果以 CEX_TRADE_AMOUNT 的目标代币在MEXC上砸盘卖出,能获得的USDT估值
|
|
|
- mexc_data, trade_value_usdt = get_mexc_spot_price_target_usdt_bid(MEXC_TARGET_PAIR_USDT)
|
|
|
- cex_price = mexc_data.get("price_target_per_usdt") # TARGET/USDT
|
|
|
- mexc_err = mexc_data.get("error")
|
|
|
+ # 1. CEX: 获取 price_target_per_usdt (例如 RATO/USDT) 和相应的 trade_value_usdt
|
|
|
+ # trade_value_usdt 是指如果以 CEX_TRADE_AMOUNT 的目标代币在CEX上砸盘卖出,能获得的USDT估值
|
|
|
+ cex_data, trade_value_usdt = get_cex_spot_price_target_usdt_bid(CEX_TARGET_PAIR_USDT)
|
|
|
+ cex_price = cex_data.get("price_target_per_usdt") # TARGET/USDT
|
|
|
+ cex_err = cex_data.get("error")
|
|
|
|
|
|
if cex_price is None:
|
|
|
- mexc_err = mexc_err or "MEXC价格为0或无效"
|
|
|
+ cex_err = cex_err or "CEX价格为0或无效"
|
|
|
|
|
|
- if mexc_err or trade_value_usdt == decimal.Decimal('0'): # 如果MEXC有问题或无法确定砸盘价值,则跳过本次循环
|
|
|
- logger.warning(f"MEXC数据获取问题: {mexc_err}, trade_value_usdt: {trade_value_usdt}. 跳过本次循环。")
|
|
|
+ if cex_err or trade_value_usdt == decimal.Decimal('0'): # 如果CEX有问题或无法确定砸盘价值,则跳过本次循环
|
|
|
+ logger.warning(f"CEX数据获取问题: {cex_err}, trade_value_usdt: {trade_value_usdt}. 跳过本次循环。")
|
|
|
with data_lock: # 依然更新错误信息
|
|
|
- latest_values_for_table["cex_error"] = mexc_err
|
|
|
+ latest_values_for_table["cex_error"] = cex_err
|
|
|
latest_values_for_table["dex_error"] = latest_values_for_table.get("dex_error") # 保持上次的dex_error
|
|
|
latest_values_for_table["last_updated"] = fetch_time_full
|
|
|
time.sleep(REFRESH_INTERVAL_SECONDS)
|
|
|
continue
|
|
|
|
|
|
# 2. 确定链上查询的输入金额 (USDT)
|
|
|
- in_amount_to_query_human = cex_price * DEX_QUERY_AMOUNT
|
|
|
+ in_amount_to_query_human = BASE_TOKEN_TRADE_AMOUNT
|
|
|
in_amount_to_query_human = in_amount_to_query_human.quantize(decimal.Decimal('1e-2'), rounding=decimal.ROUND_DOWN) # 保留两位小数,向下取整
|
|
|
if in_amount_to_query_human <= decimal.Decimal('0'):
|
|
|
logger.warning(f"计算出的链上查询金额为0或负数 ({in_amount_to_query_human} USDT),跳过。trade_value_usdt: {trade_value_usdt}")
|
|
|
@@ -296,20 +296,20 @@ def update_data_for_plotly_and_table():
|
|
|
erc20_err = erc20_data.get("error")
|
|
|
|
|
|
# 4. 计算百分比差异
|
|
|
- # diff = (MEXC卖价 - 链上买价) / 链上买价
|
|
|
- diff_erc20_vs_mexc_pct = calculate_percentage_diff(
|
|
|
- cex_price, # MEXC卖价 (USDT/TARGET)
|
|
|
+ # diff = (CEX卖价 - 链上买价) / 链上买价
|
|
|
+ diff_erc20_vs_cex_pct = calculate_percentage_diff(
|
|
|
+ cex_price, # CEX卖价 (USDT/TARGET)
|
|
|
dex_price # 链上买价 (USDT/TARGET)
|
|
|
)
|
|
|
|
|
|
# 5. 计算实际利润额 (以USDT计价)
|
|
|
- # 利润 = (MEXC每目标币卖价 - 链上每目标币买价) * 链上买入的目标币数量
|
|
|
+ # 利润 = (CEX每目标币卖价 - 链上每目标币买价) * 链上买入的目标币数量
|
|
|
# 链上买入的目标币数量 = in_amount_to_query_human / dex_price
|
|
|
# 简化:利润百分比 * 投入的USDT金额
|
|
|
actual_profit_usdt = None
|
|
|
- if diff_erc20_vs_mexc_pct is not None and dex_price is not None and dex_price > 0:
|
|
|
+ if diff_erc20_vs_cex_pct is not None and dex_price is not None and dex_price > 0:
|
|
|
# 基于百分比和投入金额
|
|
|
- actual_profit_usdt = diff_erc20_vs_mexc_pct * in_amount_to_query_human
|
|
|
+ actual_profit_usdt = diff_erc20_vs_cex_pct * in_amount_to_query_human
|
|
|
|
|
|
# block_number = web3_client.w3.eth.block_number
|
|
|
block_number = 0
|
|
|
@@ -317,10 +317,10 @@ def update_data_for_plotly_and_table():
|
|
|
global mode
|
|
|
global prev_profit_block_number
|
|
|
|
|
|
- if diff_erc20_vs_mexc_pct is not None and diff_erc20_vs_mexc_pct > OPEN_LIMIT and mode == 'trade':
|
|
|
+ if diff_erc20_vs_cex_pct is not None and diff_erc20_vs_cex_pct > OPEN_LIMIT and mode == 'trade':
|
|
|
# 确保有完整的链上数据
|
|
|
if chain_swap_full_response:
|
|
|
- send_arb_msg(diff_erc20_vs_mexc_pct, chain_swap_full_response, cex_price, dex_price)
|
|
|
+ send_arb_msg(diff_erc20_vs_cex_pct, chain_swap_full_response, cex_price, dex_price)
|
|
|
else:
|
|
|
logger.warning("利润满足但链上数据不完整,无法发送套利消息。")
|
|
|
|
|
|
@@ -330,7 +330,7 @@ def update_data_for_plotly_and_table():
|
|
|
"time": fetch_time_chart,
|
|
|
"dex_price": float(dex_price) if dex_price else None,
|
|
|
"cex_price": float(cex_price) if cex_price else None,
|
|
|
- "diff_erc20_vs_mexc": float(diff_erc20_vs_mexc_pct) if diff_erc20_vs_mexc_pct is not None else None,
|
|
|
+ "diff_erc20_vs_cex": float(diff_erc20_vs_cex_pct) if diff_erc20_vs_cex_pct is not None else None,
|
|
|
"profit_value": float(actual_profit_usdt) if actual_profit_usdt is not None else None, # 新增:用于图表的实际利润额
|
|
|
}
|
|
|
|
|
|
@@ -338,15 +338,15 @@ def update_data_for_plotly_and_table():
|
|
|
historical_data_points.append(current_point)
|
|
|
latest_values_for_table["dex_price"] = f"{dex_price:.18f}" if dex_price else "N/A"
|
|
|
latest_values_for_table["cex_price"] = f"{cex_price:.18f}" if cex_price else "N/A"
|
|
|
- latest_values_for_table["diff_dex_vs_cex_percentage"] = diff_erc20_vs_mexc_pct
|
|
|
+ latest_values_for_table["diff_dex_vs_cex_percentage"] = diff_erc20_vs_cex_pct
|
|
|
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" # 新增
|
|
|
latest_values_for_table["dex_error"] = erc20_err
|
|
|
- latest_values_for_table["cex_error"] = mexc_err
|
|
|
+ latest_values_for_table["cex_error"] = cex_err
|
|
|
latest_values_for_table["last_updated"] = fetch_time_full
|
|
|
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"
|
|
|
|
|
|
- if erc20_err or mexc_err :
|
|
|
- logger.warning(f"{fetch_time_chart} Errors: erc20:{erc20_err}, MEXC:{mexc_err}")
|
|
|
+ if erc20_err or cex_err :
|
|
|
+ logger.warning(f"{fetch_time_chart} Errors: erc20:{erc20_err}, CEX:{cex_err}")
|
|
|
|
|
|
time.sleep(REFRESH_INTERVAL_SECONDS)
|
|
|
|
|
|
@@ -355,7 +355,7 @@ def index_plotly():
|
|
|
return render_template('index_plotly_dynamic_ok.html',
|
|
|
target_asset=TARGET_ASSET_SYMBOL,
|
|
|
base_asset=BASE_CURRENCY_SYMBOL,
|
|
|
- mexc_pair_usdt=MEXC_TARGET_PAIR_USDT,
|
|
|
+ cex_pair_usdt=CEX_TARGET_PAIR_USDT,
|
|
|
refresh_interval_ms=REFRESH_INTERVAL_SECONDS * 1000)
|
|
|
|
|
|
@app.route('/table-data')
|
|
|
@@ -398,9 +398,9 @@ def get_plotly_chart_data():
|
|
|
hovertemplate=f'<b>Okx链上价</b><br>价格: %{{y:.8f}} {display_base_asset}<extra></extra>',
|
|
|
connectgaps=True)) # 处理None值不画线
|
|
|
fig_prices.add_trace(go.Scatter(x=times, y=[p['cex_price'] for p in points], mode='lines',
|
|
|
- name=f'MEXC卖1价 ({display_base_asset}/{display_target_asset})',
|
|
|
+ name=f'CEX卖1价 ({display_base_asset}/{display_target_asset})',
|
|
|
line=dict(color='rgb(255, 99, 132)', dash='dash'),
|
|
|
- hovertemplate=f'<b>MEXC卖出价</b><br>价格: %{{y:.8f}} {display_base_asset}<extra></extra>',
|
|
|
+ hovertemplate=f'<b>CEX卖出价</b><br>价格: %{{y:.8f}} {display_base_asset}<extra></extra>',
|
|
|
connectgaps=True))
|
|
|
fig_prices.update_layout(title_text=f'{display_base_asset}/{display_target_asset} 价格历史',
|
|
|
xaxis=common_xaxis_config.copy(),
|
|
|
@@ -412,9 +412,9 @@ def get_plotly_chart_data():
|
|
|
# Percentage Difference Chart
|
|
|
fig_diffs = go.Figure()
|
|
|
fig_diffs.add_trace(
|
|
|
- go.Scatter(x=times, y=[p['diff_erc20_vs_mexc'] for p in points], mode='lines', name=f'价差百分比 (MEXC卖价 vs Okx买价)',
|
|
|
+ go.Scatter(x=times, y=[p['diff_erc20_vs_cex'] for p in points], mode='lines', name=f'价差百分比 (CEX卖价 vs Okx买价)',
|
|
|
line=dict(color='rgb(255, 159, 64)'),
|
|
|
- hovertemplate=f'<b>(MEXC卖价-Okx买价)/Okx买价</b><br>百分比: %{{y:+.4%}}<extra></extra>', # 显示为百分比
|
|
|
+ hovertemplate=f'<b>(CEX卖价-Okx买价)/Okx买价</b><br>百分比: %{{y:+.4%}}<extra></extra>', # 显示为百分比
|
|
|
connectgaps=True))
|
|
|
fig_diffs.update_layout(title_text=f'价差百分比历史曲线',
|
|
|
xaxis=common_xaxis_config.copy(),
|
|
|
@@ -463,11 +463,11 @@ if __name__ == "__main__":
|
|
|
|
|
|
logger.info("应用启动...")
|
|
|
logger.info(f"目标资产: {TARGET_ASSET_SYMBOL}, 计价货币: {BASE_CURRENCY_SYMBOL}, 获取到的Decimal: {IN_TOKEN_DECIMALS}")
|
|
|
- # IN_AMOUNT_TO_QUERY 会动态变化,初始值从配置读取,但循环中会基于MEXC的trade_value更新
|
|
|
+ # IN_AMOUNT_TO_QUERY 会动态变化,初始值从配置读取,但循环中会基于CEX的trade_value更新
|
|
|
# logger.info(f"链上查询初始金额: {arb['IN_AMOUNT_TO_QUERY']} {BASE_CURRENCY_SYMBOL} -> {TARGET_ASSET_SYMBOL}")
|
|
|
- logger.info(f"MEXC期望卖出量 (用于计算深度和价值): {CEX_TRADE_AMOUNT} {TARGET_ASSET_SYMBOL}")
|
|
|
+ logger.info(f"CEX期望卖出量 (用于计算深度和价值): {CEX_TRADE_AMOUNT} {TARGET_ASSET_SYMBOL}")
|
|
|
logger.info(f"开仓阈值 > {OPEN_LIMIT} %")
|
|
|
- logger.info(f"MEXC现货交易对: {MEXC_TARGET_PAIR_USDT}")
|
|
|
+ logger.info(f"CEX现货交易对: {CEX_TARGET_PAIR_USDT}")
|
|
|
|
|
|
data_thread = threading.Thread(target=update_data_for_plotly_and_table, daemon=True)
|
|
|
data_thread.start()
|