在 GitHub 上查看
Daydream 策略
概览
Daydream 策略源自 MQL4 专家顾问 Daydream by Cothool。原始版本在 USD/JPY 的 H1 周期内运行:当价格收盘突破近期价格通道后入场,并通过虚拟的跟踪止盈锁定利润。StockSharp 实现保持了核心思想,使用 Donchian Channels 计算上下轨,通过 BuyMarket / SellMarket 发送市价单,并在策略内部维护虚拟止盈而不在交易所挂出真实委托。
主要特点:
- 任意时刻只有一个持仓,当蜡烛收盘位于上一根通道之外时才会反转方向。
- 止盈以“点”为单位虚拟跟踪,随着价格推进而收紧,一旦触发便立即平仓。
- 引入每根蜡烛只允许一次交易动作的限制,复刻 MQL4 中
LastOrderTime 的行为。
交易逻辑
- 使用
ChannelPeriod 根已完成蜡烛构建 Donchian 通道,并保存上一根蜡烛的上下轨值。
- 当蜡烛收盘价 低于 之前的下轨时:
- 平掉当前空头仓位;
- 在下一根蜡烛上按照
OrderVolume 开多头,并把虚拟止盈设置为 close + TakeProfitPips * pipSize。
- 当蜡烛收盘价 高于 之前的上轨时:
- 平掉当前多头仓位;
- 在下一根蜡烛上开空头,把虚拟止盈设置为
close - TakeProfitPips * pipSize。
- 持仓期间每根蜡烛都会收紧虚拟止盈。如果之后的收盘价触达该水平,则通过市价单退出。
点值由品种的 PriceStep 推导。例如日元货币对常见的 0.001 步长会被转换成 0.01 点,与 MetaTrader 一致。
参数说明
| 参数 |
描述 |
默认值 |
备注 |
OrderVolume |
每次开仓的交易量。 |
1 |
对应 MQL 中的 Lots。 |
ChannelPeriod |
Donchian 通道使用的完成蜡烛数量。 |
25 |
等同于原策略参数。 |
Slippage |
允许的点差滑点。 |
3 |
为兼容保留,市价单不会使用。 |
TakeProfitPips |
虚拟止盈与当前价格的距离(点)。 |
15 |
随价格移动自动收紧。 |
CandleType |
计算 Donchian 通道所用的蜡烛类型。 |
1 小时 |
继承原策略推荐周期。 |
工作流程
蜡烛收盘
│
├─► 更新 Donchian 通道(上一根上下轨)
│
├─► 向下突破?──► 平空 → 下一根准备做多
│
├─► 向上突破?──► 平多 → 下一根准备做空
│
└─► 按持仓方向收紧虚拟止盈
└─► 价格触及目标?→ 立即平仓
使用建议
- 将策略附加到任意具有蜡烛数据的品种,默认参数适用于 USD/JPY H1。
- 策略始终保持单仓位,并阻止同一根蜡烛内的重复交易,以保持与 MQL4 行为一致。
- 止盈完全在代码中处理,触发时通过市价单离场,不会在交易所挂出真实止盈单。
- 如需切换时间框架,请调整
CandleType,并确保有足够历史数据以形成通道。
与 MQL4 版本的差异
- 使用内置
DonchianChannels 指标替代手工遍历高低点。
- 保留虚拟止盈和节流逻辑,但执行由 StockSharp 的市场单完成,无需处理 MT4 的订单票据。
Slippage 参数仅为兼容保留,StockSharp 的市场执行不直接应用该值。
文件结构
CS/DaydreamStrategy.cs — C# 策略实现。
- Python 版本尚未提供。
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Daydream strategy - Donchian channel breakout.
/// Buys when price crosses above the midpoint of the channel.
/// Sells when price crosses below the midpoint.
/// </summary>
public class DaydreamStrategy : Strategy
{
private readonly StrategyParam<int> _channelPeriod;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevClose;
private decimal _prevMid;
private bool _hasPrev;
public int ChannelPeriod { get => _channelPeriod.Value; set => _channelPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public DaydreamStrategy()
{
_channelPeriod = Param(nameof(ChannelPeriod), 20)
.SetDisplay("Channel Period", "Donchian channel lookback", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
protected override void OnReseted() { base.OnReseted(); _prevClose = 0m; _prevMid = 0m; _hasPrev = false; }
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_hasPrev = false;
var highest = new Highest { Length = ChannelPeriod };
var lowest = new Lowest { Length = ChannelPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(highest, lowest, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal highest, decimal lowest)
{
if (candle.State != CandleStates.Finished)
return;
var close = candle.ClosePrice;
var mid = (highest + lowest) / 2;
if (!_hasPrev)
{
_prevClose = close;
_prevMid = mid;
_hasPrev = true;
return;
}
// Cross above midpoint
if (_prevClose <= _prevMid && close > mid && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Cross below midpoint
else if (_prevClose >= _prevMid && close < mid && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
_prevClose = close;
_prevMid = mid;
}
}
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
from StockSharp.Algo.Indicators import Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
class daydream_strategy(Strategy):
def __init__(self):
super(daydream_strategy, self).__init__()
self._channel_period = self.Param("ChannelPeriod", 20) \
.SetDisplay("Channel Period", "Donchian channel lookback", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._prev_close = 0.0
self._prev_mid = 0.0
self._has_prev = False
@property
def channel_period(self):
return self._channel_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(daydream_strategy, self).OnReseted()
self._prev_close = 0.0
self._prev_mid = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(daydream_strategy, self).OnStarted2(time)
self._has_prev = False
highest = Highest()
highest.Length = self.channel_period
lowest = Lowest()
lowest.Length = self.channel_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(highest, lowest, self.process_candle).Start()
def process_candle(self, candle, highest, lowest):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
high_val = float(highest)
low_val = float(lowest)
mid = (high_val + low_val) / 2.0
if not self._has_prev:
self._prev_close = close
self._prev_mid = mid
self._has_prev = True
return
if self._prev_close <= self._prev_mid and close > mid and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif self._prev_close >= self._prev_mid and close < mid and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_close = close
self._prev_mid = mid
def CreateClone(self):
return daydream_strategy()