Heiken Ashi Waves Strategy
Strategy blending Heikin-Ashi candles with a dual moving average wave filter. The fast SMA (2) crossing the slow SMA (30) signals potential wave changes and is confirmed by the current Heikin-Ashi candle direction.
Details
- Entry Criteria:
- Long: bullish Heikin-Ashi candle and fast SMA crossing above slow SMA
- Short: bearish Heikin-Ashi candle and fast SMA crossing below slow SMA
- Long/Short: Both
- Exit Criteria:
- Opposite cross
- Trailing stop loss
- Stops: Trailing stop in points via
StopLoss - Default Values:
FastLength= 2SlowLength= 30StopLoss= new Unit(20, UnitTypes.Point)UseTrailing= trueCandleType= TimeSpan.FromHours(1).TimeFrame()
- Filters:
- Category: Trend Following
- Direction: Both
- Indicators: Heikin Ashi, SMA
- Stops: Yes
- Complexity: Beginner
- Timeframe: Intraday
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
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>
/// Heiken Ashi Waves strategy combining Heikin-Ashi candles and moving averages.
/// Opens long positions when a bullish Heikin-Ashi candle aligns with a fast SMA crossing above a slow SMA.
/// Opens short positions on bearish candles when the fast SMA crosses below the slow SMA.
/// </summary>
public class HeikenAshiWavesStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<Unit> _stopLoss;
private readonly StrategyParam<bool> _useTrailing;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _prevHaOpen;
private decimal _prevHaClose;
private bool _isInitialized;
/// <summary>
/// Fast SMA period.
/// </summary>
public int FastLength
{
get => _fastLength.Value;
set => _fastLength.Value = value;
}
/// <summary>
/// Slow SMA period.
/// </summary>
public int SlowLength
{
get => _slowLength.Value;
set => _slowLength.Value = value;
}
/// <summary>
/// Candle type used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Trailing stop loss distance.
/// </summary>
public Unit StopLoss
{
get => _stopLoss.Value;
set => _stopLoss.Value = value;
}
/// <summary>
/// Enables trailing stop behavior.
/// </summary>
public bool UseTrailing
{
get => _useTrailing.Value;
set => _useTrailing.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="HeikenAshiWavesStrategy"/>.
/// </summary>
public HeikenAshiWavesStrategy()
{
_fastLength = Param(nameof(FastLength), 2)
.SetGreaterThanZero()
.SetDisplay("Fast SMA", "Period of the fast moving average", "Parameters")
.SetOptimize(1, 10, 1);
_slowLength = Param(nameof(SlowLength), 30)
.SetGreaterThanZero()
.SetDisplay("Slow SMA", "Period of the slow moving average", "Parameters")
.SetOptimize(20, 60, 5);
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles for calculations", "General");
_stopLoss = Param(nameof(StopLoss), new Unit(20, UnitTypes.Absolute))
.SetDisplay("Stop Loss", "Trailing stop distance in points", "Risk Management")
.SetOptimize(10m, 50m, 10m);
_useTrailing = Param(nameof(UseTrailing), true)
.SetDisplay("Use Trailing", "Enable trailing stop protection", "Risk Management");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = _prevSlow = 0m;
_prevHaOpen = _prevHaClose = 0m;
_isInitialized = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
StartProtection(
takeProfit: null,
stopLoss: StopLoss,
isStopTrailing: UseTrailing,
useMarketOrders: true
);
var fastSma = new SMA { Length = FastLength };
var slowSma = new SMA { Length = SlowLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastSma, slowSma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastSma);
DrawIndicator(area, slowSma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
decimal haOpen;
decimal haClose;
if (!_isInitialized)
{
haOpen = (candle.OpenPrice + candle.ClosePrice) / 2m;
haClose = (candle.OpenPrice + candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 4m;
_prevHaOpen = haOpen;
_prevHaClose = haClose;
_prevFast = fastValue;
_prevSlow = slowValue;
_isInitialized = true;
return;
}
haOpen = (_prevHaOpen + _prevHaClose) / 2m;
haClose = (candle.OpenPrice + candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 4m;
var isBullish = haClose > haOpen;
var crossUp = _prevFast <= _prevSlow && fastValue > slowValue;
var crossDown = _prevFast >= _prevSlow && fastValue < slowValue;
if (isBullish && crossUp && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
}
else if (!isBullish && crossDown && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
}
_prevFast = fastValue;
_prevSlow = slowValue;
_prevHaOpen = haOpen;
_prevHaClose = haClose;
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class heiken_ashi_waves_strategy(Strategy):
def __init__(self):
super(heiken_ashi_waves_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 2)
self._slow_length = self.Param("SlowLength", 30)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1)))
self._stop_loss = self.Param("StopLoss", Unit(20.0, UnitTypes.Absolute))
self._use_trailing = self.Param("UseTrailing", True)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_ha_open = 0.0
self._prev_ha_close = 0.0
self._is_initialized = False
@property
def FastLength(self):
return self._fast_length.Value
@FastLength.setter
def FastLength(self, value):
self._fast_length.Value = value
@property
def SlowLength(self):
return self._slow_length.Value
@SlowLength.setter
def SlowLength(self, value):
self._slow_length.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def StopLoss(self):
return self._stop_loss.Value
@StopLoss.setter
def StopLoss(self, value):
self._stop_loss.Value = value
@property
def UseTrailing(self):
return self._use_trailing.Value
@UseTrailing.setter
def UseTrailing(self, value):
self._use_trailing.Value = value
def OnStarted2(self, time):
super(heiken_ashi_waves_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_ha_open = 0.0
self._prev_ha_close = 0.0
self._is_initialized = False
self.StartProtection(None, self.StopLoss, self.UseTrailing)
fast_sma = SimpleMovingAverage()
fast_sma.Length = self.FastLength
slow_sma = SimpleMovingAverage()
slow_sma.Length = self.SlowLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(fast_sma, slow_sma, self.ProcessCandle).Start()
def ProcessCandle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
fast = float(fast_value)
slow = float(slow_value)
o = float(candle.OpenPrice)
h = float(candle.HighPrice)
l = float(candle.LowPrice)
c = float(candle.ClosePrice)
if not self._is_initialized:
ha_open = (o + c) / 2.0
ha_close = (o + h + l + c) / 4.0
self._prev_ha_open = ha_open
self._prev_ha_close = ha_close
self._prev_fast = fast
self._prev_slow = slow
self._is_initialized = True
return
ha_open = (self._prev_ha_open + self._prev_ha_close) / 2.0
ha_close = (o + h + l + c) / 4.0
is_bullish = ha_close > ha_open
cross_up = self._prev_fast <= self._prev_slow and fast > slow
cross_down = self._prev_fast >= self._prev_slow and fast < slow
pos = float(self.Position)
vol = float(self.Volume)
if is_bullish and cross_up and pos <= 0:
self.BuyMarket(vol + abs(pos))
elif not is_bullish and cross_down and pos >= 0:
self.SellMarket(vol + abs(pos))
self._prev_fast = fast
self._prev_slow = slow
self._prev_ha_open = ha_open
self._prev_ha_close = ha_close
def OnReseted(self):
super(heiken_ashi_waves_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_ha_open = 0.0
self._prev_ha_close = 0.0
self._is_initialized = False
def CreateClone(self):
return heiken_ashi_waves_strategy()