Стратегия размещает четыре отложенных ордера вокруг текущих цен Bid и Ask в указанные часы. Она постоянно поддерживает Buy Limit, Sell Limit, Buy Stop и Sell Stop на настраиваемом расстоянии от рынка. Каждый ордер использует фиксированные уровни стоп-лосса и тейк-профита.
Подробности
Условия входа: Отложенные ордера на расстоянии Distance тиков от текущих Bid/Ask в разрешённые часы.
Направление: В обе стороны.
Условия выхода: Тейк-профит или стоп-лосс относительно цены входа.
Стопы: Да.
Значения по умолчанию:
StartHour = 6
EndHour = 20
TakeProfit = 20
StopLoss = 100
Distance = 15
CandleType = TimeSpan.FromMinutes(1)
Фильтры:
Категория: Рендж
Направление: Оба
Индикаторы: Нет
Стопы: Да
Сложность: Базовая
Таймфрейм: Внутридневной (1m)
Сезонность: Нет
Нейросети: Нет
Дивергенция: Нет
Уровень риска: Низкий
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>
/// Strategy that buys or sells based on price breaking above/below
/// a previous candle's range by a configurable offset.
/// </summary>
public class PendingOrderStrategy : Strategy
{
private readonly StrategyParam<decimal> _distance;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevHigh;
private decimal? _prevLow;
public decimal Distance { get => _distance.Value; set => _distance.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public PendingOrderStrategy()
{
_distance = Param(nameof(Distance), 50m)
.SetDisplay("Distance", "Offset from prev candle range for entry", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle type", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevHigh = _prevLow = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new ExponentialMovingAverage { Length = 5 };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(sma, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal smaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
{
_prevHigh = candle.HighPrice;
_prevLow = candle.LowPrice;
return;
}
if (_prevHigh is decimal ph && _prevLow is decimal pl)
{
var breakUp = ph + Distance;
var breakDown = pl - Distance;
if (candle.ClosePrice > breakUp && Position <= 0)
BuyMarket();
else if (candle.ClosePrice < breakDown && Position >= 0)
SellMarket();
}
_prevHigh = candle.HighPrice;
_prevLow = candle.LowPrice;
}
}
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 ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class pending_order_strategy(Strategy):
def __init__(self):
super(pending_order_strategy, self).__init__()
self._distance = self.Param("Distance", 50.0).SetDisplay("Distance", "Offset from prev candle range for entry", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))).SetDisplay("Candle Type", "Candle type", "General")
self._prev_high = None
self._prev_low = None
@property
def distance(self): return self._distance.Value
@property
def candle_type(self): return self._candle_type.Value
def OnReseted(self):
super(pending_order_strategy, self).OnReseted()
self._prev_high = None
self._prev_low = None
def OnStarted2(self, time):
super(pending_order_strategy, self).OnStarted2(time)
sma = ExponentialMovingAverage()
sma.Length = 5
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def process_candle(self, candle, sma_value):
if candle.State != CandleStates.Finished: return
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
return
if self._prev_high is not None and self._prev_low is not None:
dist = float(self.distance)
break_up = self._prev_high + dist
break_down = self._prev_low - dist
close = float(candle.ClosePrice)
if close > break_up and self.Position <= 0:
self.BuyMarket()
elif close < break_down and self.Position >= 0:
self.SellMarket()
self._prev_high = float(candle.HighPrice)
self._prev_low = float(candle.LowPrice)
def CreateClone(self): return pending_order_strategy()