在 GitHub 上查看

OsMaSter V0 策略

概述

  • 基于 MetaTrader 5 专家顾问 “OsMaSter v0”(MQL 文件 OsMaSter v0.mq5)转换。
  • 借助 MACD 直方图(OsMA)形态来捕捉短期盘整后的动量反转。
  • 通过参数 CandleType 指定交易品种和周期,策略只处理一个订阅源。
  • 将以点(pip)为单位的止损与止盈自动换算成绝对价格偏移,换算时会考虑交易品种的最小价格步长与小数位数。

参数

名称 默认值 说明
FastPeriod 9 MACD 直方图的快速 EMA 长度。
SlowPeriod 26 MACD 直方图的慢速 EMA 长度。
SignalPeriod 5 平滑直方图的信号 EMA 周期。
StopLossPips 30 止损距离(点)。设为 0 表示不使用。
TakeProfitPips 50 止盈距离(点)。设为 0 表示不使用。
TradeVolume 1 市价单的下单量(手数)。
CandleType 15 分钟 计算指标所使用的 K 线周期。

信号逻辑

  1. 策略保存最近四个 MACD 直方图数值(hist0 为当前,hist1hist2hist3 依次向前追溯三根 K 线)。
  2. 做多 条件:hist3 > hist2hist2 < hist1hist1 < hist0,即在局部低点之后出现逐步抬高的直方图。
  3. 做空 条件:hist3 < hist2hist2 > hist1hist1 > hist0,即在局部高点之后出现逐步走低的直方图。
  4. 同一时间仅允许一笔持仓,持仓未平仓之前的后续信号会被忽略。

仓位管理

  • 通过 BuyMarket() / SellMarket()TradeVolume 执行市价开仓。
  • 调用 StartProtection 将点值参数转换为价格偏移:对于 3 或 5 位小数的外汇品种,pip=最小步长 × 10,其余品种使用最小步长本身。
  • 策略不包含额外的离场逻辑,仓位由止盈、止损或手动操作平仓。

注意事项

  • 请确认交易品种的 PriceStepDecimals 属性设置正确,否则点值换算可能与交易商规格不符。
  • 可根据市场特性调整周期与下单量,以适应不同的交易节奏。
  • 因为持仓期间不会开启新仓,如果需要更频繁地交易,可考虑降低止损/止盈距离或改进退出规则。
using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// OsMA histogram pattern strategy converted from the "OsMaSter v0" MQL expert.
/// Enters on four-bar momentum reversals identified by the MACD histogram.
/// </summary>
public class OsMaSterV0Strategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _signalPeriod;
	private readonly StrategyParam<int> _stopLossPips;
	private readonly StrategyParam<int> _takeProfitPips;
	private readonly StrategyParam<decimal> _tradeVolume;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _histCurrent;
	private decimal? _histPrev1;
	private decimal? _histPrev2;
	private decimal? _histPrev3;

	/// <summary>
	/// Initializes a new instance of the strategy.
	/// </summary>
	public OsMaSterV0Strategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 9)
			.SetDisplay("Fast EMA", "Fast EMA period for MACD histogram", "Indicators")
			.SetGreaterThanZero();

		_slowPeriod = Param(nameof(SlowPeriod), 26)
			.SetDisplay("Slow EMA", "Slow EMA period for MACD histogram", "Indicators")
			.SetGreaterThanZero();

		_signalPeriod = Param(nameof(SignalPeriod), 5)
			.SetDisplay("Signal Smoothing", "Signal moving average period", "Indicators")
			.SetGreaterThanZero();

		_stopLossPips = Param(nameof(StopLossPips), 500)
			.SetDisplay("Stop Loss (pips)", "Stop loss distance in pips", "Risk");

		_takeProfitPips = Param(nameof(TakeProfitPips), 1000)
			.SetDisplay("Take Profit (pips)", "Take profit distance in pips", "Risk");

		_tradeVolume = Param(nameof(TradeVolume), 1m)
			.SetDisplay("Trade Volume", "Order volume in lots", "Trading")
			.SetGreaterThanZero();

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles for calculations", "General");

		Volume = TradeVolume;
	}

	/// <summary>
	/// Fast EMA period used in MACD histogram calculation.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow EMA period used in MACD histogram calculation.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}

	/// <summary>
	/// Signal moving average period.
	/// </summary>
	public int SignalPeriod
	{
		get => _signalPeriod.Value;
		set => _signalPeriod.Value = value;
	}

	/// <summary>
	/// Stop loss size expressed in pips.
	/// </summary>
	public int StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.Value = value;
	}

	/// <summary>
	/// Take profit size expressed in pips.
	/// </summary>
	public int TakeProfitPips
	{
		get => _takeProfitPips.Value;
		set => _takeProfitPips.Value = value;
	}

	/// <summary>
	/// Trading volume used for market orders.
	/// </summary>
	public decimal TradeVolume
	{
		get => _tradeVolume.Value;
		set
		{
			_tradeVolume.Value = value;
			Volume = value;
		}
	}

	/// <summary>
	/// Candle type used for indicator calculations.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_histCurrent = null;
		_histPrev1 = null;
		_histPrev2 = null;
		_histPrev3 = null;

		Volume = TradeVolume;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		Volume = TradeVolume;

		var macd = new MovingAverageConvergenceDivergenceHistogram
		{
			Macd =
			{
				ShortMa = { Length = FastPeriod },
				LongMa = { Length = SlowPeriod }
			},
			SignalMa = { Length = SignalPeriod }
		};

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(macd, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, macd);
			DrawOwnTrades(area);
		}

		var step = Security?.PriceStep ?? 1m;
		var decimals = Security?.Decimals ?? 0;
		var pipSize = (decimals == 3 || decimals == 5) ? step * 10m : step;

		// Convert pip-based risk controls into absolute price offsets.
		StartProtection(
			takeProfit: TakeProfitPips > 0 ? new Unit(TakeProfitPips * pipSize, UnitTypes.Absolute) : null,
			stopLoss: StopLossPips > 0 ? new Unit(StopLossPips * pipSize, UnitTypes.Absolute) : null);
	}

	private void ProcessCandle(ICandleMessage candle, IIndicatorValue macdValue)
	{
		// Ignore incomplete candles because signals rely on closed data.
		if (candle.State != CandleStates.Finished)
			return;

		// Ensure the strategy is synchronized with the market and permitted to trade.
		if (!macdValue.IsFormed)
			return;

		var macdTyped = (MovingAverageConvergenceDivergenceHistogramValue)macdValue;
		if (macdTyped.Macd is not decimal histogram)
			return;

		// Shift stored histogram values to maintain the last four observations.
		_histPrev3 = _histPrev2;
		_histPrev2 = _histPrev1;
		_histPrev1 = _histCurrent;
		_histCurrent = histogram;

		if (_histCurrent is not decimal hist0 ||
			_histPrev1 is not decimal hist1 ||
			_histPrev2 is not decimal hist2 ||
			_histPrev3 is not decimal hist3)
		{
			return;
		}

		// Detect the specific four-bar rising pattern used for long entries.
		var bullishPattern = hist3 > hist2 && hist2 < hist1 && hist1 < hist0;

		// Detect the mirrored falling pattern used for short entries.
		var bearishPattern = hist3 < hist2 && hist2 > hist1 && hist1 > hist0;

		// The original expert opens a position only when no trades are active.
		if (Position != 0)
			return;

		if (bullishPattern)
		{
			// Enter long when the histogram forms a higher-low sequence.
			BuyMarket();
		}
		else if (bearishPattern)
		{
			// Enter short when the histogram forms a lower-high sequence.
			SellMarket();
		}
	}
}