//------------------------------------------------------------------------
// 简称: HannWindowROCTradingSystem
// 名称: 基于Hann窗滤波器和变化率的交易系统
// 类别: 公式应用
// 类型: 用户应用
// 输出: 交易信号
//------------------------------------------------------------------------

Params
    Numeric Length(20);  // 周期长度
    Numeric StopLoss1(0.4);  // 止损百分比
    Numeric TakeProfit(0.05);  // 止盈百分比

Vars
    Series<Numeric> Deriv;   // 价格波导数（Close - Open）
    Series<Numeric> Filt;    // 滤波器输出
    Numeric coef_sum;        // 系数总和（用于归一化）
    Series<Numeric> ROC;     // 变化率
    Integer count;           // 循环计数器
    Numeric EntryPrice;      // 开仓价格
    Numeric StopLossPrice;   // 止损价格
    Numeric TakeProfitPrice; // 止盈价格

Events
OnBar(ArrayRef<Integer> indexs)
{
    // 1. 计算价格波导数
    Deriv = Close - Open;

    // 2. 初始化滤波器和系数总和
    Filt = 0;
    coef_sum = 0;

    // 3. 动态计算Hann窗系数
    for count = 1 to Length
    {
        Numeric hann_coef = 1 - Cos(2 * Pi * (count - 1) / (Length - 1));  // 正确Hann窗公式
        Filt = Filt + hann_coef * Deriv[count - 1];  // Deriv索引从0开始
        coef_sum = coef_sum + hann_coef;
    }

    // 4. 归一化滤波器输出
    If (coef_sum != 0)
    {
        Filt = Filt / coef_sum;
    }

    // 5. 计算变化率
    ROC = (Length / 6.28) * (Filt - Filt[1]);

    // 6. 绘制图表
    PlotNumeric("Filt", Filt);
    PlotNumeric("ZeroLine", 0);

    // 7. 交易逻辑
    // 开多条件：ROC从负转正
    If (ROC[2] < 0 And ROC[1] > 0 And MarketPosition == 0)
    {
        Buy(1, Open);
        EntryPrice = Open;
        StopLossPrice = EntryPrice * (1 - StopLoss1);
        TakeProfitPrice = EntryPrice * (1 + TakeProfit);
    }

    // 开空条件：ROC从正转负
    If (ROC[2] > 0 And ROC[1] < 0 And MarketPosition == 0)
    {
        SellShort(1, Open);
        EntryPrice = Open;
        StopLossPrice = EntryPrice * (1 + StopLoss1);
        TakeProfitPrice = EntryPrice * (1 - TakeProfit);
    }

    // 止损条件
    If (MarketPosition == 1 And Low <= StopLossPrice)
    {
        Sell(0, Min(Open, StopLossPrice));
    }
    If (MarketPosition == -1 And High >= StopLossPrice)
    {
        BuyToCover(0, Max(Open, StopLossPrice));
    }

    // 止盈条件
    If (MarketPosition == 1 And High >= TakeProfitPrice)
    {
        Sell(0, Max(Open, TakeProfitPrice));
    }
    If (MarketPosition == -1 And Low <= TakeProfitPrice)
    {
        BuyToCover(0, Min(Open, TakeProfitPrice));
    }
}

//------------------------------------------------------------------------
// 编译版本	2025/03/17 163230
// 版权所有	songshu123
// 更改声明	TradeBlazer Software保留对TradeBlazer平台
//			每一版本的TradeBlazer公式修改和重写的权利
//------------------------------------------------------------------------

//由 Ai 生成的内容仅作为学习参考,不能保证正确性，不构成任何投资意见，风险自负。

//制作一个自己的Ai编写助手与投研助手...

//详情链接：https://mp.weixin.qq.com/s/Y-XAbLLN7EwfKHHBp4AYdQ