GitHub で見る

Swing Cyborg戦略

概要

Swing Cyborgは、トレーダー自身のトレンド予測に基づいて執行を自動化する裁量支援ツールです。ユーザーは期待するトレンド方向とその有効な時間ウィンドウを定義します。戦略はRSIインジケーターでエントリーを確認し、固定ターゲットでエグジットを管理します。

パラメーター

  • Volume – 注文量(ロット単位)。
  • TrendPrediction – 期待するトレンド方向(Uptrend または Downtrend)。
  • TrendTimeframe – RSIと取引に使用する時間軸(M30、H1またはH4)。
  • TrendStart – ユーザー定義のトレンド期間の開始。
  • TrendEnd – ユーザー定義のトレンド期間の終了。
  • Aggressiveness – マネー管理プリセット:
    • 低: テイクプロフィット300pips、ストップロス200pips。
    • 中: テイクプロフィット500pips、ストップロス250pips。
    • 高: テイクプロフィット600pips、ストップロス300pips。

トレードロジック

  1. 選択した時間軸で新しいローソク足を待つ。
  2. 現在時刻がTrendStartTrendEndの間にある場合のみ取引する。
  3. RSI(14)を計算する。
  4. オープンポジションがない場合:
    • TrendPredictionがUptrendでRSI ≤ 65 → 買い。
    • TrendPredictionがDowntrendでRSI ≥ 35 → 売り。
  5. StartProtectionは利益または損失が事前定義されたレベルに達すると自動的にポジションを閉じる。

この戦略は確定したローソク足で動作し、既存のポジションがアクティブな間は新しいポジションを開かない。

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>
/// SwingCyborg strategy using RSI overbought/oversold levels.
/// </summary>
public class SwingCyborgStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevRsi;
	private bool _hasPrev;

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

	public SwingCyborgStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "RSI period", "Parameters");
		_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;
		}

		// Buy when RSI exits oversold
		if (_prevRsi <= 30m && rsiVal > 30m && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Sell when RSI exits overbought
		else if (_prevRsi >= 70m && rsiVal < 70m && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevRsi = rsiVal;
	}
}