在 GitHub 上查看

C Factor HLH4 仅做多策略

该策略是原始 MQL 专家顾问 C_Factor_HLH4_buy_only 的 C# 翻译版本,展示如何将 MetaTrader 策略移植到 StockSharp 高级 API。

策略逻辑

  • 使用四小时周期的 K 线。
  • 当当前 K 线收盘价高于上一根 K 线的最高价时开多。
  • 当收盘价满足以下任一条件时平多:
    • 高于上一根 K 线最低价 100 个跳动点;
    • 低于上一根 K 线最高价 20 个跳动点。
  • 通过可配置的止损和止盈距离进行风险管理。
  • 订单数量根据账户权益风险百分比计算。

参数

名称 说明
StopLoss 止损距离(以跳动点计)。
TakeProfit 止盈距离(以跳动点计)。
RiskPercent 每笔交易风险占账户权益的百分比。
CandleType 分析所用的 K 线类型及周期(默认:四小时)。

备注

该策略仅用于演示目的,仅做多。实际交易前请根据个人需求调整参数和风险设置。

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;

/// <summary>
/// C Factor HLH4 buy-only strategy.
/// Buys when close breaks above previous high, sells on EMA cross.
/// </summary>
public class CFactorHlh4BuyOnlyStrategy : Strategy
{
	private readonly StrategyParam<int> _emaPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevHigh;
	private decimal _prevLow;
	private bool _hasPrev;

	public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public CFactorHlh4BuyOnlyStrategy()
	{
		_emaPeriod = Param(nameof(EmaPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("EMA Period", "EMA period for trend filter", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevHigh = 0;
		_prevLow = 0;
		_hasPrev = false;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var ema = new ExponentialMovingAverage { Length = EmaPeriod };

		SubscribeCandles(CandleType)
			.Bind(ema, ProcessCandle)
			.Start();
	}

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

		if (!_hasPrev)
		{
			_prevHigh = candle.HighPrice;
			_prevLow = candle.LowPrice;
			_hasPrev = true;
			return;
		}

		var close = candle.ClosePrice;

		if (close > _prevHigh && Position <= 0 && close > emaVal)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (close < _prevLow && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevHigh = candle.HighPrice;
		_prevLow = candle.LowPrice;
	}
}