GitHub で見る

RSIを使った自動売買戦略

この戦略は直近のRSI値を平均化して取引シグナルを生成します。設定可能な期間で標準的な相対力指数(RSI)を計算し、次にRSI自体に単純移動平均を適用します。平均化されたRSIが事前定義された閾値を越えると取引が開かれ、反対の閾値に達すると閉じられます。

トレードロジック

  1. RSI計算
    • インジケーターは RsiPeriod を使用してローソク足の終値に基づいてRSIを計算します。
  2. RSI平均化
    • 直近の AveragePeriod 個のRSI値を単純移動平均で平滑化します。
  3. エントリールール
    • BuyEnabledtrue でポジションが開いていない場合、平均RSIが BuyThreshold(デフォルト55)を超えると 買い 注文が送信されます。
    • SellEnabledtrue でポジションが開いていない場合、平均RSIが SellThreshold(デフォルト45)を下回ると 売り 注文が送信されます。
  4. エグジットルール
    • CloseBySignaltrue の場合、開いているポジションは反対シグナルで閉じられます:
      • 平均RSIが CloseBuyThreshold(デフォルト47)を下回るとロングポジションが閉じられます。
      • 平均RSIが CloseSellThreshold(デフォルト52)を上回るとショートポジションが閉じられます。

パラメーター

  • BuyEnabled – ロングエントリーを有効または無効にします。
  • SellEnabled – ショートエントリーを有効または無効にします。
  • CloseBySignal – 反対のRSIシグナルでのエグジットを許可します。
  • RsiPeriod – RSI計算の長さ。
  • AveragePeriod – 平均化に使用するRSI値の数。
  • BuyThreshold – ロングポジションが開かれる平均RSI値の上限。
  • SellThreshold – ショートポジションが開かれる平均RSI値の下限。
  • CloseBuyThreshold – ロングポジションが閉じられる平均RSI値の下限。
  • CloseSellThreshold – ショートポジションが閉じられる平均RSI値の上限。
  • CandleType – サブスクリプション用のローソク足タイプ。

注記

この戦略はStockSharpの高レベルAPIでバインディングによりインジケーター値を組み合わせる方法を示しています。元のMQLバージョンのトレーリングストップと資金管理機能は簡略化のため省略されています。

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;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy that trades based on averaged RSI values.
/// Uses RSI smoothed by SMA to generate signals.
/// </summary>
public class AutoTradeWithRsiStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<int> _averagePeriod;
	private readonly StrategyParam<decimal> _buyThreshold;
	private readonly StrategyParam<decimal> _sellThreshold;
	private readonly StrategyParam<DataType> _candleType;

	private ExponentialMovingAverage _rsiAvg;

	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public int AveragePeriod { get => _averagePeriod.Value; set => _averagePeriod.Value = value; }
	public decimal BuyThreshold { get => _buyThreshold.Value; set => _buyThreshold.Value = value; }
	public decimal SellThreshold { get => _sellThreshold.Value; set => _sellThreshold.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public AutoTradeWithRsiStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "RSI calculation period", "Indicator");

		_averagePeriod = Param(nameof(AveragePeriod), 21)
			.SetGreaterThanZero()
			.SetDisplay("Average Period", "SMA period to smooth RSI", "Indicator");

		_buyThreshold = Param(nameof(BuyThreshold), 55m)
			.SetDisplay("Buy Threshold", "Averaged RSI above which to buy", "Rules");

		_sellThreshold = Param(nameof(SellThreshold), 45m)
			.SetDisplay("Sell Threshold", "Averaged RSI below which to sell", "Rules");

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

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_rsiAvg = null;
	}

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

		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
		_rsiAvg = new ExponentialMovingAverage { Length = AveragePeriod };
		Indicators.Add(_rsiAvg);

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(rsi, ProcessCandle)
			.Start();

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

			var area2 = CreateChartArea();
			if (area2 != null)
				DrawIndicator(area2, rsi);
		}
	}

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

		if (!rsiValue.IsFormed)
			return;

		var avgResult = _rsiAvg.Process(rsiValue);
		if (!avgResult.IsFormed)
			return;

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var avgRsi = avgResult.GetValue<decimal>();

		if (avgRsi > BuyThreshold && Position <= 0)
			BuyMarket();
		else if (avgRsi < SellThreshold && Position >= 0)
			SellMarket();
	}
}