Esta estratégia replica o MetaTrader 5 Expert Advisor Expert_AMS_ES_CCI usando o StockSharp API de alto nível. Ele verifica os padrões de reversão de três velas Morning Star e Evening Star e requer confirmação do Commodity Channel Index (CCI) antes de abrir novas posições. A lógica funciona apenas com velas finalizadas e opera no título primário especificado nas configurações da estratégia.
Lógica de negociação
Entrada longa Morning Star
Detecte três velas consecutivas que formam um padrão Morning Star:
Vela 1: corpo de baixa forte (tamanho do corpo maior que o corpo médio na janela selecionada).
Vela 2: vela de corpo pequeno com intervalo menor que a Vela 1.
Vela 3: fecha acima do ponto médio da Vela 1.
Confirme se o valor CCI na barra de sinal é menor que o limite de entrada negativo (padrão −50).
Entrada curta do Evening Star
Detecte um padrão válido do Evening Star:
Vela 1: corpo forte de alta.
Vela 2: vela de corpo pequeno que fica acima da Vela 1.
Vela 3: fecha abaixo do ponto médio da Vela 1.
Confirme se o valor CCI na barra de sinal é maior que o limite de entrada positivo (padrão +50).
Regras de saída de posição
Fechar posições curtas quando CCI cruzar novamente acima de −NeutralThreshold ou cair abaixo de +NeutralThreshold (padrão ±80).
Feche posições longas quando CCI cruzar abaixo de +NeutralThreshold ou cair abaixo de −NeutralThreshold.
Nenhuma regra adicional de stop-loss ou take-profit está incorporada; os usuários podem adicionar proteções externas, se necessário.
Indicadores
Índice de canal de commodities (CCI) – filtro de confirmação, período padrão 25.
Média Móvel Simples dos corpos das velas – calcula o tamanho médio do corpo nas últimas velas BodyAveragePeriod (padrão 5) para validar a força do padrão.
Parâmetros
Nome
Descrição
Padrão
Notas
CciPeriod
Número de barras usadas no cálculo CCI.
25
Otimizável.
BodyAveragePeriod
Número de velas usadas para medir o tamanho médio do corpo.
5
Otimizável.
EntryThreshold
Valor absoluto de CCI necessário para novas negociações.
50
Valor positivo; a estratégia verifica ±EntryThreshold.
NeutralThreshold
Nível CCI absoluto que define a zona de saída.
80
Valor positivo; a estratégia verifica ±NeutralThreshold.
CandleType
Tipo de vela (prazo) utilizado para análise.
Período de 1 hora
Altere para corresponder à resolução desejada.
Notas
A estratégia assina atualizações de velas via SubscribeCandles e usa Bind para receber valores de indicadores.
As negociações são executadas com ordens de mercado usando BuyMarket e SellMarket.
Todos os comentários no código são escritos em inglês, conforme necessário.
Para ampliar o gerenciamento de risco, combine a estratégia com StartProtection ou módulos personalizados de gerenciamento de dinheiro.
namespace StockSharp.Samples.Strategies;
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;
/// <summary>
/// Morning/Evening Star + CCI strategy.
/// Buys on morning star with negative CCI, sells on evening star with positive CCI.
/// </summary>
public class MorningEveningStarCciStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cciPeriod;
private readonly StrategyParam<decimal> _cciLevel;
private ICandleMessage _prevCandle;
private ICandleMessage _prevPrevCandle;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int CciPeriod { get => _cciPeriod.Value; set => _cciPeriod.Value = value; }
public decimal CciLevel { get => _cciLevel.Value; set => _cciLevel.Value = value; }
public MorningEveningStarCciStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
_cciPeriod = Param(nameof(CciPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("CCI Period", "CCI period", "Indicators");
_cciLevel = Param(nameof(CciLevel), 0m)
.SetDisplay("CCI Level", "CCI threshold for confirmation", "Signals");
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevCandle = null;
_prevPrevCandle = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevCandle = null;
_prevPrevCandle = null;
var cci = new CommodityChannelIndex { Length = CciPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(cci, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal cciValue)
{
if (candle.State != CandleStates.Finished) return;
if (_prevCandle != null && _prevPrevCandle != null)
{
var prevBody = Math.Abs(_prevCandle.ClosePrice - _prevCandle.OpenPrice);
var prevRange = _prevCandle.HighPrice - _prevCandle.LowPrice;
var isSmallBody = prevRange > 0 && prevBody < prevRange * 0.3m;
var firstBearish = _prevPrevCandle.OpenPrice > _prevPrevCandle.ClosePrice;
var currBullish = candle.ClosePrice > candle.OpenPrice;
var isMorningStar = firstBearish && isSmallBody && currBullish &&
candle.ClosePrice > _prevPrevCandle.OpenPrice * 0.5m + _prevPrevCandle.ClosePrice * 0.5m;
var firstBullish = _prevPrevCandle.ClosePrice > _prevPrevCandle.OpenPrice;
var currBearish = candle.OpenPrice > candle.ClosePrice;
var isEveningStar = firstBullish && isSmallBody && currBearish &&
candle.ClosePrice < _prevPrevCandle.OpenPrice * 0.5m + _prevPrevCandle.ClosePrice * 0.5m;
if (isMorningStar && cciValue < -CciLevel && Position <= 0)
BuyMarket();
else if (isEveningStar && cciValue > CciLevel && Position >= 0)
SellMarket();
}
_prevPrevCandle = _prevCandle;
_prevCandle = candle;
}
}
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 CommodityChannelIndex
from StockSharp.Algo.Strategies import Strategy
class morning_evening_star_cci_strategy(Strategy):
"""
Morning/Evening Star + CCI: buy on morning star with negative CCI, sell on evening star with positive CCI.
"""
def __init__(self):
super(morning_evening_star_cci_strategy, self).__init__()
self._cci_period = self.Param("CciPeriod", 14).SetDisplay("CCI Period", "CCI period", "Indicators")
self._cci_level = self.Param("CciLevel", 0.0).SetDisplay("CCI Level", "CCI threshold", "Signals")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Candles", "General")
self._prev_candle = None
self._prev_prev_candle = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(morning_evening_star_cci_strategy, self).OnReseted()
self._prev_candle = None
self._prev_prev_candle = None
def OnStarted2(self, time):
super(morning_evening_star_cci_strategy, self).OnStarted2(time)
cci = CommodityChannelIndex()
cci.Length = self._cci_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(cci, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, cci)
self.DrawOwnTrades(area)
def _process_candle(self, candle, cci_val):
if candle.State != CandleStates.Finished:
return
cci = float(cci_val)
cci_level = float(self._cci_level.Value)
if self._prev_candle is not None and self._prev_prev_candle is not None:
prev_body = abs(float(self._prev_candle.ClosePrice) - float(self._prev_candle.OpenPrice))
prev_range = float(self._prev_candle.HighPrice) - float(self._prev_candle.LowPrice)
is_small_body = prev_range > 0 and prev_body < prev_range * 0.3
pp_open = float(self._prev_prev_candle.OpenPrice)
pp_close = float(self._prev_prev_candle.ClosePrice)
c_open = float(candle.OpenPrice)
c_close = float(candle.ClosePrice)
first_bearish = pp_open > pp_close
curr_bullish = c_close > c_open
is_morning = first_bearish and is_small_body and curr_bullish and c_close > pp_open * 0.5 + pp_close * 0.5
first_bullish = pp_close > pp_open
curr_bearish = c_open > c_close
is_evening = first_bullish and is_small_body and curr_bearish and c_close < pp_open * 0.5 + pp_close * 0.5
if is_morning and cci < -cci_level and self.Position <= 0:
self.BuyMarket()
elif is_evening and cci > cci_level and self.Position >= 0:
self.SellMarket()
self._prev_prev_candle = self._prev_candle
self._prev_candle = candle
def CreateClone(self):
return morning_evening_star_cci_strategy()