在 GitHub 上查看
符号切换面板策略
概述
符号切换面板策略 是 MQL 面板 “Symbol Swap Panel” 在 StockSharp 平台上的移植版。原始专家顾问提供了一个图表面板,让交易者可以输入符号、切换当前图表,并实时查看 OHLC、成交量以及点差等关键指标。该策略在 StockSharp 中复刻了这一体验:启动后即可在日志中持续输出与面板标签一致的信息,并允许通过参数即时跳转到新的标的。
核心行为
- 为当前标的订阅蜡烛数据和 Level1 报价。
- 每根闭合蜡烛都会输出包含开高低收、总成交量以及最新点差的详细日志。
- 缓存买价/卖价以计算与 MQL 面板一致的实时点差。
- 响应手动的切换请求,在不中断策略的情况下重建订阅并监控新的符号。
- 记录最近一次已应用的符号,避免重复切换造成的无效重启。
参数
| 名称 |
类型 |
说明 |
TargetSecurityId |
string |
触发切换时要监控的证券 ID。留空会记录警告并忽略请求。 |
CandleType |
DataType |
蜡烛聚合类型,默认使用 1 小时蜡烛,对应原面板的刷新周期。 |
SwapRequested |
bool |
手动切换开关,设为 true 后会立即尝试切换到 TargetSecurityId,完成后自动复位为 false。 |
数据订阅
- 根据
CandleType 为当前标的创建蜡烛订阅。
- 打开 Level1 订阅以接收买卖报价并计算点差。
- 每当标的发生变化时,旧的订阅都会被安全地停止并重新建立。
工作流程
- 启动时优先使用
Strategy.Security 作为初始标的,如未设置则尝试根据 TargetSecurityId 解析。
- 为该标的打开蜡烛与 Level1 数据流。
- 每根闭合蜡烛都会在日志中输出与原面板一致的文本信息。
- Level1 更新会刷新缓存的买价和卖价,为点差提供最新数值。
- 当
SwapRequested 设为 true 且 TargetSecurityId 有效时,立即切换标的并重建所有订阅。
使用说明
- 策略仅用于行情监控,不会发送任何交易指令。
- 只有在买价与卖价均有效的情况下才会输出点差值。
- 如果提供了无效或未知的符号,会记录警告并忽略请求,同时保持现有订阅不变。
- 原 MQL 面板每秒刷新一次,如需更频繁的日志输出,可将蜡烛周期调整为更短的时间帧。
保留的 MQL 特性
- 通过文本输入实现的手动符号切换。
- 实时展示所选符号的 OHLC、成交量与点差。
- 对空输入或无法添加到 Market Watch 的符号给出提示(在此转换中表现为警告日志)。
与原实现的差异
- StockSharp 策略通过日志输出信息,而不是在图表面板上显示文本,更契合该平台的典型工作流。
- 图表切换通过重新指定策略的
Security 并重建订阅来实现,而不是直接控制终端窗口。
- 定时刷新机制被蜡烛闭合事件取代,以充分利用 StockSharp 的高层 API。
依赖条件
- 需要一个连接到目标市场的 StockSharp 连接器。
- 需要 Level1 报价数据源以便计算点差。
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>
/// Price monitoring strategy that logs OHLC metrics and trades on candle patterns.
/// Simplified from the "Symbol Swap Panel" MQL display widget.
/// </summary>
public class SymbolSwapPanelStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _maPeriod;
private SimpleMovingAverage _sma;
private decimal _entryPrice;
private decimal _prevClose;
/// <summary>
/// Candle type for monitoring.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Moving average period for trend signals.
/// </summary>
public int MaPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Initializes strategy parameters.
/// </summary>
public SymbolSwapPanelStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Candle series for monitoring and signals", "General");
_maPeriod = Param(nameof(MaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Moving average period for entry signals", "Indicators");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, CandleType);
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_sma = null;
_entryPrice = 0m;
_prevClose = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_sma = new SimpleMovingAverage { Length = MaPeriod };
SubscribeCandles(CandleType)
.Bind(_sma, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal smaValue)
{
if (candle.State != CandleStates.Finished)
return;
var price = candle.ClosePrice;
var high = candle.HighPrice;
var low = candle.LowPrice;
// Log price info
LogInfo(
$"Time: {candle.CloseTime:O}, O: {candle.OpenPrice}, H: {high}, L: {low}, C: {price}, " +
$"Vol: {candle.TotalVolume}, SMA: {smaValue:F5}");
// Exit: reversal or profit target
if (Position != 0 && _entryPrice > 0m)
{
var pnl = Position > 0
? price - _entryPrice
: _entryPrice - price;
// Exit on trend reversal
if ((Position > 0 && price < smaValue) ||
(Position < 0 && price > smaValue))
{
if (Position > 0)
SellMarket(Math.Abs(Position));
else
BuyMarket(Math.Abs(Position));
_entryPrice = 0m;
_prevClose = price;
return;
}
}
// Entry: follow MA trend with momentum confirmation
if (Position == 0 && _prevClose > 0m)
{
if (price > smaValue && _prevClose <= smaValue)
{
BuyMarket();
_entryPrice = price;
}
else if (price < smaValue && _prevClose >= smaValue)
{
SellMarket();
_entryPrice = price;
}
}
_prevClose = price;
}
}
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 SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class symbol_swap_panel_strategy(Strategy):
def __init__(self):
super(symbol_swap_panel_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Candle series for monitoring and signals", "General")
self._ma_period = self.Param("MaPeriod", 20) \
.SetGreaterThanZero() \
.SetDisplay("MA Period", "Moving average period for entry signals", "Indicators")
self._entry_price = 0.0
self._prev_close = 0.0
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def MaPeriod(self):
return self._ma_period.Value
@MaPeriod.setter
def MaPeriod(self, value):
self._ma_period.Value = value
def OnReseted(self):
super(symbol_swap_panel_strategy, self).OnReseted()
self._entry_price = 0.0
self._prev_close = 0.0
def OnStarted2(self, time):
super(symbol_swap_panel_strategy, self).OnStarted2(time)
sma = SimpleMovingAverage()
sma.Length = self.MaPeriod
self.SubscribeCandles(self.CandleType) \
.Bind(sma, self._process_candle) \
.Start()
def _process_candle(self, candle, sma_value):
if candle.State != CandleStates.Finished:
return
price = float(candle.ClosePrice)
sma_v = float(sma_value)
# Exit: reversal against trend
if self.Position != 0 and self._entry_price > 0:
if (self.Position > 0 and price < sma_v) or \
(self.Position < 0 and price > sma_v):
if self.Position > 0:
self.SellMarket(abs(self.Position))
else:
self.BuyMarket(abs(self.Position))
self._entry_price = 0.0
self._prev_close = price
return
# Entry: follow MA trend with momentum confirmation
if self.Position == 0 and self._prev_close > 0:
if price > sma_v and self._prev_close <= sma_v:
self.BuyMarket()
self._entry_price = price
elif price < sma_v and self._prev_close >= sma_v:
self.SellMarket()
self._entry_price = price
self._prev_close = price
def CreateClone(self):
return symbol_swap_panel_strategy()