Escape 策略
该策略基于蜡烛开盘价的简单移动平均线进行交易。它比较最近完成的 5 分钟收盘价与两个开盘价的移动平均:
- 快速 SMA(4 周期) – 用于判断做空信号。
- 慢速 SMA(5 周期) – 用于判断做多信号。
工作原理
- 每当一根 5 分钟蜡烛收盘时,策略更新基于开盘价的两条 SMA。
- 如果当前没有持仓:
- 当最新收盘价低于慢速 SMA 时开多。
- 当最新收盘价高于快速 SMA 时开空。
- 入场后设置固定的止损和止盈(价格单位)。
- 当价格触及止盈或止损时平仓。
该策略使用 StockSharp 高级 API,主要用于示例说明。
参数
| 名称 | 说明 | 默认值 |
|---|---|---|
FastLength |
快速 SMA 的周期。 | 4 |
SlowLength |
慢速 SMA 的周期。 | 5 |
TakeProfitLong |
多头止盈距离(价格单位)。 | 25 |
TakeProfitShort |
空头止盈距离(价格单位)。 | 26 |
StopLossLong |
多头止损距离(价格单位)。 | 25 |
StopLossShort |
空头止损距离(价格单位)。 | 3 |
CandleType |
使用的蜡烛类型。 | TimeFrame(5m) |
所有参数均可在 StockSharp 优化器中进行优化。
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>
/// Simple strategy based on SMA of open prices and previous close comparison.
/// Buys when the previous close is below the slow SMA.
/// Sells short when the previous close is above the fast SMA.
/// Uses fixed take profit and stop loss levels for both directions.
/// </summary>
public class EscapeStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<decimal> _takeProfitLong;
private readonly StrategyParam<decimal> _takeProfitShort;
private readonly StrategyParam<decimal> _stopLossLong;
private readonly StrategyParam<decimal> _stopLossShort;
private readonly StrategyParam<DataType> _candleType;
private SimpleMovingAverage _fastMa;
private SimpleMovingAverage _slowMa;
private bool _initialized;
private decimal _previousClose;
private decimal _previousFast;
private decimal _previousSlow;
/// <summary>
/// Length of fast SMA.
/// </summary>
public int FastLength
{
get => _fastLength.Value;
set => _fastLength.Value = value;
}
/// <summary>
/// Length of slow SMA.
/// </summary>
public int SlowLength
{
get => _slowLength.Value;
set => _slowLength.Value = value;
}
/// <summary>
/// Take profit distance for long positions in price units.
/// </summary>
public decimal TakeProfitLong
{
get => _takeProfitLong.Value;
set => _takeProfitLong.Value = value;
}
/// <summary>
/// Take profit distance for short positions in price units.
/// </summary>
public decimal TakeProfitShort
{
get => _takeProfitShort.Value;
set => _takeProfitShort.Value = value;
}
/// <summary>
/// Stop loss distance for long positions in price units.
/// </summary>
public decimal StopLossLong
{
get => _stopLossLong.Value;
set => _stopLossLong.Value = value;
}
/// <summary>
/// Stop loss distance for short positions in price units.
/// </summary>
public decimal StopLossShort
{
get => _stopLossShort.Value;
set => _stopLossShort.Value = value;
}
/// <summary>
/// Candle type to analyze.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public EscapeStrategy()
{
_fastLength = Param(nameof(FastLength), 4)
.SetDisplay("Fast SMA Length", "Length of fast SMA", "Parameters")
.SetGreaterThanZero()
;
_slowLength = Param(nameof(SlowLength), 5)
.SetDisplay("Slow SMA Length", "Length of slow SMA", "Parameters")
.SetGreaterThanZero()
;
_takeProfitLong = Param(nameof(TakeProfitLong), 25m)
.SetDisplay("Take Profit Long", "Take profit for long trades", "Trading")
.SetGreaterThanZero();
_takeProfitShort = Param(nameof(TakeProfitShort), 26m)
.SetDisplay("Take Profit Short", "Take profit for short trades", "Trading")
.SetGreaterThanZero();
_stopLossLong = Param(nameof(StopLossLong), 25m)
.SetDisplay("Stop Loss Long", "Stop loss for long trades", "Trading")
.SetGreaterThanZero();
_stopLossShort = Param(nameof(StopLossShort), 3m)
.SetDisplay("Stop Loss Short", "Stop loss for short trades", "Trading")
.SetGreaterThanZero();
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_fastMa = null;
_slowMa = null;
_initialized = false;
_previousClose = 0m;
_previousFast = 0m;
_previousSlow = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fastMa = new SMA { Length = FastLength };
_slowMa = new SMA { Length = SlowLength };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _fastMa);
DrawIndicator(area, _slowMa);
DrawOwnTrades(area);
}
StartProtection(
takeProfit: new Unit(2, UnitTypes.Percent),
stopLoss: new Unit(1, UnitTypes.Percent)
);
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var fast = _fastMa!.Process(new DecimalIndicatorValue(_fastMa, candle.OpenPrice, candle.OpenTime) { IsFinal = true }).ToDecimal();
var slow = _slowMa!.Process(new DecimalIndicatorValue(_slowMa, candle.OpenPrice, candle.OpenTime) { IsFinal = true }).ToDecimal();
if (!_initialized)
{
_initialized = true;
_previousClose = candle.ClosePrice;
_previousFast = fast;
_previousSlow = slow;
return;
}
var close = candle.ClosePrice;
var buySignal = _previousClose >= _previousSlow && close < slow;
var sellSignal = _previousClose <= _previousFast && close > fast;
if (Position == 0)
{
if (buySignal)
BuyMarket();
else if (sellSignal)
SellMarket();
}
_previousClose = close;
_previousFast = fast;
_previousSlow = slow;
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class escape_strategy(Strategy):
def __init__(self):
super(escape_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 4)
self._slow_length = self.Param("SlowLength", 5)
self._take_profit_long = self.Param("TakeProfitLong", 25.0)
self._take_profit_short = self.Param("TakeProfitShort", 26.0)
self._stop_loss_long = self.Param("StopLossLong", 25.0)
self._stop_loss_short = self.Param("StopLossShort", 3.0)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._fast_ma = None
self._slow_ma = None
self._initialized = False
self._entry_price = 0.0
self._stop_price = 0.0
self._take_price = 0.0
self._previous_close = 0.0
self._previous_fast = 0.0
self._previous_slow = 0.0
@property
def FastLength(self):
return self._fast_length.Value
@FastLength.setter
def FastLength(self, value):
self._fast_length.Value = value
@property
def SlowLength(self):
return self._slow_length.Value
@SlowLength.setter
def SlowLength(self, value):
self._slow_length.Value = value
@property
def TakeProfitLong(self):
return self._take_profit_long.Value
@TakeProfitLong.setter
def TakeProfitLong(self, value):
self._take_profit_long.Value = value
@property
def TakeProfitShort(self):
return self._take_profit_short.Value
@TakeProfitShort.setter
def TakeProfitShort(self, value):
self._take_profit_short.Value = value
@property
def StopLossLong(self):
return self._stop_loss_long.Value
@StopLossLong.setter
def StopLossLong(self, value):
self._stop_loss_long.Value = value
@property
def StopLossShort(self):
return self._stop_loss_short.Value
@StopLossShort.setter
def StopLossShort(self, value):
self._stop_loss_short.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(escape_strategy, self).OnStarted2(time)
self._initialized = False
self._entry_price = 0.0
self._stop_price = 0.0
self._take_price = 0.0
self._previous_close = 0.0
self._previous_fast = 0.0
self._previous_slow = 0.0
self._fast_ma = SimpleMovingAverage()
self._fast_ma.Length = self.FastLength
self._slow_ma = SimpleMovingAverage()
self._slow_ma.Length = self.SlowLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self.ProcessCandle).Start()
self.StartProtection(
Unit(2.0, UnitTypes.Percent),
Unit(1.0, UnitTypes.Percent))
def ProcessCandle(self, candle):
if candle.State != CandleStates.Finished:
return
t = candle.OpenTime
fast_result = process_float(self._fast_ma, candle.OpenPrice, t, True)
slow_result = process_float(self._slow_ma, candle.OpenPrice, t, True)
if not self._fast_ma.IsFormed or not self._slow_ma.IsFormed:
return
fast = float(fast_result)
slow = float(slow_result)
if not self._initialized:
self._initialized = True
self._previous_close = float(candle.ClosePrice)
self._previous_fast = fast
self._previous_slow = slow
return
close = float(candle.ClosePrice)
buy_signal = self._previous_close >= self._previous_slow and close < slow
sell_signal = self._previous_close <= self._previous_fast and close > fast
if self.Position == 0:
if buy_signal:
self.BuyMarket()
elif sell_signal:
self.SellMarket()
self._previous_close = close
self._previous_fast = fast
self._previous_slow = slow
def OnReseted(self):
super(escape_strategy, self).OnReseted()
self._fast_ma = None
self._slow_ma = None
self._initialized = False
self._entry_price = 0.0
self._stop_price = 0.0
self._take_price = 0.0
self._previous_close = 0.0
self._previous_fast = 0.0
self._previous_slow = 0.0
def CreateClone(self):
return escape_strategy()