在 GitHub 上查看

Simple Trade 策略

概述

该策略是 MetaTrader 5 智能交易系统 “SimpleTrade (barabashkakvn's edition)” 的 C# 版本。策略比较当前K线的开盘价与三根之前K线的开盘价:若当前开盘价更高,则做多;否则做空。每一笔交易只持有一个完整的K线周期,并使用以点值(pip)表示的固定止损距离进行保护。

在 StockSharp 中,策略通过高级 API 订阅所选的K线序列,仅在收到收盘状态的K线后才进行决策,确保信号基于已经完成的数据。当出现下一根K线或当前K线触及止损价位时,仓位都会被关闭。

交易逻辑

  • 开仓
    • 每当一根K线收盘时,记录该K线的开盘价,并维护最近四个开盘价的滚动历史。
    • 当没有持仓并且已经记录了至少四个开盘价时,将最新的开盘价与三根之前的开盘价进行比较。
    • 如果当前开盘价高于三根之前的开盘价,则买入做多;否则卖出做空。
  • 平仓
    • 每笔交易都会根据 StopLossPips × 点值 相对于开仓价计算出固定止损水平。
    • 下一根K线到来时,无论盈亏都会主动平仓,以复现原始EA“一根K线持仓”的规则。
    • 如果在当前K线内,高点(空单)或低点(多单)突破了止损价格,策略会立即通过市价单尝试离场。

参数

参数 默认值 说明
StopLossPips 120 以点值表示的止损距离。代码遵循 MetaTrader 的处理方式:对于报价小数位为 3 或 5 的品种,将价格步长乘以 10 以获得常用的 pip 大小。
TradeVolume 1 市价单的交易手数,请根据品种合约规模进行调整。
CandleType 1 小时时间框架 指定要订阅的K线类型,应与在 MetaTrader 中使用的周期保持一致。

所有参数都以 StrategyParam<T> 暴露,可在界面中调整或用于优化。

实现细节

  • 为符合仓库规范,开盘价历史使用简单的字段轮换,而非集合容器。
  • 策略不会提交独立的止损委托,而是通过检查K线的最高价和最低价来判断止损是否被触发,并在触发时提交市价平仓。
  • 鉴于 StockSharp 中持仓更新是异步的,策略在寻找新的入场信号之前会先关闭现有仓位,避免同时存在多个相反订单,行为与原始EA“先平后开”的流程一致。
  • 点值由 Security.PriceStep 计算得出,对于 3 位或 5 位小数的品种会额外乘以 10,以匹配 MetaTrader 中对 pip 的定义。

使用建议

  • 适用于拥有稳定最小报价单位的工具,例如主要外汇货币对,使得基于点值的止损具有可比性。
  • 根据不同品种优化 StopLossPips,较大的数值可以提供更宽的缓冲,较小的数值则能更快响应波动。
  • 确保券商连接能够提供带有最终状态的K线更新,从而获得准确的开盘价数据。

风险与限制

  • 仅持有一根K线的设计使策略对时间框架非常敏感,需针对不同周期进行回测和参数验证。
  • 使用K线极值来模拟止损执行,在波动剧烈的行情中可能产生与真实止损单不同的滑点。
  • 当历史数据充足后,策略几乎始终保持在多头或空头仓位中,在盘整市场可能产生较高的交易频率。
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;

using StockSharp.Algo;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Simple trade strategy converted from MetaTrader that compares the current open with the open three bars ago.
/// The logic holds positions for a single bar and protects the trade with a fixed stop distance.
/// </summary>
public class SimpleTradeStrategy : Strategy
{
	private readonly StrategyParam<int> _stopLossPips;
	private readonly StrategyParam<decimal> _tradeVolume;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _openCurrent;
	private decimal _openMinus1;
	private decimal _openMinus2;
	private decimal _openMinus3;
	private int _historyCount;
	private decimal? _stopPrice;

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

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

	/// <summary>
	/// Candle type processed by the strategy.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initialize <see cref="SimpleTradeStrategy"/> parameters.
	/// </summary>
	public SimpleTradeStrategy()
	{
		_stopLossPips = Param(nameof(StopLossPips), 120)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss (pips)", "Fixed protective distance in pips", "Risk Management")
			;

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

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Primary candle source for decisions", "General");
	}

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

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

		_openCurrent = 0m;
		_openMinus1 = 0m;
		_openMinus2 = 0m;
		_openMinus3 = 0m;
		_historyCount = 0;
		_stopPrice = null;
	}

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

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(ProcessCandle)
			.Start();
	}

	private void ProcessCandle(ICandleMessage candle)
	{
		if (candle.State != CandleStates.Finished)
			return;

		// Exit existing trades before evaluating new entries to mimic the original MQL behaviour.
		if (TryCloseExistingPosition(candle))
			return;

		UpdateHistory(candle.OpenPrice);

		// Need at least four opens to compare with the value three bars ago.
		if (_historyCount < 4)
			return;

		ExecuteEntry(candle);
	}

	private bool TryCloseExistingPosition(ICandleMessage candle)
	{
		if (Position > 0)
		{
			var volume = Position;

			// Close long trades at the protective stop or at the bar change.
			if (_stopPrice is decimal stop && candle.LowPrice <= stop)
			{
				SellMarket();
			}
			else
			{
				if (Position > 0) SellMarket(); else if (Position < 0) BuyMarket();
			}

			_stopPrice = null;
			return true;
		}

		if (Position < 0)
		{
			var volume = Math.Abs(Position);

			// Close short trades at the protective stop or at the bar change.
			if (_stopPrice is decimal stop && candle.HighPrice >= stop)
			{
				BuyMarket();
			}
			else
			{
				if (Position > 0) SellMarket(); else if (Position < 0) BuyMarket();
			}

			_stopPrice = null;
			return true;
		}

		return false;
	}

	private void UpdateHistory(decimal currentOpen)
	{
		// Shift the stored opens so that _openMinus3 keeps the value three candles back.
		_openMinus3 = _openMinus2;
		_openMinus2 = _openMinus1;
		_openMinus1 = _openCurrent;
		_openCurrent = currentOpen;

		if (_historyCount < 4)
			_historyCount++;
	}

	private void ExecuteEntry(ICandleMessage candle)
	{
		var pipSize = CalculatePipSize();
		var stopOffset = pipSize * StopLossPips;

		// Enter long when the current open is above the open three bars ago, otherwise enter short.
		if (_openCurrent > _openMinus3)
		{
			BuyMarket();
			_stopPrice = candle.OpenPrice - stopOffset;
		}
		else
		{
			SellMarket();
			_stopPrice = candle.OpenPrice + stopOffset;
		}
	}

	private decimal CalculatePipSize()
	{
		// Reproduce the MetaTrader adjustment: multiply by ten for symbols with 3 or 5 decimals.
		var step = Security?.PriceStep ?? 1m;
		var decimals = Security?.Decimals;

		if (decimals == 3 || decimals == 5)
			step *= 10m;

		return step;
	}
}