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.
Learn how to create plugins, using either C# or Python, in our step-by-step guides.
BacktestingInPlugins Sample plugin code is available in our public C# and Python repositories. The same code is provided as a template in the algorithm creation wizard in cTrader Windows or Mac, or you can simply copy and use the snippet below:
usingSystem;usingcAlgo.API;usingcAlgo.API.Collections;usingcAlgo.API.Indicators;usingcAlgo.API.Internals;usingSystem.Linq;usingSystem.Text.Json;usingSystem.Text.Json.Nodes;namespacecAlgo.Plugins{[Plugin(AccessRights = AccessRights.None)]publicclassBacktestingInPluginsSample:Plugin{// Declaring the necessary UI elements// and the cBot (RobotType) selected in the ComboBoxprivateGrid_grid;privateComboBox_cBotsComboBox;privateButton_startBacktestingButton;privateTextBlock_resultsTextBlock;privateRobotType_selectedRobotType;protectedoverridevoidOnStart(){// Initialising and structuring the UI elements_grid=newGrid(3,1);_cBotsComboBox=newComboBox();_startBacktestingButton=newButton{BackgroundColor=Color.Green,CornerRadius=newCornerRadius(5),Text="Start Backtesting",};_resultsTextBlock=newTextBlock{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);varblock=Asp.SymbolTab.AddBlock("Backtesting Plugin");block.Child=_grid;// Populating the ComboBox with existing cBotsPopulateCBotsComboBox();// 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;}protectedvoidStartBacktestingButton_Click(ButtonClickEventArgsobj){// Initialising and configuring the backtesting settingsvarbacktestingSettings=newBacktestingSettings{DataMode=BacktestingDataMode.M1,StartTimeUtc=newDateTime(2023,6,1),EndTimeUtc=DateTime.UtcNow,Balance=10000,};// Starting backtesting on EURUSD h1Backtesting.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...";}protectedvoidPopulateCBotsComboBox(){// Iterating over the AlgoRegistry and// getting the names of all installed cBotsforeach(varrobotTypeinAlgoRegistry.OfType<RobotType>()){_cBotsComboBox.AddItem(robotType.Name);}}protectedvoidBacktesting_Completed(BacktestingCompletedEventArgsobj){// Attaining the JSON results of backtestingstringjsonResults=obj.JsonReport;// Converting the JSON string into a JsonNodeJsonNoderesultsNode=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;}protectedvoidCBotsComboBox_SelectedItemChanged(ComboBoxSelectedItemChangedEventArgsobj){// Updating the variable to always contain// the cBot selected in the ComboBox_selectedRobotType=AlgoRegistry.Get(obj.SelectedItem)asRobotType;}}}
importclrclr.AddReference("cAlgo.API")fromcAlgo.APIimport*fromSystemimportDateTimefromSystem.Text.Json.NodesimportJsonNodefromSystem.Text.JsonimportJsonDocumentOptionsimportjsonclassBacktestingInPluginsSample():defon_start(self):self.grid=Grid(3,1)self.cBotsComboBox=ComboBox()self.startBacktestingButton=Button()self.startBacktestingButton.BackgroundColor=Color.Greenself.startBacktestingButton.CornerRadius=CornerRadius(5)self.startBacktestingButton.Text="Start Backtesting"self.resultsTextBlock=TextBlock()self.resultsTextBlock.HorizontalAlignment=HorizontalAlignment.Centerself.resultsTextBlock.VerticalAlignment=VerticalAlignment.Centerself.resultsTextBlock.Text="Select a cBot..."self.grid.AddChild(self.cBotsComboBox,0,0)self.grid.AddChild(self.startBacktestingButton,1,0)self.grid.AddChild(self.resultsTextBlock,2,0)block=api.Asp.SymbolTab.AddBlock("Backtesting Plugin")block.Child=self.grid# Populating the ComboBox with existing cBotsself.populate_cbots_combobox();self.startBacktestingButton.Click+=self.on_start_backtesting_button_click;self.cBotsComboBox.SelectedItemChanged+=self.on_cbots_combobox_selected_item_changed;api.Backtesting.Completed+=self.on_backtesting_completed;defpopulate_cbots_combobox(self):# Iterating over the AlgoRegistry and getting the names of all installed cBotsforrobotTypeinapi.AlgoRegistry.Robots:self.cBotsComboBox.AddItem(robotType.Name)defon_start_backtesting_button_click(self,args):backtestingSettings=BacktestingSettings()backtestingSettings.DataMode=BacktestingDataMode.M1backtestingSettings.StartTimeUtc=DateTime(DateTime.UtcNow.Year-2,DateTime.UtcNow.Month,DateTime.UtcNow.Day)backtestingSettings.EndTimeUtc=DateTime.UtcNowbacktestingSettings.Balance=10000# Starting backtesting on EURUSD h1self.backtestingProcess=api.Backtesting.Start(self.selectedRobotType,"EURUSD",TimeFrame.Hour,backtestingSettings)# Disabling other controls and changing the text inside the TextBlockself.cBotsComboBox.IsEnabled=Falseself.startBacktestingButton.IsEnabled=Falseself.resultsTextBlock.Text="Backtesting in progress..."defon_cbots_combobox_selected_item_changed(self,args):self.selectedRobotType=RobotType(api.AlgoRegistry.Get(args.SelectedItem))defon_backtesting_completed(self,args):ifint(args.Process.BacktestingError)>0:api.Print(f"Backtesting failed with error {args.Process.BacktestingError}")returnjsonResults=json.loads(args.JsonReport)# # Attaining the ROI and net profit from backtesting resultsself.resultsTextBlock.Text=f"ROI: {jsonResults["main"]["roi"]}\nNet Profit: {jsonResults["main"]["netProfit"]}"# Re-enabling controls after backteting is finishedself.cBotsComboBox.IsEnabled=True;self.startBacktestingButton.IsEnabled=True;
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.
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.
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.