TV自动交易脚本编写成MT5版本量化EA
TradingView自动交易脚本编写成MT5版本量化EA,最小开仓手数0.01(可自行调节),指标可显示图表//@version=5
strategy(" 超级趋势与 EMA 结合的动态趋势跟踪策略", overlay=true)
// 超级趋势的输入参数
atr_length = input.int(10, title="ATR 长度")// 定义 ATR 长度的输入,默认为 10
factor = input.float(3.0, title="ATR 因子")// 定义 ATR 因子的输入,默认为 3.0
// EMA 的输入参数
ema_length = input.int(100, title="EMA 长度")// 定义 EMA 长度的输入,默认为 200
// 止损和止盈的输入参数
stop_loss_perc = input.float(1.0, title="止损百分比", step=0.1) / 100// 定义止损百分比的输入,默认为 1.0%
take_profit_perc = input.float(5.0, title="止盈百分比", step=0.1) / 100// 定义止盈百分比的输入,默认为 5.0%
// 计算 EMA 200
ema_200 = ta.ema(close, ema_length)// 计算收盘价的 EMA 200
// 计算超级趋势
atr = ta.atr(atr_length)// 计算 ATR 值
upperband = hl2 + (factor * atr)// 计算上轨
lowerband = hl2 - (factor * atr)// 计算下轨
var float supertrend = na// 定义超级趋势变量并初始化为 na
var int direction = na// 定义方向变量并初始化为 na
// 在第一根柱线上初始化超级趋势
if (na(supertrend[1]))// 如果前一根柱线的超级趋势为 na
supertrend := lowerband// 将超级趋势初始化为下轨
direction := 1// 方向初始化为 1
else
// 更新超级趋势的值
if (direction == 1)// 如果当前方向为 1
supertrend := close < supertrend[1]? upperband : math.max(supertrend[1], lowerband)// 根据条件更新超级趋势
else
supertrend := close > supertrend[1]? lowerband : math.min(supertrend[1], upperband)// 根据条件更新超级趋势
// 更新方向
direction := close > supertrend? 1 : -1// 根据收盘价与超级趋势的关系更新方向
// 多头条件:超级趋势为绿色且价格高于 EMA 200
longCondition = direction == 1 and close > ema_200// 定义多头条件
// 空头条件:超级趋势为红色且价格低于 EMA 200
shortCondition = direction == -1 and close < ema_200// 定义空头条件
// 绘制 EMA 200
plot(ema_200, title="EMA 200", color=color.blue, linewidth=2)// 绘制 EMA 200 曲线
// 绘制超级趋势
plot(supertrend, title="超级趋势", color=direction == 1? color.green : color.red, linewidth=2)// 绘制超级趋势曲线
// 计算多头头寸的止损和止盈水平
long_stop_loss = close * (1 - stop_loss_perc)// 计算多头止损水平
long_take_profit = close * (1 + take_profit_perc)// 计算多头止盈水平
// 计算空头头寸的止损和止盈水平
short_stop_loss = close * (1 + stop_loss_perc)// 计算空头止损水平
short_take_profit = close * (1 - take_profit_perc)// 计算空头止盈水平
// 多头头寸的策略入场和出场
if (longCondition and not na(supertrend))// 如果满足多头条件且超级趋势不为 na
strategy.entry("Long", strategy.long, stop=long_stop_loss, limit=long_take_profit,comment="开多")// 进行多头入场操作
if (strategy.position_size > 0 and shortCondition)// 如果多头头寸持仓且满足空头条件
strategy.close("Long",comment="平多")// 关闭多头头寸
// 空头头寸的策略入场和出场
if (shortCondition and not na(supertrend))// 如果满足空头条件且超级趋势不为 na
strategy.entry("Short", strategy.short, stop=short_stop_loss, limit=short_take_profit,comment="开空")// 进行空头入场操作
if (strategy.position_size < 0 and longCondition)// 如果空头头寸持仓且满足多头条件
strategy.close("Short",comment="平空")// 关闭空头头寸
页:
[1]