Стратегия Full Candle
Конфигурация Full Candle входит, когда свеча закрывается за пределами своей EMA и оставляет лишь небольшой хвост со стороны пробоя. Цель — торговать импульсные свечи, демонстрирующие решительное движение без значительного отката. По желанию используются процентные уровни тейк-профита и стоп-лосса для управления позицией.
Система лучше всего подходит для краткосрочных пробоев, где сильные свечи часто приводят к быстрому продолжению.
Детали
- Критерии входа:
- Длинная позиция: бычья свеча закрывается выше EMA, хвост ≤ порога
- Короткая позиция: медвежья свеча закрывается ниже EMA, хвост ≤ порога
- Длинные/короткие: обе стороны
- Критерии выхода:
- Процентные цели тейк-профита или стоп-лосса, если включены
- Стопы: опционально
- Значения по умолчанию:
EmaLength= 10ShadowPercent= 5TPPercent= 1.2SLPercent= 1.8
- Фильтры:
- Категория: Пробой
- Направление: Оба
- Индикаторы: EMA, ценовое действие
- Стопы: Опционально
- Сложность: Низкая
- Таймфрейм: Краткосрочный
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
namespace StockSharp.Samples.Strategies;
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// Full Candle Strategy.
/// Trades on "full body" candles (small shadows) with EMA trend filter.
/// Buys on bullish full candle above EMA. Sells on bearish full candle below EMA.
/// </summary>
public class FullCandleStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleTypeParam;
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<decimal> _shadowPercent;
private readonly StrategyParam<int> _cooldownBars;
private ExponentialMovingAverage _ema;
private decimal? _entryPrice;
private int _cooldownRemaining;
public FullCandleStrategy()
{
_candleTypeParam = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle type", "Candle type for strategy calculation.", "General");
_emaLength = Param(nameof(EmaLength), 20)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA period", "Moving Averages");
_shadowPercent = Param(nameof(ShadowPercent), 10m)
.SetDisplay("Shadow Percent", "Maximum shadow percentage of candle range", "Strategy");
_cooldownBars = Param(nameof(CooldownBars), 15)
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk");
}
public DataType CandleType
{
get => _candleTypeParam.Value;
set => _candleTypeParam.Value = value;
}
public int EmaLength
{
get => _emaLength.Value;
set => _emaLength.Value = value;
}
public decimal ShadowPercent
{
get => _shadowPercent.Value;
set => _shadowPercent.Value = value;
}
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_ema = null;
_entryPrice = null;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_ema = new ExponentialMovingAverage { Length = EmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_ema, OnProcess)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _ema);
DrawOwnTrades(area);
}
}
private void OnProcess(ICandleMessage candle, decimal emaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_ema.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
return;
}
var close = candle.ClosePrice;
var open = candle.OpenPrice;
var high = candle.HighPrice;
var low = candle.LowPrice;
var candleSize = high - low;
if (candleSize <= 0)
return;
var bodySize = Math.Abs(close - open);
// Calculate shadow sizes
decimal upperShadow, lowerShadow;
if (close > open)
{
upperShadow = high - close;
lowerShadow = open - low;
}
else
{
upperShadow = high - open;
lowerShadow = close - low;
}
var totalShadowPercent = ((upperShadow + lowerShadow) * 100) / candleSize;
// Full candle = small shadows (body fills most of the range)
var isFullCandle = totalShadowPercent <= ShadowPercent && bodySize > 0;
// Exit conditions
if (Position > 0 && _entryPrice.HasValue && close > _entryPrice.Value * 1.003m)
{
SellMarket(Math.Abs(Position));
_entryPrice = null;
_cooldownRemaining = CooldownBars;
return;
}
else if (Position < 0 && _entryPrice.HasValue && close < _entryPrice.Value * 0.997m)
{
BuyMarket(Math.Abs(Position));
_entryPrice = null;
_cooldownRemaining = CooldownBars;
return;
}
// Entry: full bullish candle above EMA
if (isFullCandle && close > open && close > emaValue && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
_entryPrice = close;
_cooldownRemaining = CooldownBars;
}
// Entry: full bearish candle below EMA
else if (isFullCandle && close < open && close < emaValue && Position >= 0)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
SellMarket(Volume);
_entryPrice = close;
_cooldownRemaining = CooldownBars;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class full_candle_strategy(Strategy):
"""Full Candle Strategy. Trades on full body candles with EMA trend filter."""
def __init__(self):
super(full_candle_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle type", "Candle type for strategy calculation.", "General")
self._ema_length = self.Param("EmaLength", 20) \
.SetDisplay("EMA Length", "EMA period", "Moving Averages")
self._shadow_percent = self.Param("ShadowPercent", 10.0) \
.SetDisplay("Shadow Percent", "Maximum shadow percentage of candle range", "Strategy")
self._cooldown_bars = self.Param("CooldownBars", 15) \
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk")
self._ema = None
self._entry_price = None
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(full_candle_strategy, self).OnReseted()
self._ema = None
self._entry_price = None
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(full_candle_strategy, self).OnStarted2(time)
self._ema = ExponentialMovingAverage()
self._ema.Length = int(self._ema_length.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._ema, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._ema)
self.DrawOwnTrades(area)
def _on_process(self, candle, ema_val):
if candle.State != CandleStates.Finished:
return
if not self._ema.IsFormed:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
return
close = float(candle.ClosePrice)
opn = float(candle.OpenPrice)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
ev = float(ema_val)
cooldown = int(self._cooldown_bars.Value)
shadow_pct_threshold = float(self._shadow_percent.Value)
candle_size = high - low
if candle_size <= 0:
return
body_size = abs(close - opn)
if close > opn:
upper_shadow = high - close
lower_shadow = opn - low
else:
upper_shadow = high - opn
lower_shadow = close - low
total_shadow_pct = ((upper_shadow + lower_shadow) * 100.0) / candle_size
is_full_candle = total_shadow_pct <= shadow_pct_threshold and body_size > 0
# Exit conditions
if self.Position > 0 and self._entry_price is not None and close > self._entry_price * 1.003:
self.SellMarket(Math.Abs(self.Position))
self._entry_price = None
self._cooldown_remaining = cooldown
return
elif self.Position < 0 and self._entry_price is not None and close < self._entry_price * 0.997:
self.BuyMarket(Math.Abs(self.Position))
self._entry_price = None
self._cooldown_remaining = cooldown
return
# Entry: full bullish candle above EMA
if is_full_candle and close > opn and close > ev and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket(self.Volume)
self._entry_price = close
self._cooldown_remaining = cooldown
# Entry: full bearish candle below EMA
elif is_full_candle and close < opn and close < ev and self.Position >= 0:
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self.SellMarket(self.Volume)
self._entry_price = close
self._cooldown_remaining = cooldown
def CreateClone(self):
return full_candle_strategy()