Larry Connors 3 Day High Low Strategy
实现 Larry Connors 的“三日高低”均值回归策略。
逻辑
- 满足以下条件时买入:
- 收盘价高于长期SMA;
- 收盘价低于短期SMA;
- 最近三根K线的高点和低点连续下降。
- 当收盘价再次上穿短期SMA时平仓。
参数
- Long MA Length —— 长期SMA周期(默认200)
- Short MA Length —— 短期SMA周期(默认5)
- Candle Type —— 使用的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>
/// Larry Connors 3 Day High/Low strategy.
/// Buys after three consecutive lower highs and lows below a short moving average while price is above a long moving average.
/// Exits when price crosses above the short moving average.
/// </summary>
public class LarryConnors3DayHighLowStrategy : Strategy
{
private readonly StrategyParam<int> _longMaLength;
private readonly StrategyParam<int> _shortMaLength;
private readonly StrategyParam<int> _maxEntries;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
private SMA _longSma;
private SMA _shortSma;
private int _barCount;
private decimal _high1;
private decimal _high2;
private decimal _high3;
private decimal _low1;
private decimal _low2;
private decimal _low3;
private int _entriesExecuted;
private int _barsSinceSignal;
/// <summary>
/// Long moving average period.
/// </summary>
public int LongMaLength
{
get => _longMaLength.Value;
set => _longMaLength.Value = value;
}
/// <summary>
/// Short moving average period.
/// </summary>
public int ShortMaLength
{
get => _shortMaLength.Value;
set => _shortMaLength.Value = value;
}
/// <summary>
/// Type of candles to use.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Maximum entries per run.
/// </summary>
public int MaxEntries
{
get => _maxEntries.Value;
set => _maxEntries.Value = value;
}
/// <summary>
/// Minimum bars between orders.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Initializes a new instance of the strategy.
/// </summary>
public LarryConnors3DayHighLowStrategy()
{
_longMaLength = Param(nameof(LongMaLength), 50)
.SetGreaterThanZero()
.SetDisplay("Long MA Length", "Period of the long moving average", "General")
.SetOptimize(20, 100, 10);
_shortMaLength = Param(nameof(ShortMaLength), 5)
.SetGreaterThanZero()
.SetDisplay("Short MA Length", "Period of the short moving average", "General")
.SetOptimize(3, 10, 1);
_maxEntries = Param(nameof(MaxEntries), 35)
.SetGreaterThanZero()
.SetDisplay("Max Entries", "Maximum entries per run", "Risk");
_cooldownBars = Param(nameof(CooldownBars), 15)
.SetGreaterThanZero()
.SetDisplay("Cooldown Bars", "Minimum bars between orders", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_longSma = null;
_shortSma = null;
_barCount = 0;
_high1 = _high2 = _high3 = 0m;
_low1 = _low2 = _low3 = 0m;
_entriesExecuted = 0;
_barsSinceSignal = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_longSma = new SMA { Length = LongMaLength };
_shortSma = new SMA { Length = ShortMaLength };
_entriesExecuted = 0;
_barsSinceSignal = CooldownBars;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_longSma, _shortSma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _longSma);
DrawIndicator(area, _shortSma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal longMa, decimal shortMa)
{
if (candle.State != CandleStates.Finished)
return;
_barsSinceSignal++;
if (_longSma.IsFormed && _shortSma.IsFormed && _barCount >= 3)
{
// Exit: close long when price crosses above short MA
if (candle.ClosePrice > shortMa && Position > 0)
{
SellMarket(Math.Abs(Position));
_barsSinceSignal = 0;
}
// Entry: buy after 3 consecutive lower highs/lows, close below short MA, above long MA
else if (_barsSinceSignal >= CooldownBars && Position <= 0 && _entriesExecuted < MaxEntries)
{
var aboveLongMa = candle.ClosePrice > longMa;
var belowShortMa = candle.ClosePrice < shortMa;
var lowerHighsLows3 = _high2 < _high3 && _low2 < _low3;
var lowerHighsLows2 = _high1 < _high2 && _low1 < _low2;
var lowerHighsLows1 = candle.HighPrice < _high1 && candle.LowPrice < _low1;
if (aboveLongMa && belowShortMa && lowerHighsLows3 && lowerHighsLows2 && lowerHighsLows1)
{
BuyMarket(Volume + Math.Abs(Position));
_entriesExecuted++;
_barsSinceSignal = 0;
}
}
}
_barCount++;
_high3 = _high2;
_high2 = _high1;
_high1 = candle.HighPrice;
_low3 = _low2;
_low2 = _low1;
_low1 = candle.LowPrice;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class larry_connors_3_day_high_low_strategy(Strategy):
def __init__(self):
super(larry_connors_3_day_high_low_strategy, self).__init__()
self._long_ma_length = self.Param("LongMaLength", 50) \
.SetGreaterThanZero() \
.SetDisplay("Long MA Length", "Period of the long moving average", "General")
self._short_ma_length = self.Param("ShortMaLength", 5) \
.SetGreaterThanZero() \
.SetDisplay("Short MA Length", "Period of the short moving average", "General")
self._max_entries = self.Param("MaxEntries", 35) \
.SetGreaterThanZero() \
.SetDisplay("Max Entries", "Maximum entries per run", "Risk")
self._cooldown_bars = self.Param("CooldownBars", 15) \
.SetGreaterThanZero() \
.SetDisplay("Cooldown Bars", "Minimum bars between orders", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._bar_count = 0
self._high1 = 0.0
self._high2 = 0.0
self._high3 = 0.0
self._low1 = 0.0
self._low2 = 0.0
self._low3 = 0.0
self._entries_executed = 0
self._bars_since_signal = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(larry_connors_3_day_high_low_strategy, self).OnReseted()
self._bar_count = 0
self._high1 = 0.0
self._high2 = 0.0
self._high3 = 0.0
self._low1 = 0.0
self._low2 = 0.0
self._low3 = 0.0
self._entries_executed = 0
self._bars_since_signal = 0
def OnStarted2(self, time):
super(larry_connors_3_day_high_low_strategy, self).OnStarted2(time)
self._entries_executed = 0
self._bars_since_signal = self._cooldown_bars.Value
self._long_sma = SimpleMovingAverage()
self._long_sma.Length = self._long_ma_length.Value
self._short_sma = SimpleMovingAverage()
self._short_sma.Length = self._short_ma_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._long_sma, self._short_sma, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._long_sma)
self.DrawIndicator(area, self._short_sma)
self.DrawOwnTrades(area)
def OnProcess(self, candle, long_ma_val, short_ma_val):
if candle.State != CandleStates.Finished:
return
self._bars_since_signal += 1
close = float(candle.ClosePrice)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
lma = float(long_ma_val)
sma = float(short_ma_val)
if self._long_sma.IsFormed and self._short_sma.IsFormed and self._bar_count >= 3:
# Exit: close long when price crosses above short MA
if close > sma and self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self._bars_since_signal = 0
# Entry: buy after 3 consecutive lower highs/lows, close below short MA, above long MA
elif self._bars_since_signal >= self._cooldown_bars.Value and self.Position <= 0 and self._entries_executed < self._max_entries.Value:
above_long_ma = close > lma
below_short_ma = close < sma
lower_highs_lows_3 = self._high2 < self._high3 and self._low2 < self._low3
lower_highs_lows_2 = self._high1 < self._high2 and self._low1 < self._low2
lower_highs_lows_1 = high < self._high1 and low < self._low1
if above_long_ma and below_short_ma and lower_highs_lows_3 and lower_highs_lows_2 and lower_highs_lows_1:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
self._entries_executed += 1
self._bars_since_signal = 0
self._bar_count += 1
self._high3 = self._high2
self._high2 = self._high1
self._high1 = high
self._low3 = self._low2
self._low2 = self._low1
self._low1 = low
def CreateClone(self):
return larry_connors_3_day_high_low_strategy()