GitHub で見る

ラインオーダー戦略

ラインオーダー戦略は、価格がユーザー定義の水平線を越えたときに成行注文を発動します。元のMQLスクリプトLineOrder.mq4の簡略化されたコンバージョンとして意図されており、StockSharpの高レベルAPIを通じて手動ライン取引機能を提供します。

この戦略は方向、エントリーレベル、リスク管理を制御するパラメーターを公開します。ポジションに入った後、オプションのストップロス、テイクプロフィット、トレーリングストップレベルが完了した各ローソク足で監視されます。ロジックは完全にイベント駆動で、カスタムコレクションを維持しません。

パラメーター

  • LinePrice – 注文を置くための価格レベル。
  • IsBuytrueでロングエントリー、falseでショートエントリー。
  • StopLoss – 価格単位でのストップロス距離(0で無効化)。
  • TakeProfit – 価格単位でのテイクプロフィット距離(0で無効化)。
  • TrailingStop – 価格単位でのトレーリングストップ距離(0で無効化)。
  • Volume – 注文数量。
  • CandleType – 価格監視に使用するローソク足タイプ。

取引ルール

  • エントリー: 終値が選択した方向にLinePriceを越えたとき。
  • ストップロス: 損失がエントリーからのStopLoss距離を超えたときにポジションをクローズ。
  • テイクプロフィット: 利益がTakeProfit距離に達したときにポジションをクローズ。
  • トレーリングストップ: エントリー後、最も有利な価格に調整し、価格がポジションに対してTrailingStop分動いたときにクローズ。

注記

  • StockSharpでサポートされている任意の銘柄で動作します。
  • MQLからの手動ライン取引の移行を示す教育目的で設計されています。
  • Pythonバージョンは意図的に省略されています。
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>
/// Executes a market order when price crosses a moving average "line".
/// Manages stop-loss and take-profit via candle monitoring.
/// </summary>
public class LineOrderStrategy : Strategy
{
	private readonly StrategyParam<int> _maLength;
	private readonly StrategyParam<decimal> _stopLossPct;
	private readonly StrategyParam<decimal> _takeProfitPct;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _entryPrice;
	private decimal _prevClose;
	private decimal _prevMa;
	private bool _hasPrev;

	public int MaLength { get => _maLength.Value; set => _maLength.Value = value; }
	public decimal StopLossPct { get => _stopLossPct.Value; set => _stopLossPct.Value = value; }
	public decimal TakeProfitPct { get => _takeProfitPct.Value; set => _takeProfitPct.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public LineOrderStrategy()
	{
		_maLength = Param(nameof(MaLength), 20)
			.SetGreaterThanZero()
			.SetDisplay("MA Length", "Moving average period for line", "Indicators");

		_stopLossPct = Param(nameof(StopLossPct), 2m)
			.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");

		_takeProfitPct = Param(nameof(TakeProfitPct), 3m)
			.SetDisplay("Take Profit %", "Take profit percentage", "Risk");

		_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();
		_entryPrice = 0;
		_prevClose = 0;
		_prevMa = 0;
		_hasPrev = false;
	}

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

		var ma = new SimpleMovingAverage { Length = MaLength };

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

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

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevClose = close;
			_prevMa = maVal;
			_hasPrev = true;
			return;
		}

		// Check stop-loss / take-profit for existing positions
		if (Position > 0 && _entryPrice > 0)
		{
			if (close <= _entryPrice * (1 - StopLossPct / 100m) ||
				close >= _entryPrice * (1 + TakeProfitPct / 100m))
			{
				SellMarket();
				_entryPrice = 0;
				_prevClose = close;
				_prevMa = maVal;
				return;
			}
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (close >= _entryPrice * (1 + StopLossPct / 100m) ||
				close <= _entryPrice * (1 - TakeProfitPct / 100m))
			{
				BuyMarket();
				_entryPrice = 0;
				_prevClose = close;
				_prevMa = maVal;
				return;
			}
		}

		// Cross above MA line -> buy
		if (_prevClose <= _prevMa && close > maVal)
		{
			if (Position < 0)
			{
				BuyMarket();
				_entryPrice = 0;
			}
			if (Position <= 0)
			{
				BuyMarket();
				_entryPrice = close;
			}
		}
		// Cross below MA line -> sell
		else if (_prevClose >= _prevMa && close < maVal)
		{
			if (Position > 0)
			{
				SellMarket();
				_entryPrice = 0;
			}
			if (Position >= 0)
			{
				SellMarket();
				_entryPrice = close;
			}
		}

		_prevClose = close;
		_prevMa = maVal;
	}
}