Эта стратегия на основе времени открывает одну длинную или короткую позицию в заданном окне и закрывает её в другом окне. Направление входа задаётся параметром, также контролируются уровни стоп-лосса и тейк-профита. Стратегия работает только с завершёнными свечами и не использует индикаторы.
Подробности
Условия входа:
Если время текущей свечи попадает в интервал [OpenTime, OpenTime + TradeInterval) и позиция отсутствует, открывается позиция в выбранном направлении.
Условия выхода:
Позиция закрывается, когда время попадает в интервал [CloseTime, CloseTime + TradeInterval).
Также выход осуществляется при срабатывании стоп-лосса или тейк-профита.
Длинные/короткие: регулируется параметром.
Стопы: стоп-лосс и тейк-профит задаются в ценовых единицах относительно цены входа.
Значения по умолчанию:
Trade = Sell.
OpenTime = 1970-01-01 00:00.
CloseTime = 3000-01-01 00:00.
TradeInterval = 1 минута.
StopLoss = 1000.
TakeProfit = 2000.
Volume = 0.1.
Фильтры:
Категория: временная
Направление: одно
Индикаторы: нет
Стопы: да
Сложность: простая
Таймфрейм: краткосрочный
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>
/// Time based strategy that opens and closes a position at specified hours of the day.
/// Opens at OpenHour and closes at CloseHour, with SL/TP protection.
/// </summary>
public class TimesDirectionStrategy : Strategy
{
private readonly StrategyParam<int> _openHour;
private readonly StrategyParam<int> _closeHour;
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<decimal> _takeProfit;
private readonly StrategyParam<DataType> _candleType;
private decimal _entryPrice;
public int OpenHour { get => _openHour.Value; set => _openHour.Value = value; }
public int CloseHour { get => _closeHour.Value; set => _closeHour.Value = value; }
public decimal StopLoss { get => _stopLoss.Value; set => _stopLoss.Value = value; }
public decimal TakeProfit { get => _takeProfit.Value; set => _takeProfit.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public TimesDirectionStrategy()
{
_openHour = Param(nameof(OpenHour), 2)
.SetDisplay("Open Hour", "Hour of day to open position (UTC)", "General");
_closeHour = Param(nameof(CloseHour), 14)
.SetDisplay("Close Hour", "Hour of day to close position (UTC)", "General");
_stopLoss = Param(nameof(StopLoss), 500m)
.SetDisplay("Stop Loss", "Stop loss distance in price units", "Risk");
_takeProfit = Param(nameof(TakeProfit), 1000m)
.SetDisplay("Take Profit", "Take profit distance in price units", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to process", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_entryPrice = 0m;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_entryPrice = 0m;
var sub = SubscribeCandles(CandleType);
sub.Bind(ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, sub);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var hour = candle.OpenTime.Hour;
if (Position == 0)
{
if (hour == OpenHour && candle.OpenTime.DayOfWeek == DayOfWeek.Monday)
{
_entryPrice = candle.ClosePrice;
BuyMarket();
}
}
else
{
// Close at specified hour
if (hour == CloseHour && candle.OpenTime.DayOfWeek == DayOfWeek.Friday)
{
SellMarket();
_entryPrice = 0m;
return;
}
// SL/TP check
if (_entryPrice != 0m && Position > 0)
{
var sl = _entryPrice - StopLoss;
var tp = _entryPrice + TakeProfit;
if (candle.LowPrice <= sl || candle.HighPrice >= tp)
{
SellMarket();
_entryPrice = 0m;
}
}
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, DayOfWeek
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Strategies import Strategy
class times_direction_strategy(Strategy):
def __init__(self):
super(times_direction_strategy, self).__init__()
self._open_hour = self.Param("OpenHour", 2)
self._close_hour = self.Param("CloseHour", 14)
self._stop_loss = self.Param("StopLoss", 500.0)
self._take_profit = self.Param("TakeProfit", 1000.0)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._entry_price = 0.0
@property
def OpenHour(self): return self._open_hour.Value
@OpenHour.setter
def OpenHour(self, v): self._open_hour.Value = v
@property
def CloseHour(self): return self._close_hour.Value
@CloseHour.setter
def CloseHour(self, v): self._close_hour.Value = v
@property
def StopLoss(self): return self._stop_loss.Value
@StopLoss.setter
def StopLoss(self, v): self._stop_loss.Value = v
@property
def TakeProfit(self): return self._take_profit.Value
@TakeProfit.setter
def TakeProfit(self, v): self._take_profit.Value = v
@property
def CandleType(self): return self._candle_type.Value
@CandleType.setter
def CandleType(self, v): self._candle_type.Value = v
def OnStarted2(self, time):
super(times_direction_strategy, self).OnStarted2(time)
self._entry_price = 0.0
sub = self.SubscribeCandles(self.CandleType)
sub.Bind(self.ProcessCandle).Start()
def ProcessCandle(self, candle):
if candle.State != CandleStates.Finished: return
hour = candle.OpenTime.Hour
if self.Position == 0:
if hour == self.OpenHour and candle.OpenTime.DayOfWeek == DayOfWeek.Monday:
self._entry_price = float(candle.ClosePrice)
self.BuyMarket()
else:
if hour == self.CloseHour and candle.OpenTime.DayOfWeek == DayOfWeek.Friday:
self.SellMarket()
self._entry_price = 0.0
return
if self._entry_price != 0.0 and self.Position > 0:
sl = self._entry_price - float(self.StopLoss)
tp = self._entry_price + float(self.TakeProfit)
if float(candle.LowPrice) <= sl or float(candle.HighPrice) >= tp:
self.SellMarket()
self._entry_price = 0.0
def OnReseted(self):
super(times_direction_strategy, self).OnReseted()
self._entry_price = 0.0
def CreateClone(self):
return times_direction_strategy()