蜡烛趋势策略
概述
该策略根据连续蜡烛的方向开仓。 当连续出现指定数量的阳线时开多单;当连续出现相同数量的阴线时开空单。 当出现相反信号时,可平掉现有头寸。
参数
- Candle Type:用于分析的蜡烛时间框架。
- Trend Candles:触发操作所需的连续同方向蜡烛数量。
- Take Profit %:可选的止盈百分比。
- Stop Loss %:可选的止损百分比。
- Enable Long Entry:允许开多。
- Enable Short Entry:允许开空。
- Enable Long Exit:允许在相反信号时平多。
- Enable Short Exit:允许在相反信号时平空。
逻辑
- 订阅所选时间框架的蜡烛数据。
- 统计连续上涨和下跌蜡烛的数量。
- 当上涨计数达到设定值时:
- 若允许则平空。
- 若允许则开多。
- 当下跌计数达到设定值时:
- 若允许则平多。
- 若允许则开空。
- 使用
StartProtection设置可选的保护单。
注意
- 仅在蜡烛收盘后处理信号。
- 策略使用
BuyMarket和SellMarket进行交易。 - 代码中的注释均为英文。
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>
/// Strategy that trades based on consecutive candle directions.
/// Enters long after several bullish candles in a row and short after several bearish candles.
/// </summary>
public class CandleTrendStrategy : Strategy
{
private readonly StrategyParam<int> _trendCandles;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _takeProfitPercent;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<bool> _enableLongEntry;
private readonly StrategyParam<bool> _enableShortEntry;
private readonly StrategyParam<bool> _enableLongExit;
private readonly StrategyParam<bool> _enableShortExit;
private int _upCount;
private int _downCount;
/// <summary>
/// Number of consecutive candles required to trigger an action.
/// </summary>
public int TrendCandles
{
get => _trendCandles.Value;
set => _trendCandles.Value = value;
}
/// <summary>
/// Type of candles used for analysis.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Take profit as percentage from entry price.
/// </summary>
public decimal TakeProfitPercent
{
get => _takeProfitPercent.Value;
set => _takeProfitPercent.Value = value;
}
/// <summary>
/// Stop loss as percentage from entry price.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Allow opening long positions.
/// </summary>
public bool EnableLongEntry
{
get => _enableLongEntry.Value;
set => _enableLongEntry.Value = value;
}
/// <summary>
/// Allow opening short positions.
/// </summary>
public bool EnableShortEntry
{
get => _enableShortEntry.Value;
set => _enableShortEntry.Value = value;
}
/// <summary>
/// Allow closing long positions.
/// </summary>
public bool EnableLongExit
{
get => _enableLongExit.Value;
set => _enableLongExit.Value = value;
}
/// <summary>
/// Allow closing short positions.
/// </summary>
public bool EnableShortExit
{
get => _enableShortExit.Value;
set => _enableShortExit.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="CandleTrendStrategy"/>.
/// </summary>
public CandleTrendStrategy()
{
_trendCandles = Param(nameof(TrendCandles), 3)
.SetGreaterThanZero()
.SetDisplay("Trend Candles", "Number of candles in one direction", "General")
;
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles for analysis", "General");
_takeProfitPercent = Param(nameof(TakeProfitPercent), 0m)
.SetDisplay("Take Profit %", "Take profit percentage", "Risk Management")
;
_stopLossPercent = Param(nameof(StopLossPercent), 0m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management")
;
_enableLongEntry = Param(nameof(EnableLongEntry), true)
.SetDisplay("Enable Long Entry", "Permission to enter long", "General");
_enableShortEntry = Param(nameof(EnableShortEntry), true)
.SetDisplay("Enable Short Entry", "Permission to enter short", "General");
_enableLongExit = Param(nameof(EnableLongExit), true)
.SetDisplay("Enable Long Exit", "Permission to exit long", "General");
_enableShortExit = Param(nameof(EnableShortExit), true)
.SetDisplay("Enable Short Exit", "Permission to exit short", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_upCount = 0;
_downCount = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var tp = TakeProfitPercent > 0 ? new Unit(TakeProfitPercent, UnitTypes.Percent) : null;
var sl = StopLossPercent > 0 ? new Unit(StopLossPercent, UnitTypes.Percent) : null;
StartProtection(tp, sl);
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var isBull = candle.ClosePrice > candle.OpenPrice;
var isBear = candle.ClosePrice < candle.OpenPrice;
if (isBull)
{
_upCount++;
_downCount = 0;
}
else if (isBear)
{
_downCount++;
_upCount = 0;
}
else
{
_upCount = 0;
_downCount = 0;
}
if (_upCount >= TrendCandles)
{
if (Position < 0 && EnableLongExit)
BuyMarket();
if (Position <= 0 && EnableLongEntry)
BuyMarket();
}
else if (_downCount >= TrendCandles)
{
if (Position > 0 && EnableShortExit)
SellMarket();
if (Position >= 0 && EnableShortEntry)
SellMarket();
}
}
}
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.Strategies import Strategy
class candle_trend_strategy(Strategy):
def __init__(self):
super(candle_trend_strategy, self).__init__()
self._trend_candles = self.Param("TrendCandles", 3) \
.SetDisplay("Trend Candles", "Number of candles in one direction", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles for analysis", "General")
self._take_profit_percent = self.Param("TakeProfitPercent", 0.0) \
.SetDisplay("Take Profit %", "Take profit percentage", "Risk Management")
self._stop_loss_percent = self.Param("StopLossPercent", 0.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management")
self._enable_long_entry = self.Param("EnableLongEntry", True) \
.SetDisplay("Enable Long Entry", "Permission to enter long", "General")
self._enable_short_entry = self.Param("EnableShortEntry", True) \
.SetDisplay("Enable Short Entry", "Permission to enter short", "General")
self._enable_long_exit = self.Param("EnableLongExit", True) \
.SetDisplay("Enable Long Exit", "Permission to exit long", "General")
self._enable_short_exit = self.Param("EnableShortExit", True) \
.SetDisplay("Enable Short Exit", "Permission to exit short", "General")
self._up_count = 0
self._down_count = 0
@property
def trend_candles(self):
return self._trend_candles.Value
@property
def candle_type(self):
return self._candle_type.Value
@property
def take_profit_percent(self):
return self._take_profit_percent.Value
@property
def stop_loss_percent(self):
return self._stop_loss_percent.Value
@property
def enable_long_entry(self):
return self._enable_long_entry.Value
@property
def enable_short_entry(self):
return self._enable_short_entry.Value
@property
def enable_long_exit(self):
return self._enable_long_exit.Value
@property
def enable_short_exit(self):
return self._enable_short_exit.Value
def OnReseted(self):
super(candle_trend_strategy, self).OnReseted()
self._up_count = 0
self._down_count = 0
def OnStarted2(self, time):
super(candle_trend_strategy, self).OnStarted2(time)
tp_val = float(self.take_profit_percent)
sl_val = float(self.stop_loss_percent)
tp = Unit(tp_val, UnitTypes.Percent) if tp_val > 0 else None
sl = Unit(sl_val, UnitTypes.Percent) if sl_val > 0 else None
self.StartProtection(tp, sl)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.process_candle).Start()
def process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
open_p = float(candle.OpenPrice)
is_bull = close > open_p
is_bear = close < open_p
if is_bull:
self._up_count += 1
self._down_count = 0
elif is_bear:
self._down_count += 1
self._up_count = 0
else:
self._up_count = 0
self._down_count = 0
tc = int(self.trend_candles)
if self._up_count >= tc:
if self.Position < 0 and self.enable_long_exit:
self.BuyMarket()
if self.Position <= 0 and self.enable_long_entry:
self.BuyMarket()
elif self._down_count >= tc:
if self.Position > 0 and self.enable_short_exit:
self.SellMarket()
if self.Position >= 0 and self.enable_short_entry:
self.SellMarket()
def CreateClone(self):
return candle_trend_strategy()