Ver no GitHub

Estratégia Swing Cyborg

Visão geral

Swing Cyborg é um assistente discricionário que automatiza a execução com base na própria previsão de tendência do trader. O usuário define a direção esperada da tendência e a janela de tempo em que ela deve ser válida. A estratégia confirma entradas com o indicador RSI e gerencia saídas com alvos fixos.

Parâmetros

  • Volume – volume de ordem em lotes.
  • TrendPrediction – direção esperada da tendência (Uptrend ou Downtrend).
  • TrendTimeframe – período usado para RSI e negociação (M30, H1 ou H4).
  • TrendStart – início do período de tendência definido pelo usuário.
  • TrendEnd – fim do período de tendência definido pelo usuário.
  • Aggressiveness – preset de gestão de dinheiro:
    • Baixo: take profit 300 pips, stop loss 200 pips.
    • Médio: take profit 500 pips, stop loss 250 pips.
    • Alto: take profit 600 pips, stop loss 300 pips.

Lógica de trading

  1. Aguardar uma nova vela no período selecionado.
  2. Operar apenas se o horário atual estiver entre TrendStart e TrendEnd.
  3. Calcular RSI(14).
  4. Se não houver posição aberta:
    • Se TrendPrediction for Uptrend e RSI ≤ 65 → comprar.
    • Se TrendPrediction for Downtrend e RSI ≥ 35 → vender.
  5. StartProtection fecha automaticamente a posição quando o lucro ou perda atingir o nível predefinido.

A estratégia opera em velas fechadas e não abre uma nova posição enquanto houver uma ativa.

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;
	}
}