Diese Strategie ist eine StockSharp-Übersetzung des MetaTrader 4-Skripts TPSL-Insert.mq4. Sie generiert keine Ein- oder Ausstiegssignale. Ihr einziger Zweck ist es, Take-Profit- und Stop-Loss-Aufträge an bestehende Positionen anzuhängen.
Funktionsweise
Beim Start liest die Strategie die Parameter TakeProfitPips und StopLossPips.
Die Werte werden von Pips in Preis umgerechnet, mithilfe des PriceStep des Wertpapiers.
StartProtection wird aufgerufen, um Schutzaufträge zu platzieren.
Wenn bereits eine Position vorhanden ist, werden Schutzaufträge sofort gesendet.
Zukünftige von der Strategie eröffnete Positionen werden automatisch geschützt.
Dieses Verhalten ist nützlich, wenn Positionen manuell oder durch externe Systeme geöffnet werden und Sie schnell Risikolimits einfügen müssen.
Parameter
Name
Beschreibung
Standard
TakeProfitPips
Take-Profit-Abstand in Pips.
35
StopLossPips
Stop-Loss-Abstand in Pips.
100
Hinweise
Die Strategie abonniert keine Marktdaten und enthält keine Handelslogik.
StartProtection übernimmt die Erstellung und Stornierung von Schutzaufträgen.
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>
/// EMA crossover strategy with take-profit and stop-loss protection.
/// </summary>
public class TpslInsertStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevDiff;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public TpslInsertStrategy()
{
_fastLength = Param(nameof(FastLength), 8)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA period", "General");
_slowLength = Param(nameof(SlowLength), 21)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA period", "General");
_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();
_prevDiff = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var emaFast = new ExponentialMovingAverage { Length = FastLength };
var emaSlow = new ExponentialMovingAverage { Length = SlowLength };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(emaFast, emaSlow, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, emaFast);
DrawIndicator(area, emaSlow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
var diff = fast - slow;
var crossUp = _prevDiff <= 0 && diff > 0;
var crossDown = _prevDiff >= 0 && diff < 0;
_prevDiff = diff;
if (crossUp && Position <= 0)
BuyMarket();
else if (crossDown && Position >= 0)
SellMarket();
}
}
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 tpsl_insert_strategy(Strategy):
def __init__(self):
super(tpsl_insert_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 8) \
.SetDisplay("Fast EMA", "Fast EMA period", "General")
self._slow_length = self.Param("SlowLength", 21) \
.SetDisplay("Slow EMA", "Slow EMA period", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle Type", "General")
self._prev_diff = 0.0
@property
def fast_length(self):
return self._fast_length.Value
@property
def slow_length(self):
return self._slow_length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(tpsl_insert_strategy, self).OnReseted()
self._prev_diff = 0.0
def OnStarted2(self, time):
super(tpsl_insert_strategy, self).OnStarted2(time)
ema_fast = ExponentialMovingAverage()
ema_fast.Length = self.fast_length
ema_slow = ExponentialMovingAverage()
ema_slow.Length = self.slow_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema_fast, ema_slow, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema_fast)
self.DrawIndicator(area, ema_slow)
self.DrawOwnTrades(area)
def on_process(self, candle, fast, slow):
if candle.State != CandleStates.Finished:
return
diff = fast - slow
cross_up = self._prev_diff <= 0 and diff > 0
cross_down = self._prev_diff >= 0 and diff < 0
self._prev_diff = diff
if cross_up and self.Position <= 0:
self.BuyMarket()
elif cross_down and self.Position >= 0:
self.SellMarket()
def CreateClone(self):
return tpsl_insert_strategy()