跳转至

自定义通知

自定义通知 API 包括允许交易算法直接在 cTrader 中发送实时弹出警报的类型。 这些弹出窗口允许 cBot、指标和插件以可视化和上下文相关的方式向用户传达进度、成功、错误或一般信息。

有了自定义通知 API 支持,cBot 不再需要依赖 日志 选项卡、图表对象或外部 Telegram 桥接进行通信。 算法只需通过 cTrader 中的标准通知系统直接告诉交易者发生了什么。 算法开发者和用户可以受益于速度、可靠性和清晰度,而无需任何复杂的设置。

相关的 API 接口包括:

  • INotifications.ShowPopup(caption, message, state) 用于显示带有给定标题、消息和状态(PopupNotificationState)的弹出通知。
  • PopupNotification 接口用于通过调用 .Complete() 来更新最终状态,以编程方式控制长时间运行或渐进式通知。

自定义通知 API 传递的消息会立即出现,按状态进行颜色编码,并可以稍后完成。 通知状态使用 PopupNotificationState 枚举定义:

  • InProgress 表示长时间运行的进程或待处理状态。 示例:

  • Success 表示操作已成功完成。 示例:

  • Error 表示失败或异常。 示例:

  • Partial 表示部分成功的结果(例如,某些订单成功)。 示例:

  • Information 用于一般警报、更新或反馈。 示例:

提示

使用弹出通知来跟踪交易活动、调试逻辑流程、提醒用户市场事件或数据错误,并在实时或手动策略操作期间提供动态 UI 反馈。

通知 API 对象可用于执行以下操作:

功能或操作 示例
订单跟踪和反馈 显示订单执行反馈
确认止盈/止损退出
跟踪追踪止损修改
风险和基于规则的警报 警告低保证金水平
显示被阻止交易的警报
进度和诊断 通过弹出窗口显示分析进度
手动交易互动 为交易操作提供反馈
警告手动覆盖或干预
市场事件和信号警报 发出指标交叉信号
宣布交易时段开始或价格突破
策略调试和透明度 可视化跟踪策略/逻辑步骤
报告逻辑失败

基本示例

当此 cBot 的实例被添加到图表时,它会提供五个按钮,每个按钮对应一种通知状态。 点击按钮会触发弹出通知。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None, AddIndicators = true)]
    public class PopupNotificationStatesDemo : Robot
    {
        protected override void OnStart()
        {
            var panel = new StackPanel
            {
                Orientation = Orientation.Vertical,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center
            };

            // InProgress
            var inProgressBtn = new Button { Text = "Show: InProgress", Margin = 5 };
            inProgressBtn.Click += _ =>
            {
                Notifications.ShowPopup(
                    "In progress",
                    "Starting a long-running task…",
                    PopupNotificationState.InProgress
                );
            };
            panel.AddChild(inProgressBtn);

            // Success
            var successBtn = new Button { Text = "Show: Success", Margin = 5 };
            successBtn.Click += _ =>
            {
                Notifications.ShowPopup(
                    "Success",
                    "The operation completed successfully.",
                    PopupNotificationState.Success
                );
            };
            panel.AddChild(successBtn);

            // Error
            var errorBtn = new Button { Text = "Show: Error", Margin = 5 };
            errorBtn.Click += _ =>
            {
                Notifications.ShowPopup(
                    "Error",
                    "Something went wrong. Please check the logs or try again.",
                    PopupNotificationState.Error
                );
            };
            panel.AddChild(errorBtn);

            // Partial
            var partialBtn = new Button { Text = "Show: Partial", Margin = 5 };
            partialBtn.Click += _ =>
            {
                Notifications.ShowPopup(
                    "Partial result",
                    "Completed with partial success (e.g. some orders filled).",
                    PopupNotificationState.Partial
                );
            };
            panel.AddChild(partialBtn);

            // Information
            var infoBtn = new Button { Text = "Show: Information", Margin = 5 };
            infoBtn.Click += _ =>
            {
                Notifications.ShowPopup(
                    "Information",
                    "General update: your settings were saved.",
                    PopupNotificationState.Information
                );
            };
            panel.AddChild(infoBtn);

            Chart.AddControl(panel);
        }

        protected override void OnTick()
        {
            // Handle price updates here if needed
        }

        protected override void OnStop()
        {
            // Cleanup if needed
        }
    }
}

订单跟踪和反馈

显示订单执行反馈

使用弹出通知立即查看您的市价订单是否成功。 例如,在您的 cBot 下达买入订单后,如果交易成交,它会显示成功弹窗;如果经纪商拒绝,则显示错误弹窗。

1
2
3
var result = ExecuteMarketOrder(TradeType.Buy, SymbolName, 1000);
var state = result.IsSuccessful ? PopupNotificationState.Success : PopupNotificationState.Error;
Notifications.ShowPopup("Order Execution", $"Order result: {result.Error}", state);

确认止盈或止损退出

当您的 cBot 交易因止盈或止损而退出时获得通知。 弹窗会显示退出原因以及已平仓头寸的盈亏。 这种退出时刻的实时反馈有助于您跟踪交易并及时了解活跃头寸的结果。

1
2
3
4
5
6
protected override void OnPositionClosed(PositionClosedEventArgs args)
{
    var pos = args.Position;
    var reason = pos.ClosingReason.ToString();
    Notifications.ShowPopup("Position Closed", $"Closed due to {reason}. PnL: {pos.GrossProfit}", PopupNotificationState.Information);
}

跟踪追踪止损修改

每次追踪止损更新头寸的止损时都会看到弹窗。 通知包括新的止损值,并显示追踪止损如何跟踪价格走势。 这些提醒让您无需打开任何面板即可监控交易保护如何调整。

1
2
3
4
5
6
7
protected override void OnPositionModified(PositionModifiedEventArgs args)
{
    if (args.Reason == PositionModificationReason.TrailingStop)
    {
        Notifications.ShowPopup("Trailing Stop Moved", $"New SL: {args.Position.StopLoss}", PopupNotificationState.Information);
    }
}

风险和规则基础警报

警告低保证金水平

当您账户的保证金水平低于临界阈值(例如 80%)时,收到弹窗警报。 该警告有助于您及时采取行动,如平仓或追加资金,以避免强制平仓或追加保证金通知。 弹窗根据实时风险数据充当自动保护措施。

1
2
3
4
5
6
7
protected override void OnTick()
{
    if (Account.MarginLevel < 80)
    {
        Notifications.ShowPopup("Low Margin Warning", $"Current margin level: {Account.MarginLevel:0.00}%", PopupNotificationState.Error);
    }
}

显示被阻止交易的警报

某些 cBot 被编程为在触发内部安全规则(如低净值或过度回撤)时停止下单。 弹窗可以解释阻止原因并向您显示违反了哪个条件。 此通知确保您了解为什么跳过了信号,并强化了有纪律的策略行为。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
protected override void OnBar()
{
    if (Account.Equity < 100)
    {
        Notifications.ShowPopup("Trade Blocked", "Equity too low to place trade", PopupNotificationState.Error);
        return;
    }

    ExecuteMarketOrder(TradeType.Sell, SymbolName, 1000);
}

进度和诊断

通过弹窗显示分析进度

使用"进行中"弹窗来指示长时间运行的进程的开始,如数据验证或回测准备。 操作完成后,将弹窗更新为"成功"或"错误"状态。 显示的进度报告让您无需查看日志或调试消息即可随时了解情况。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private PopupNotification _progressPopup;

protected override void OnStart()
{
    _progressPopup = Notifications.ShowPopup("Analysis Started", "Running analysis...", PopupNotificationState.InProgress);
    Timer.Start(4); // Simulate 4-second task
}

protected override void OnTimer()
{
    _progressPopup.Complete(PopupNotificationState.Success);
    Timer.Stop();
}

手动交易互动

按钮触发交易后通知用户

点击自定义控件或按钮后,您的 cBot 可以下单并立即显示结果弹窗。 通知确认您的手动操作是否成功或失败,并显示经纪商返回的任何错误。 这种视觉反馈减少了猜测,提高了您对手动干预的信心。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
protected override void OnStart()
{
    var panel = new StackPanel();
    var button = new Button { Text = "Manual Buy" };

    button.Click += args =>
    {
        var result = ExecuteMarketOrder(TradeType.Buy, SymbolName, 1000);
        var status = result.IsSuccessful ? PopupNotificationState.Success : PopupNotificationState.Error;
        Notifications.ShowPopup("Manual Trade", $"Buy order result: {result.Error}", status);
    };

    panel.AddChild(button);
    Chart.AddControl(panel);
}

警告手动覆盖或干预

当您覆盖自动逻辑或执行手动覆盖(例如在阻止状态下强制交易)时,弹窗可以确认该操作。

1
2
3
4
5
button.Click += args =>
{
    Notifications.ShowPopup("Manual Override", "User manually triggered a trade", PopupNotificationState.Information);
    ExecuteMarketOrder(TradeType.Sell, SymbolName, 1000);
};

市场事件和信号警报

信号指标交叉

监控关键技术事件,如移动平均线交叉或 RSI 阈值,并在发生时显示弹窗警报。 通知突出显示指标和满足的条件,如看涨交叉。 这让您随时了解技术信号,使您的策略更加透明和可追踪。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
private MovingAverage _fast, _slow;

protected override void OnStart()
{
    _fast = Indicators.MovingAverage(MarketSeries.Close, 5, MovingAverageType.Exponential);
    _slow = Indicators.MovingAverage(MarketSeries.Close, 20, MovingAverageType.Exponential);
}

protected override void OnBar()
{
    int i = MarketSeries.Close.Count - 1;
    if (_fast.Result[i] > _slow.Result[i] && _fast.Result[i - 1] <= _slow.Result[i - 1])
    {
        Notifications.ShowPopup("MA Crossover", "Fast MA crossed above Slow MA", PopupNotificationState.Information);
    }
}

提醒交易时段开始或价格突破

创建在重要市场事件发生时触发的弹窗,如伦敦交易时段开始或短时间内的快速价格变动。 这些通知充当情境感知工具,帮助您对潜在波动做出反应或为市场活动做好准备。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
protected override void OnBar()
{
    var time = Server.Time;
    if (time.TimeOfDay.Hours == 8 && time.TimeOfDay.Minutes == 0)
    {
        Notifications.ShowPopup("London Session Open", "London market has opened", PopupNotificationState.Information);
    }

    if (Math.Abs(Symbol.Bid - Symbol.Ask) / Symbol.PipSize > 15)
    {
        Notifications.ShowPopup("Spread Spike", "Spread exceeded 15 pips!", PopupNotificationState.Warning);
    }
}

策略调试和透明度

直观跟踪策略步骤

使用一系列弹窗来显示策略的逻辑流程。 例如,在检查趋势、确认信号或验证风险时显示消息。 每个弹窗代表一个特定检查点,让您实时跟踪策略如何做出决策。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
protected override void OnBar()
{
    Notifications.ShowPopup("Step 1", "Checking market condition", PopupNotificationState.Information);

    if (MarketSeries.Close.Last(1) > MarketSeries.Open.Last(1))
    {
        Notifications.ShowPopup("Step 2", "Bullish candle detected", PopupNotificationState.Information);
    }

    Notifications.ShowPopup("Step 3", "Trade logic complete", PopupNotificationState.Success);
}

报告逻辑失败或意外数据

当您的策略遇到错误或无效数据(如价格不匹配或指标不可用)时,使用弹窗显示具体问题。 这种设置有助于您在开发和模拟/实盘交易期间识别错误或数据缺口,从而更快地调试并提高逻辑的稳健性。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
protected override void OnBar()
{
    try
    {
        // Assume some strategy logic
        if (Symbol.Bid < 0) throw new Exception("Invalid price feed");

        Notifications.ShowPopup("Logic OK", "Price validation passed", PopupNotificationState.Success);
    }
    catch (Exception ex)
    {
        Notifications.ShowPopup("Logic error", ex.Message, PopupNotificationState.Error);
    }
}