三层网格策略
该策略实现一个对称的网格交易系统,可设置多达三层获利等级。 在当前价格上下按照固定间距挂出限价单,当入场单成交后,会在 预设的获利价格挂出反向限价单以锁定利润。策略适用于价格在区间 内震荡的市场环境。
参数
Grid Size– 相邻网格之间的价格间距。Levels– 每一侧的网格层数。Base Take Profit– 第一获利等级的基础利润距离。Order Volume– 每个网格订单的数量。Enable Rank1– 启用基础获利等级。Enable Rank2– 启用基础加一倍网格间距的获利等级。Enable Rank3– 启用基础加两倍网格间距的获利等级。Allow Longs– 允许做多一侧的网格。Allow Shorts– 允许做空一侧的网格。Candle Type– 用于确定初始参考价格的蜡烛类型。
交易逻辑
- 策略启动后订阅蜡烛并等待第一根完成的蜡烛。
- 使用该蜡烛的收盘价构建具有指定层数的网格。
- 根据允许的方向在各层挂出买入和/或卖出限价单。
- 入场单成交后,根据选择的获利等级计算价格并挂出反向限价单。
- 订单保持在市场中直至成交或被人工取消。
该实现是对原始 MQL 网格系统的简化转换,展示了在 StockSharp 高层 API 中实现核心机制的方法。
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>
/// Three-level grid strategy using EMA as center line.
/// Buys on dips below EMA at different levels, sells on rises above EMA.
/// </summary>
public class ThreeLevelGridStrategy : Strategy
{
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<DataType> _candleType;
public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ThreeLevelGridStrategy()
{
_emaLength = Param(nameof(EmaLength), 30)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA period for center line", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaLength };
var atr = new StandardDeviation { Length = 14 };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ema, atr, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal emaVal, decimal atrVal)
{
if (candle.State != CandleStates.Finished)
return;
if (atrVal <= 0)
return;
var close = candle.ClosePrice;
var diff = close - emaVal;
// Buy at different grid levels below EMA
if (diff < -1.5m * atrVal && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Sell at different grid levels above EMA
else if (diff > 1.5m * atrVal && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
// Mean reversion exit
else if (Position > 0 && close > emaVal + 0.5m * atrVal)
{
SellMarket();
}
else if (Position < 0 && close < emaVal - 0.5m * atrVal)
{
BuyMarket();
}
}
}
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 ExponentialMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class three_level_grid_strategy(Strategy):
def __init__(self):
super(three_level_grid_strategy, self).__init__()
self._ema_length = self.Param("EmaLength", 30) \
.SetDisplay("EMA Length", "EMA period for center line", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
@property
def ema_length(self):
return self._ema_length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(three_level_grid_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self.ema_length
atr = StandardDeviation()
atr.Length = 14
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, atr, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, ema_val, atr_val):
if candle.State != CandleStates.Finished:
return
if atr_val <= 0:
return
close = candle.ClosePrice
diff = close - ema_val
# Buy at different grid levels below EMA
if diff < -1.5 * atr_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Sell at different grid levels above EMA
elif diff > 1.5 * atr_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
# Mean reversion exit
elif self.Position > 0 and close > ema_val + 0.5 * atr_val:
self.SellMarket()
elif self.Position < 0 and close < ema_val - 0.5 * atr_val:
self.BuyMarket()
def CreateClone(self):
return three_level_grid_strategy()