Стратегия AI Grid размещает слои заявок на покупку и продажу вокруг текущей цены. Поддерживаются пробойный (стоп) и контр-трендовый (лимитный) режимы. После исполнения заявки автоматически выставляется тейк-профит на фиксированном расстоянии.
Детали
Условия входа: цена достигает одного из уровней сетки.
Длинные/короткие: управляются через AllowLong и AllowShort.
Условия выхода: тейк-профит на расстоянии TakeProfit.
Стопы: стоп-лосс отсутствует.
Значения по умолчанию:
GridSize = 50m
GridSteps = 10
TakeProfit = 50m
AllowLong = true
AllowShort = true
UseBreakout = true
UseCounter = true
CandleType = TimeSpan.FromMinutes(1)
Фильтры:
Категория: Сетка
Направление: Оба
Индикаторы: Нет
Стопы: Только тейк-профит
Сложность: Средняя
Таймфрейм: Внутридневной (1м)
Сезонность: Нет
Нейросети: Нет
Дивергенция: Нет
Уровень риска: Средний
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>
/// Grid-style mean reversion strategy.
/// Buys dips relative to SMA, sells rallies, using ATR-based grid spacing.
/// </summary>
public class AiGridStrategy : Strategy
{
private readonly StrategyParam<int> _maLength;
private readonly StrategyParam<DataType> _candleType;
public int MaLength { get => _maLength.Value; set => _maLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public AiGridStrategy()
{
_maLength = Param(nameof(MaLength), 20)
.SetGreaterThanZero()
.SetDisplay("MA Length", "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 = MaLength };
var atr = new StandardDeviation { Length = 14 };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, atr, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal smaVal, decimal atrVal)
{
if (candle.State != CandleStates.Finished)
return;
if (atrVal <= 0)
return;
var close = candle.ClosePrice;
var deviation = close - smaVal;
// Grid buy: price dropped by more than 1 ATR below SMA
if (deviation < -atrVal && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Grid sell: price rose by more than 1 ATR above SMA
else if (deviation > atrVal && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
// Take profit at mean
else if (Position > 0 && close > smaVal)
{
SellMarket();
}
else if (Position < 0 && close < smaVal)
{
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 ai_grid_strategy(Strategy):
def __init__(self):
super(ai_grid_strategy, self).__init__()
self._ma_length = self.Param("MaLength", 20) \
.SetDisplay("MA Length", "SMA period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
@property
def ma_length(self):
return self._ma_length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(ai_grid_strategy, self).OnStarted2(time)
sma = SimpleMovingAverage()
sma.Length = self.ma_length
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_val, atr_val):
if candle.State != CandleStates.Finished:
return
if atr_val <= 0:
return
close = candle.ClosePrice
deviation = close - sma_val
# Grid buy: price dropped by more than 1 ATR below SMA
if deviation < -atr_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Grid sell: price rose by more than 1 ATR above SMA
elif deviation > atr_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
# Take profit at mean
elif self.Position > 0 and close > sma_val:
self.SellMarket()
elif self.Position < 0 and close < sma_val:
self.BuyMarket()
def CreateClone(self):
return ai_grid_strategy()