GitHub で見る

Revolveを用いたレベル戦略

この戦略は、市場価格がユーザー定義のレベルを越えたときにトレードを開きます。価格がレベルを上抜けると買い注文が出され、下抜けると売り注文が出されます。反対のシグナルが現れた場合、システムはオプションで既存のポジションを反転させることができます。また、価格単位で測定されたオプションのストップロスおよびテイクプロフィット距離もサポートされています。

戦略はロウソク足を購読し、ロウソク足が完全に形成された場合にのみ反応します。すべての計算は完成した各ロウソク足の終値に基づいて行われます。反転モードが有効な場合、次のシグナルで現在のポジションが閉じられ、反対方向の新しいポジションが開かれます。

詳細

  • エントリー条件:
    • ロング: 終値が LevelPrice を上抜ける。
    • ショート: 終値が LevelPrice を下抜ける。
  • ロング/ショート: 両方の方向。
  • 反転: オプション、EnableReversal で制御。
  • ストップ: 価格単位でのオプションのストップロスおよびテイクプロフィット。
  • デフォルト値:
    • LevelPrice = 100.
    • StopLoss = 0 (無効).
    • TakeProfit = 0 (無効).
    • EnableReversal = false.
    • CandleType = 1分時間軸。
  • フィルター:
    • カテゴリ: ブレイクアウト
    • 方向: 両方
    • インジケーター: なし
    • ストップ: オプション
    • 複雑さ: シンプル
    • 時間軸: 短期
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: いいえ
    • リスクレベル: 中
using System;
using System.Collections.Generic;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy that opens a position when price crosses a moving average level.
/// Reverses the position when price crosses in the opposite direction.
/// </summary>
public class LevelsWithRevolveStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _maPeriod;
	private readonly StrategyParam<decimal> _stopPct;
	private readonly StrategyParam<decimal> _takePct;

	private decimal _prevPrice;
	private decimal _prevMa;
	private bool _hasPrev;
	private decimal _entryPrice;

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

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

	public decimal StopPct
	{
		get => _stopPct.Value;
		set => _stopPct.Value = value;
	}

	public decimal TakePct
	{
		get => _takePct.Value;
		set => _takePct.Value = value;
	}

	public LevelsWithRevolveStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");

		_maPeriod = Param(nameof(MaPeriod), 50)
			.SetDisplay("MA Period", "Moving average period for the level", "Parameters");

		_stopPct = Param(nameof(StopPct), 1.5m)
			.SetDisplay("Stop %", "Stop loss percent from entry", "Risk");

		_takePct = Param(nameof(TakePct), 3m)
			.SetDisplay("Take %", "Take profit percent from entry", "Risk");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevPrice = 0;
		_prevMa = 0;
		_hasPrev = false;
		_entryPrice = 0;
	}

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

		_prevPrice = 0;
		_prevMa = 0;
		_hasPrev = false;
		_entryPrice = 0;

		var ma = new ExponentialMovingAverage { Length = MaPeriod };

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

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, ma);
			DrawOwnTrades(area);
		}
	}

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

		var price = candle.ClosePrice;

		// Check stop/take
		if (Position > 0 && _entryPrice > 0)
		{
			var pnlPct = (price - _entryPrice) / _entryPrice * 100m;
			if (pnlPct >= TakePct || pnlPct <= -StopPct)
			{
				SellMarket();
				_entryPrice = 0;
			}
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			var pnlPct = (_entryPrice - price) / _entryPrice * 100m;
			if (pnlPct >= TakePct || pnlPct <= -StopPct)
			{
				BuyMarket();
				_entryPrice = 0;
			}
		}

		if (!_hasPrev)
		{
			_prevPrice = price;
			_prevMa = maValue;
			_hasPrev = true;
			return;
		}

		// Cross above MA - buy (or reverse short)
		if (_prevPrice < _prevMa && price >= maValue)
		{
			if (Position < 0)
				BuyMarket();
			if (Position <= 0)
			{
				BuyMarket();
				_entryPrice = price;
			}
		}
		// Cross below MA - sell (or reverse long)
		else if (_prevPrice > _prevMa && price <= maValue)
		{
			if (Position > 0)
				SellMarket();
			if (Position >= 0)
			{
				SellMarket();
				_entryPrice = price;
			}
		}

		_prevPrice = price;
		_prevMa = maValue;
	}
}