Bỏ qua

Các loại tham số có thể tùy chỉnh

Vì C# là ngôn ngữ kiểu mạnh, cần phải chỉ định kiểu dữ liệu khi khai báo biến và thuộc tính lớp trong cBot, chỉ báo và plugin. Ngược lại, Python là kiểu động, vì vậy kiểu biến được suy ra tự động. Tuy nhiên, khi phát triển cBot sử dụng cTrader API, các kiểu khái niệm tương tự được giữ nguyên để đảm bảo tính nhất quán giữa cả hai ngôn ngữ.

API cTrader Algo không cho phép sử dụng tất cả các kiểu dữ liệu làm tham số có thể tùy chỉnh, và đó là lý do tại sao các nhà phát triển thuật toán cần hiểu và điều hướng cẩn thận giữa các kiểu được hỗ trợ.

Ghi chú

Các cBot, chỉ báo và plugin Python sử dụng các tham số có thể tùy chỉnh được khai báo trong các tệp .cs của chúng.

Trường hợp sử dụng tham số và giao diện người dùng

cTrader chỉ hỗ trợ các loại tham số này với các trường hợp sử dụng chính và các phần tử giao diện người dùng liên quan được phản ánh trong bảng dưới đây.

C# Python Trường hợp sử dụng Phần tử giao diện người dùng
int int Khối lượng lệnh, số lượng nến, số chu kỳ, v.v. Trường nhập số (có nút tăng giảm)
double float Giá trị giá, khối lượng lệnh, v.v. Trường nhập số (có nút tăng giảm)
string str Tin nhắn tùy chỉnh, nhãn vị thế, v.v. Trường nhập văn bản
bool bool Cơ chế bảo vệ, cho phép giao dịch, cho phép email, v.v. Danh sách thả xuống có/không
DataSeries api.DataSeries Nguồn giá thị trường, v.v. Danh sách thả xuống
TimeFrame api.TimeFrame Khung thời gian đã chọn, v.v. Bộ chọn chu kỳ
enum Enum Căn chỉnh bản vẽ biểu đồ, mức độ rủi ro cá nhân, v.v. Danh sách thả xuống
Color Color Bản vẽ biểu đồ, màu sắc của phương tiện phân tích kỹ thuật, phần tử tùy chỉnh, v.v. Bộ chọn màu
DateTime DateTime Lấy ngày và giờ kiểu mạnh trong múi giờ của thuật toán Bộ chọn ngày và giờ
DateOnly DateOnly Lấy ngày kiểu mạnh Bộ chọn ngày
TimeSpan TimeSpan Lấy khoảng thời gian hoặc thời gian trong ngày kiểu mạnh Bộ chọn thời gian
Symbol Symbol Lấy một biểu tượng kiểu mạnh Bộ chọn biểu tượng
Symbol[] Symbol[] Lấy nhiều biểu tượng kiểu mạnh trong một mảng Bộ chọn nhiều biểu tượng
Enum[] Enum[] Lấy nhiều giá trị kiểu Enum kiểu mạnh trong một mảng Bộ chọn nhiều giá trị enum
TimeFrame[] TimeFrame[] Lấy nhiều giá trị TimeFrame kiểu mạnh trong một mảng Bộ chọn nhiều chu kỳ

Cảnh báo

Bạn có thể không sử dụng được một số loại tham số trên nếu bạn đang sử dụng phiên bản cũ hơn của cTrader hoặc Algo API.

Ví dụ, giao diện người dùng cTrader phản ánh các kiểu bool, double, int của C# và bool, float, int của Python như sau.

Image title

Ba ví dụ tiếp theo cho thấy các kiểu dữ liệu DataSeries, enum tùy chỉnh, string của C# và api.DataSeries, Enum, str của Python (mà chúng tôi cũng cung cấp mã đầy đủ trong hướng dẫn này).

DataSeries

Enum

String

Như được hiển thị bên dưới, kiểu tham số Color của C# và Color của Python được biểu diễn bằng một bộ chọn màu.

Image title

Cuối cùng, giao diện người dùng của kiểu dữ liệu TimeFrame của C# và api.TimeFrame của Python phản ánh các tùy chọn chu kỳ có sẵn trong biểu đồ giao dịch trong ứng dụng Trade.

Image title

Ví dụ về cBot

Nhãn vị thế là tham số string của C# và str của Python trong cBot sau đây.

 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None)]
    public class NewcBot2 : Robot
    {
        [Parameter(DefaultValue = "my label")]
        public string PositionLabel { get; set; }

        protected override void OnStart()
        {
            ExecuteMarketOrder(TradeType.Buy, "XAGUSD", 1000, PositionLabel);
        }

        protected override void OnStop()
        {
            var positionToFind = Positions.Find(PositionLabel);
            positionToFind.Close();
        }
    }
}

Ghi chú

Các cBot Python sử dụng các tham số có thể tùy chỉnh được khai báo trong các tệp .cs của chúng.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import clr

clr.AddReference("cAlgo.API")

from cAlgo.API import *
from robot_wrapper import *


class NewcBot2():
    def on_start(self):
        api.ExecuteMarketOrder(TradeType.Buy, "XAGUSD", 1000, api.PositionLabel)

    def on_stop(self):
        position_to_find = api.Positions.Find(api.PositionLabel)
        if position_to_find is not None:
            position_to_find.Close()

Các kiểu dữ liệu DataSeries, int, bool của C# và api.DataSeries, int, bool của Python được minh họa trong thuật toán dưới đây.

 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class SamplecBotReferenceSMA : Robot
    {
        [Parameter("Source")]
        public DataSeries Source { get; set; }

        [Parameter("SMA Period", DefaultValue = 14)]
        public int SmaPeriod { get; set; }

        [Parameter("Enable Trade", DefaultValue = true)]
        public bool EnableTrade { get; set; }

        private SimpleMovingAverage sma;

        protected override void OnStart()
        {
            sma = Indicators.SimpleMovingAverage(Source, SmaPeriod);
        }

        protected override void OnTick()
        {
            double currentSMA = sma.Result.LastValue;
            double currentPrice = Symbol.Bid;

            if (EnableTrade)
            {
                if (currentPrice > currentSMA)
                {
                    ExecuteMarketOrder(TradeType.Buy, Symbol, 1000, "Buy Order");
                }
                else if (currentPrice < currentSMA)
                {
                    ExecuteMarketOrder(TradeType.Sell, Symbol, 1000, "Sell Order");
                }
            }

            Print("Current Price: {0}, Current SMA: {1}", currentPrice, currentSMA);
        }
    }
}

Ghi chú

Các cBot Python sử dụng các tham số có thể tùy chỉnh được khai báo trong các tệp .cs của chúng.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import clr

clr.AddReference("cAlgo.API")

from cAlgo.API import *
from robot_wrapper import *


class SamplecBotReferenceSMA():
    def on_start(self):
        self.sma = api.Indicators.SimpleMovingAverage(api.Source, api.SmaPeriod)

    def on_tick(self):
        currentSMA = self.sma.Result.LastValue
        currentPrice = api.Symbol.Bid

        if api.EnableTrade:
            if currentPrice > currentSMA:
                api.ExecuteMarketOrder(TradeType.Buy, api.Symbol, 1000, "Buy Order")
            elif currentPrice < currentSMA:
                api.ExecuteMarketOrder(TradeType.Sell, api.Symbol, 1000, "Sell Order")

        api.Print("Current Price: {0}, Current SMA: {1}".format(currentPrice, currentSMA))

cBot này sử dụng Color làm tham số để xác định cách hiển thị văn bản trong khu vực biểu đồ:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None)]
    public class NewcBot : Robot
    {
        [Parameter(DefaultValue = "Yellow")]
        public Color TextColor { get; set; }

        protected override void OnBar() 
        {
            Chart.DrawStaticText("static", "cBot running!", VerticalAlignment.Center, HorizontalAlignment.Left, TextColor);
        }
    }
}

Trong ví dụ dưới đây, kiểu dữ liệu double của C# và float của Python đóng vai trò là tham số để nhập khối lượng lệnh tính bằng lot. cBot thực hiện lệnh mua thị trường sau ba nến đỏ liên tiếp.

 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class RedBarsBot : Robot
    {
        [Parameter("Order Volume (Lots)", DefaultValue = 0.1)]
        public double OrderVolume { get; set; }

        private int redBarsCount = 0;

        protected override void OnBar()
        {
            if (IsRedBar())
            {
                redBarsCount++;
                if (redBarsCount == 3)
                {
                    PlaceMarketOrder(TradeType.Buy);
                    redBarsCount = 0;
                }
            }
            else
            {
                redBarsCount = 0;
            }
        }

        private bool IsRedBar()
        {
            var currentBar = MarketSeries.Close.Last(1);
            var previousBar = MarketSeries.Close.Last(2);

            return currentBar < previousBar;
        }

        private void PlaceMarketOrder(TradeType tradeType)
        {
            var symbol = Symbol;
            var volume = Symbol.QuantityToVolume(OrderVolume);

            ExecuteMarketOrder(tradeType, symbol, volume);
        }
    }
}

Ghi chú

Các cBot Python sử dụng các tham số có thể tùy chỉnh được khai báo trong các tệp .cs của chúng.

 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
import clr

clr.AddReference("cAlgo.API")

from cAlgo.API import *
from robot_wrapper import *

class RedBarsBot():
    def __init__(self):
        self.redBarsCount = 0

    def on_bar(self):
        if self.is_red_bar():
            self.redBarsCount += 1
            if self.redBarsCount == 3:
                self.place_market_order(TradeType.Buy)
                self.redBarsCount = 0
        else:
            self.redBarsCount = 0

    def is_red_bar(self):
        currentBar = api.MarketSeries.Close.Last(1)
        previousBar = api.MarketSeries.Close.Last(2)
        return currentBar < previousBar

    def place_market_order(self, tradeType):
        symbol = api.Symbol
        volume = api.Symbol.QuantityToVolume(api.OrderVolume)
        api.ExecuteMarketOrder(tradeType, symbol, volume)

Trong ví dụ dưới đây, các kiểu dữ liệu DateTime, DateOnlyTimeSpan đóng vai trò là tham số.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using cAlgo.API;

namespace cAlgo.Robots;

[Robot(AccessRights = AccessRights.None)]
public class TimeParameters : Robot
{
    [Parameter("DateTime Parameter", MinValue = "1970-01-01T00:00:00", MaxValue = "2025-11-01T00:00:00", DefaultValue = "2025-01-01T10:00:00")]
    public DateTime DateTimeParameter { get; set; }

    [Parameter("DateOnly Parameter", MinValue = "1970-01-01", MaxValue = "2025-11-01", DefaultValue = "2025-01-01")]
    public DateOnly DateOnlyParameter { get; set; }

    [Parameter("TimeSpan Parameter", MinValue = "00:00:00", MaxValue = "23:59:59", DefaultValue = "04:10:20")]
    public TimeSpan TimeSpanParameter { get; set; }

    protected override void OnStart()
    {
        Print($"DateTimeParameter: {DateTimeParameter:o}");
        Print($"DateOnlyParameter: {DateOnlyParameter:o}");
        Print($"TimeSpanParameter: {TimeSpanParameter}");
    }
}

Ghi chú

Các cBot Python sử dụng các tham số có thể tùy chỉnh được khai báo trong các tệp .cs của chúng.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
using System;
using cAlgo.API;

namespace cAlgo.Robots;

[Robot(AccessRights = AccessRights.None)]
public class TimeParameters : Robot
{
    [Parameter("DateTime Parameter", MinValue = "1970-01-01T00:00:00", MaxValue = "2025-11-01T00:00:00", DefaultValue = "2025-01-01T10:00:00")]
    public DateTime DateTimeParameter { get; set; }

    [Parameter("DateOnly Parameter", MinValue = "1970-01-01", MaxValue = "2025-11-01", DefaultValue = "2025-01-01")]
    public DateOnly DateOnlyParameter { get; set; }

    [Parameter("TimeSpan Parameter", MinValue = "00:00:00", MaxValue = "23:59:59", DefaultValue = "04:10:20")]
    public TimeSpan TimeSpanParameter { get; set; }
}
Sử dụng các tham số trong cBot Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import clr

clr.AddReference("cAlgo.API")

# Import cAlgo API types
from cAlgo.API import *

# Import trading wrapper functions
from robot_wrapper import *

class TimeParameters():
    def on_start(self):
        print(f"DateTimeParameter: {api.DateTimeParameter}")
        print(f"DateOnlyParameter: {api.DateOnlyParameter}")
        print(f"TimeSpanParameter: {api.TimeSpanParameter}")

Ghi chú

Giá trị tham số DateTime được tự động chuyển đổi từ múi giờ nền tảng của người dùng sang múi giờ của thuật toán, loại bỏ nhu cầu chuyển đổi thủ công.

Trong ví dụ dưới đây, kiểu dữ liệu Symbol đóng vai trò là tham số.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
using System;
using cAlgo.API;
using cAlgo.API.Internals;

namespace cAlgo.Robots;

[Robot(AccessRights = AccessRights.None)]
public class SymbolParameterTest : Robot
{
    [Parameter("Symbol Parameter", DefaultValue = "EURUSD")]
    public Symbol SymbolParameter { get; set; }

    protected override void OnStart()
    {
        Print($"Symbol Bid Price is: {SymbolParameter.Bid}");
    }
}

Ghi chú

Các cBot Python sử dụng các tham số có thể tùy chỉnh được khai báo trong các tệp .cs của chúng.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
using System;
using cAlgo.API;
using cAlgo.API.Internals;

namespace cAlgo.Robots;

[Robot(AccessRights = AccessRights.None)]
public class SymbolParameterTest : Robot
{
    [Parameter("Symbol Parameter", DefaultValue = "EURUSD")]
    public Symbol SymbolParameter { get; set; }
}
Sử dụng các tham số trong cBot Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import clr

clr.AddReference("cAlgo.API")

# Import cAlgo API types
from cAlgo.API import *

# Import trading wrapper functions
from robot_wrapper import *

class SymbolParameterTest():
    def on_start(self):
        print(f"Symbol Bid Price is: {api.SymbolParameter.Bid}")

Trong ví dụ dưới đây, chúng ta sử dụng các kiểu tham số đa Enum, SymbolTimeFrame, được biểu diễn bằng kiểu mảng C#.

 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
using System;
    using cAlgo.API;
using cAlgo.API.Internals;
using System.Linq;

namespace cAlgo.Robots;

[Robot(AccessRights = AccessRights.None)]
public class MultiValueParametersTest : Robot
{
    [Parameter(DefaultValue = "EURUSD,GBPUSD")]
    public Symbol[] SymbolsParameter { get; set; }

    [Parameter(DefaultValue = "Sell")]
    public TradeType[] TradeTypesParameter { get; set; }

    [Parameter(DefaultValue = "Daily,Hour")]
    public TimeFrame[] TimeFramesParameter { get; set; }

    protected override void OnStart()
    {
        Print($"Selected symbols are: {string.Join(", ", SymbolsParameter.Select(symbol => symbol.Name))}");
        Print($"Selected trade types are: {string.Join(", ", TradeTypesParameter.Select(tradeType => tradeType.ToString()))}");
        Print($"Selected time frames are: {string.Join(", ", TimeFramesParameter.Select(timeFrame => timeFrame.ToString()))}");
    }
}

Ghi chú

Các cBot Python sử dụng các tham số có thể tùy chỉnh được khai báo trong các tệp .cs của chúng.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
using System;
using cAlgo.API;
using cAlgo.API.Internals;

namespace cAlgo.Robots;

[Robot(AccessRights = AccessRights.None)]
public class MultiValueParametersTest : Robot
{
    [Parameter(DefaultValue = "EURUSD,GBPUSD")]
    public Symbol[] SymbolsParameter { get; set; }

    [Parameter(DefaultValue = "Sell")]
    public TradeType[] TradeTypesParameter { get; set; }

    [Parameter(DefaultValue = "Daily,Hour")]
    public TimeFrame[] TimeFramesParameter { get; set; }
}
Sử dụng các tham số trong cBot Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import clr

clr.AddReference("cAlgo.API")

# Import cAlgo API types
from cAlgo.API import *

# Import trading wrapper functions
from robot_wrapper import *

class MultiValueParametersTest():
    def on_start(self):
        print(f"Selected symbols are: {[symbol.Name for symbol in api.SymbolsParameter]}")
        print(f"Selected trade types are: {[str(tradeType) for tradeType in api.TradeTypesParameter]}")
        print(f"Selected time frames are: {[str(timeFrame) for timeFrame in api.TimeFramesParameter]}")

Ví dụ về chỉ báo

Mã chỉ báo sau đây minh họa cách sử dụng tham số TimeFrame:

 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo
{
    [Indicator(AccessRights = AccessRights.None)]
    public class NewIndicator4 : Indicator
    {
        private Bars _hourlyTimeFrameBars;
        private Bars _targetTimeFrameBars;

        [Parameter("Chosen Time Frame")]
        public TimeFrame TargetTimeFrame { get; set; }

        [Output("Main")]
        public IndicatorDataSeries Result { get; set; }

        protected override void Initialize()
        {
            _hourlyTimeFrameBars = MarketData.GetBars(TimeFrame.Hour);
            _targetTimeFrameBars = MarketData.GetBars(TargetTimeFrame);
        }

        public override void Calculate(int index)
        {
            Result[index] = _hourlyTimeFrameBars.HighPrices[index] - _targetTimeFrameBars.HighPrices[index];
        }
    }
}

Có một chỉ báo vui nhộn (kiểm tra mù màu) cung cấp các tùy chọn thị giác màu enum (ví dụ: bình thường, mù màu và thang độ xám) để người dùng xác định màu sắc của đường ngang được vẽ trên biểu đồ.

 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo
{

    public enum ColorVision
    {
        Normal,
        Colorblind,
        Greyscale
    }

    [Indicator(AccessRights = AccessRights.None)]
    public class ColorblindTest : Indicator
    {

        [Parameter("Color Vision", DefaultValue = ColorVision.Normal)]
        public ColorVision ColorVision { get; set; }

        public override void Calculate(int index) {}

        protected override void Initialize()
        {

            Color lineColor = Color.Green;

            switch (ColorVision) 
            {
                case ColorVision.Normal:
                    lineColor = Color.Red;
                    break;
                case ColorVision.Colorblind:
                    lineColor = Color.Yellow;
                    break;
                case ColorVision.Greyscale:
                    lineColor = Color.White;
                    break;

            }

            var trendLine = Chart.DrawHorizontalLine("line", Bars.HighPrices.Maximum(10), lineColor);
        }

    }

}

Tóm lại, bằng cách chọn đúng kiểu dữ liệu cho các biến và thuộc tính lớp được khai báo, bạn sẽ có thể tạo ra các cBot và chỉ báo có khả năng xử lý ngay cả những tác vụ không tiêu chuẩn.

Image title