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
Aguardar uma nova vela no período selecionado.
Operar apenas se o horário atual estiver entre TrendStart e TrendEnd.
Calcular RSI(14).
Se não houver posição aberta:
Se TrendPrediction for Uptrend e RSI ≤ 65 → comprar.
Se TrendPrediction for Downtrend e RSI ≥ 35 → vender.
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;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class swing_cyborg_strategy(Strategy):
def __init__(self):
super(swing_cyborg_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "RSI period", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle type", "General")
self._prev_rsi = 0.0
self._has_prev = False
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(swing_cyborg_strategy, self).OnReseted()
self._prev_rsi = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(swing_cyborg_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
self.SubscribeCandles(self.candle_type) \
.Bind(rsi, self.process_candle) \
.Start()
def process_candle(self, candle, rsi_val):
if candle.State != CandleStates.Finished:
return
rsi_val = float(rsi_val)
if not self._has_prev:
self._prev_rsi = rsi_val
self._has_prev = True
return
if self._prev_rsi <= 30.0 and rsi_val > 30.0 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif self._prev_rsi >= 70.0 and rsi_val < 70.0 and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_rsi = rsi_val
def CreateClone(self):
return swing_cyborg_strategy()