TEMA Custom Slope 策略
基于三重指数移动平均线(TEMA)斜率变化的反转策略。指标在指定的时间框架上计算,策略在方向改变时做出反应。
工作原理
- 入场条件:
- 多头:TEMA 先下降后转为上升。
- 空头:TEMA 先上升后转为下降。
- 出场条件:反向信号平掉当前仓位。
- 指标:Triple Exponential Moving Average。
关键参数
TemaLength– TEMA 计算的周期数。CandleType– 使用的 K 线时间框架。
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>
/// Strategy based on slope reversals of the Triple Exponential Moving Average.
/// </summary>
public class TemaCustomSlopeStrategy : Strategy
{
private readonly StrategyParam<int> _temaLength;
private readonly StrategyParam<decimal> _stopLossPct;
private readonly StrategyParam<decimal> _takeProfitPct;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prev1;
private decimal? _prev2;
public int TemaLength
{
get => _temaLength.Value;
set => _temaLength.Value = value;
}
public decimal StopLossPct
{
get => _stopLossPct.Value;
set => _stopLossPct.Value = value;
}
public decimal TakeProfitPct
{
get => _takeProfitPct.Value;
set => _takeProfitPct.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public TemaCustomSlopeStrategy()
{
_temaLength = Param(nameof(TemaLength), 12)
.SetDisplay("TEMA Length", "Length of the TEMA", "Indicators");
_stopLossPct = Param(nameof(StopLossPct), 2m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");
_takeProfitPct = Param(nameof(TakeProfitPct), 3m)
.SetDisplay("Take Profit %", "Take profit percentage", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prev1 = null;
_prev2 = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var tema = new TripleExponentialMovingAverage { Length = TemaLength };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(tema, ProcessCandle).Start();
StartProtection(
takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent),
stopLoss: new Unit(StopLossPct, UnitTypes.Percent),
useMarketOrders: true);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, tema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal tema)
{
if (candle.State != CandleStates.Finished)
return;
if (_prev1 is null || _prev2 is null)
{
_prev2 = _prev1;
_prev1 = tema;
return;
}
var falling = _prev1 < _prev2;
var rising = _prev1 > _prev2;
var turnedUp = falling && tema > _prev1;
var turnedDown = rising && tema < _prev1;
_prev2 = _prev1;
_prev1 = tema;
if (turnedUp && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (turnedDown && Position >= 0)
{
if (Position > 0) SellMarket();
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import TripleExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class tema_custom_slope_strategy(Strategy):
def __init__(self):
super(tema_custom_slope_strategy, self).__init__()
self._tema_length = self.Param("TemaLength", 12) \
.SetDisplay("TEMA Length", "Length of the TEMA", "Indicators")
self._stop_loss_pct = self.Param("StopLossPct", 2.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
self._take_profit_pct = self.Param("TakeProfitPct", 3.0) \
.SetDisplay("Take Profit %", "Take profit percentage", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe of candles", "General")
self._prev1 = None
self._prev2 = None
@property
def tema_length(self):
return self._tema_length.Value
@property
def stop_loss_pct(self):
return self._stop_loss_pct.Value
@property
def take_profit_pct(self):
return self._take_profit_pct.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(tema_custom_slope_strategy, self).OnReseted()
self._prev1 = None
self._prev2 = None
def OnStarted2(self, time):
super(tema_custom_slope_strategy, self).OnStarted2(time)
tema = TripleExponentialMovingAverage()
tema.Length = self.tema_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(tema, self.process_candle).Start()
self.StartProtection(
takeProfit=Unit(self.take_profit_pct, UnitTypes.Percent),
stopLoss=Unit(self.stop_loss_pct, UnitTypes.Percent),
useMarketOrders=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, tema)
self.DrawOwnTrades(area)
def process_candle(self, candle, tema):
if candle.State != CandleStates.Finished:
return
tema = float(tema)
if self._prev1 is None or self._prev2 is None:
self._prev2 = self._prev1
self._prev1 = tema
return
falling = self._prev1 < self._prev2
rising = self._prev1 > self._prev2
turned_up = falling and tema > self._prev1
turned_down = rising and tema < self._prev1
self._prev2 = self._prev1
self._prev1 = tema
if turned_up and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif turned_down and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
def CreateClone(self):
return tema_custom_slope_strategy()