Time Trader 策略
基于时间的策略,在指定的时刻根据设置选择做多或做空,并使用止盈止损保护头寸。
细节
- 入场条件:在
TradeHour:TradeMinute:TradeSecond时,如果AllowBuy为真则买入,如果AllowSell为真则卖出 - 多空方向:根据设置可做多或做空
- 出场条件:止盈或止损
- 止损:是
- 默认值:
Volume= 1TakeProfit= 0.2StopLoss= 0.2TradeHour= 0TradeMinute= 0TradeSecond= 0AllowBuy= trueAllowSell= trueCandleType= TimeSpan.FromSeconds(1).TimeFrame()
- 过滤器:
- 分类: Time
- 方向: 双向
- 指标: 无
- 止损: 是
- 复杂度: 基础
- 时间框架: 日内
- 季节性: 否
- 神经网络: 否
- 背离: 否
- 风险等级: 中等
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>
/// Time-based trader using EMA trend for directional entries.
/// </summary>
public class TimeTraderStrategy : Strategy
{
private readonly StrategyParam<int> _emaPeriod;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevEma;
private bool _hasPrev;
public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public TimeTraderStrategy()
{
_emaPeriod = Param(nameof(EmaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("EMA Period", "EMA period", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevEma = 0;
_hasPrev = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
SubscribeCandles(CandleType).Bind(ema, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal emaVal)
{
if (candle.State != CandleStates.Finished)
return;
if (!_hasPrev)
{
_prevEma = emaVal;
_hasPrev = true;
return;
}
var close = candle.ClosePrice;
// EMA rising and price above EMA -> buy
if (emaVal > _prevEma && close > emaVal && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
// EMA falling and price below EMA -> sell
else if (emaVal < _prevEma && close < emaVal && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_prevEma = emaVal;
}
}
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 time_trader_strategy(Strategy):
def __init__(self):
super(time_trader_strategy, self).__init__()
self._ema_period = self.Param("EmaPeriod", 20) \
.SetDisplay("EMA Period", "EMA period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_ema = 0.0
self._has_prev = False
@property
def ema_period(self):
return self._ema_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(time_trader_strategy, self).OnReseted()
self._prev_ema = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(time_trader_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self.ema_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, ema_val):
if candle.State != CandleStates.Finished:
return
if not self._has_prev:
self._prev_ema = ema_val
self._has_prev = True
return
close = candle.ClosePrice
# EMA rising and price above EMA -> buy
if ema_val > self._prev_ema and close > ema_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# EMA falling and price below EMA -> sell
elif ema_val < self._prev_ema and close < ema_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_ema = ema_val
def CreateClone(self):
return time_trader_strategy()