Стратегия Xbug Free
Контртрендовая стратегия на скользящей средней: покупает при пересечении цены вниз через среднюю и продаёт при пересечении вверх. Использует симметричные уровни тейк-профита и стоп-лосса.
Детали
- Критерий входа: пересечение цены и простой скользящей средней
- Длин/Шорт: обе стороны
- Критерий выхода: противоположный сигнал или защитный стоп
- Стопы: да
- Значения по умолчанию:
MaPeriod= 19MaShift= 15StopPoints= 270Volume= 0.1CandleType= 4 часа
- Фильтры:
- Категория: Mean Reversion
- Направление: обе стороны
- Индикаторы: MA
- Стопы: да
- Сложность: базовая
- Таймфрейм: свинг
- Сезонность: нет
- Нейросети: нет
- Дивергенция: нет
- Уровень риска: средний
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>
/// Counter-trend strategy. Buys after price drops below SMA, exits when price returns to SMA.
/// </summary>
public class XbugFreeStrategy : Strategy
{
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<DataType> _candleType;
public int MaPeriod { get => _maPeriod.Value; set => _maPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public XbugFreeStrategy()
{
_maPeriod = Param(nameof(MaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("MA Period", "SMA period", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = MaPeriod };
var atr = new StandardDeviation { Length = 14 };
SubscribeCandles(CandleType).Bind(sma, atr, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal sma, decimal atr)
{
if (candle.State != CandleStates.Finished) return;
if (atr <= 0) return;
var close = candle.ClosePrice;
// Counter-trend: buy when price drops below SMA by 1 ATR
if (close < sma - atr && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
// Counter-trend: sell when price rises above SMA by 1 ATR
else if (close > sma + atr && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
// Exit long at SMA
else if (Position > 0 && close >= sma)
SellMarket();
// Exit short at SMA
else if (Position < 0 && close <= sma)
BuyMarket();
}
}
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, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class xbug_free_strategy(Strategy):
def __init__(self):
super(xbug_free_strategy, self).__init__()
self._ma_period = self.Param("MaPeriod", 20) \
.SetDisplay("MA Period", "SMA period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
@property
def ma_period(self):
return self._ma_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(xbug_free_strategy, self).OnStarted2(time)
sma = SimpleMovingAverage()
sma.Length = self.ma_period
atr = StandardDeviation()
atr.Length = 14
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, atr, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, sma, atr):
if candle.State != CandleStates.Finished:
return
if atr <= 0:
return
close = candle.ClosePrice
# Counter-trend: buy when price drops below SMA by 1 ATR
if close < sma - atr and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Counter-trend: sell when price rises above SMA by 1 ATR
elif close > sma + atr and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
# Exit long at SMA
elif self.Position > 0 and close >= sma:
self.SellMarket()
# Exit short at SMA
elif self.Position < 0 and close <= sma:
self.BuyMarket()
def CreateClone(self):
return xbug_free_strategy()