Eugene烛形策略
该策略基于"Eugene"蜡烛形态进行交易。算法分析最近四根K线,识别内包线以及特殊的"鸟"形态,并计算突破水平。当价格突破前一根K线的极值且满足额外确认条件时入场。止损和止盈以价格步长表示。
细节
- 入场条件:
- 多头:当前最高价高于前一根,前一根最低价低于更早一根的最高价,当前最低价高于前一根,并由zig水平或时间过滤确认。
- 空头:当前最低价低于前一根,前一根最高价高于更早一根的最低价,当前最高价低于前一根,并由zig水平或时间过滤确认。
- 方向:双向
- 出场条件:
- 多头:出现反向信号或触发止损/止盈时卖出。
- 空头:出现反向信号或触发止损/止盈时买入。
- 止损:固定价格步长
- 默认值:
Volume= 1mStopLossPoints= 0TakeProfitPoints= 0InvertSignals= falseCandleType= TimeSpan.FromMinutes(1).TimeFrame()
- 过滤器:
- 分类:形态
- 方向:双向
- 指标:无
- 止损:可选
- 复杂度:中等
- 时间框架:短期
- 季节性:日内(小时>=8过滤)
- 神经网络:否
- 背离:否
- 风险水平:中等
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Candle pattern strategy with breakout confirmation.
/// </summary>
public class EugeneCandlePatternStrategy : Strategy
{
private readonly StrategyParam<int> _sl;
private readonly StrategyParam<int> _tp;
private readonly StrategyParam<bool> _inv;
private readonly StrategyParam<DataType> _cType;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<decimal> _minBodyPercent;
private readonly ICandleMessage[] _recent = new ICandleMessage[4];
private decimal _stop;
private decimal _take;
private int _cooldownRemaining;
public int StopLossPoints { get => _sl.Value; set => _sl.Value = value; }
public int TakeProfitPoints { get => _tp.Value; set => _tp.Value = value; }
public bool InvertSignals { get => _inv.Value; set => _inv.Value = value; }
public DataType CandleType { get => _cType.Value; set => _cType.Value = value; }
public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }
public decimal MinBodyPercent { get => _minBodyPercent.Value; set => _minBodyPercent.Value = value; }
public EugeneCandlePatternStrategy()
{
_sl = Param(nameof(StopLossPoints), 500).SetDisplay("Stop Loss (points)", "Stop loss in price steps, 0 - disabled", "Risk");
_tp = Param(nameof(TakeProfitPoints), 800).SetDisplay("Take Profit (points)", "Take profit in price steps, 0 - disabled", "Risk");
_inv = Param(nameof(InvertSignals), false).SetDisplay("Invert Signals", "Swap buy and sell signals", "General");
_cType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame()).SetDisplay("Candle Type", "Type of candles", "General");
_cooldownBars = Param(nameof(CooldownBars), 4).SetDisplay("Cooldown Bars", "Completed candles to wait after a position change", "Trading");
_minBodyPercent = Param(nameof(MinBodyPercent), 0.0015m).SetDisplay("Minimum Body %", "Minimum candle body size relative to close price", "Filters");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
Array.Clear(_recent, 0, _recent.Length);
_stop = 0m;
_take = 0m;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var subscription = SubscribeCandles(CandleType);
subscription.Bind(Process).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
StartProtection(null, null);
}
private void Process(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
if (_cooldownRemaining > 0)
_cooldownRemaining--;
CheckStops(candle);
_recent[3] = _recent[2];
_recent[2] = _recent[1];
_recent[1] = _recent[0];
_recent[0] = candle;
if (_recent[3] is null)
return;
ComputeSignals(out var openBuy, out var openSell, out var closeBuy, out var closeSell);
if (InvertSignals)
{
(openBuy, openSell) = (openSell, openBuy);
(closeBuy, closeSell) = (closeSell, closeBuy);
}
if (Position > 0 && closeBuy)
ClosePosition();
else if (Position < 0 && closeSell)
ClosePosition();
if (_cooldownRemaining > 0)
return;
if (Position <= 0 && openBuy && !openSell)
{
if (Position < 0)
BuyMarket();
BuyMarket();
SetStops(candle.ClosePrice, true);
_cooldownRemaining = CooldownBars;
}
else if (Position >= 0 && openSell && !openBuy)
{
if (Position > 0)
SellMarket();
SellMarket();
SetStops(candle.ClosePrice, false);
_cooldownRemaining = CooldownBars;
}
}
private void ComputeSignals(out bool openBuy, out bool openSell, out bool closeBuy, out bool closeSell)
{
var current = _recent[0];
var prev = _recent[1];
var prev2 = _recent[2];
openBuy = false;
openSell = false;
closeBuy = false;
closeSell = false;
var prevBody = Math.Abs(prev.ClosePrice - prev.OpenPrice);
var currentBody = Math.Abs(current.ClosePrice - current.OpenPrice);
var prevBodyPercent = prev.ClosePrice != 0m ? prevBody / prev.ClosePrice : 0m;
var currentBodyPercent = current.ClosePrice != 0m ? currentBody / current.ClosePrice : 0m;
var bullishSetup = prev.ClosePrice < prev.OpenPrice && prev.LowPrice > prev2.LowPrice;
var bearishSetup = prev.ClosePrice > prev.OpenPrice && prev.HighPrice < prev2.HighPrice;
var bullishBreakout = current.ClosePrice > prev.HighPrice && current.ClosePrice > current.OpenPrice;
var bearishBreakout = current.ClosePrice < prev.LowPrice && current.ClosePrice < current.OpenPrice;
openBuy = bullishSetup && bullishBreakout && prevBodyPercent >= MinBodyPercent && currentBodyPercent >= MinBodyPercent;
openSell = bearishSetup && bearishBreakout && prevBodyPercent >= MinBodyPercent && currentBodyPercent >= MinBodyPercent;
closeBuy = current.ClosePrice < prev.LowPrice;
closeSell = current.ClosePrice > prev.HighPrice;
}
private void SetStops(decimal price, bool longPos)
{
var step = Security.PriceStep ?? 1m;
if (longPos)
{
_stop = StopLossPoints > 0 ? price - step * StopLossPoints : 0m;
_take = TakeProfitPoints > 0 ? price + step * TakeProfitPoints : 0m;
}
else
{
_stop = StopLossPoints > 0 ? price + step * StopLossPoints : 0m;
_take = TakeProfitPoints > 0 ? price - step * TakeProfitPoints : 0m;
}
}
private void ClosePosition()
{
if (Position > 0)
SellMarket();
else if (Position < 0)
BuyMarket();
_stop = 0m;
_take = 0m;
_cooldownRemaining = CooldownBars;
}
private void CheckStops(ICandleMessage candle)
{
if (Position > 0)
{
if ((_stop != 0m && candle.LowPrice <= _stop) || (_take != 0m && candle.HighPrice >= _take))
ClosePosition();
}
else if (Position < 0)
{
if ((_stop != 0m && candle.HighPrice >= _stop) || (_take != 0m && candle.LowPrice <= _take))
ClosePosition();
}
}
}
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.Strategies import Strategy
class eugene_candle_pattern_strategy(Strategy):
"""
Candle pattern strategy with breakout confirmation.
Detects bullish/bearish setup patterns and trades breakouts with SL/TP management.
"""
def __init__(self):
super(eugene_candle_pattern_strategy, self).__init__()
self._sl = self.Param("StopLossPoints", 500) \
.SetDisplay("Stop Loss (points)", "Stop loss in price steps", "Risk")
self._tp = self.Param("TakeProfitPoints", 800) \
.SetDisplay("Take Profit (points)", "Take profit in price steps", "Risk")
self._inv = self.Param("InvertSignals", False) \
.SetDisplay("Invert Signals", "Swap buy and sell signals", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._cooldown_bars = self.Param("CooldownBars", 4) \
.SetDisplay("Cooldown Bars", "Bars to wait after position change", "Trading")
self._min_body_percent = self.Param("MinBodyPercent", 0.0015) \
.SetDisplay("Minimum Body %", "Min candle body size relative to close", "Filters")
self._recent = [None, None, None, None]
self._stop = 0.0
self._take = 0.0
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(eugene_candle_pattern_strategy, self).OnReseted()
self._recent = [None, None, None, None]
self._stop = 0.0
self._take = 0.0
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(eugene_candle_pattern_strategy, self).OnStarted2(time)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def _process(self, candle):
if candle.State != CandleStates.Finished:
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
self._check_stops(candle)
self._recent[3] = self._recent[2]
self._recent[2] = self._recent[1]
self._recent[1] = self._recent[0]
self._recent[0] = {
"open": float(candle.OpenPrice),
"close": float(candle.ClosePrice),
"high": float(candle.HighPrice),
"low": float(candle.LowPrice)
}
if self._recent[3] is None:
return
open_buy, open_sell, close_buy, close_sell = self._compute_signals()
if self._inv.Value:
open_buy, open_sell = open_sell, open_buy
close_buy, close_sell = close_sell, close_buy
if self.Position > 0 and close_buy:
self._close_position()
elif self.Position < 0 and close_sell:
self._close_position()
if self._cooldown_remaining > 0:
return
if self.Position <= 0 and open_buy and not open_sell:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._set_stops(self._recent[0]["close"], True)
self._cooldown_remaining = self._cooldown_bars.Value
elif self.Position >= 0 and open_sell and not open_buy:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._set_stops(self._recent[0]["close"], False)
self._cooldown_remaining = self._cooldown_bars.Value
def _compute_signals(self):
current = self._recent[0]
prev = self._recent[1]
prev2 = self._recent[2]
prev_body = abs(prev["close"] - prev["open"])
current_body = abs(current["close"] - current["open"])
prev_body_pct = prev_body / prev["close"] if prev["close"] != 0 else 0
current_body_pct = current_body / current["close"] if current["close"] != 0 else 0
min_body = float(self._min_body_percent.Value)
bullish_setup = prev["close"] < prev["open"] and prev["low"] > prev2["low"]
bearish_setup = prev["close"] > prev["open"] and prev["high"] < prev2["high"]
bullish_breakout = current["close"] > prev["high"] and current["close"] > current["open"]
bearish_breakout = current["close"] < prev["low"] and current["close"] < current["open"]
open_buy = bullish_setup and bullish_breakout and prev_body_pct >= min_body and current_body_pct >= min_body
open_sell = bearish_setup and bearish_breakout and prev_body_pct >= min_body and current_body_pct >= min_body
close_buy = current["close"] < prev["low"]
close_sell = current["close"] > prev["high"]
return open_buy, open_sell, close_buy, close_sell
def _set_stops(self, price, long_pos):
step = 1.0
if self.Security is not None and self.Security.PriceStep is not None:
step = float(self.Security.PriceStep)
if step <= 0:
step = 1.0
sl_pts = self._sl.Value
tp_pts = self._tp.Value
if long_pos:
self._stop = price - step * sl_pts if sl_pts > 0 else 0.0
self._take = price + step * tp_pts if tp_pts > 0 else 0.0
else:
self._stop = price + step * sl_pts if sl_pts > 0 else 0.0
self._take = price - step * tp_pts if tp_pts > 0 else 0.0
def _close_position(self):
if self.Position > 0:
self.SellMarket()
elif self.Position < 0:
self.BuyMarket()
self._stop = 0.0
self._take = 0.0
self._cooldown_remaining = self._cooldown_bars.Value
def _check_stops(self, candle):
low = float(candle.LowPrice)
high = float(candle.HighPrice)
if self.Position > 0:
if (self._stop != 0 and low <= self._stop) or (self._take != 0 and high >= self._take):
self._close_position()
elif self.Position < 0:
if (self._stop != 0 and high >= self._stop) or (self._take != 0 and low <= self._take):
self._close_position()
def CreateClone(self):
return eugene_candle_pattern_strategy()