TradingView到AICoin转换
Tạo vào: 13 tháng 1, 2025
Tạo vào: 13 tháng 1, 2025
能将以下tradingview的策略转换成AICoin使用的策略吗?
//@version=5
strategy(title='3 EMA + RSI with Trail Stop', shorttitle='3 EMA + RSI + Trail Stop', overlay=true, pyramiding=3, currency=currency.USDT, default_qty_type=strategy.percent_of_equity, initial_capital=1000, default_qty_value=50, commission_type=strategy.commission.percent, commission_value=0.1)
// Bollinger Bands
len = input.int(14, minval=1, title='Length', group='RSI')
src = input.source(close, 'Source', group='RSI')
rsi = ta.rsi(src, len)
long_rsi = input.int(20, minval=1, title='Exit Short RSI', group='RSI')
short_rsi = input.int(80, minval=1, title='Exit Long RSI', group='RSI')
// Moving Averages
len_a = input.int(5, minval=1, title='EMA A Length', group='Moving Averages')
out_a = ta.ema(close, len_a)
plot(out_a, title='EMA A', color=color.purple)
len_b = input.int(7, minval=1, title='EMA B Length', group='Moving Averages')
out_b = ta.ema(close, len_b)
plot(out_b, title='EMA B', color=color.orange)
len_c = input.int(80, minval=1, title='EMA C Length', group='Moving Averages')
out_c = ta.ema(close, len_c)
plot(out_c, title='EMA C', color=color.green)
// Trailing Stop Parameters
trail_point = input.float(50, title='Trail Points', group='Trailing Stop')
trail_offset = input.float(1, title='Trail Offset', group='Trailing Stop')
// NEW: Fixed Stop-Loss (%)
fixStopLossPerc = input.float(3.0, title='Fixed Stop Loss (%)', group='Stop Loss')
// Strategy Conditions
stratGroup = 'Strategy'
showLong = input.bool(true, title='Long entries', group=stratGroup)
showShort = input.bool(true, title='Short entries', group=stratGroup)
closeAfterXBars = input.bool(true, title='Close after X # bars', tooltip='If trade is in profit', group=stratGroup)
xBars = input.int(24, title='# bars')
entryLong = ta.crossover(out_a, out_b) and out_a > out_c and close > open
exitLong = rsi > short_rsi
entryShort = ta.crossunder(out_a, out_b) and out_a < out_c and close < open
exitShort = rsi < long_rsi
bought = strategy.opentrades[0] == 1 and strategy.position_size[0] > strategy.position_size[1]
entry_price = ta.valuewhen(bought, open, 0)
var int nPastBars = 0
if strategy.position_size > 0
nPastBars := nPastBars + 1
nPastBars
if strategy.position_size == 0
nPastBars := 0
nPastBars
if closeAfterXBars
exitLong := nPastBars >= xBars and close > entry_price ? true : exitLong
exitLong
exitShort := nPastBars >= xBars and close < entry_price ? true : exitShort
exitShort
// ────────────────────────────────────────────────────────────────────────────────
// Orders
// ────────────────────────────────────────────────────────────────────────────────
//
// Instead of calling 'strategy.entry' + 'strategy.close' unconditionally,
// we can incorporate logic to close an opposite position first if a new signal arises.
//
// 1) If we get a long signal while not already in a long, close the short first (if any).
if entryLong and showLong
// If there's an open short position, close it first
if strategy.position_size < 0
strategy.close('Short', comment='Close Short → New Long')
text// Now open the new Long position strategy.entry('Long', strategy.long)
// 2) If we get a short signal while not already in a short, close the long first (if any).
if entryShort and showShort
// If there's an open long position, close it first
if strategy.position_size > 0
strategy.close('Long', comment='Close Long → New Short')
text// Now open the new Short position strategy.entry('Short', strategy.short)
// Use strategy.close for “normal” RSI-based exit conditions only if the position is still open
if strategy.position_size > 0
// If RSI exit condition is met for a long, close it
if exitLong
strategy.close('Long', comment='RSI Exit Long')
if strategy.position_size < 0
// If RSI exit condition is met for a short, close it
if exitShort
strategy.close('Short', comment='RSI Exit Short')
// For a long position: stop-loss below avg price by fixStopLossPerc%
if strategy.position_size > 0
// Fixed stop loss for a LONG is (AvgPrice * (1 - X/100))
float longStopPrice = strategy.position_avg_price * (1 - fixStopLossPerc / 100.0)
strategy.exit('Trail Stop Long', from_entry='Long', stop = longStopPrice, trail_points=trail_point, trail_offset=trail_offset)
// For a short position: stop-loss above avg price by fixStopLossPerc%
if strategy.position_size < 0
// Fixed stop loss for a SHORT is (AvgPrice * (1 + X/100))
float shortStopPrice = strategy.position_avg_price * (1 + fixStopLossPerc / 100.0)
strategy.exit('Trail Stop Short', from_entry='Short',stop = shortStopPrice, trail_points=trail_point, trail_offset=trail_offset)
下面给出一个示例,演示如何将 TradingView(PineScript)中的主要逻辑,大致转换到 AICoin 策略环境下。由于两个平台在语法、函数命名和执行机制等方面都有较大差异,下述代码仅作示例,帮助你理清思路。你需要根据自己在 AICoin 策略平台上的实际函数和变量命名进行进一步调整和测试。
注意:AICoin 与 TradingView 的策略函数、事件调用方式有明显区别,以下示例仅供参考,须根据 AICoin 官方文档和策略回测环境进行适配、测试与修正。
从 TradingView 的脚本中,我们可以提炼出以下核心交易逻辑:
rsi > short_rsi
rsi < long_rsi
EMA A = ema(close, 5)
EMA B = ema(close, 7)
EMA C = ema(close, 80)
以下示例使用了伪代码风格,演示如何在 AICoin 中定义参数、计算指标并进行下单与止损处理。你需要根据 AICoin 官方文档中的函数名和事件回调(如 onTick
, onBar
等)进行落地修改。
lua------------------------------------------------- -- 在 AICoin 策略平台上定义参数(示例) ------------------------------------------------- -- RSI相关 local param_rsiLength = input("RSI Length", 14) local param_rsiLongExit = input("Exit Short RSI", 20) local param_rsiShortExit= input("Exit Long RSI", 80) -- EMA相关 local param_emaFast = input("EMA A Length", 5) local param_emaMid = input("EMA B Length", 7) local param_emaSlow = input("EMA C Length", 80) -- 移动止损参数 local param_trailPoints = input("Trail Points", 50) local param_trailOffset = input("Trail Offset", 1) -- 固定止损(%) local param_fixStopPerc = input("Fixed Stop Loss (%)", 3.0) -- 其他策略控制 local param_closeAfterXBars = input("Close after X bars?", true) -- 是否启用持仓时间限制 local param_xBars = input("Number of bars to hold", 24) -- 持仓限制bar数 ------------------------------------------------- -- 全局变量示例(需要根据AICoin环境实现) ------------------------------------------------- local barsSinceEntry = 0 -- 持仓后经过的bar数 local entryPrice = 0.0 -- 记录开仓价格(多 / 空) local inPosition = 0 -- 记录当前仓位方向: 1=多,-1=空,0=无 local positionSize = 0 -- 仓位大小 ------------------------------------------------- -- onBar() 事件示例:每根新K线触发 -- AICoin实际回调名字可能不同 ------------------------------------------------- function onBar() ------------------------- -- 1) 计算指标 ------------------------- local closePrice = Close() -- 获取当前K线收盘价 local openPrice = Open() -- 获取当前K线开盘价 local rsiValue = RSI(closePrice, param_rsiLength) -- 假设 AICoin 有内置函数 RSI() local emaA = EMA(closePrice, param_emaFast) local emaB = EMA(closePrice, param_emaMid) local emaC = EMA(closePrice, param_emaSlow) -- 计算多、空开仓条件 local longSignal = crossOver(emaA, emaB) and (emaA > emaC) and (closePrice > openPrice) local shortSignal = crossUnder(emaA, emaB) and (emaA < emaC) and (closePrice < openPrice) ------------------------- -- 2) 判断平仓/止损 ------------------------- -- 根据方向做不同判断 if inPosition == 1 then -- 多头持仓 -- (a) RSI 到达高位 -> 平仓 if rsiValue > param_rsiShortExit then closeLong("RSI Exit Long") -- 平多单(伪函数) end -- (b) 达到固定止损价 (多单价格下跌 param_fixStopPerc%) -- stopPrice = entryPrice * (1 - param_fixStopPerc/100) local stopPriceLong = entryPrice * (1 - param_fixStopPerc / 100.0) if closePrice <= stopPriceLong then closeLong("Fixed Stop Loss Long") end -- (c) 移动止损 (trailPoints, trailOffset) - 在AICoin中可能需要另外的函数 -- 假设提供 trailStop 函数,示例: -- trailStop("Long", param_trailPoints, param_trailOffset) -- (d) 如果启用 closeAfterXBars 并且达到X bars,且当前有浮盈 if param_closeAfterXBars == true then if barsSinceEntry >= param_xBars and closePrice > entryPrice then closeLong("Time-based Exit Long") end end elseif inPosition == -1 then -- 空头持仓 -- (a) RSI 到达低位 -> 平仓 if rsiValue < param_rsiLongExit then closeShort("RSI Exit Short") -- 平空单(伪函数) end -- (b) 达到固定止损价 (空单价格上涨 param_fixStopPerc%) -- stopPrice = entryPrice * (1 + param_fixStopPerc/100) local stopPriceShort = entryPrice * (1 + param_fixStopPerc / 100.0) if closePrice >= stopPriceShort then closeShort("Fixed Stop Loss Short") end -- (c) 移动止损 -- trailStop("Short", param_trailPoints, param_trailOffset) -- (d) 如果启用 closeAfterXBars 并且达到X bars,且当前有浮盈 if param_closeAfterXBars == true then if barsSinceEntry >= param_xBars and closePrice < entryPrice then closeShort("Time-based Exit Short") end end end ------------------------- -- 3) 判断是否要开新仓 ------------------------- -- 如果出现多单信号 && 当前无多单持仓 if longSignal and inPosition ~= 1 then -- 如果目前是空头,先平仓空头再开多 if inPosition == -1 then closeShort("Close Short -> New Long") end openLong("Long Entry") -- 开多单 end -- 如果出现空单信号 && 当前无空单持仓 if shortSignal and inPosition ~= -1 then -- 如果目前是多头,先平仓多头再开空 if inPosition == 1 then closeLong("Close Long -> New Short") end openShort("Short Entry") -- 开空单 end ------------------------- -- 4) 维护持仓 bar 计数 ------------------------- if inPosition ~= 0 then barsSinceEntry = barsSinceEntry + 1 else barsSinceEntry = 0 end end ------------------------------------------------- -- 伪函数示例:实际需要用AICoin提供的API替换 ------------------------------------------------- function openLong(comment) -- 下单操作,需使用AICoin的API entryPrice = Close() inPosition = 1 positionSize = yourPositionSizeLogicHere() -- 根据资金管理、杠杆等 barsSinceEntry = 0 log("Open Long: "..comment) end function openShort(comment) -- 下单操作 entryPrice = Close() inPosition = -1 positionSize = yourPositionSizeLogicHere() barsSinceEntry = 0 log("Open Short: "..comment) end function closeLong(comment) -- 平多操作 if inPosition == 1 then -- 在此用 AICoin 的API做实际平仓 inPosition = 0 positionSize = 0 barsSinceEntry = 0 log("Close Long: "..comment) end end function closeShort(comment) -- 平空操作 if inPosition == -1 then -- 在此用 AICoin 的API做实际平仓 inPosition = 0 positionSize = 0 barsSinceEntry = 0 log("Close Short: "..comment) end end -- 伪函数: crossover / crossunder function crossOver(seriesA, seriesB) -- 判断最近一根K线是否从下方向上穿越 -- 需自己存储前一bar的数值,或利用AICoin的内置 cross() 函数 return (seriesA[1] < seriesB[1]) and (seriesA[0] > seriesB[0]) end function crossUnder(seriesA, seriesB) -- 判断最近一根K线是否从上方向下穿越 return (seriesA[1] > seriesB[1]) and (seriesA[0] < seriesB[0]) end function log(msg) -- 在AICoin中一般有print或其他日志函数 print(msg) end
自定义函数:
AICoin 的脚本和 TradingView PineScript 的内置函数有很多不同之处,比如 ta.rsi()
、ta.ema()
在 AICoin 上往往需要用 RSI()
、EMA()
或自己封装的指标函数实现;strategy.entry
、strategy.close
、strategy.exit
等函数在 AICoin 并不一定存在,需要改写成交易指令的形式,例如 BUY / SELL
或自定义函数 openLong
, closeLong
等。
Bar 计数:
TradingView 里通过 strategy.opentrades
和 valuewhen()
判断开仓并计数,这里示例用一个全局变量 barsSinceEntry
进行简单累加。你可以根据实际需要(如只在新 Bar 收到后 +1,或在 Tick 中处理)来完善此逻辑。
移动止损:
在 PineScript 里通过 strategy.exit(..., trail_points, trail_offset)
完成;在 AICoin 里通常需要自己跟踪最高/最低浮动盈亏并动态调整 stop
。有的平台也提供了相应的“移动止损”指令,需要查看官方文档或示例。
固定止损:
AvgPrice * (1 - fixStopLossPerc/100)
AvgPrice * (1 + fixStopLossPerc/100)
资金管理:
如果想做“用 50% 资金开仓”,需要根据 AICoin 的下单接口,把当前策略账户可用资金乘以 50% 后,再除以价格,得到下单数量。示例中留了 yourPositionSizeLogicHere()
供你自行实现。
pyramiding:
如果要在 AICoin 上复现 pine 般可多次加仓功能,需要在开仓后判断是否可以继续加仓,同时记录每次加仓的均价和仓位;并在平仓时一次性或分批平掉。示例中仅做了单次开/平仓,若需多次加仓可自行扩展。
以上示例演示了如何将 TradingView 策略中关键的指标与交易逻辑迁移到 AICoin 环境。你需要:
BUY
, SELL
, COVER
, SHORT
等),或者使用更高级的函数/接口。希望能帮助你更快地在 AICoin 上复现并改进这套策略!