MartinGale Scalping 策略
当 SMA(3) 与 SMA(8) 交叉时进入仓位,并采用马丁格尔方式加仓,直到触发止损或止盈。
细节
- 入场条件:
SMA3高于SMA8做多,低于则做空;信号持续时每根K线加仓。 - 多空:通过
TradingMode设置。 - 出场条件:价格达到
TakeProfit或StopLoss且 SMA 关系反转。 - 止损:是,基于慢速 SMA。
- 默认值:
FastLength= 3SlowLength= 8TakeProfit= 1.03StopLoss= 0.95TradingMode= LongCandleType= 5 分钟MaxPyramids= 5
- 过滤器:
- 类别: Trend
- 方向: 可配置
- 指标: SMA
- 止损: 是
- 复杂度: 初级
- 时间框架: 日内
- 季节性: 否
- 神经网络: 否
- 背离: 否
- 风险等级: 高
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// MartinGale scalping strategy based on SMA cross with pyramiding entries.
/// </summary>
public class MartinGaleScalpingStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<decimal> _takeProfit;
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<string> _tradeDirection;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _maxPyramids;
private decimal _stopPrice;
private decimal _takePrice;
private decimal _prevSlow;
private int _pyramids;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public decimal TakeProfit { get => _takeProfit.Value; set => _takeProfit.Value = value; }
public decimal StopLoss { get => _stopLoss.Value; set => _stopLoss.Value = value; }
public string TradeDirection { get => _tradeDirection.Value; set => _tradeDirection.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int MaxPyramids { get => _maxPyramids.Value; set => _maxPyramids.Value = value; }
public MartinGaleScalpingStrategy()
{
_fastLength = Param(nameof(FastLength), 10)
.SetGreaterThanZero()
.SetDisplay("Fast SMA Length", "Length for fast SMA", "General");
_slowLength = Param(nameof(SlowLength), 20)
.SetGreaterThanZero()
.SetDisplay("Slow SMA Length", "Length for slow SMA", "General");
_takeProfit = Param(nameof(TakeProfit), 1.03m)
.SetGreaterThanZero()
.SetDisplay("Take Profit Mult", "Take profit multiplier", "Risk");
_stopLoss = Param(nameof(StopLoss), 0.95m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss Mult", "Stop loss multiplier", "Risk");
_tradeDirection = Param(nameof(TradeDirection), "Long")
.SetDisplay("Trade Direction", "Trade direction", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for candles", "General");
_maxPyramids = Param(nameof(MaxPyramids), 2)
.SetGreaterThanZero()
.SetDisplay("Max Pyramids", "Maximum pyramid entries", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_stopPrice = 0m;
_takePrice = 0m;
_prevSlow = 0m;
_pyramids = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastSma = new SimpleMovingAverage { Length = FastLength };
var slowSma = new SimpleMovingAverage { Length = SlowLength };
_stopPrice = 0m;
_takePrice = 0m;
_prevSlow = 0m;
_pyramids = 0;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(fastSma, slowSma, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastSma);
DrawIndicator(area, slowSma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
var crossover = fast > slow;
var crossunder = fast < slow;
if (Position == 0)
{
_pyramids = 0;
if (crossover && AllowLong())
EnterLong(candle, slow);
else if (crossunder && AllowShort())
EnterShort(candle, slow);
}
else if (Position > 0)
{
if ((candle.ClosePrice > _takePrice || candle.ClosePrice < _stopPrice) && crossunder)
{
SellMarket();
ResetLevels();
}
else if (crossover && AllowLong() && _pyramids < MaxPyramids)
{
BuyMarket();
_pyramids++;
UpdateLevels(candle, slow);
}
}
else if (Position < 0)
{
if ((candle.ClosePrice > _takePrice || candle.ClosePrice < _stopPrice) && crossover)
{
BuyMarket();
ResetLevels();
}
else if (crossunder && AllowShort() && _pyramids < MaxPyramids)
{
SellMarket();
_pyramids++;
UpdateLevels(candle, slow);
}
}
_prevSlow = slow;
}
private void EnterLong(ICandleMessage candle, decimal slow)
{
BuyMarket();
_pyramids = 1;
UpdateLevels(candle, slow);
}
private void EnterShort(ICandleMessage candle, decimal slow)
{
SellMarket();
_pyramids = 1;
UpdateLevels(candle, slow);
}
private void UpdateLevels(ICandleMessage candle, decimal slow)
{
if (_prevSlow == 0m)
return;
_stopPrice = Position > 0
? candle.ClosePrice - StopLoss * _prevSlow
: candle.ClosePrice + StopLoss * _prevSlow;
_takePrice = Position > 0
? candle.ClosePrice + TakeProfit * _prevSlow
: candle.ClosePrice - TakeProfit * _prevSlow;
}
private void ResetLevels()
{
_stopPrice = 0m;
_takePrice = 0m;
}
private bool AllowLong() => TradeDirection != "Short";
private bool AllowShort() => TradeDirection != "Long";
}
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 SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class martin_gale_scalping_strategy(Strategy):
def __init__(self):
super(martin_gale_scalping_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 10) \
.SetDisplay("Fast SMA Length", "Length for fast SMA", "General")
self._slow_length = self.Param("SlowLength", 20) \
.SetDisplay("Slow SMA Length", "Length for slow SMA", "General")
self._take_profit = self.Param("TakeProfit", 1.03) \
.SetDisplay("Take Profit Mult", "Take profit multiplier", "Risk")
self._stop_loss = self.Param("StopLoss", 0.95) \
.SetDisplay("Stop Loss Mult", "Stop loss multiplier", "Risk")
self._trade_direction = self.Param("TradeDirection", "Long") \
.SetDisplay("Trade Direction", "Trade direction", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Timeframe for candles", "General")
self._max_pyramids = self.Param("MaxPyramids", 2) \
.SetDisplay("Max Pyramids", "Maximum pyramid entries", "General")
self._stop_price = 0.0
self._take_price = 0.0
self._prev_slow = 0.0
self._pyramids = 0
@property
def fast_length(self):
return self._fast_length.Value
@property
def slow_length(self):
return self._slow_length.Value
@property
def take_profit(self):
return self._take_profit.Value
@property
def stop_loss(self):
return self._stop_loss.Value
@property
def trade_direction(self):
return self._trade_direction.Value
@property
def candle_type(self):
return self._candle_type.Value
@property
def max_pyramids(self):
return self._max_pyramids.Value
def OnReseted(self):
super(martin_gale_scalping_strategy, self).OnReseted()
self._stop_price = 0.0
self._take_price = 0.0
self._prev_slow = 0.0
self._pyramids = 0
def OnStarted2(self, time):
super(martin_gale_scalping_strategy, self).OnStarted2(time)
fast_sma = SimpleMovingAverage()
fast_sma.Length = self.fast_length
slow_sma = SimpleMovingAverage()
slow_sma.Length = self.slow_length
self._stop_price = 0.0
self._take_price = 0.0
self._prev_slow = 0.0
self._pyramids = 0
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_sma, slow_sma, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_sma)
self.DrawIndicator(area, slow_sma)
self.DrawOwnTrades(area)
def on_process(self, candle, fast, slow):
if candle.State != CandleStates.Finished:
return
crossover = fast > slow
crossunder = fast < slow
if self.Position == 0:
self._pyramids = 0
if crossover and self._allow_long():
self._enter_long(candle, slow)
elif crossunder and self._allow_short():
self._enter_short(candle, slow)
elif self.Position > 0:
if (candle.ClosePrice > self._take_price or candle.ClosePrice < self._stop_price) and crossunder:
self.SellMarket()
self._reset_levels()
elif crossover and self._allow_long() and self._pyramids < self.max_pyramids:
self.BuyMarket()
self._pyramids += 1
self._update_levels(candle, slow)
elif self.Position < 0:
if (candle.ClosePrice > self._take_price or candle.ClosePrice < self._stop_price) and crossover:
self.BuyMarket()
self._reset_levels()
elif crossunder and self._allow_short() and self._pyramids < self.max_pyramids:
self.SellMarket()
self._pyramids += 1
self._update_levels(candle, slow)
self._prev_slow = slow
def _enter_long(self, candle, slow):
self.BuyMarket()
self._pyramids = 1
self._update_levels(candle, slow)
def _enter_short(self, candle, slow):
self.SellMarket()
self._pyramids = 1
self._update_levels(candle, slow)
def _update_levels(self, candle, slow):
if self._prev_slow == 0:
return
if self.Position > 0:
self._stop_price = float(candle.ClosePrice) - self.stop_loss * self._prev_slow
self._take_price = float(candle.ClosePrice) + self.take_profit * self._prev_slow
else:
self._stop_price = float(candle.ClosePrice) + self.stop_loss * self._prev_slow
self._take_price = float(candle.ClosePrice) - self.take_profit * self._prev_slow
def _reset_levels(self):
self._stop_price = 0.0
self._take_price = 0.0
def _allow_long(self):
return self.trade_direction != "Short"
def _allow_short(self):
return self.trade_direction != "Long"
def CreateClone(self):
return martin_gale_scalping_strategy()