MACD Aggressive Scalp Simple Strategy
Реализует скальперскую стратегию на основе гистограммы MACD и фильтра EMA(50).
- Покупка при пересечении гистограммы выше нуля и цене выше EMA.
- Продажа при пересечении гистограммы ниже нуля и цене ниже EMA.
- Закрытие позиции при развороте импульса гистограммы.
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>
/// MACD histogram scalping with EMA filter.
/// </summary>
public class MacdAggressiveScalpSimpleStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<DataType> _candleType;
private ExponentialMovingAverage _emaFast;
private ExponentialMovingAverage _emaSlow;
private ExponentialMovingAverage _emaFilter;
private decimal _prevMacd;
private bool _initialized;
private int _cooldown;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public MacdAggressiveScalpSimpleStrategy()
{
_fastLength = Param(nameof(FastLength), 12).SetGreaterThanZero()
.SetDisplay("Fast", "MACD fast", "MACD");
_slowLength = Param(nameof(SlowLength), 26).SetGreaterThanZero()
.SetDisplay("Slow", "MACD slow", "MACD");
_emaLength = Param(nameof(EmaLength), 50).SetGreaterThanZero()
.SetDisplay("EMA", "EMA trend filter", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevMacd = default;
_initialized = false;
_cooldown = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_emaFast = new ExponentialMovingAverage { Length = FastLength };
_emaSlow = new ExponentialMovingAverage { Length = SlowLength };
_emaFilter = new ExponentialMovingAverage { Length = EmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_emaFast, _emaSlow, _emaFilter, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _emaFast);
DrawIndicator(area, _emaSlow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal ema)
{
if (candle.State != CandleStates.Finished)
return;
if (!_emaFast.IsFormed || !_emaSlow.IsFormed || !_emaFilter.IsFormed)
return;
var macdLine = fast - slow;
if (!_initialized)
{
_prevMacd = macdLine;
_initialized = true;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevMacd = macdLine;
return;
}
var crossUp = _prevMacd <= 0 && macdLine > 0;
var crossDown = _prevMacd >= 0 && macdLine < 0;
// Entry with EMA filter
if (crossUp && candle.ClosePrice >= ema && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
_cooldown = 5;
}
else if (crossDown && candle.ClosePrice <= ema && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
_cooldown = 5;
}
_prevMacd = macdLine;
}
}
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 ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class macd_aggressive_scalp_simple_strategy(Strategy):
def __init__(self):
super(macd_aggressive_scalp_simple_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 12) \
.SetGreaterThanZero() \
.SetDisplay("Fast", "MACD fast", "MACD")
self._slow_length = self.Param("SlowLength", 26) \
.SetGreaterThanZero() \
.SetDisplay("Slow", "MACD slow", "MACD")
self._ema_length = self.Param("EmaLength", 50) \
.SetGreaterThanZero() \
.SetDisplay("EMA", "EMA trend filter", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Candles", "General")
self._prev_macd = 0.0
self._initialized = False
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(macd_aggressive_scalp_simple_strategy, self).OnReseted()
self._prev_macd = 0.0
self._initialized = False
self._cooldown = 0
def OnStarted2(self, time):
super(macd_aggressive_scalp_simple_strategy, self).OnStarted2(time)
self._prev_macd = 0.0
self._initialized = False
self._cooldown = 0
self._ema_fast = ExponentialMovingAverage()
self._ema_fast.Length = self._fast_length.Value
self._ema_slow = ExponentialMovingAverage()
self._ema_slow.Length = self._slow_length.Value
self._ema_filter = ExponentialMovingAverage()
self._ema_filter.Length = self._ema_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._ema_fast, self._ema_slow, self._ema_filter, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._ema_fast)
self.DrawIndicator(area, self._ema_slow)
self.DrawOwnTrades(area)
def OnProcess(self, candle, fast, slow, ema):
if candle.State != CandleStates.Finished:
return
if not self._ema_fast.IsFormed or not self._ema_slow.IsFormed or not self._ema_filter.IsFormed:
return
fv = float(fast)
sv = float(slow)
ev = float(ema)
macd_line = fv - sv
if not self._initialized:
self._prev_macd = macd_line
self._initialized = True
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_macd = macd_line
return
close = float(candle.ClosePrice)
cross_up = self._prev_macd <= 0.0 and macd_line > 0.0
cross_down = self._prev_macd >= 0.0 and macd_line < 0.0
if cross_up and close >= ev and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._cooldown = 5
elif cross_down and close <= ev and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._cooldown = 5
self._prev_macd = macd_line
def CreateClone(self):
return macd_aggressive_scalp_simple_strategy()