Механическая торговая стратегия
Временная механическая стратегия, выполняющая одну сделку в указанный час каждый день. Направление позиции задаётся параметром Short Mode. Сделка автоматически защищена стоп-лоссом и тейк-профитом в процентах от цены входа.
Детали
- Условия входа:
- Long: в
TradeHour, еслиShort Modeвыключен. - Short: в
TradeHour, еслиShort Modeвключен.
- Long: в
- Направление торговли: Long и Short.
- Условия выхода:
Profit Target (%)выше/ниже входа.Stop Loss (%)ниже/выше входа.
- Стопы: есть стоп-лосс и тейк-профит.
- Значения по умолчанию:
Profit Target (%)= 0.4.Stop Loss (%)= 0.2.Trade Hour= 16.
- Фильтры:
- Категория: Время
- Направление: Оба
- Индикаторы: Нет
- Стопы: Да
- Сложность: Базовая
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Низкий
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>
/// Mechanical trading strategy - enters at a fixed hour with profit target and stop loss.
/// </summary>
public class MechanicalTradingStrategy : Strategy
{
private readonly StrategyParam<decimal> _profitTarget;
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<int> _tradeHour;
private readonly StrategyParam<bool> _isShort;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// Profit target percentage from entry price.
/// </summary>
public decimal ProfitTarget
{
get => _profitTarget.Value;
set => _profitTarget.Value = value;
}
/// <summary>
/// Stop loss percentage from entry price.
/// </summary>
public decimal StopLoss
{
get => _stopLoss.Value;
set => _stopLoss.Value = value;
}
/// <summary>
/// Hour of day to enter trade.
/// </summary>
public int TradeHour
{
get => _tradeHour.Value;
set => _tradeHour.Value = value;
}
/// <summary>
/// Enter short instead of long.
/// </summary>
public bool IsShort
{
get => _isShort.Value;
set => _isShort.Value = value;
}
/// <summary>
/// Candle type for processing.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="MechanicalTradingStrategy"/>.
/// </summary>
public MechanicalTradingStrategy()
{
_profitTarget = Param(nameof(ProfitTarget), 0.4m)
.SetNotNegative()
.SetDisplay("Profit Target (%)", "Take profit percentage", "Risk Management")
.SetOptimize(0.1m, 1m, 0.1m);
_stopLoss = Param(nameof(StopLoss), 0.2m)
.SetNotNegative()
.SetDisplay("Stop Loss (%)", "Stop loss percentage", "Risk Management")
.SetOptimize(0.1m, 1m, 0.1m);
_tradeHour = Param(nameof(TradeHour), 16)
.SetRange(0, 23)
.SetDisplay("Trade Hour", "Hour of the day to enter", "General");
_isShort = Param(nameof(IsShort), false)
.SetDisplay("Short Mode", "Enter short instead of long", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
StartProtection(
takeProfit: new Unit(ProfitTarget, UnitTypes.Percent),
stopLoss: new Unit(StopLoss, UnitTypes.Percent));
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var time = candle.OpenTime;
if (time.Hour != TradeHour || time.Minute != 0)
return;
if (Position != 0)
return;
if (IsShort)
SellMarket();
else
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.Strategies import Strategy
class mechanical_trading_strategy(Strategy):
def __init__(self):
super(mechanical_trading_strategy, self).__init__()
self._profit_target = self.Param("ProfitTarget", 0.4) \
.SetDisplay("Profit Target (%)", "Take profit percentage", "Risk Management")
self._stop_loss = self.Param("StopLoss", 0.2) \
.SetDisplay("Stop Loss (%)", "Stop loss percentage", "Risk Management")
self._trade_hour = self.Param("TradeHour", 16) \
.SetDisplay("Trade Hour", "Hour of the day to enter", "General")
self._is_short = self.Param("IsShort", False) \
.SetDisplay("Short Mode", "Enter short instead of long", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._entry_price = 0.0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(mechanical_trading_strategy, self).OnReseted()
self._entry_price = 0.0
def OnStarted2(self, time):
super(mechanical_trading_strategy, self).OnStarted2(time)
self._entry_price = 0.0
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def OnProcess(self, candle):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
hour = candle.OpenTime.Hour
minute = candle.OpenTime.Minute
tp_pct = float(self._profit_target.Value) / 100.0
sl_pct = float(self._stop_loss.Value) / 100.0
if self.Position > 0 and self._entry_price > 0.0:
tp = self._entry_price * (1.0 + tp_pct)
sl = self._entry_price * (1.0 - sl_pct)
if close >= tp or close <= sl:
self.SellMarket()
self._entry_price = 0.0
return
elif self.Position < 0 and self._entry_price > 0.0:
tp = self._entry_price * (1.0 - tp_pct)
sl = self._entry_price * (1.0 + sl_pct)
if close <= tp or close >= sl:
self.BuyMarket()
self._entry_price = 0.0
return
if hour != self._trade_hour.Value or minute != 0:
return
if self.Position != 0:
return
if self._is_short.Value:
self.SellMarket()
else:
self.BuyMarket()
self._entry_price = close
def CreateClone(self):
return mechanical_trading_strategy()