Skip to content

BacktestingInPlugins Sample

Overview

The BacktestingInPlugins Sample plugin enables running historical strategy testing directly from the cTrader platform interface using the following key functionalities:

  • Creates a structured panel layout with a dropdown menu, action button and results display field.
  • Lists all installed cBots in the dropdown for easy selection.
  • Runs a backtest on the set symbol using historical data when triggered.
  • Displays return on investment (ROI) and net profit from the backtest results.

This plugin runs in a custom panel within Active Symbol Panel and remains active while cTrader Windows or Mac is open. It stops automatically when the platform is closed or restarted.

Plugin creation

Learn how to create, edit and build plugins from a template or from scratch in our step-by-step guide.

You can find the code of the BacktestingInPlugins Sample plugin on GitHub, or simply copy it below.

Sample code
using System;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace cAlgo.Plugins
{
    [Plugin(AccessRights = AccessRights.None)]
    public class BacktestingInPluginsSample : Plugin
    {
        // Declaring the necessary UI elements
        // and the cBot (RobotType) selected in the ComboBox
        private Grid _grid;
        private ComboBox _cBotsComboBox;
        private Button _startBacktestingButton;
        private TextBlock _resultsTextBlock;
        private RobotType _selectedRobotType;

        protected override void OnStart()
        {
            // Initialising and structuring the UI elements
            _grid = new Grid(3, 1);
            _cBotsComboBox = new ComboBox();
            _startBacktestingButton = new Button
            {
                BackgroundColor = Color.Green,
                CornerRadius = new CornerRadius(5),
                Text = "Start Backtesting",
            };
            _resultsTextBlock = new TextBlock
            {
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
                Text = "Select a cBot...",
            };

            _grid.AddChild(_cBotsComboBox, 0, 0);
            _grid.AddChild(_startBacktestingButton, 1, 0);
            _grid.AddChild(_resultsTextBlock, 2, 0);

            var block = Asp.SymbolTab.AddBlock("Backtesting Plugin");
            block.Child = _grid;

            // Populating the ComboBox with existing cBots
            PopulateCBotsComboBox();

            // Assigning event handlers to the Button.Click,
            // ComboBox.SelectedItemChanged, and Backtesting.Completed events
            _startBacktestingButton.Click += StartBacktestingButton_Click;
            _cBotsComboBox.SelectedItemChanged += CBotsComboBox_SelectedItemChanged;
            Backtesting.Completed += Backtesting_Completed;
        }

        protected void StartBacktestingButton_Click(ButtonClickEventArgs obj)
        {
            // Initialising and configuring the backtesting settings
            var backtestingSettings = new BacktestingSettings 
            {
                DataMode = BacktestingDataMode.M1,
                StartTimeUtc = new DateTime(2023, 6, 1),
                EndTimeUtc = DateTime.UtcNow,
                Balance = 10000,
            };

            // Starting backtesting on EURUSD h1
            Backtesting.Start(_selectedRobotType, "EURUSD", TimeFrame.Hour, backtestingSettings);

            // Disabling other controls and changing
            // the text inside the TextBlock
            _cBotsComboBox.IsEnabled = false;
            _startBacktestingButton.IsEnabled = false;
            _resultsTextBlock.Text = "Backtesting in progress...";
        }

        protected void PopulateCBotsComboBox()
        {
            // Iterating over the AlgoRegistry and
            // getting the names of all installed cBots
            foreach (var robotType in AlgoRegistry.OfType<RobotType>())
            {
                _cBotsComboBox.AddItem(robotType.Name);
            }
        }

        protected void Backtesting_Completed(BacktestingCompletedEventArgs obj)
        {
            // Attaining the JSON results of backtesting
            string jsonResults = obj.JsonReport;

            // Converting the JSON string into a JsonNode
            JsonNode resultsNode = JsonNode.Parse(jsonResults);

            // Attaining the ROI and net profit from backtesting results
            _resultsTextBlock.Text = $"ROI: {resultsNode["main"]["roi"]}\nNet Profit: {resultsNode["main"]["netProfit"]}";

            // Re-enabling controls after backtesting is finished
            _cBotsComboBox.IsEnabled = true;
            _startBacktestingButton.IsEnabled = true;
        }

        protected void CBotsComboBox_SelectedItemChanged(ComboBoxSelectedItemChangedEventArgs obj)
        {
            // Updating the variable to always contain
            // the cBot selected in the ComboBox
            _selectedRobotType = AlgoRegistry.Get(obj.SelectedItem) as RobotType;
        }
    }
}

Customisation options

This plugin provides a direct interface for initiating backtests and viewing basic results. The table below outlines its key components and their functions:

Parameter Description Possible values
_grid Defines the layout for the plugin interface. (3, 1), (2, 2), etc.
_startBacktestingButton Customises the appearance and label of the start button. Start Backtesting, Color.Green, new CornerRadius(5)
_cBotsComboBox.AddItem Populates the ComboBox with cBots from the registry. robottype.name
_resultsTextBlock.Text Displays messages during the backtest cycle. Select a cBot..., Backtesting in progress..., Backtesting results summary, etc.
CBotsComboBox_SelectedItemChanged Updates the selected cBot for testing. obj.selecteditem
StartTimeUtc Backtest start date and time in UTC. new datetime(2023, 6, 1)
EndTimeUtc Backtest end date and time in UTC. datetime.utcnow
DataMode Defines what represents each data point move (1 minute, 1 hour or 1 day). backtestingdatamode.m1
Balance Starting virtual account balance. 10000, 20000, etc.
Backtesting.Start Defines what symbol and timeframe to run backtests on. eurusd, timeframe.hour
Backtesting_Completed Extracts and shows test results in the UI. resultsnode[main][roi], resultsnode[main][netprofit], etc.

Note

Ensure at least one cBot is installed in cTrader for the dropdown to populate correctly.

Use cases

This plugin provides a way to run historical strategy tests in Active Symbol Panel. It simplifies selecting and testing cBots, making it ideal for strategy evaluation. Below are practical use cases that show how the plugin may be applied to real trading scenarios.

Use case Scenario Value
Strategy comparison Run backtests on multiple cBots using identical test conditions. Enables direct performance comparison within a single session.
Quick performance review Test any installed cBot on a standard market setup. Helps you assess the performance of a cBot before running it on a live account.
Fixed rules backtest Validate algorithm changes by launching a predefined backtest. Ensures consistency in test conditions when debugging or version-testing strategies.
Quick insights tool View ROI and profit feedback immediately after testing installed cBots. Saves time compared to launching separate testing sessions.

Summary

This plugin provides a streamlined interface for selecting a cBot and running a historical backtest using predefined settings. It runs the test on a chosen symbol and time frame, then displays key performance metrics such as ROI and net profit. The structure supports quick strategy validation and is adaptable for various trading scenarios.

For further development details, refer to our plugin documentation.