在 GitHub 上查看

Pure Price Action Fractal 策略

概述

纯价格行为策略 是 MetaTrader 专家顾问“Pure Price Action”(MQL 编号 24291)的 StockSharp 版本。 策略将比尔·威廉姆斯分形的回测突破、较高时间框架上的动量过滤以及长期 MACD 趋势过滤结合在一起,旨在在市场重新测试最近的分形水平时捕捉顺势交易。

交易逻辑

  1. 信号时间框架 – 交易决策基于用户选择的时间框架(默认 15 分钟)。
  2. 分形触发确认 – 仅当最新完成的 K 线收盘价在最新确认分形价位的一个最小价格步长以内时,才允许下单(空头使用上分形, 多头使用下分形)。
  3. 蜡烛实体结构 – 最新蜡烛的实体绝对值必须小于上一根蜡烛实体,而上一根蜡烛实体必须大于更早一根蜡烛实体,以模拟原始 EA 中的动量回撤过滤条件。
  4. 加权移动平均线 – 两条线性加权移动平均线(默认 6 与 85)用于识别趋势。多头要求快线高于慢线,空头要求快线低于慢线。
  5. 动量过滤 – 在较高时间框架(默认 1 小时)计算的 14 周期动量指标,在最近三次计算中至少一次偏离 100 水平超过设定阈值。
  6. MACD 过滤 – 在更高时间框架(默认 30 天,模拟月线)计算的 MACD(12, 26, 9),多头要求主线高于信号线,空头要求主线低于信号线。
  7. 仓位大小 – 策略使用基础 Strategy 类的 Volume 属性;如果未设置,则默认使用 1 手。MaxPosition 参数限制最大净头寸规模。

仓位管理

  • 初始保护 – 可选的止损与止盈距离以价格步长表示,对多空对称生效。
  • 移动止损 – 启用时,根据入场后达到的最高价/最低价减去(或加上)设定距离进行跟踪。
  • 保本移动 – 当浮盈达到触发距离后,将保护水平移动到入场价加/减偏移量以锁定利润。
  • 手动平仓 – 每根完成的蜡烛都会评估止损、止盈、移动止损和保本条件,一旦满足即全部平仓。

参数说明

  • CandleType – 主信号时间框架(默认 15 分钟)。
  • MomentumCandleType – 动量指标使用的时间框架(默认 1 小时)。
  • MacdCandleType – MACD 使用的时间框架(默认 30 天时间框架,模拟月线)。
  • FastPeriod / SlowPeriod – 快、慢线性加权移动平均长度。
  • MomentumPeriod – 动量指标周期。
  • MomentumThreshold – 动量与 100 之间的最小绝对偏差。
  • MacdFastPeriodMacdSlowPeriodMacdSignalPeriod – MACD 的参数。
  • StopLossPointsTakeProfitPoints – 以价格步长表示的止损与止盈距离。
  • TrailingStopPoints – 移动止损距离。
  • BreakEvenTriggerPointsBreakEvenOffsetPoints – 保本触发距离与偏移量。
  • MaxPosition – 策略允许的最大绝对持仓量。
  • EnableTrailingEnableBreakEvenUseStopLossUseTakeProfit – 风险管理模块的开关。

其他说明

  • 代码中的注释全部使用英文,以符合仓库要求。
  • 策略仅在蜡烛收盘后进行计算,不处理未完成的 K 线数据。
  • 使用多个时间框架的数据订阅来复刻原始 EA 的行为(默认 M15 信号、H1 动量、月线 MACD)。
  • 本目录未包含自动化测试,按照要求无需改动仓库现有的测试套件。
using System;
using System.Collections.Generic;

using Ecng.Common;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

public class PurePriceActionFractalStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
	public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	public PurePriceActionFractalStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
		_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

	protected override void OnReseted()
	{
		base.OnReseted();
		_fast = null; _slow = null;
		_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };
		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished) return;
		if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
		if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}

		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}