GitHub で見る
Secwenta MultiBar Signals戦略
概要
この戦略はMetaTraderエキスパートアドバイザー「Secwenta」(MQL ID 22977)のStockSharpポートです。アルゴリズムは完成したローソク足をスキャンし、短いローリング履歴内で何本が陽線(終値 > 始値)または陰線(終値 < 始値)で終了したかを数えます。設定に応じて、買いのみ、売りのみ、または双方向の反転モードで動作できます。必要な数の陽線または陰線が現れると、戦略は元のロット設定を反映した固定ボリュームを使って市場ポジションを開くか閉じます。
シグナル評価
- 選択した
CandleTypeの完成したローソク足のみが、高レベルサブスクリプションAPIを通じて処理されます。
- 各ローソク足について戦略は陽線、陰線、またはニュートラル(ドージ)かを記録します。内部バッファは最新のN方向を保持し、Nは有効化されている側(買いおよび/または売り)の
BullishBarCountとBearishBarCountのうち大きい方です。
- ローソク足が始値を上回って終値をつけると陽線カウンターが増分し、始値を下回って終値をつけると陰線カウンターが増分します。ニュートラルなローソク足はカウンターに影響しません。
- 対応するカウンターがローリング・ウィンドウ内で設定されたしきい値に達するとシグナルが発動します。これは要求された数の陽線または陰線が見つかるまで直近のバーを反復した元のMQLロジックを再現します。
取引ルール
- 買いのみモード(
UseBuySignals = true、UseSellSignals = false):
- 陰線カウンターが
BearishBarCountに達すると、既存のロングポジションは成行売り注文でクローズされます。
- 陽線カウンターが
BullishBarCountに達し、戦略がフラットの場合、OrderVolumeを使って新しいロングポジションが開かれます。
- 売りのみモード(
UseBuySignals = false、UseSellSignals = true):
- 陽線カウンターが
BullishBarCountに達すると、オープンのショートポジションは成行買い注文でカバーされます。
- 陰線カウンターが
BearishBarCountに達し、戦略がフラットの場合、OrderVolumeを使って新しいショートポジションが開かれます。
- 反転モード(
UseBuySignals = trueかつUseSellSignals = true):
- 陽線トリガーはショートエクスポージャーをクローズし、戦略がまだロングでなければ、
OrderVolumeにショートポジションの絶対サイズを加えた量を買うことで新しいロングポジションを開きます。これは売りをクローズしてから買いを開くという元のシーケンスを模倣します。
- 陰線トリガーはロングエクスポージャーをクローズし、戦略がまだショートでなければ、
OrderVolumeにロングポジションの絶対サイズを加えた量を売ることで新しいショートポジションを開きます。
すべての市場操作はStockSharpのBuyMarketおよびSellMarketヘルパーを再利用し、戦略はStartProtection()を呼び出してアカウントレベルの保護を必要に応じて重ねることができます。
パラメーター
| パラメーター |
説明 |
デフォルト |
メモ |
CandleType |
シーケンス評価に使用するローソク足データタイプ(時間足)。 |
1時間足 |
StockSharpがサポートする任意のローソク足タイプを選択可能。 |
OrderVolume |
MQLのロットサイズを反映したベース成行注文ボリューム。 |
1 |
ポジション反転時にクローズボリュームに加算されます。 |
UseBuySignals |
陽線シグナル処理を有効化します。 |
true |
無効時は新しいロングトレードを開きません。 |
BullishBarCount |
陽線イベントを発動するために必要な陽線ローソク足の数。 |
2 |
買いのみモードで実行する場合、クローズしきい値と一致させる必要があります。 |
UseSellSignals |
陰線シグナル処理を有効化します。 |
false |
無効時は新しいショートトレードを開きません。 |
BearishBarCount |
陰線イベントを発動するために必要な陰線ローソク足の数。 |
1 |
ショートの開設しきい値とロングの決済しきい値の両方として機能します。 |
実装メモ
- ローリング・ウィンドウはキューを使用して最新のローソク足方向を保持し、パラメーター変更後もカウンターがウィンドウサイズと一致することを保証します。
- 元の「新バー」イベント処理に忠実であるため、完成したローソク足のみが処理されます。
- ニュートラル(ドージ)ローソク足はMQLコードと同様にカウンターを変更しません。
- 反転は単一の成行注文で実行され、クローズとオープンのボリュームを組み合わせ、確定的なエクスポージャー変更を維持します。
- バッファ長は最大のアクティブしきい値に等しく、一方の側が無効化されている場合は対応するしきい値のみがルックバック長に寄与し、MQLバージョンの
CopyRatesの動作と一致します。
ファイル
CS/SecwentaMultiBarSignalsStrategy.cs – StockSharp高レベル戦略APIに基づいたメインC#実装。
注意: このIDにはPython翻訳は提供されません。要求されたC#バージョンのみが提供されています。
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>
/// Secwenta MultiBar Signals strategy using SmoothedMA crossover.
/// Buys when fast SmoothedMA crosses above slow SmoothedMA, sells on reverse.
/// </summary>
public class SecwentaMultiBarSignalsStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _takeProfitPoints;
private SmoothedMovingAverage _fast;
private SmoothedMovingAverage _slow;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private int _cooldown;
/// <summary>
/// Fast SmoothedMA period.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow SmoothedMA period.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Stop-loss distance in price steps.
/// </summary>
public int StopLossPoints
{
get => _stopLossPoints.Value;
set => _stopLossPoints.Value = value;
}
/// <summary>
/// Take-profit distance in price steps.
/// </summary>
public int TakeProfitPoints
{
get => _takeProfitPoints.Value;
set => _takeProfitPoints.Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="SecwentaMultiBarSignalsStrategy"/> class.
/// </summary>
public SecwentaMultiBarSignalsStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 15)
.SetGreaterThanZero()
.SetDisplay("Fast Period", "Fast SmoothedMA period", "Indicator");
_slowPeriod = Param(nameof(SlowPeriod), 60)
.SetGreaterThanZero()
.SetDisplay("Slow Period", "Slow SmoothedMA period", "Indicator");
_stopLossPoints = Param(nameof(StopLossPoints), 200)
.SetNotNegative()
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 400)
.SetNotNegative()
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_fast = null;
_slow = null;
_prevFast = 0;
_prevSlow = 0;
_entryPrice = 0;
_cooldown = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fast = new SmoothedMovingAverage { Length = FastPeriod };
_slow = new SmoothedMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
subscription.Bind(_fast, _slow, ProcessCandle);
subscription.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_fast.IsFormed || !_slow.IsFormed)
{
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
var close = candle.ClosePrice;
var step = Security?.PriceStep ?? 1m;
// Check SL/TP
if (Position > 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step)
{
SellMarket();
_entryPrice = 0;
_cooldown = 80;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step)
{
SellMarket();
_entryPrice = 0;
_cooldown = 80;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
}
else if (Position < 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step)
{
BuyMarket();
_entryPrice = 0;
_cooldown = 80;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step)
{
BuyMarket();
_entryPrice = 0;
_cooldown = 80;
_prevFast = fastValue;
_prevSlow = slowValue;
return;
}
}
// SmoothedMA crossover
if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
_entryPrice = close;
_cooldown = 80;
}
else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
_entryPrice = close;
_cooldown = 80;
}
_prevFast = fastValue;
_prevSlow = slowValue;
}
}
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 SmoothedMovingAverage
from StockSharp.Algo.Strategies import Strategy
class secwenta_multi_bar_signals_strategy(Strategy):
def __init__(self):
super(secwenta_multi_bar_signals_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 15) \
.SetDisplay("Fast Period", "Fast MA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 60) \
.SetDisplay("Slow Period", "Slow MA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200) \
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400) \
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def take_profit_points(self):
return self._take_profit_points.Value
def OnReseted(self):
super(secwenta_multi_bar_signals_strategy, self).OnReseted()
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(secwenta_multi_bar_signals_strategy, self).OnStarted2(time)
self._fast = SmoothedMovingAverage()
self._fast.Length = self.fast_period
self._slow = SmoothedMovingAverage()
self._slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(self._fast, self._slow, self._process_candle)
subscription.Start()
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if not self._fast.IsFormed or not self._slow.IsFormed:
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if self.Position > 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close <= self._entry_price - self.stop_loss_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close >= self._entry_price + self.take_profit_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close >= self._entry_price + self.stop_loss_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close <= self._entry_price - self.take_profit_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._prev_fast <= self._prev_slow and fast_val > slow_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 80
elif self._prev_fast >= self._prev_slow and fast_val < slow_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return secwenta_multi_bar_signals_strategy()