バックテストモジュール
この戦略はTradingViewの「Backtesting Module」のデフォルト動作を再現します。シンプルな移動平均クロスオーバーを取引します。50期間SMAが200期間SMAを上抜けたときにロングポジションを建て、逆のクロスオーバーが発生したときにショートポジションを建てます。取引は指定された開始時刻と終了時刻の間のみ許可されます。
詳細
- エントリー条件: 50期間SMAが200期間SMAをクロス。
- ロング/ショート: 両方。
- エグジット条件: 逆クロスオーバーまたは時間区間の離脱。
- ストップ: なし。
- デフォルト値:
FastLength= 50SlowLength= 200StartTime= 1 Jan 1980EndTime= 31 Dec 2050CandleType= TimeSpan.FromMinutes(1)
- フィルター:
- カテゴリ: トレンドフォロー
- 方向: 両方
- インジケーター: SMA
- ストップ: いいえ
- 複雑さ: 基本
- 時間軸: 可変
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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>
/// Backtesting module strategy.
/// Inside the StartTime..EndTime interval a fast SMA crossing above the slow SMA goes long and a cross below goes short,
/// reversing an opposite position. Outside the interval no entries are taken and an open position is closed.
/// </summary>
public class BacktestingModuleStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<DateTime> _startTime;
private readonly StrategyParam<DateTime> _endTime;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevFast;
private decimal? _prevSlow;
/// <summary>
/// Fast SMA period.
/// </summary>
public int FastLength
{
get => _fastLength.Value;
set => _fastLength.Value = value;
}
/// <summary>
/// Slow SMA period.
/// </summary>
public int SlowLength
{
get => _slowLength.Value;
set => _slowLength.Value = value;
}
/// <summary>
/// Start of the trading interval.
/// </summary>
public DateTime StartTime
{
get => _startTime.Value;
set => _startTime.Value = value;
}
/// <summary>
/// End of the trading interval.
/// </summary>
public DateTime EndTime
{
get => _endTime.Value;
set => _endTime.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public BacktestingModuleStrategy()
{
_fastLength = Param(nameof(FastLength), 50)
.SetGreaterThanZero()
.SetDisplay("Fast Length", "Fast SMA period", "Indicators");
_slowLength = Param(nameof(SlowLength), 200)
.SetGreaterThanZero()
.SetDisplay("Slow Length", "Slow SMA period", "Indicators");
_startTime = Param(nameof(StartTime), new DateTime(1980, 1, 1, 0, 0, 0, DateTimeKind.Utc))
.SetDisplay("Start Time", "Start of the trading interval", "Time");
_endTime = Param(nameof(EndTime), new DateTime(2050, 12, 31, 0, 0, 0, DateTimeKind.Utc))
.SetDisplay("End Time", "End of the trading interval", "Time");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(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 OnReseted()
{
base.OnReseted();
_prevFast = null;
_prevSlow = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevFast = null;
_prevSlow = null;
var fast = new SimpleMovingAverage { Length = FastLength };
var slow = new SimpleMovingAverage { Length = SlowLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fast, slow, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fast);
DrawIndicator(area, slow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
var prevFast = _prevFast;
var prevSlow = _prevSlow;
_prevFast = fast;
_prevSlow = slow;
if (prevFast is not decimal pf || prevSlow is not decimal ps)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var inWindow = candle.OpenTime >= StartTime && candle.OpenTime <= EndTime;
if (!inWindow)
{
if (Position > 0)
SellMarket(Position);
else if (Position < 0)
BuyMarket(-Position);
return;
}
if (pf <= ps && fast > slow && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (pf >= ps && fast < slow && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, DateTime, DateTimeKind
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class backtesting_module_strategy(Strategy):
"""
Backtesting module strategy.
Inside the StartTime..EndTime interval a fast SMA crossing above the slow SMA goes long and a cross below goes short,
reversing an opposite position. Outside the interval no entries are taken and an open position is closed.
"""
def __init__(self):
super(backtesting_module_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 50) \
.SetGreaterThanZero() \
.SetDisplay("Fast Length", "Fast SMA period", "Indicators")
self._slow_length = self.Param("SlowLength", 200) \
.SetGreaterThanZero() \
.SetDisplay("Slow Length", "Slow SMA period", "Indicators")
self._start_time = self.Param("StartTime", DateTime(1980, 1, 1, 0, 0, 0, DateTimeKind.Utc)) \
.SetDisplay("Start Time", "Start of the trading interval", "Time")
self._end_time = self.Param("EndTime", DateTime(2050, 12, 31, 0, 0, 0, DateTimeKind.Utc)) \
.SetDisplay("End Time", "End of the trading interval", "Time")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_fast = None
self._prev_slow = None
@property
def CandleType(self):
return self._candle_type.Value
def GetWorkingSecurities(self):
return [(self.Security, self.CandleType)]
def OnReseted(self):
super(backtesting_module_strategy, self).OnReseted()
self._prev_fast = None
self._prev_slow = None
def OnStarted2(self, time):
super(backtesting_module_strategy, self).OnStarted2(time)
self._prev_fast = None
self._prev_slow = None
fast = SimpleMovingAverage()
fast.Length = self._fast_length.Value
slow = SimpleMovingAverage()
slow.Length = self._slow_length.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(fast, slow, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast)
self.DrawIndicator(area, slow)
self.DrawOwnTrades(area)
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast = float(fast_value)
slow = float(slow_value)
prev_fast = self._prev_fast
prev_slow = self._prev_slow
self._prev_fast = fast
self._prev_slow = slow
if prev_fast is None or prev_slow is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
open_time = candle.OpenTime
in_window = open_time >= self._start_time.Value and open_time <= self._end_time.Value
if not in_window:
if self.Position > 0:
self.SellMarket(self.Position)
elif self.Position < 0:
self.BuyMarket(-self.Position)
return
if prev_fast <= prev_slow and fast > slow and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif prev_fast >= prev_slow and fast < slow and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
def CreateClone(self):
return backtesting_module_strategy()