Esta estratégia opera com base na cor das velas suavizadas. Para cada vela concluída, a diferença entre o preço de fechamento e abertura é passada por uma média móvel. Quando essa diferença suavizada muda de sinal, a "cor" da vela muda e a estratégia inverte sua posição.
Lógica
Inscrever-se em uma série de velas configurável.
Calcular diff = close - open para cada vela concluída.
Suavizar o diff usando a média móvel selecionada.
Determinar a cor da vela:
Cor 0 se smoothed diff > 0 (fechamento acima da abertura).
Cor 1 caso contrário.
Gerar sinais:
Comprar quando a cor muda de 0 para 1.
Vender quando a cor muda de 1 para 0.
A posição atual é fechada antes de abrir uma nova.
Parâmetros
CandleType – período das velas processadas. Padrão é 1 hora.
MaLength – comprimento da média móvel de suavização. Padrão é 30.
MaMethods – algoritmo de média móvel: Simple, Exponential, Smma ou Weighted. Padrão é Weighted.
Notas
A estratégia usa ordens a mercado via BuyMarket e SellMarket.
A API de alto nível é usada para assinatura de velas e visualização de gráficos.
Os valores do indicador são acessados via TryGetValue para evitar chamadas diretas ao buffer.
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 based on smoothed candle body direction.
/// Smooths (close-open) with WMA, trades on color changes.
/// </summary>
public class CandlesSmoothedStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _maLength;
private WeightedMovingAverage _ma;
private int? _prevColor;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int MaLength { get => _maLength.Value; set => _maLength.Value = value; }
public CandlesSmoothedStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Time frame", "General");
_maLength = Param(nameof(MaLength), 30)
.SetGreaterThanZero()
.SetDisplay("MA Length", "Moving average smoothing length", "Indicator");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_ma = null;
_prevColor = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_ma = new WeightedMovingAverage { Length = MaLength };
Indicators.Add(_ma);
// Use a dummy EMA for warmup binding
var warmup = new ExponentialMovingAverage { Length = MaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(warmup, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal _smaValue)
{
if (candle.State != CandleStates.Finished)
return;
// Calculate close-open diff and smooth with WMA
var diff = candle.ClosePrice - candle.OpenPrice;
var maResult = _ma.Process(new DecimalIndicatorValue(_ma, diff, candle.OpenTime) { IsFinal = true });
if (!maResult.IsFormed)
return;
var smoothed = maResult.GetValue<decimal>();
var color = smoothed > 0m ? 0 : 1;
if (!IsFormedAndOnlineAndAllowTrading())
{
_prevColor = color;
return;
}
if (_prevColor is int prev)
{
// Color change from negative to positive -> buy
if (color == 1 && prev == 0 && Position <= 0)
BuyMarket();
// Color change from positive to negative -> sell
else if (color == 0 && prev == 1 && Position >= 0)
SellMarket();
}
_prevColor = color;
}
}
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 WeightedMovingAverage, ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class candles_smoothed_strategy(Strategy):
def __init__(self):
super(candles_smoothed_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Time frame", "General")
self._ma_length = self.Param("MaLength", 30) \
.SetDisplay("MA Length", "Moving average smoothing length", "Indicator")
self._ma = None
self._prev_color = None
@property
def candle_type(self):
return self._candle_type.Value
@property
def ma_length(self):
return self._ma_length.Value
def OnReseted(self):
super(candles_smoothed_strategy, self).OnReseted()
self._ma = None
self._prev_color = None
def OnStarted2(self, time):
super(candles_smoothed_strategy, self).OnStarted2(time)
self._ma = WeightedMovingAverage()
self._ma.Length = self.ma_length
self.Indicators.Add(self._ma)
warmup = ExponentialMovingAverage()
warmup.Length = self.ma_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(warmup, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def process_candle(self, candle, _sma_value):
if candle.State != CandleStates.Finished:
return
diff = float(candle.ClosePrice) - float(candle.OpenPrice)
ma_result = process_float(self._ma, diff, candle.OpenTime, True)
if not ma_result.IsFormed:
return
smoothed = float(ma_result)
color = 0 if smoothed > 0 else 1
if self._prev_color is not None:
if color == 1 and self._prev_color == 0 and self.Position <= 0:
self.BuyMarket()
elif color == 0 and self._prev_color == 1 and self.Position >= 0:
self.SellMarket()
self._prev_color = color
def CreateClone(self):
return candles_smoothed_strategy()