策略源码
// @version=6
indicator("现货三角套利监控", overlay=true)
// 交易所选择
var string BINANCE = "BINANCE"
var string OKX = "OKX"
var string BYBIT = "BYBIT"
exchange = input.string(BINANCE, "选择交易所", options=[BINANCE, OKX, BYBIT])
// 交易对输入
pair1 = input.symbol("BINANCE:BTCUSDT", "交易对1", inline="pair1")
pair2 = input.symbol("BINANCE:ETHUSDT", "交易对2", inline="pair2")
pair3 = input.symbol("BINANCE:ETHBTC", "交易对3", inline="pair3")
// 手续费和滑点设置
fee_maker = input.float(0.1, "Maker手续费(%)", minval=0.0, step=0.01) / 100
fee_taker = input.float(0.2, "Taker手续费(%)", minval=0.0, step=0.01) / 100
slippage = input.float(0.1, "滑点缓冲(%)", minval=0.0, step=0.01) / 100
// 获取价格
price1 = request.security(pair1, timeframe.period, close)
price2 = request.security(pair2, timeframe.period, close)
price3 = request.security(pair3, timeframe.period, close)
// 计算三角套利机会
// 路径1: USDT -> BTC -> ETH -> USDT
path1_profit = ((1 / price1) * (1 / price3) * price2) - 1
// 路径2: USDT -> ETH -> BTC -> USDT
path2_profit = ((1 / price2) * price3 * price1) - 1
// 计算总手续费(来回3次交易)
total_fee = (fee_maker + fee_taker) * 3 + slippage
// 判断是否有套利机会
profitable_path1 = path1_profit > total_fee
profitable_path2 = path2_profit > total_fee
// 计算实际收益率(减去手续费)
net_profit1 = profitable_path1 ? path1_profit - total_fee : 0
net_profit2 = profitable_path2 ? path2_profit - total_fee : 0
// 绘制套利机会标记
plotshape(profitable_path1, "正向套利", style=shape.triangleup, location=location.belowbar,
color=color.new(color.green, 0), size=size.small)
plotshape(profitable_path2, "反向套利", style=shape.triangledown, location=location.abovebar,
color=color.new(color.red, 0), size=size.small)
// 显示收益率
var table_position = position.top_right
var profit_table = table.new(table_position, 2, 3, color.new(color.gray, 90),
border_width=1, border_color=color.gray)
// 更新表格内容
if barstate.islast
table.cell(profit_table, 0, 0, "套利方向", text_color=color.white)
table.cell(profit_table, 1, 0, "收益率(%)", text_color=color.white)
table.cell(profit_table, 0, 1, "正向套利",
text_color=profitable_path1 ? color.green : color.gray)
table.cell(profit_table, 1, 1, str.tostring(net_profit1 * 100, "#.###") + "%",
text_color=profitable_path1 ? color.green : color.gray)
table.cell(profit_table, 0, 2, "反向套利",
text_color=profitable_path2 ? color.red : color.gray)
table.cell(profit_table, 1, 2, str.tostring(net_profit2 * 100, "#.###") + "%",
text_color=profitable_path2 ? color.red : color.gray)
// 设置报警条件
// 替换 alertcondition 为 alert 函数
if profitable_path1
alert("发现正向三角套利机会,收益率: " + str.tostring(net_profit1 * 100, "#.###") + "%", alert.freq_once_per_bar)
if profitable_path2
alert("发现反向三角套利机会,收益率: " + str.tostring(net_profit2 * 100, "#.###") + "%", alert.freq_once_per_bar)