Twenty Pips Price Channel 策略
概述
Twenty Pips Price Channel 策略源自 MetaTrader 平台的 20 pips 智能交易程序,结合了类似唐奇安通道的价格通道与简单移动平均线过滤。策略寻找当前 K 线开盘价与上一根方向相反的情况,通过典型价均线确认趋势方向,并使用 20 点固定止盈加通道式移动止损来管理仓位。
在移植到 StockSharp 时,核心思路保持不变,同时按照高阶 API 改写了下单逻辑。开仓和平仓均通过市价委托完成,止盈在策略内部监控,而原有的 OrderModify 被通道条件和价格偏移的止损更新所替代。
交易逻辑
指标体系
- 1 周期的简单移动平均线计算典型价 (High + Low + Close)/3,相当于上一根 K 线的典型价。
- 可配置的慢速简单移动平均线(默认 20)计算收盘价,对应原始 EA 中的
MA_Low过滤条件。 - 最高价和最低价指标(长度与通道周期一致)重建自定义 Price Channel 指标的上下边界。
入场条件
- 做多:上一根快速均线值高于慢速均线,并且当前 K 线开盘价低于上一根开盘价。若上一笔交易亏损,则把开仓量乘以恢复系数(默认 2)。入场价会被记录用于盈亏评估。
- 做空:上一根快速均线值低于慢速均线,并且当前 K 线开盘价高于上一根开盘价。恢复系数同样适用。
仓位管理
- 开仓时即设定固定止盈,距离为
TakeProfitPips乘以合约的价格步长。 - 通道移动止损模拟原 EA 的
OrderModify:如果上一根 K 线的极值突破了通道(为了复现 MT4 中shift = 2的调用,这里使用两根 K 线的位移),则把保护价调整到前一极值加/减TrailingOffsetPips。若下一根 K 线跳空穿越该极值,立即按开盘价平仓。 - 止盈、移动止损以及跳空退出均通过市价单执行,并记录实际离场价格,用于更新“上一笔是否亏损”的标记,从而驱动马丁倍数逻辑。
- 开仓时即设定固定止盈,距离为
马丁复原
- 每当一笔交易亏损,下一次开仓量会乘以
RecoveryMultiplier。盈利交易会把标记清零,恢复到基础手数。
- 每当一笔交易亏损,下一次开仓量会乘以
参数
| 参数 | 说明 | 默认值 |
|---|---|---|
CandleType |
主图使用的 K 线类型。 | 1 小时 K 线 |
ChannelPeriod |
价格通道回溯周期。 | 20 |
SlowMaPeriod |
慢速均线周期。 | 20 |
TakeProfitPips |
固定止盈的点数距离。 | 20 |
TrailingOffsetPips |
移动止损的点数偏移。 | 10 |
RecoveryMultiplier |
亏损后加倍的系数。 | 2 |
Volume |
基础交易量。 | 0.1 |
使用建议
- 策略假设
Security.PriceStep等同于品种的 1 个点大小,如与实际点值不同请调节TakeProfitPips与TrailingOffsetPips。 - 因为平仓使用市价单,回测时可能出现与 MT4 止损/止盈订单不同的滑点,但触发价格保持一致。
- 通道值向前平移两根 K 线,以匹配原脚本
iCustom中的shift = 2行为。 - 将
RecoveryMultiplier设为 1 即可关闭马丁复原机制。
using System;
using System.Linq;
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>
/// Converted "20 pips" price channel strategy.
/// Uses Donchian channel breakouts with MA filter, trailing stop, and recovery multiplier.
/// </summary>
public class TwentyPipsPriceChannelStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _channelPeriod;
private readonly StrategyParam<int> _slowMaPeriod;
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<decimal> _takeProfit;
private readonly List<decimal> _highs = new();
private readonly List<decimal> _lows = new();
private decimal? _prevChannelUpper;
private decimal? _prevChannelLower;
/// <summary>
/// Candle type to process.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Donchian channel lookback period.
/// </summary>
public int ChannelPeriod
{
get => _channelPeriod.Value;
set => _channelPeriod.Value = value;
}
/// <summary>
/// Slow moving average length.
/// </summary>
public int SlowMaPeriod
{
get => _slowMaPeriod.Value;
set => _slowMaPeriod.Value = value;
}
/// <summary>
/// Stop loss distance in absolute price units.
/// </summary>
public decimal StopLoss
{
get => _stopLoss.Value;
set => _stopLoss.Value = value;
}
/// <summary>
/// Take profit distance in absolute price units.
/// </summary>
public decimal TakeProfit
{
get => _takeProfit.Value;
set => _takeProfit.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="TwentyPipsPriceChannelStrategy"/>.
/// </summary>
public TwentyPipsPriceChannelStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Primary candle type", "General");
_channelPeriod = Param(nameof(ChannelPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Channel Period", "Donchian channel lookback", "Parameters");
_slowMaPeriod = Param(nameof(SlowMaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Slow MA Period", "Slow moving average length", "Parameters");
_stopLoss = Param(nameof(StopLoss), 500m)
.SetNotNegative()
.SetDisplay("Stop Loss", "Stop loss distance", "Risk");
_takeProfit = Param(nameof(TakeProfit), 500m)
.SetNotNegative()
.SetDisplay("Take Profit", "Take profit distance", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return new[] { (Security, CandleType) };
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_highs.Clear();
_lows.Clear();
_prevChannelUpper = null;
_prevChannelLower = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
var slowMa = new SMA { Length = SlowMaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(slowMa, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, slowMa);
DrawOwnTrades(area);
}
// Use StartProtection for SL/TP
var tp = TakeProfit > 0 ? new Unit(TakeProfit, UnitTypes.Absolute) : null;
var sl = StopLoss > 0 ? new Unit(StopLoss, UnitTypes.Absolute) : null;
StartProtection(tp, sl);
base.OnStarted2(time);
}
private void ProcessCandle(ICandleMessage candle, decimal slowMaValue)
{
if (candle.State != CandleStates.Finished)
return;
// Track highs and lows for manual Donchian channel
_highs.Add(candle.HighPrice);
_lows.Add(candle.LowPrice);
while (_highs.Count > ChannelPeriod)
_highs.RemoveAt(0);
while (_lows.Count > ChannelPeriod)
_lows.RemoveAt(0);
if (_highs.Count < ChannelPeriod)
{
_prevChannelUpper = null;
_prevChannelLower = null;
return;
}
var channelUpper = _highs.Max();
var channelLower = _lows.Min();
if (!IsFormedAndOnlineAndAllowTrading())
{
_prevChannelUpper = channelUpper;
_prevChannelLower = channelLower;
return;
}
// Channel breakout with MA filter
if (_prevChannelUpper.HasValue && _prevChannelLower.HasValue)
{
// Breakout above the previous channel high -> buy signal
if (candle.ClosePrice > _prevChannelUpper.Value && candle.ClosePrice > slowMaValue && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
}
// Breakout below the previous channel low -> sell signal
else if (candle.ClosePrice < _prevChannelLower.Value && candle.ClosePrice < slowMaValue && Position >= 0)
{
if (Position > 0)
SellMarket(Position);
SellMarket(Volume);
}
}
_prevChannelUpper = channelUpper;
_prevChannelLower = channelLower;
}
}
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, UnitTypes, Unit
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class twenty_pips_price_channel_strategy(Strategy):
"""Donchian channel breakout with SMA filter and StartProtection SL/TP."""
def __init__(self):
super(twenty_pips_price_channel_strategy, self).__init__()
self._channel_period = self.Param("ChannelPeriod", 20).SetGreaterThanZero().SetDisplay("Channel Period", "Donchian channel lookback", "Parameters")
self._slow_ma_period = self.Param("SlowMaPeriod", 20).SetGreaterThanZero().SetDisplay("Slow MA Period", "Slow MA length", "Parameters")
self._sl = self.Param("StopLoss", 500).SetNotNegative().SetDisplay("Stop Loss", "SL distance", "Risk")
self._tp = self.Param("TakeProfit", 500).SetNotNegative().SetDisplay("Take Profit", "TP distance", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Timeframe", "General")
@property
def CandleType(self): return self._candle_type.Value
@CandleType.setter
def CandleType(self, value): self._candle_type.Value = value
def OnReseted(self):
super(twenty_pips_price_channel_strategy, self).OnReseted()
self._highs = []
self._lows = []
self._prev_upper = None
self._prev_lower = None
def OnStarted2(self, time):
super(twenty_pips_price_channel_strategy, self).OnStarted2(time)
self._highs = []
self._lows = []
self._prev_upper = None
self._prev_lower = None
slow_ma = SimpleMovingAverage()
slow_ma.Length = self._slow_ma_period.Value
sub = self.SubscribeCandles(self.CandleType)
sub.Bind(slow_ma, self.OnProcess).Start()
sl_val = float(self._sl.Value)
tp_val = float(self._tp.Value)
tp = Unit(tp_val, UnitTypes.Absolute) if tp_val > 0 else None
sl = Unit(sl_val, UnitTypes.Absolute) if sl_val > 0 else None
self.StartProtection(tp, sl)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, sub)
self.DrawIndicator(area, slow_ma)
self.DrawOwnTrades(area)
def OnProcess(self, candle, slow_ma_val):
if candle.State != CandleStates.Finished:
return
high = float(candle.HighPrice)
low = float(candle.LowPrice)
close = float(candle.ClosePrice)
ma_val = float(slow_ma_val)
period = self._channel_period.Value
self._highs.append(high)
self._lows.append(low)
while len(self._highs) > period:
self._highs.pop(0)
while len(self._lows) > period:
self._lows.pop(0)
if len(self._highs) < period:
self._prev_upper = None
self._prev_lower = None
return
ch_upper = max(self._highs)
ch_lower = min(self._lows)
if self._prev_upper is not None and self._prev_lower is not None and self.IsFormedAndOnlineAndAllowTrading():
if close > self._prev_upper and close > ma_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(abs(self.Position))
self.BuyMarket(self.Volume)
elif close < self._prev_lower and close < ma_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket(self.Position)
self.SellMarket(self.Volume)
self._prev_upper = ch_upper
self._prev_lower = ch_lower
def CreateClone(self):
return twenty_pips_price_channel_strategy()