Ana içeriğe geç

BacktestingInPlugins Sample

Genel Bakış

BacktestingInPlugins Sample eklentisi, aşağıdaki temel işlevleri kullanarak geçmiş strateji testini doğrudan cTrader platform arayüzünden çalıştırmayı sağlar:

  • Açılır menü, eylem düğmesi ve sonuç görüntüleme alanına sahip yapılandırılmış bir panel düzeni oluşturur.
  • Kolay seçim için yüklü tüm cBot'ları açılır menüde listeler.
  • Tetiklendiğinde, belirlenen sembol üzerinde geçmiş verileri kullanarak geriye dönük bir test çalıştırır.
  • Geriye dönük test sonuçlarından yatırım getirisini (ROI) ve net kârı görüntüler.

Bu eklenti, Aktif Sembol Paneli içinde özel bir panelde çalışır ve cTrader Windows veya Mac açıkken aktif kalır. Platform kapatıldığında veya yeniden başlatıldığında otomatik olarak durur.

Eklenti oluşturma

Adım adım rehberlerimizde C# veya Python kullanarak eklentiler oluşturmayı öğrenin.

BacktestingInPlugins Sample eklenti kodu, genel C# ve Python depolarımızda mevcuttur. Aynı kod, cTrader Windows veya Mac'teki algoritma oluşturma sihirbazında bir şablon olarak sağlanmıştır veya aşağıdaki kod parçasını kopyalayıp kullanabilirsiniz:

  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
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;
        }
    }
}
 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
import clr
clr.AddReference("cAlgo.API")

from cAlgo.API import *

from System import DateTime
from System.Text.Json.Nodes import JsonNode
from System.Text.Json import JsonDocumentOptions
import json

class BacktestingInPluginsSample():
    def on_start(self):
        self.grid = Grid(3, 1)

        self.cBotsComboBox = ComboBox()

        self.startBacktestingButton = Button()
        self.startBacktestingButton.BackgroundColor = Color.Green
        self.startBacktestingButton.CornerRadius = CornerRadius(5)
        self.startBacktestingButton.Text = "Start Backtesting"

        self.resultsTextBlock = TextBlock()
        self.resultsTextBlock.HorizontalAlignment = HorizontalAlignment.Center
        self.resultsTextBlock.VerticalAlignment = VerticalAlignment.Center
        self.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 cBots
        self.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;

    def populate_cbots_combobox(self):
        # Iterating over the AlgoRegistry and getting the names of all installed cBots
        for robotType in api.AlgoRegistry.Robots:
            self.cBotsComboBox.AddItem(robotType.Name)

    def on_start_backtesting_button_click(self, args):
        backtestingSettings = BacktestingSettings()
        backtestingSettings.DataMode = BacktestingDataMode.M1
        backtestingSettings.StartTimeUtc = DateTime(DateTime.UtcNow.Year - 2, DateTime.UtcNow.Month, DateTime.UtcNow.Day)
        backtestingSettings.EndTimeUtc = DateTime.UtcNow
        backtestingSettings.Balance = 10000

        # Starting backtesting on EURUSD h1
        self.backtestingProcess = api.Backtesting.Start(self.selectedRobotType, "EURUSD", TimeFrame.Hour, backtestingSettings)

        # Disabling other controls and changing the text inside the TextBlock
        self.cBotsComboBox.IsEnabled = False
        self.startBacktestingButton.IsEnabled = False
        self.resultsTextBlock.Text = "Backtesting in progress..."

    def on_cbots_combobox_selected_item_changed(self, args):
        self.selectedRobotType = RobotType(api.AlgoRegistry.Get(args.SelectedItem))

    def on_backtesting_completed(self, args):
        if int(args.Process.BacktestingError) > 0:
            api.Print(f"Backtesting failed with error {args.Process.BacktestingError}")
            return

        jsonResults = json.loads(args.JsonReport)

        # # Attaining the ROI and net profit from backtesting results
        self.resultsTextBlock.Text = f"ROI: {jsonResults["main"]["roi"]}\nNet Profit: {jsonResults["main"]["netProfit"]}"

        # Re-enabling controls after backteting is finished
        self.cBotsComboBox.IsEnabled = True;
        self.startBacktestingButton.IsEnabled = True;

Özelleştirme seçenekleri

Bu eklenti, geriye dönük testleri başlatmak ve temel sonuçları görüntülemek için doğrudan bir arayüz sağlar. Aşağıdaki tablo, temel bileşenlerini ve işlevlerini özetlemektedir:

Parametre Açıklama Olası değerler
_grid Eklenti arayüzü için düzeni tanımlar. (3, 1), (2, 2), vb.
_startBacktestingButton Başlat düğmesinin görünümünü ve etiketini özelleştirir. Start Backtesting, Color.Green, new CornerRadius(5)
_cBotsComboBox.AddItem Açılır kutuyu kayıttaki cBot'larla doldurur. robottype.name
_resultsTextBlock.Text Geriye dönük test döngüsü sırasında mesajları görüntüler. Bir cBot seçin..., Geriye dönük test devam ediyor..., Geriye dönük test sonuçları özeti, vb.
CBotsComboBox_SelectedItemChanged Test için seçilen cBot'u günceller. obj.selecteditem
StartTimeUtc Geriye dönük test başlangıç tarihi ve UTC saati. new datetime(2023, 6, 1)
EndTimeUtc Geriye dönük test bitiş tarihi ve UTC saati. datetime.utcnow
DataMode Her veri noktası hareketini neyin temsil ettiğini tanımlar (1 dakika, 1 saat veya 1 gün). backtestingdatamode.m1
Balance Başlangıç sanal hesap bakiyesi. 10000, 20000, vb.
Backtesting.Start Hangi sembol ve zaman diliminde geriye dönük testlerin çalıştırılacağını tanımlar. eurusd, timeframe.hour
Backtesting_Completed Test sonuçlarını çıkarır ve kullanıcı arayüzünde gösterir. resultsnode[main][roi], resultsnode[main][netprofit], vb.

Not

Açılır menünün doğru şekilde doldurulması için cTrader'da en az bir cBot'un yüklü olduğundan emin olun.

Kullanım durumları

Bu eklenti, Aktif Sembol Panelinde geçmiş strateji testlerini çalıştırmak için bir yol sağlar. cBot'ları seçmeyi ve test etmeyi basitleştirir, bu da onu strateji değerlendirmesi için ideal kılar. Aşağıda, eklentinin gerçek işlem senaryolarına nasıl uygulanabileceğini gösteren pratik kullanım durumları bulunmaktadır.

Kullanım durumu Senaryo Değer
Strateji karşılaştırması Aynı test koşullarını kullanarak birden fazla cBot üzerinde geriye dönük testler çalıştırın. Tek bir seans içinde doğrudan performans karşılaştırması sağlar.
Hızlı performans incelemesi Yüklü herhangi bir cBot'u standart bir piyasa kurulumunda test edin. Canlı bir hesapta çalıştırmadan önce bir cBot'un performansını değerlendirmenize yardımcı olur.
Sabit kurallar geriye dönük testi Önceden tanımlanmış bir geriye dönük test başlatarak algoritma değişikliklerini doğrulayın. Stratejileri hata ayıklarken veya sürüm test ederken test koşullarında tutarlılık sağlar.
Hızlı analiz aracı Yüklü cBot'ları test ettikten hemen sonra ROI ve kâr geri bildirimini görüntüleyin. Ayrı test oturumları başlatmaya kıyasla zaman kazandırır.

Özet

Bu eklenti, bir cBot seçmek ve önceden tanımlanmış ayarları kullanarak geçmişe dönük bir geriye dönük test çalıştırmak için kolaylaştırılmış bir arayüz sağlar. Seçilen bir sembol ve zaman aralığında testi çalıştırır, ardından ROI ve net kâr gibi temel performans metriklerini görüntüler. Yapı, hızlı strateji doğrulamayı destekler ve çeşitli işlem senaryolarına uyarlanabilir.

Daha fazla geliştirme ayrıntısı için eklenti belgelerimize bakın.