GitHub で見る

RSI Value 戦略

相対強度指数(RSI)が中央値をクロスすることに基づいて取引する戦略。

RSIが設定可能なレベル(デフォルト50)を上回るか下回るかを監視します。インジケーターがこのレベルを下から上に移動するとロングポジションが開かれます。逆にレベルを下回るとショートポジションが開かれます。既存のポジションは反対のクロスで終了します。オプションのストップロス、テイクプロフィット、トレーリングストップが取引を保護します。

詳細

  • エントリー条件: RSIがレベルを上抜けたときに買い。RSIがレベルを下抜けたときに売り。
  • ロング/ショート: 両方向。
  • エグジット条件: 反対のクロスまたはトレーリングストップ。
  • ストップ: オプションの固定ストップロス、テイクプロフィット、トレーリングストップ。
  • デフォルト値:
    • RsiPeriod = 14
    • RsiLevel = 50
    • StopLoss = 100
    • TakeProfit = 200
    • TrailingStop = 0
    • CandleType = TimeSpan.FromMinutes(5)
  • フィルター:
    • カテゴリ: オシレーター
    • 方向: 両方
    • インジケーター: RSI
    • ストップ: あり
    • 複雑さ: 基本
    • 時間軸: イントラデイ (5m)
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: いいえ
    • リスクレベル: 中
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>
/// RSI level crossing strategy.
/// </summary>
public class RsiValueStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<decimal> _rsiLevel;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevRsi;
	private bool _hasPrev;

	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public decimal RsiLevel { get => _rsiLevel.Value; set => _rsiLevel.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public RsiValueStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "RSI period", "Indicators");
		_rsiLevel = Param(nameof(RsiLevel), 50m)
			.SetDisplay("RSI Level", "RSI crossing level", "Indicators");
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevRsi = 0;
		_hasPrev = false;
	}

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

		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };

		SubscribeCandles(CandleType)
			.Bind(rsi, ProcessCandle)
			.Start();
	}

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

		if (!_hasPrev)
		{
			_prevRsi = rsiVal;
			_hasPrev = true;
			return;
		}

		var crossUp = _prevRsi <= RsiLevel && rsiVal > RsiLevel;
		var crossDown = _prevRsi >= RsiLevel && rsiVal < RsiLevel;

		if (crossUp && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (crossDown && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevRsi = rsiVal;
	}
}