GitHub で見る
ScalpWiz 9001 戦略
概要
ScalpWiz 9001は、同名のMetaTraderエキスパートアドバイザーの動作を再現する多層式ブレイクアウトスキャルピングシステムです。この戦略は最新のローソク足がボリンジャーバンドのエンベロープをどれだけ超えてクローズするかを測定し、ボラティリティが急激に拡大したとき、市場の上または下にペンディングのストップ注文のグリッドを展開します。元のマネーマネジメントモジュールが保存されています:各ペンディング注文は固定ロットを使用するか、口座資本の設定可能な割合をリスクにさらすことができます。
ストップ注文の1つが約定すると、残りの注文はキャンセルされ、アクティブなポジションは追加バッファーが達成された後にのみトレーリングを開始する従来のストップロス、テイクプロフィット、トレーリングコンポーネントで保護されます。この戦略は低いタイムフレームでの高頻度スキャルピングを目的としていますが、StockSharpがサポートするすべてのインストルメントで実行できます。
シグナルロジック
- 設定されたタイムフレームをサブスクライブし、偏差係数
BandsDeviation(デフォルト2)で20期間のボリンジャーバンドを計算する。
- 終値が上または下のバンドからどれだけ離れているかを確認する。終値が少なくとも第4レベルの距離(
Level3Pips を価格に変換)でバンドを超えると、戦略は動きをフェードする準備をする:
- 終値が上バンドより上 → 市場の下に売りストップ注文を発注。
- 終値が下バンドより下 → 市場の上に買いストップ注文を発注。
- 4つのペンディング注文が増加する距離(
Level0Pips … Level3Pips)で発注される。各注文はそのティアに割り当てられた固定ボリュームまたはリスク割合を使用する。注文は未接触のまま ExpirationMinutes 後に期限切れになる。
- エントリー注文が約定すると、すべての未処理注文がキャンセルされる。約定したポジションはストップロス(
StopLossPips)、テイクプロフィット(TakeProfitPips)、トレーリングパラメーター(TrailingStopPips、TrailingStepPips)で管理される。トレーリングはエントリーから少なくとも TrailingStopPips + TrailingStepPips を価格が移動した場合にのみ保護ストップを移動する。
- 完成したローソク足でトレーリングストップまたは利益ターゲットに触れると、成行注文でエグジットが実行される。
パラメーター
- Candle Type – ボリンジャー計算のタイムフレーム。
- Bands Period / Bands Deviation – ボリンジャー設定。
- Stop Loss (pips) – ピップでの保護ストップ距離。
- Take Profit (pips) – ピップでの利益ターゲット距離。
- Trailing Stop (pips) – 追加バッファーの後の動きに続くトレーリングストップ距離。
- Trailing Step (pips) – トレーリングが有効化される前に必要な追加距離。
- Expiration (minutes) – ペンディングストップ注文の寿命。無期限に注文を保持するには0に設定する。
- Management Mode –
FixedVolume と RiskPercent の間で選択する。
- Level 0-3 Value – 各ペンディング層の固定ロットまたはリスク割合。
- Level 0-3 Pips – 各ペンディング層のエントリーオフセット。
マネーマネジメント
ManagementMode が RiskPercent の場合、戦略は口座資本と設定されたストップロス距離から注文ボリュームを計算する:
注文ボリューム = (equity × riskPercent / 100) / (stopOffset / priceStep × stepPrice)
市場メタデータ(価格ステップ、ステップ価格またはボリュームステップ)が利用できない場合、安全のために注文サイズがゼロにフォールバックします。FixedVolume では、層の値が直接使用され、インストルメントのボリュームステップと範囲に丸められます。
トレーリングと保護
- ストップロスとテイクプロフィットは、実際の約定価格に対するピップ距離を使用して初期化されます。
- トレーリングロジックはMetaTraderの実装を反映します:価格が
TrailingStop + TrailingStep 進むまでストップは移動せず、その後 TrailingStop のギャップを維持します。
- エグジットは成行注文として発行され、サーバーサイドの保護注文をサポートしない会場との互換性を確保します。
実用的な注意事項
- インストルメントのティックサイズに応じてピップ距離を設定する。5桁のFXシンボルでは、各ピップは10の価格ステップに対応し、戦略はアセットの小数点を検査することで自動的に調整します。
- 戦略はストップ注文に依存するため、ブローカー固有のストップレベル要件を確認し、必要に応じてレベル距離を調整する。
- リスク割合サイジングには有効なポートフォリオ評価とアセットステップメタデータが必要です;そうでないと、注文ボリュームはゼロになります。
- 戦略は完成したローソク足で動作するため、バーごとに1回反応し、元のティックベースのエキスパートと比較してノイズを滑らかにします。
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>
/// Bollinger Bands breakout scalping strategy.
/// Buys when price breaks below lower band (mean reversion) and sells when price breaks above upper band.
/// Uses stop-loss and take-profit for risk management.
/// </summary>
public class ScalpWiz9001Strategy : Strategy
{
private readonly StrategyParam<int> _bandsPeriod;
private readonly StrategyParam<decimal> _bandsDeviation;
private readonly StrategyParam<int> _stopLossPips;
private readonly StrategyParam<int> _takeProfitPips;
private BollingerBands _bollinger;
private decimal _entryPrice;
private int _cooldown;
/// <summary>
/// Bollinger Bands lookback period.
/// </summary>
public int BandsPeriod
{
get => _bandsPeriod.Value;
set => _bandsPeriod.Value = value;
}
/// <summary>
/// Bollinger Bands deviation multiplier.
/// </summary>
public decimal BandsDeviation
{
get => _bandsDeviation.Value;
set => _bandsDeviation.Value = value;
}
/// <summary>
/// Stop loss distance in price steps.
/// </summary>
public int StopLossPips
{
get => _stopLossPips.Value;
set => _stopLossPips.Value = value;
}
/// <summary>
/// Take profit distance in price steps.
/// </summary>
public int TakeProfitPips
{
get => _takeProfitPips.Value;
set => _takeProfitPips.Value = value;
}
/// <summary>
/// Initializes strategy parameters.
/// </summary>
public ScalpWiz9001Strategy()
{
_bandsPeriod = Param(nameof(BandsPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Bands Period", "Bollinger Bands period", "Indicator");
_bandsDeviation = Param(nameof(BandsDeviation), 1.5m)
.SetGreaterThanZero()
.SetDisplay("Bands Deviation", "Bollinger Bands deviation", "Indicator");
_stopLossPips = Param(nameof(StopLossPips), 100)
.SetNotNegative()
.SetDisplay("Stop Loss", "Stop-loss distance in price steps", "Risk");
_takeProfitPips = Param(nameof(TakeProfitPips), 150)
.SetNotNegative()
.SetDisplay("Take Profit", "Take-profit distance 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();
_bollinger = null;
_entryPrice = 0;
_cooldown = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_bollinger = new BollingerBands
{
Length = BandsPeriod,
Width = BandsDeviation
};
var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
subscription.BindEx(_bollinger, ProcessCandle);
subscription.Start();
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue value)
{
if (candle.State != CandleStates.Finished)
return;
var bb = (BollingerBandsValue)value;
if (bb.UpBand is not decimal upper ||
bb.LowBand is not decimal lower)
return;
if (!_bollinger.IsFormed)
return;
if (_cooldown > 0)
{
_cooldown--;
return;
}
var close = candle.ClosePrice;
var step = Security?.PriceStep ?? 1m;
// Check SL/TP for existing positions
if (Position > 0 && _entryPrice > 0)
{
if (StopLossPips > 0 && close <= _entryPrice - StopLossPips * step)
{
SellMarket();
_entryPrice = 0;
_cooldown = 5;
return;
}
if (TakeProfitPips > 0 && close >= _entryPrice + TakeProfitPips * step)
{
SellMarket();
_entryPrice = 0;
_cooldown = 5;
return;
}
}
else if (Position < 0 && _entryPrice > 0)
{
if (StopLossPips > 0 && close >= _entryPrice + StopLossPips * step)
{
BuyMarket();
_entryPrice = 0;
_cooldown = 5;
return;
}
if (TakeProfitPips > 0 && close <= _entryPrice - TakeProfitPips * step)
{
BuyMarket();
_entryPrice = 0;
_cooldown = 5;
return;
}
}
// Entry signals
if (Position == 0)
{
// Buy when price touches lower band (mean reversion up)
if (close <= lower)
{
BuyMarket();
_entryPrice = close;
_cooldown = 5;
}
// Sell when price touches upper band (mean reversion down)
else if (close >= upper)
{
SellMarket();
_entryPrice = close;
_cooldown = 5;
}
}
}
}
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 BollingerBands
from StockSharp.Algo.Strategies import Strategy
class scalp_wiz9001_strategy(Strategy):
def __init__(self):
super(scalp_wiz9001_strategy, self).__init__()
self._bands_period = self.Param("BandsPeriod", 20) \
.SetDisplay("Bands Period", "Bollinger Bands period", "Indicator")
self._bands_deviation = self.Param("BandsDeviation", 1.5) \
.SetDisplay("Bands Deviation", "Bollinger Bands deviation", "Indicator")
self._stop_loss_pips = self.Param("StopLossPips", 100) \
.SetDisplay("Stop Loss", "Stop-loss distance in price steps", "Risk")
self._take_profit_pips = self.Param("TakeProfitPips", 150) \
.SetDisplay("Take Profit", "Take-profit distance in price steps", "Risk")
self._bollinger = None
self._entry_price = 0.0
self._cooldown = 0
@property
def bands_period(self):
return self._bands_period.Value
@property
def bands_deviation(self):
return self._bands_deviation.Value
@property
def stop_loss_pips(self):
return self._stop_loss_pips.Value
@property
def take_profit_pips(self):
return self._take_profit_pips.Value
def OnReseted(self):
super(scalp_wiz9001_strategy, self).OnReseted()
self._bollinger = None
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(scalp_wiz9001_strategy, self).OnStarted2(time)
self._bollinger = BollingerBands()
self._bollinger.Length = self.bands_period
self._bollinger.Width = self.bands_deviation
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.BindEx(self._bollinger, self._process_candle).Start()
def _process_candle(self, candle, bb_value):
if candle.State != CandleStates.Finished:
return
upper = bb_value.UpBand
lower = bb_value.LowBand
if upper is None or lower is None:
return
if not self._bollinger.IsFormed:
return
if self._cooldown > 0:
self._cooldown -= 1
return
close = float(candle.ClosePrice)
upper_val = float(upper)
lower_val = float(lower)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
sl_pips = self.stop_loss_pips
tp_pips = self.take_profit_pips
# Check SL/TP for existing long position
if self.Position > 0 and self._entry_price > 0:
if sl_pips > 0 and close <= self._entry_price - sl_pips * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 5
return
if tp_pips > 0 and close >= self._entry_price + tp_pips * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 5
return
elif self.Position < 0 and self._entry_price > 0:
if sl_pips > 0 and close >= self._entry_price + sl_pips * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 5
return
if tp_pips > 0 and close <= self._entry_price - tp_pips * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 5
return
# Entry signals
if self.Position == 0:
if close <= lower_val:
self.BuyMarket()
self._entry_price = close
self._cooldown = 5
elif close >= upper_val:
self.SellMarket()
self._entry_price = close
self._cooldown = 5
def CreateClone(self):
return scalp_wiz9001_strategy()