2MA Bunny Cross Expert
The 2MA Bunny Cross Expert strategy trades the crossover of two simple moving averages. A long trade is opened when the fast average moves above the slow one, while a short trade is opened when the fast average drops below the slow one. Any opposite position is closed before a new one is opened.
Details
- Purpose: trend following via moving average crossover
- Trading: long and short
- Indicators: fast and slow Simple Moving Average
- Stops: none
- Default Values:
CandleType= 1 minuteFastLength= 5SlowLength= 20
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>
/// Two moving average crossover strategy converted from "2MA Bunny Cross Expert".
/// Uses fast and slow simple moving averages to generate signals.
/// </summary>
public class TwoMaBunnyCrossStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private SimpleMovingAverage _fastSma;
private SimpleMovingAverage _slowSma;
private decimal _prevFast;
private decimal _prevSlow;
/// <summary>
/// Candle type for calculations.
/// </summary>
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
/// <summary>
/// Fast moving average length.
/// </summary>
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
/// <summary>
/// Slow moving average length.
/// </summary>
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
/// <summary>
/// Initializes a new instance of <see cref="TwoMaBunnyCrossStrategy"/>.
/// </summary>
public TwoMaBunnyCrossStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for candles", "General");
_fastLength = Param(nameof(FastLength), 5)
.SetGreaterThanZero()
.SetDisplay("Fast MA Length", "Length of fast moving average", "Parameters")
;
_slowLength = Param(nameof(SlowLength), 20)
.SetGreaterThanZero()
.SetDisplay("Slow MA Length", "Length of slow moving average", "Parameters")
;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0m;
_prevSlow = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fastSma = new SMA { Length = FastLength };
_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 fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
if (fast > slow && candle.ClosePrice > slow && Position <= 0)
BuyMarket();
else if (fast < slow && candle.ClosePrice < slow && Position >= 0)
SellMarket();
_prevFast = fast;
_prevSlow = slow;
}
}
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 SimpleMovingAverage as SMA
from StockSharp.Algo.Strategies import Strategy
class two_ma_bunny_cross_strategy(Strategy):
def __init__(self):
super(two_ma_bunny_cross_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1)))
self._fast_length = self.Param("FastLength", 5)
self._slow_length = self.Param("SlowLength", 20)
self._prev_fast = 0.0
self._prev_slow = 0.0
@property
def CandleType(self): return self._candle_type.Value
@CandleType.setter
def CandleType(self, v): self._candle_type.Value = v
@property
def FastLength(self): return self._fast_length.Value
@FastLength.setter
def FastLength(self, v): self._fast_length.Value = v
@property
def SlowLength(self): return self._slow_length.Value
@SlowLength.setter
def SlowLength(self, v): self._slow_length.Value = v
def OnStarted2(self, time):
super(two_ma_bunny_cross_strategy, self).OnStarted2(time)
fast_sma = SMA()
fast_sma.Length = self.FastLength
slow_sma = SMA()
slow_sma.Length = self.SlowLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(fast_sma, slow_sma, self.ProcessCandle).Start()
def ProcessCandle(self, candle, fast, slow):
if candle.State != CandleStates.Finished: return
f = float(fast)
s = float(slow)
close = float(candle.ClosePrice)
if f > s and close > s and self.Position <= 0:
self.BuyMarket()
elif f < s and close < s and self.Position >= 0:
self.SellMarket()
self._prev_fast = f
self._prev_slow = s
def OnReseted(self):
super(two_ma_bunny_cross_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
def CreateClone(self):
return two_ma_bunny_cross_strategy()