Candle 策略
概述
Candle Strategy 是 MT5 经典专家顾问 “Candle.mq5” 的完整移植版。策略在选定周期上分析每一根已完成 K 线的颜色,并让持仓方向始终跟随最新收盘价。收盘价高于开盘价时持有多头,收盘价低于开盘价时持有空头,平收的 K 线则保持现有仓位不变。风险控制通过以点数为单位的止盈和追踪止损来实现,并依据品种的最小报价步长换算成绝对价格。
为避免盘中噪声,策略只在蜡烛完全收盘后做出决策。在开始交易之前,它会确认历史中至少存在 MinBars * 2 根已完成 K 线,并在每次交易后等待一个可配置的冷却时间。凭借这些约束,StockSharp 版本可以忠实地复现原始 MetaTrader 逻辑,而无需直接访问底层时间序列。
交易逻辑
准备阶段
- 仅订阅
CandleType指定的蜡烛,不需要其他数据源。 - 在处理完至少
2 * MinBars根已完成的蜡烛之前不会开仓。 - 只有在策略处于在线、已形成且允许交易的状态下才执行订单。
- 任意两次交易之间都会强制等待
TradeCooldown(默认 10 秒)的冷却时间。
入场与反向规则
- 空仓状态:
- 当蜡烛收盘价高于开盘价时,通过
BuyMarket建立多头。 - 当蜡烛收盘价低于开盘价时,通过
SellMarket建立空头。
- 当蜡烛收盘价高于开盘价时,通过
- 已有仓位:
- 持有多头且出现阴线时,卖出
|Position| + Volume,先平掉当前仓位,再立即建立大小为Volume的空头。 - 持有空头且出现阳线时,买入
|Position| + Volume,先平掉当前仓位,再立即建立大小为Volume的多头。
- 持有多头且出现阴线时,卖出
- 十字或平收:
- 收盘价等于开盘价时不进行手动操作,只保留保护性订单的自动退出。
风险管理与退出
- 通过
StartProtection设置以点数计的止盈和追踪止损。策略使用(PriceStep * 10)计算点值,与原始专家在 3 位或 5 位报价下的 “digits adjust” 逻辑相一致。 - 仅当
TrailingStopPips大于零时才启用追踪止损,盈利时自动沿价格移动。 - 止盈在达到设定距离后自动平仓,保护性订单执行后会撤销相反方向的挂单。
- 由于反向操作会先平仓后反手,因此不会与保护性订单产生冲突。
参数
CandleType– 用于分析的蜡烛周期(默认 15 分钟)。TakeProfitPips– 止盈距离,单位为点(默认 50 点)。TrailingStopPips– 追踪止损距离,单位为点(默认 30 点)。MinBars– 开始交易前所需的最少历史柱数(默认 26,对应等待 52 根已完成蜡烛)。TradeCooldown– 每次交易后的冷却时间(默认 10 秒)。
请在运行前设置策略的 Volume 属性。策略在反向时会自动发送足够的成交量,既能平掉旧仓位,也能同时建立新仓位。
实现细节
- 只处理状态为
CandleStates.Finished的蜡烛,这与原始 MQL 专家通过CopyOpen/CopyClose读取已收盘数据的行为一致。 - 代码完全基于 StockSharp 高层 API:
SubscribeCandles订阅数据,Bind绑定处理方法,BuyMarket/SellMarket执行订单。 - 保护性订单由
StartProtection自动管理,无需手动维护止损或止盈。 - 点值计算
(PriceStep * 10)复刻了原策略在三位和五位报价中的调节方式。 - 由于信号直接来自最新蜡烛的实体颜色,策略通常持续持仓,并在颜色切换时立即反手。
可以根据所交易的品种调整点距、冷却时间和时间框架。默认参数与 MT5 示例保持一致,也可通过 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>
/// Candle color reversal strategy with pip-based protection and trade cooldown.
/// </summary>
public class CandleStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _takeProfitPips;
private readonly StrategyParam<decimal> _trailingStopPips;
private readonly StrategyParam<int> _minBars;
private readonly StrategyParam<TimeSpan> _tradeCooldown;
private decimal _pipSize;
private int _finishedCandles;
private DateTimeOffset _nextAllowedTime;
/// <summary>
/// Initializes a new instance of the <see cref="CandleStrategy"/>.
/// </summary>
public CandleStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe used for candle evaluation", "General");
_takeProfitPips = Param(nameof(TakeProfitPips), 50m)
.SetDisplay("Take Profit (pips)", "Distance to take profit in pips", "Risk")
.SetGreaterThanZero();
_trailingStopPips = Param(nameof(TrailingStopPips), 30m)
.SetDisplay("Trailing Stop (pips)", "Trailing stop distance in pips", "Risk")
.SetGreaterThanZero();
_minBars = Param(nameof(MinBars), 26)
.SetDisplay("Minimum Bars", "History length required before trading", "General")
.SetGreaterThanZero();
_tradeCooldown = Param(nameof(TradeCooldown), TimeSpan.FromSeconds(10))
.SetDisplay("Trade Cooldown", "Waiting time after each trade", "Risk");
}
/// <summary>
/// Candle type and timeframe used by the strategy.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Take profit distance expressed in pips.
/// </summary>
public decimal TakeProfitPips
{
get => _takeProfitPips.Value;
set => _takeProfitPips.Value = value;
}
/// <summary>
/// Trailing stop distance expressed in pips.
/// </summary>
public decimal TrailingStopPips
{
get => _trailingStopPips.Value;
set => _trailingStopPips.Value = value;
}
/// <summary>
/// Minimum number of bars required on the chart.
/// </summary>
public int MinBars
{
get => _minBars.Value;
set => _minBars.Value = value;
}
/// <summary>
/// Cooldown between consecutive trading operations.
/// </summary>
public TimeSpan TradeCooldown
{
get => _tradeCooldown.Value;
set => _tradeCooldown.Value = value;
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_pipSize = 0m;
_finishedCandles = 0;
_nextAllowedTime = DateTimeOffset.MinValue;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_pipSize = (Security?.PriceStep ?? 1m) * 10m;
Unit takeProfit = TakeProfitPips > 0m && _pipSize > 0m
? new Unit(TakeProfitPips * _pipSize, UnitTypes.Absolute)
: null;
Unit trailingStop = TrailingStopPips > 0m && _pipSize > 0m
? new Unit(TrailingStopPips * _pipSize, UnitTypes.Absolute)
: null;
// Enable automatic protective orders and trailing stop handling.
if (trailingStop != null || takeProfit != null)
StartProtection(takeProfit, trailingStop);
// Subscribe to candle data for the configured timeframe.
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
// Draw candles and executions on the chart if visualization is available.
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
// Skip unfinished candles to work only with final prices.
if (candle.State != CandleStates.Finished)
return;
_finishedCandles++;
// Wait until the chart has enough historical data.
if (_finishedCandles < MinBars * 2)
return;
var time = candle.CloseTime;
// Enforce cooldown between trading operations.
if (time < _nextAllowedTime)
return;
var isBullish = candle.ClosePrice > candle.OpenPrice;
var isBearish = candle.ClosePrice < candle.OpenPrice;
var tradeExecuted = false;
if (Position > 0 && isBearish)
{
// Reverse from long to short when a bearish candle appears.
var volume = Math.Abs(Position) + Volume;
if (volume > 0m)
{
SellMarket();
tradeExecuted = true;
}
}
else if (Position < 0 && isBullish)
{
// Reverse from short to long when a bullish candle appears.
var volume = Math.Abs(Position) + Volume;
if (volume > 0m)
{
BuyMarket();
tradeExecuted = true;
}
}
else if (Position == 0)
{
if (isBullish)
{
// Enter long on bullish close.
if (Volume > 0m)
{
BuyMarket();
tradeExecuted = true;
}
}
else if (isBearish)
{
// Enter short on bearish close.
if (Volume > 0m)
{
SellMarket();
tradeExecuted = true;
}
}
}
if (tradeExecuted)
{
_nextAllowedTime = time + TradeCooldown;
}
}
}
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, DateTimeOffset
from StockSharp.Messages import DataType, CandleStates, UnitTypes, Unit
from StockSharp.Algo.Strategies import Strategy
class candle_strategy(Strategy):
"""
Candle color reversal strategy with pip-based protection and trade cooldown.
"""
def __init__(self):
super(candle_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe used for candle evaluation", "General")
self._take_profit_pips = self.Param("TakeProfitPips", 50.0) \
.SetDisplay("Take Profit (pips)", "Distance to take profit in pips", "Risk")
self._trailing_stop_pips = self.Param("TrailingStopPips", 30.0) \
.SetDisplay("Trailing Stop (pips)", "Trailing stop distance in pips", "Risk")
self._min_bars = self.Param("MinBars", 26) \
.SetDisplay("Minimum Bars", "History length required before trading", "General")
self._trade_cooldown = self.Param("TradeCooldown", TimeSpan.FromSeconds(10)) \
.SetDisplay("Trade Cooldown", "Waiting time after each trade", "Risk")
self._pip_size = 0.0
self._finished_candles = 0
self._next_allowed_time = DateTimeOffset.MinValue
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
@property
def take_profit_pips(self):
return self._take_profit_pips.Value
@take_profit_pips.setter
def take_profit_pips(self, value):
self._take_profit_pips.Value = value
@property
def trailing_stop_pips(self):
return self._trailing_stop_pips.Value
@trailing_stop_pips.setter
def trailing_stop_pips(self, value):
self._trailing_stop_pips.Value = value
@property
def min_bars(self):
return self._min_bars.Value
@min_bars.setter
def min_bars(self, value):
self._min_bars.Value = value
@property
def trade_cooldown(self):
return self._trade_cooldown.Value
@trade_cooldown.setter
def trade_cooldown(self, value):
self._trade_cooldown.Value = value
def OnReseted(self):
super(candle_strategy, self).OnReseted()
self._pip_size = 0.0
self._finished_candles = 0
self._next_allowed_time = DateTimeOffset.MinValue
def OnStarted2(self, time):
super(candle_strategy, self).OnStarted2(time)
self._pip_size = (self.Security.PriceStep if self.Security.PriceStep is not None else 1.0) * 10.0
tp = None
trailing = None
if self.take_profit_pips > 0 and self._pip_size > 0:
tp = Unit(self.take_profit_pips * self._pip_size, UnitTypes.Absolute)
if self.trailing_stop_pips > 0 and self._pip_size > 0:
trailing = Unit(self.trailing_stop_pips * self._pip_size, UnitTypes.Absolute)
if trailing is not None or tp is not None:
self.StartProtection(tp, trailing)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle):
if candle.State != CandleStates.Finished:
return
self._finished_candles += 1
if self._finished_candles < self.min_bars * 2:
return
close_time = candle.CloseTime
if self._next_allowed_time != DateTimeOffset.MinValue:
try:
if close_time < self._next_allowed_time:
return
except:
if DateTimeOffset(close_time) < self._next_allowed_time:
return
is_bullish = candle.ClosePrice > candle.OpenPrice
is_bearish = candle.ClosePrice < candle.OpenPrice
trade_executed = False
if self.Position > 0 and is_bearish:
self.SellMarket()
trade_executed = True
elif self.Position < 0 and is_bullish:
self.BuyMarket()
trade_executed = True
elif self.Position == 0:
if is_bullish:
self.BuyMarket()
trade_executed = True
elif is_bearish:
self.SellMarket()
trade_executed = True
if trade_executed:
self._next_allowed_time = close_time + self.trade_cooldown
def CreateClone(self):
return candle_strategy()