Стратегия сеточной торговли
Эта стратегия реализует простую сеточную систему. Она размещает отложенные заявки Buy Stop и Sell Stop через равные интервалы GridStep. Каждая исполненная заявка закрывается по фиксированному тейк-профиту. При достижении прибыли ProfitTarget позиции и заявки закрываются, сетка сбрасывается. По желанию объем новых заявок увеличивается по принципу мартингейла.
Детали
- Условия входа:
- Buy Stop на шаг выше текущей цены.
- Sell Stop на шаг ниже текущей цены.
- Лонг/Шорт: Оба направления.
- Условия выхода:
- Закрытие по тейк-профиту.
- Закрытие всех позиций при достижении общей прибыли
ProfitTarget.
- Стопы: Только тейк-профит.
- Фильтры: Нет.
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Simple grid trading strategy.
/// Buys when price moves up a grid level, sells when down.
/// Closes on profit target.
/// </summary>
public class GridStrategy : Strategy
{
private readonly StrategyParam<decimal> _gridStep;
private readonly StrategyParam<decimal> _profitTarget;
private readonly StrategyParam<DataType> _candleType;
private decimal _lastGridLevel;
private decimal _entryPrice;
public decimal GridStep { get => _gridStep.Value; set => _gridStep.Value = value; }
public decimal ProfitTarget { get => _profitTarget.Value; set => _profitTarget.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public GridStrategy()
{
_gridStep = Param(nameof(GridStep), 500m)
.SetGreaterThanZero()
.SetDisplay("Grid Step", "Step size in price units", "General");
_profitTarget = Param(nameof(ProfitTarget), 2000m)
.SetDisplay("Profit Target", "Profit to close position", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle type", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_lastGridLevel = 0;
_entryPrice = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
SubscribeCandles(CandleType)
.Bind(ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var step = GridStep;
var currentLevel = Math.Floor(candle.ClosePrice / step) * step;
if (_lastGridLevel == 0)
{
_lastGridLevel = currentLevel;
return;
}
if (currentLevel > _lastGridLevel)
{
if (Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
_entryPrice = candle.ClosePrice;
}
}
else if (currentLevel < _lastGridLevel)
{
if (Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
_entryPrice = candle.ClosePrice;
}
}
_lastGridLevel = currentLevel;
// Check profit target
if (Position > 0 && _entryPrice > 0)
{
if (candle.ClosePrice - _entryPrice >= ProfitTarget)
{
SellMarket();
_entryPrice = 0;
}
}
else if (Position < 0 && _entryPrice > 0)
{
if (_entryPrice - candle.ClosePrice >= ProfitTarget)
{
BuyMarket();
_entryPrice = 0;
}
}
}
}
import clr
import math
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.Strategies import Strategy
class grid_strategy(Strategy):
"""
Simple grid trading strategy.
Buys when price moves up a grid level, sells when down.
Closes on profit target.
"""
def __init__(self):
super(grid_strategy, self).__init__()
self._grid_step = self.Param("GridStep", 500.0) \
.SetDisplay("Grid Step", "Step size in price units", "General")
self._profit_target = self.Param("ProfitTarget", 2000.0) \
.SetDisplay("Profit Target", "Profit to close position", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle type", "General")
self._last_grid_level = 0.0
self._entry_price = 0.0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(grid_strategy, self).OnReseted()
self._last_grid_level = 0.0
self._entry_price = 0.0
def OnStarted2(self, time):
super(grid_strategy, self).OnStarted2(time)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._process_candle).Start()
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
step = self._grid_step.Value
if step <= 0:
return
close = float(candle.ClosePrice)
current_level = math.floor(close / step) * step
if self._last_grid_level == 0.0:
self._last_grid_level = current_level
return
if current_level > self._last_grid_level:
if self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
elif current_level < self._last_grid_level:
if self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._last_grid_level = current_level
profit_target = self._profit_target.Value
if self.Position > 0 and self._entry_price > 0:
if close - self._entry_price >= profit_target:
self.SellMarket()
self._entry_price = 0.0
elif self.Position < 0 and self._entry_price > 0:
if self._entry_price - close >= profit_target:
self.BuyMarket()
self._entry_price = 0.0
def CreateClone(self):
return grid_strategy()