GitHub で見る

Secwenta MultiBar Signals戦略

概要

この戦略はMetaTraderエキスパートアドバイザー「Secwenta」(MQL ID 22977)のStockSharpポートです。アルゴリズムは完成したローソク足をスキャンし、短いローリング履歴内で何本が陽線(終値 > 始値)または陰線(終値 < 始値)で終了したかを数えます。設定に応じて、買いのみ、売りのみ、または双方向の反転モードで動作できます。必要な数の陽線または陰線が現れると、戦略は元のロット設定を反映した固定ボリュームを使って市場ポジションを開くか閉じます。

シグナル評価

  • 選択したCandleTypeの完成したローソク足のみが、高レベルサブスクリプションAPIを通じて処理されます。
  • 各ローソク足について戦略は陽線、陰線、またはニュートラル(ドージ)かを記録します。内部バッファは最新のN方向を保持し、Nは有効化されている側(買いおよび/または売り)のBullishBarCountBearishBarCountのうち大きい方です。
  • ローソク足が始値を上回って終値をつけると陽線カウンターが増分し、始値を下回って終値をつけると陰線カウンターが増分します。ニュートラルなローソク足はカウンターに影響しません。
  • 対応するカウンターがローリング・ウィンドウ内で設定されたしきい値に達するとシグナルが発動します。これは要求された数の陽線または陰線が見つかるまで直近のバーを反復した元のMQLロジックを再現します。

取引ルール

  1. 買いのみモード(UseBuySignals = trueUseSellSignals = false):
    • 陰線カウンターがBearishBarCountに達すると、既存のロングポジションは成行売り注文でクローズされます。
    • 陽線カウンターがBullishBarCountに達し、戦略がフラットの場合、OrderVolumeを使って新しいロングポジションが開かれます。
  2. 売りのみモード(UseBuySignals = falseUseSellSignals = true):
    • 陽線カウンターがBullishBarCountに達すると、オープンのショートポジションは成行買い注文でカバーされます。
    • 陰線カウンターがBearishBarCountに達し、戦略がフラットの場合、OrderVolumeを使って新しいショートポジションが開かれます。
  3. 反転モード(UseBuySignals = trueかつUseSellSignals = true):
    • 陽線トリガーはショートエクスポージャーをクローズし、戦略がまだロングでなければ、OrderVolumeにショートポジションの絶対サイズを加えた量を買うことで新しいロングポジションを開きます。これは売りをクローズしてから買いを開くという元のシーケンスを模倣します。
    • 陰線トリガーはロングエクスポージャーをクローズし、戦略がまだショートでなければ、OrderVolumeにロングポジションの絶対サイズを加えた量を売ることで新しいショートポジションを開きます。

すべての市場操作はStockSharpのBuyMarketおよびSellMarketヘルパーを再利用し、戦略はStartProtection()を呼び出してアカウントレベルの保護を必要に応じて重ねることができます。

パラメーター

パラメーター 説明 デフォルト メモ
CandleType シーケンス評価に使用するローソク足データタイプ(時間足)。 1時間足 StockSharpがサポートする任意のローソク足タイプを選択可能。
OrderVolume MQLのロットサイズを反映したベース成行注文ボリューム。 1 ポジション反転時にクローズボリュームに加算されます。
UseBuySignals 陽線シグナル処理を有効化します。 true 無効時は新しいロングトレードを開きません。
BullishBarCount 陽線イベントを発動するために必要な陽線ローソク足の数。 2 買いのみモードで実行する場合、クローズしきい値と一致させる必要があります。
UseSellSignals 陰線シグナル処理を有効化します。 false 無効時は新しいショートトレードを開きません。
BearishBarCount 陰線イベントを発動するために必要な陰線ローソク足の数。 1 ショートの開設しきい値とロングの決済しきい値の両方として機能します。

実装メモ

  • ローリング・ウィンドウはキューを使用して最新のローソク足方向を保持し、パラメーター変更後もカウンターがウィンドウサイズと一致することを保証します。
  • 元の「新バー」イベント処理に忠実であるため、完成したローソク足のみが処理されます。
  • ニュートラル(ドージ)ローソク足はMQLコードと同様にカウンターを変更しません。
  • 反転は単一の成行注文で実行され、クローズとオープンのボリュームを組み合わせ、確定的なエクスポージャー変更を維持します。
  • バッファ長は最大のアクティブしきい値に等しく、一方の側が無効化されている場合は対応するしきい値のみがルックバック長に寄与し、MQLバージョンのCopyRatesの動作と一致します。

ファイル

  • CS/SecwentaMultiBarSignalsStrategy.cs – StockSharp高レベル戦略APIに基づいたメインC#実装。

注意: このIDにはPython翻訳は提供されません。要求された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>
/// Secwenta MultiBar Signals strategy using SmoothedMA crossover.
/// Buys when fast SmoothedMA crosses above slow SmoothedMA, sells on reverse.
/// </summary>
public class SecwentaMultiBarSignalsStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private SmoothedMovingAverage _fast;
	private SmoothedMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	/// <summary>
	/// Fast SmoothedMA period.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow SmoothedMA period.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}

	/// <summary>
	/// Stop-loss distance in price steps.
	/// </summary>
	public int StopLossPoints
	{
		get => _stopLossPoints.Value;
		set => _stopLossPoints.Value = value;
	}

	/// <summary>
	/// Take-profit distance in price steps.
	/// </summary>
	public int TakeProfitPoints
	{
		get => _takeProfitPoints.Value;
		set => _takeProfitPoints.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the <see cref="SecwentaMultiBarSignalsStrategy"/> class.
	/// </summary>
	public SecwentaMultiBarSignalsStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 15)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Fast SmoothedMA period", "Indicator");

		_slowPeriod = Param(nameof(SlowPeriod), 60)
			.SetGreaterThanZero()
			.SetDisplay("Slow Period", "Slow SmoothedMA period", "Indicator");

		_stopLossPoints = Param(nameof(StopLossPoints), 200)
			.SetNotNegative()
			.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400)
			.SetNotNegative()
			.SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

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

		_fast = null;
		_slow = null;
		_prevFast = 0;
		_prevSlow = 0;
		_entryPrice = 0;
		_cooldown = 0;
	}

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

		_fast = new SmoothedMovingAverage { Length = FastPeriod };
		_slow = new SmoothedMovingAverage { Length = SlowPeriod };

		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

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

		if (!_fast.IsFormed || !_slow.IsFormed)
		{
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		if (_cooldown > 0)
		{
			_cooldown--;
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		// Check SL/TP
		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}

			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step)
			{
				SellMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}

			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step)
			{
				BuyMarket();
				_entryPrice = 0;
				_cooldown = 80;
				_prevFast = fastValue;
				_prevSlow = slowValue;
				return;
			}
		}

		// SmoothedMA crossover
		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();

			BuyMarket();
			_entryPrice = close;
			_cooldown = 80;
		}
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{
			if (Position > 0)
				SellMarket();

			SellMarket();
			_entryPrice = close;
			_cooldown = 80;
		}

		_prevFast = fastValue;
		_prevSlow = slowValue;
	}
}