Oscilador de Gráfico
Esta estratégia opera usando um oscilador selecionável. Escolha entre Estocástico, RSI ou MFI. Compra quando o oscilador sinaliza condições de sobrevenda e vende quando está sobrecomprado. Para a opção Estocástico, os sinais usam cruzamentos de %K e %D.
Os testes mostram bom desempenho em mercados voláteis como criptomoedas.
As posições se invertem quando surgem condições opostas ou o stop-loss é acionado.
Detalhes
- Critérios de entrada: Níveis de sobrevenda/sobrecompra do oscilador e cruzamentos de %K/%D.
- Comprado/Vendido: Ambos.
- Critérios de saída: Sinal oposto ou stop.
- Stops: Sim.
- Valores padrão:
Choice= OscillatorChoice.StochasticLength= 14KPeriod= 14DPeriod= 3SmoothK= 3Overbought= 80Oversold= 20CandleType= TimeSpan.FromMinutes(5)StopLossPercent= 2.0m
- Filtros:
- Categoria: Oscilador
- Direção: Ambos
- Indicadores: Stochastic/RSI/MFI
- Stops: Sim
- Complexidade: Básico
- Período: Intradiário
- Sazonalidade: Não
- Redes neurais: Não
- Divergência: Não
- Nível de risco: Médio
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>
/// Chart Oscillator strategy.
/// Trades a selectable oscillator. With Stochastic, a %K cross above %D while %K is below Oversold buys and a %K cross below %D
/// while %K is above Overbought sells. With RSI or MFI, a reading below Oversold buys and a reading above Overbought sells.
/// An opposite signal reverses the position and a percent stop limits the loss.
/// </summary>
public class ChartOscillatorStrategy : Strategy
{
/// <summary>
/// Oscillator choices.
/// </summary>
public enum OscillatorChoice
{
/// <summary>
/// Stochastic %K/%D.
/// </summary>
Stochastic,
/// <summary>
/// Relative Strength Index.
/// </summary>
Rsi,
/// <summary>
/// Money Flow Index.
/// </summary>
Mfi,
}
private readonly StrategyParam<OscillatorChoice> _choice;
private readonly StrategyParam<int> _length;
private readonly StrategyParam<int> _kPeriod;
private readonly StrategyParam<int> _dPeriod;
private readonly StrategyParam<int> _smoothK;
private readonly StrategyParam<decimal> _overbought;
private readonly StrategyParam<decimal> _oversold;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private SimpleMovingAverage _kSmoother;
private SimpleMovingAverage _dAverage;
private decimal? _prevK;
private decimal? _prevD;
/// <summary>
/// Oscillator used for signals.
/// </summary>
public OscillatorChoice Choice
{
get => _choice.Value;
set => _choice.Value = value;
}
/// <summary>
/// Period of RSI and MFI.
/// </summary>
public int Length
{
get => _length.Value;
set => _length.Value = value;
}
/// <summary>
/// Stochastic %K lookback.
/// </summary>
public int KPeriod
{
get => _kPeriod.Value;
set => _kPeriod.Value = value;
}
/// <summary>
/// Stochastic %D smoothing.
/// </summary>
public int DPeriod
{
get => _dPeriod.Value;
set => _dPeriod.Value = value;
}
/// <summary>
/// Stochastic %K smoothing.
/// </summary>
public int SmoothK
{
get => _smoothK.Value;
set => _smoothK.Value = value;
}
/// <summary>
/// Overbought level.
/// </summary>
public decimal Overbought
{
get => _overbought.Value;
set => _overbought.Value = value;
}
/// <summary>
/// Oversold level.
/// </summary>
public decimal Oversold
{
get => _oversold.Value;
set => _oversold.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Stop loss percentage from entry price.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public ChartOscillatorStrategy()
{
_choice = Param(nameof(Choice), OscillatorChoice.Stochastic)
.SetDisplay("Oscillator", "Oscillator used for signals", "Indicators");
_length = Param(nameof(Length), 14)
.SetGreaterThanZero()
.SetDisplay("Length", "Period of RSI and MFI", "Indicators");
_kPeriod = Param(nameof(KPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("%K Period", "Stochastic %K lookback", "Indicators");
_dPeriod = Param(nameof(DPeriod), 3)
.SetGreaterThanZero()
.SetDisplay("%D Period", "Stochastic %D smoothing", "Indicators");
_smoothK = Param(nameof(SmoothK), 3)
.SetGreaterThanZero()
.SetDisplay("Smooth %K", "Stochastic %K smoothing", "Indicators");
_overbought = Param(nameof(Overbought), 80m)
.SetDisplay("Overbought", "Overbought level", "Signals");
_oversold = Param(nameof(Oversold), 20m)
.SetDisplay("Oversold", "Oversold level", "Signals");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_stopLossPercent = Param(nameof(StopLossPercent), 2.0m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_kSmoother = null;
_dAverage = null;
_prevK = null;
_prevD = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevK = null;
_prevD = null;
var rawK = new StochasticK { Length = KPeriod };
var rsi = new RelativeStrengthIndex { Length = Length };
var mfi = new MoneyFlowIndex { Length = Length };
_kSmoother = new SimpleMovingAverage { Length = SmoothK };
_dAverage = new SimpleMovingAverage { Length = DPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(rawK, rsi, mfi, ProcessCandle)
.Start();
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
// The stop has to see prices between candles, not only at their close.
foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
{
var quotes = new Subscription(DataType.Level1, Security);
quotes.MarketData.BuildField = field;
SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
}
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
var oscillators = CreateChartArea();
if (oscillators != null)
{
switch (Choice)
{
case OscillatorChoice.Rsi:
DrawIndicator(oscillators, rsi);
break;
case OscillatorChoice.Mfi:
DrawIndicator(oscillators, mfi);
break;
default:
DrawIndicator(oscillators, rawK);
break;
}
}
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// The high-level handler activates native protection before this callback, also between signal bars.
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue rawKValue, IIndicatorValue rsiValue, IIndicatorValue mfiValue)
{
if (candle.State != CandleStates.Finished)
return;
bool buy;
bool sell;
switch (Choice)
{
case OscillatorChoice.Rsi:
case OscillatorChoice.Mfi:
{
var value = Choice == OscillatorChoice.Rsi ? rsiValue : mfiValue;
if (!value.IsFormed)
return;
var oscillator = value.ToDecimal();
buy = oscillator < Oversold;
sell = oscillator > Overbought;
break;
}
default:
{
if (!rawKValue.IsFormed)
return;
var kValue = _kSmoother.Process(rawKValue.ToDecimal(), candle.OpenTime, true);
if (!kValue.IsFormed)
return;
var k = kValue.ToDecimal();
var dValue = _dAverage.Process(k, candle.OpenTime, true);
if (!dValue.IsFormed)
return;
var d = dValue.ToDecimal();
var prevK = _prevK;
var prevD = _prevD;
_prevK = k;
_prevD = d;
if (prevK is not decimal pk || prevD is not decimal pd)
return;
buy = pk <= pd && k > d && k < Oversold;
sell = pk >= pd && k < d && k > Overbought;
break;
}
}
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (buy && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (sell && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import StochasticK, RelativeStrengthIndex, MoneyFlowIndex, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class OscillatorChoice:
"""Oscillator choices."""
Stochastic = 0
Rsi = 1
Mfi = 2
class chart_oscillator_strategy(Strategy):
"""
Chart Oscillator strategy.
Trades a selectable oscillator. With Stochastic, a %K cross above %D while %K is below Oversold buys and a %K cross below %D
while %K is above Overbought sells. With RSI or MFI, a reading below Oversold buys and a reading above Overbought sells.
An opposite signal reverses the position and a percent stop limits the loss.
"""
def __init__(self):
super(chart_oscillator_strategy, self).__init__()
self._choice = self.Param("Choice", OscillatorChoice.Stochastic).SetDisplay("Oscillator", "Oscillator used for signals", "Indicators")
self._length = self.Param("Length", 14).SetGreaterThanZero().SetDisplay("Length", "Period of RSI and MFI", "Indicators")
self._k_period = self.Param("KPeriod", 14).SetGreaterThanZero().SetDisplay("%K Period", "Stochastic %K lookback", "Indicators")
self._d_period = self.Param("DPeriod", 3).SetGreaterThanZero().SetDisplay("%D Period", "Stochastic %D smoothing", "Indicators")
self._smooth_k = self.Param("SmoothK", 3).SetGreaterThanZero().SetDisplay("Smooth %K", "Stochastic %K smoothing", "Indicators")
self._overbought = self.Param("Overbought", 80.0).SetDisplay("Overbought", "Overbought level", "Signals")
self._oversold = self.Param("Oversold", 20.0).SetDisplay("Oversold", "Oversold level", "Signals")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._k_smoother = None
self._d_average = None
self._reset_state()
@property
def candle_type(self):
return self._candle_type.Value
def _reset_state(self):
self._prev_k = None
self._prev_d = None
def OnReseted(self):
super(chart_oscillator_strategy, self).OnReseted()
self._k_smoother = None
self._d_average = None
self._reset_state()
def OnStarted2(self, time):
super(chart_oscillator_strategy, self).OnStarted2(time)
self._reset_state()
raw_k = StochasticK()
raw_k.Length = self._k_period.Value
rsi = RelativeStrengthIndex()
rsi.Length = self._length.Value
mfi = MoneyFlowIndex()
mfi.Length = self._length.Value
self._k_smoother = SimpleMovingAverage()
self._k_smoother.Length = self._smooth_k.Value
self._d_average = SimpleMovingAverage()
self._d_average.Length = self._d_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(raw_k, rsi, mfi, self._process_candle).Start()
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
# The stop has to see prices between candles, not only at their close.
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
oscillators = self.CreateChartArea()
if oscillators is not None:
choice = self._choice.Value
if choice == OscillatorChoice.Rsi:
self.DrawIndicator(oscillators, rsi)
elif choice == OscillatorChoice.Mfi:
self.DrawIndicator(oscillators, mfi)
else:
self.DrawIndicator(oscillators, raw_k)
def _observe_protection_quote(self, quote):
# The high-level handler activates native protection before the callback, including between bars.
pass
def _process_candle(self, candle, raw_k_value, rsi_value, mfi_value):
if candle.State != CandleStates.Finished:
return
choice = self._choice.Value
overbought = Decimal(self._overbought.Value)
oversold = Decimal(self._oversold.Value)
if choice == OscillatorChoice.Rsi or choice == OscillatorChoice.Mfi:
value = rsi_value if choice == OscillatorChoice.Rsi else mfi_value
if not value.IsFormed:
return
oscillator = value.GetValue[Decimal](None)
buy = oscillator < oversold
sell = oscillator > overbought
else:
if not raw_k_value.IsFormed:
return
k_result = process_value(self._k_smoother, raw_k_value.GetValue[Decimal](None), candle.OpenTime, True)
if not k_result.IsFormed:
return
k = k_result.GetValue[Decimal](None)
d_result = process_value(self._d_average, k, candle.OpenTime, True)
if not d_result.IsFormed:
return
d = d_result.GetValue[Decimal](None)
prev_k = self._prev_k
prev_d = self._prev_d
self._prev_k = k
self._prev_d = d
if prev_k is None or prev_d is None:
return
buy = prev_k <= prev_d and k > d and k < oversold
sell = prev_k >= prev_d and k < d and k > overbought
if not self.IsFormedAndOnlineAndAllowTrading():
return
if buy and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif sell and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return chart_oscillator_strategy()