GitHub で見る

MAクロスによる決済戦略

この戦略は単純移動平均(MA)を監視し、ローソク足のクローズがMAラインをクロスしたとき、オープンポジションを自動的に決済します。手動または他のシステムでエントリーを管理するトレーダーが、トレンドが反転したときに自動的に退出するために設計されています。

ロジックは終値とMAの関係を追跡します。新しい確定ローソク足がMAの一方側から他方側にクロスすると、戦略はポジションを解消するための成行注文を送信します。新しいポジションは開かれません。

詳細

  • エントリー条件: なし。ポジションは外部で開く必要があります。
  • エグジット条件:
    • ロング: 前のクローズがMA上で、現在のクローズがMA下の場合、決済売りを発動。
    • ショート: 前のクローズがMA下で、現在のクローズがMA上の場合、決済買いを発動。
  • ロング/ショート: 両方向がサポートされています。
  • ストップ: 使用しません。MAクロスが退出シグナルとして機能します。
  • デフォルト値:
    • MA Period = 50。
    • Candle Type = 1分の時間軸。
  • フィルター:
    • カテゴリ: トレンドフォロー
    • 方向: 両方
    • インジケーター: 単一
    • ストップ: いいえ
    • 複雑さ: シンプル
    • 時間軸: 任意
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: いいえ
    • リスクレベル: 中程度
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>
/// Price cross MA strategy.
/// </summary>
public class CloseCrossMaStrategy : Strategy
{
	private readonly StrategyParam<int> _maPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevDiff;
	private bool _hasPrev;

	public int MaPeriod { get => _maPeriod.Value; set => _maPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public CloseCrossMaStrategy()
	{
		_maPeriod = Param(nameof(MaPeriod), 50)
			.SetGreaterThanZero()
			.SetDisplay("MA Period", "EMA period", "Parameters");
		_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();
		_prevDiff = 0;
		_hasPrev = false;
	}

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

		var ema = new ExponentialMovingAverage { Length = MaPeriod };

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

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

		var diff = candle.ClosePrice - emaVal;

		if (!_hasPrev)
		{
			_prevDiff = diff;
			_hasPrev = true;
			return;
		}

		// Price crosses above EMA
		if (_prevDiff <= 0 && diff > 0 && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Price crosses below EMA
		else if (_prevDiff >= 0 && diff < 0 && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevDiff = diff;
	}
}