回测脚本

Posted by Gregorius Blog on May 19, 2025

//@version=6 strategy(“Brooks_A_Share_Pro_V46_Final”, overlay=true, initial_capital=100000, process_orders_on_close=true)

// — 交易设置 — t0_enabled = input.bool(false, “开启T+0日内交易”) start_hour = input.int(10, “交易开始小时”, minval=9, maxval=15) end_hour = input.int(14, “交易结束小时”, minval=9, maxval=15)

// 基础指标 ema20 = ta.ema(close, 20) ema50 = ta.ema(close, 50) // ATR atr_value = ta.atr(14)

// 涨幅逻辑 (放宽至 3.01% - 6.99% 以捕捉更多启动) kline_change_pct = float((close - open) / open * 100) entry_and_growth_logic = (kline_change_pct > 2.01 and kline_change_pct < 6.99) is_strong_bar = (close > open) and (math.abs(close - open) / (high - low) > 0.6)

var bool is_trading_time = true if(t0_enabled == false) is_trading_time := (hour >= start_hour and hour <= end_hour)

// — 离场变量记录 — var int last_entry_date = 0 var float trend_stop_level = 0.0 var float entry_price = 0.0

// — 进场逻辑 — bool is_uptrend = (ema20 > ema50) and close > open bool is_price_above_ema = (close > ema20)

if (strategy.position_size == 0 and is_uptrend and is_price_above_ema and is_strong_bar and is_trading_time and entry_and_growth_logic) strategy.entry(“Trend_Buy”, strategy.long) entry_price := close trend_stop_level := low - syminfo.mintick last_entry_date := year * 10000 + month * 100 + dayofmonth

// — 动态移动止盈逻辑 — if (strategy.position_size > 0) // T+1 安全校验:只有当启用 T+0 或 当前日期 > 入场日期时才允许出场 bool can_exit_today = t0_enabled or (year * 10000 + month * 100 + dayofmonth > last_entry_date)

if (can_exit_today)
    // 1. 平手保护:盈利超过 2% 锁定保本
    if (high >= entry_price * 1.02)
        trend_stop_level := math.max(trend_stop_level, entry_price)
    
    // 2. 趋势跟随:出现强趋势K线,止损抬升至该K线最低价
    if (is_strong_bar)
        // 使用 ATR 作为缓冲:止损位 = 当前最高价 - 2倍ATR
        // 这样止损位是随行就市的
        float atr_stop = high - (atr_value * 2) 

        // 依然保留“只升不降”原则
        trend_stop_level := math.max(trend_stop_level, atr_stop)
    
    // 执行出场
    strategy.exit("Trend_Exit", "Trend_Buy", stop=trend_stop_level)

// — 绘图 — plot(ema20, color=color.blue, title=”EMA20”) plot(ema50, color=color.red, title=”EMA50”) plot(strategy.position_size > 0 ? trend_stop_level : na, color=color.orange, style=plot.style_linebr, linewidth=2, title=”动态趋势止损线”)