Saltar a contenido

Backtesting en plugins

cTrader Algo permite realizar backtesting de cBots directamente desde un plugin, lo que abre muchas posibilidades para los desarrolladores de algoritmos. Lea nuestro resumen de un minuto a continuación para obtener más información.

¡Backtesting en plugins en un minuto!

  • Inicie el backtesting de forma programática o en respuesta a la retroalimentación del usuario y muestre los resultados en cualquier lugar adecuado de la interfaz de usuario de cTrader donde se pueda colocar un plugin.
  • Amplíe las capacidades de backtesting integradas en cTrader añadiendo nuevas estrategias de backtesting como la simulación de Monte Carlo.
  • Añada estadísticas personalizadas a los resultados del backtesting y muéstrelas directamente en la interfaz de usuario de cTrader.
  • Cree métodos de optimización complejos que vayan más allá del algoritmo genético estándar.

Cómo funciona el backtesting en plugins

La clase base Plugin tiene acceso a la interfaz Backtesting desde la que puede llamar al método Start() con la siguiente firma.

1
BacktestingProcess Start(RobotType robotType, string symbolName, TimeFrame timeFrame, BacktestingSettings settings, params object[] parameterValues);

Parámetros

En el array parameterValues, los parámetros del cBot deben pasarse en un orden fijo (el orden en el que se especifican en la interfaz de usuario de cTrader). Si faltan algunos parámetros, se insertan automáticamente valores predeterminados.

Procesos de backtesting

Al iniciar el backtesting de forma programática, puede lanzar varios procesos de backtesting en paralelo, lo que potencialmente podría ahorrarle mucho tiempo.

Además, la interfaz también contiene dos eventos, a saber, ProgressChanged y Completed. Los argumentos para el evento Completed (BacktestingCompletedEventArgs) contienen un objeto JSON de los resultados finales del backtesting (JsonReport), lo que le permite interpretarlos según sea necesario y mostrar las estadísticas resultantes a los nuevos usuarios.

Crear un plugin de ejemplo

El siguiente plugin muestra un nuevo bloque en el Panel de símbolo activo (ASP). Dentro del bloque, el plugin permite a los usuarios elegir cualquier cBot que posean y realizar un backtesting en EURUSD h1. Después de que concluya el backtesting, el plugin muestra el ROI final y el beneficio neto.

  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
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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)
        {
            // Updading the variable to always contain
            // the cBot selected in the ComboBox
            _selectedRobotType = AlgoRegistry.Get(obj.SelectedItem) as RobotType;
        }

    }
}

El plugin reacciona dinámicamente al estado del proceso de backtesting. Tan pronto como finaliza el backtesting, el plugin muestra los resultados en el TextBlock. El _startBacktestingButton y el _cBotsComboBox están deshabilitados durante todo el backtesting.

Resumen

El backtesting a través de plugins es una función poderosa que le permite crear extensiones de interfaz de usuario sobre la ya potente lógica de backtesting proporcionada por cTrader. Junto con otros miembros de la API como AlgoRegistry, el backtesting en plugins ofrece numerosas posibilidades para cualquiera que venda y desarrolle algoritmos de cTrader.

Image title