GitHub で見る

Cheduecoglioni交互戦略

概要

この戦略はMQL5エキスパートアドバイザー「cheduecoglioni」のStockSharpポートです。ショートとロングポジションを交互に切り替えることで、常にトレーダーを市場に留まらせます。各エントリーはpipsで定義され、インストゥルメントの精度に応じて価格オフセットに変換された固定のテイクプロフィットとストップロスレベルで保護されます。

トレードルール

  • 戦略は設定されたロウソク足シリーズ(デフォルト1分)を監視し、ロウソク足が完全に閉じたときにのみ反応します。このイベントが元のエキスパートアドバイザーのティックベースのループを置き換えます。
  • オープンポジションがなく、成行注文の実行待ちもない場合、戦略は_nextSide状態に格納された方向に成行注文を送信します。開始後の最初の取引は売りで、MQL5の実装と一致します。
  • ポジションがアクティブになったら、アルゴリズムは保護注文または手動介入によってクローズされるのを待ちます。ポジションがゼロに戻ったら、次の方向が反転するため、次の取引は反対方向になります。
  • ストップロスとテイクプロフィットの距離はStartProtectionによって自動的に適用され、すべての取引が設定されたリスク・リワード距離を持つことを保証します。

パラメーター

  • Trade Volume – 各成行エントリーに使用するボリューム。これはInpLots入力を反映します。
  • Take Profit (pips) – テイクプロフィット注文のpips単位の距離。戦略は検出されたpipサイズを使用して絶対価格距離に変換します。
  • Stop Loss (pips) – 保護ストップロスのpips単位の距離。同じpipサイズロジックで変換されます。
  • Candle Type – 意思決定ループを駆動するロウソク足の時間軸。サポートされているあらゆるDataTypeを指定できます。

実装の詳細

  • pipサイズはSecurity.PriceStepから導出されます。3桁または5桁のFXシンボルの場合、分数pipから標準pipに移行するために値が10倍され、MLQの調整を再現します。
  • 前の注文が実行待ちの間に重複した成行注文を防ぐ待機フラグがあります。ブローカーが注文を拒否した場合、OnOrderFailedがフラグをクリアして次のロウソク足が再試行できるようにします。
  • OnPositionChangedはアクティブポジションの方向を追跡し、各フラット状態の後に_nextSideを切り替えます。これは各エグジット後に反対サイドをオープンしたMQLロジックを反映します。
  • 保護注文はStartProtectionによって成行エグジットで管理され、エキスパートアドバイザーが注文配置時に行った即時ストップロスとテイクプロフィットの割り当てと一致します。

注記

  • Pythonバージョンはまだ意図的に作成されていません。
  • この戦略はユニットテストを変更しません。
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>
/// Alternates buy and sell market orders with fixed stop loss and take profit distances.
/// </summary>
public class CheduecoglioniAlternatingStrategy : Strategy
{
	private readonly StrategyParam<decimal> _tradeVolume;
	private readonly StrategyParam<decimal> _takeProfitPips;
	private readonly StrategyParam<decimal> _stopLossPips;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _pipSize;
	private Sides _nextSide;
	private Sides? _activeSide;

	/// <summary>
	/// Initializes a new instance of the <see cref="CheduecoglioniAlternatingStrategy"/> class.
	/// </summary>
	public CheduecoglioniAlternatingStrategy()
	{
		_tradeVolume = Param(nameof(TradeVolume), 1m)
			.SetDisplay("Trade Volume", "Volume per trade", "General")
			.SetGreaterThanZero();

		_takeProfitPips = Param(nameof(TakeProfitPips), 10m)
			.SetDisplay("Take Profit (pips)", "Distance to take profit", "Risk")
			.SetGreaterThanZero();

		_stopLossPips = Param(nameof(StopLossPips), 10m)
			.SetDisplay("Stop Loss (pips)", "Distance to stop loss", "Risk")
			.SetGreaterThanZero();

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Source candles for timing", "General");
	}

	/// <summary>
	/// Volume used for each market order.
	/// </summary>
	public decimal TradeVolume
	{
		get => _tradeVolume.Value;
		set => _tradeVolume.Value = value;
	}

	/// <summary>
	/// Take profit distance expressed in pips.
	/// </summary>
	public decimal TakeProfitPips
	{
		get => _takeProfitPips.Value;
		set => _takeProfitPips.Value = value;
	}

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

	/// <summary>
	/// Candle type that triggers trading decisions.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

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

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

		Volume = TradeVolume;
		_nextSide = Sides.Sell;
		_activeSide = null;
		_pipSize = 0m;
	}

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

		Volume = TradeVolume; // Align the base volume with the strategy parameter.

		var priceStep = Security?.PriceStep ?? 0m;
		if (priceStep <= 0m)
		{
			var decimals = Security?.Decimals ?? 4;
			priceStep = (decimal)Math.Pow(10, -decimals);
		}

		_pipSize = priceStep;

		var secDecimals = Security?.Decimals;
		if (secDecimals is int digits && (digits == 3 || digits == 5))
		{
			_pipSize *= 10m; // Convert from fractional pip to full pip for FX symbols.
		}

		if (_pipSize <= 0m)
		{
			_pipSize = 1m; // Fallback to a neutral value if the instrument metadata is missing.
		}

		StartProtection(
			takeProfit: new Unit(TakeProfitPips * _pipSize, UnitTypes.Absolute),
			stopLoss: new Unit(StopLossPips * _pipSize, UnitTypes.Absolute),
			useMarketOrders: true);

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

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

		// Strategy has no bound indicators, always allow trading.

		if (Position != 0)
			return; // Skip if a position exists.

		var volume = TradeVolume;
		if (volume <= 0m)
			return;

		if (_nextSide == Sides.Buy)
			BuyMarket();
		else
			SellMarket();

	}

	/// <inheritdoc />
	protected override void OnPositionReceived(Position position)
	{
		base.OnPositionReceived(position);

		if (Position > 0)
		{
			_activeSide = Sides.Buy;
			return;
		}

		if (Position < 0)
		{
			_activeSide = Sides.Sell;
			return;
		}

		if (_activeSide.HasValue)
		{
			_nextSide = _activeSide == Sides.Buy ? Sides.Sell : Sides.Buy; // Alternate direction after a flat position.
			_activeSide = null;
		}

	}

}