GitHub で見る

Tester v0.14 戦略

このサンプル戦略は、EURUSD のH4時間軸向けに設計されたMQL4スクリプト「Tester v0.14」を簡略化した移植版です。

ロジック

  • 14期間の単純移動平均線とMACDを計算する。
  • 終値がSMAを上回り、MACDがプラスの場合に買いシグナルを生成する。
  • 終値がSMAを下回り、MACDがマイナスの場合に売りシグナルを生成する。
  • 注文が開かれた後、設定可能な本数のバー後にポジションをクローズする。

この移植版はStockSharpの高レベルAPIを使用し、SubscribeCandlesBind に依存してインジケーター値を受け取ります。

パラメーター

  • MinSignSum – ポジションを開くために必要な最小シグナル数。
  • Risk – マネーマネジメントに使用する口座残高のパーセンテージ。
  • TakeProfit / StopLoss – ポイント単位の固定レベル。
  • BarsNumber – ポジションを保持するバー数。
  • CandleType – 使用するローソク足シリーズ(デフォルト: 4H)。

注記

元のMQLファイルには数百のルールの組み合わせが含まれていました。このC#の例は、わかりやすさのために縮小されたルールセットを使って構造を示しています。

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>
/// Tester strategy using SMA and MACD for entries.
/// Closes after specified number of bars.
/// </summary>
public class TesterV014Strategy : Strategy
{
	private readonly StrategyParam<int> _barsNumber;
	private readonly StrategyParam<DataType> _candleType;

	private int _barsCounter;
	private bool _positionOpened;

	public int BarsNumber { get => _barsNumber.Value; set => _barsNumber.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public TesterV014Strategy()
	{
		_barsNumber = Param(nameof(BarsNumber), 3)
			.SetGreaterThanZero()
			.SetDisplay("Bars Number", "Holding period in bars", "General");

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

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_barsCounter = 0;
		_positionOpened = false;
	}

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

		var sma = new SimpleMovingAverage { Length = 14 };
		var macd = new MovingAverageConvergenceDivergence();

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

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

		// Close after specified bars
		if (_positionOpened)
		{
			_barsCounter++;
			if (_barsCounter >= BarsNumber)
			{
				if (Position > 0)
					SellMarket();
				else if (Position < 0)
					BuyMarket();
				_positionOpened = false;
				_barsCounter = 0;
			}
		}

		// Entry
		if (Position == 0 && !_positionOpened)
		{
			if (candle.ClosePrice > smaVal && macdVal > 0)
			{
				BuyMarket();
				_barsCounter = 0;
				_positionOpened = true;
			}
			else if (candle.ClosePrice < smaVal && macdVal < 0)
			{
				SellMarket();
				_barsCounter = 0;
				_positionOpened = true;
			}
		}
	}
}