在 GitHub 上查看
ScalpWiz 9001 策略
概述
ScalpWiz 9001 是一个多层次的突破反转系统,移植自同名 MetaTrader 专家顾问。策略会评估最新 K 线的收盘价相对布林带边界的突破幅度,当出现剧烈扩张时,会在价格上下方布置多笔挂单。原版的资金管理方案得以保留:每一层挂单既可以使用固定手数,也可以按照账户权益的百分比计算风险。
当某笔挂单成交后,其余挂单立即取消,同时持仓由止损、止盈以及带缓冲区的跟踪止损保护。该策略主要用于低周期的高频交易,但在 StockSharp 支持的任何市场上都可以运行。
信号逻辑
- 订阅指定的时间框架,并以
BandsPeriod(默认 20)和 BandsDeviation(默认 2)计算布林带。
- 判断收盘价相对布林带上下轨的突破距离。当突破幅度达到第 4 层距离
Level3Pips(折算为价格)时,策略准备进行反向挂单:
- 收盘高于上轨 → 在价格下方布置卖出止损挂单。
- 收盘低于下轨 → 在价格上方布置买入止损挂单。
- 共放置四笔挂单,使用
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 – 各层挂单的价格偏移(点)。
资金管理
在 RiskPercent 模式下,策略根据账户权益和止损距离计算下单手数:
手数 = (equity × riskPercent / 100) / (stopOffset / priceStep × stepPrice)
若市场数据缺少价格步长、步长价值或成交量步长,为避免异常下单,策略会将手数设为 0。选择 FixedVolume 模式时,直接使用配置的手数并按照成交量步长进行舍入。
持仓管理
- 止损与止盈价格均基于实际成交价加减点数距离计算。
- 跟踪止损完全遵循原始 EA 的实现:只有当价格额外运行一个缓冲距离后,才会把保护价移动到新的位置。
- 退出操作使用市价单执行,因此即使交易所不支持服务器端止损/止盈也可以工作。
使用建议
- 请根据交易品种的最小价格步长设定
LevelXPips,对于五位报价的外汇品种,一个点等于十个最小步长,策略会根据小数位数自动调整。
- 某些经纪商限制挂单到现价的最小距离,如有需要请增大挂单距离或有效期。
- 风险百分比模式需要有效的账户估值以及价格步长信息,否则无法计算手数。
- 策略只在 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>
/// 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()