콘텐츠로 이동

플러그인에서 백테스트

cTrader Algo는 플러그인에서 직접 cBot을 백테스트할 수 있도록 하여 알고리즘 개발자에게 많은 가능성을 열어줍니다. 아래의 1분 요약을 읽어보세요.

플러그인에서 백테스트를 1분 만에!

  • 프로그래밍 방식으로 또는 사용자 피드백에 따라 백테스트를 시작하고 결과를 cTrader UI의 플러그인이 배치될 수 있는 적절한 위치에 출력합니다.
  • Monte Carlo 시뮬레이션과 같은 새로운 백테스트 전략을 추가하여 cTrader 내장 백테스트 기능을 확장합니다.
  • 백테스트 결과에 커스텀 통계를 추가하고 이를 cTrader UI에 직접 표시합니다.
  • 표준 유전자 알고리즘을 넘어서는 복잡한 최적화 방법을 생성합니다.

플러그인에서 백테스트가 작동하는 방식

Plugin 기본 클래스는 Backtesting 인터페이스에 액세스할 수 있으며, 이를 통해 다음 시그니처를 가진 Start() 메서드를 호출할 수 있습니다.

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

매개변수

parameterValues 배열에서 cBot 매개변수는 고정된 순서로 전달되어야 합니다(cTrader UI에서 지정된 순서). 일부 매개변수가 누락된 경우 기본값이 자동으로 삽입됩니다.

백테스트 프로세스

프로그래밍 방식으로 백테스트를 시작할 때 여러 백테스트 프로세스를 병렬로 시작할 수 있으며, 이는 잠재적으로 많은 시간을 절약할 수 있습니다.

또한, 이 인터페이스는 ProgressChangedCompleted라는 두 가지 이벤트를 포함합니다. Completed 이벤트(BacktestingCompletedEventArgs)의 인수는 최종 백테스트 결과(JsonReport)의 JSON 객체를 포함하여 필요에 따라 해석하고 결과 통계를 새로운 사용자에게 표시할 수 있습니다.

예제 플러그인 생성

다음 플러그인은 활성 심벌 패널(ASP)에 새로운 블록을 표시합니다. 블록 내부에서 플러그인은 사용자가 소유한 모든 cBot을 선택하고 EURUSD h1에서 백테스트할 수 있도록 합니다. 백테스트가 완료되면 플러그인은 최종 ROI와 순이익을 표시합니다.

  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;
        }

    }
}

플러그인은 백테스트 프로세스의 상태에 동적으로 반응합니다. 백테스트가 완료되면 플러그인은 TextBlock에 결과를 표시합니다. _startBacktestingButton_cBotsComboBox는 백테스트 동안 비활성화됩니다.

요약

플러그인을 통한 백테스트는 cTrader가 제공하는 강력한 백테스트 로직 위에 UI 확장을 구축할 수 있는 강력한 기능입니다. AlgoRegistry와 같은 다른 API 멤버와 결합하여 플러그인에서의 백테스트는 cTrader 알고리즘을 판매하고 개발하는 모든 사람에게 많은 가능성을 제공합니다.

Image title