GitHub で見る

My Line Order 戦略

この戦略は価格が事前に定義した水平レベルをクロスした時に成行注文を発動します。ユーザーはロングとショートのエントリーに別々のレベルとpips単位のリスクパラメーターを指定します。ポジションを建てた後、戦略はストップロス、テイクプロフィット、オプションのトレーリングストップを追跡します。

エントリーレベルが事前にわかっている裁量トレードのセットアップに適しています。価格レベルのみに依存するため、あらゆる銘柄と時間軸で機能します。

詳細

  • エントリー条件:
    • ロング: 終値がBuyPriceを上抜けする。
    • ショート: 終値がSellPriceを下抜けする。
  • ロング/ショート: 両方。
  • エグジット条件:
    • StopLossPipsでのストップロス。
    • TakeProfitPipsでのテイクプロフィット。
    • TrailingStopPips > 0の場合はトレーリングストップ。
  • ストップ: あり、pips単位。
  • デフォルト値:
    • BuyPrice = 0 (無効)
    • SellPrice = 0 (無効)
    • TakeProfitPips = 30
    • StopLossPips = 20
    • TrailingStopPips = 0
    • CandleType = TimeSpan.FromMinutes(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>
/// Line order strategy using SMA as dynamic support/resistance levels.
/// </summary>
public class MyLineOrderStrategy : Strategy
{
	private readonly StrategyParam<int> _smaLength;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevClose;
	private decimal _prevSma;
	private bool _hasPrev;

	public int SmaLength { get => _smaLength.Value; set => _smaLength.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public MyLineOrderStrategy()
	{
		_smaLength = Param(nameof(SmaLength), 14)
			.SetGreaterThanZero()
			.SetDisplay("SMA", "SMA period", "Indicators");

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

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

		var sma = new SimpleMovingAverage { Length = SmaLength };

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

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

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevClose = close;
			_prevSma = sma;
			_hasPrev = true;
			return;
		}

		// Cross above SMA
		if (_prevClose <= _prevSma && close > sma)
		{
			if (Position < 0) BuyMarket();
			if (Position <= 0) BuyMarket();
		}
		// Cross below SMA
		else if (_prevClose >= _prevSma && close < sma)
		{
			if (Position > 0) SellMarket();
			if (Position >= 0) SellMarket();
		}

		_prevClose = close;
		_prevSma = sma;
	}
}