Bạn có thể phát triển một cBot giao dịch nhiều ký hiệu ngoài ký hiệu được chỉ định khi tạo một trường hợp mới.
Để làm điều này có thể, Symbols là một bộ sưu tập của tất cả các ký hiệu có sẵn cho tài khoản giao dịch của bạn. Bạn có thể lặp qua nó bằng cách sử dụng vòng lặp; ngoài ra, bạn có thể tìm kiếm qua nó để tìm các ký hiệu cụ thể.
Để làm việc chính xác với nhiều ký hiệu, cBot cần biết những thông tin sau:
Khối lượng tối thiểu và tối đa được phép
Bước khối lượng
Kích thước tick pip
Giá trị tick pip (giá trị tiền tệ của một pip hoặc tick trong đơn vị tiền gửi của tài khoản)
Dữ liệu này có thể được lấy từ đối tượng Symbol. Trong đoạn mã dưới đây, chúng ta tìm một ký hiệu có tên là "GBPUSD" và sau đó tạo một lệnh thị trường cho nó. Chúng ta cũng sử dụng khối lượng tối thiểu được phép của nó làm khối lượng lệnh.
importclrclr.AddReference("cAlgo.API")# Import cAlgo API typesfromcAlgo.APIimport*fromcAlgo.API.Internalsimport*# Import trading wrapper functionsfromrobot_wrapperimport*classSample_cBot():defon_start(self):symbol=api.Symbols.GetSymbol("GBPUSD")ifsymbolisnotNone:api.ExecuteMarketOrder(TradeType.Sell,symbol.Name,symbol.VolumeInUnitsMin)
Chuyển đổi pip thành tick
Khi lập trình cBot, rất dễ gặp phải lỗi phát sinh từ việc một số giá trị biến được tính bằng đơn vị trong khi các giá trị khác được tính bằng pip.
Lớp SymbolExtensions dưới đây minh họa cách pip có thể được chuyển đổi thành tick. Nó cũng thể hiện cách pip có thể được thêm vào giá trị giá tuyệt đối.
usingSystem;usingcAlgo.API;usingcAlgo.API.Internals;namespaceSamples{[Robot(AccessRights = AccessRights.None)]publicclassSample:Robot{protectedoverridevoidOnStart(){varspreadInPips=Symbol.NormalizePips(Symbol.ToPips(Symbol.Spread));Print(spreadInPips);varspreadInTicks=Math.Round(Symbol.ToTicks(Symbol.Spread));Print(spreadInTicks);/* Calculating a long position stop loss using the absolute price value. */varstopLossInPips=60;/* We use 'NormalizePips' to avoid the 'invalid decimal places' error in case our stop loss value has too many decimals. */varstopLossInPrice=Symbol.Ask-(Symbol.NormalizePips(stopLossInPips)*Symbol.PipSize);Print(stopLossInPrice);}}publicstaticclassSymbolExtensions{/// <summary>/// Returns a symbol pip value/// </summary>/// <param name="symbol"></param>/// <returns>double</returns>publicstaticdoubleGetPip(thisSymbolsymbol){returnsymbol.TickSize/symbol.PipSize*Math.Pow(10,symbol.Digits);}/// <summary>/// Returns a price value in terms of pips/// </summary>/// <param name="symbol"></param>/// <param name="price">The price level</param>/// <returns>double</returns>publicstaticdoubleToPips(thisSymbolsymbol,doubleprice){returnprice*symbol.GetPip();}/// <summary>/// Returns a price value in terms of ticks/// </summary>/// <param name="symbol"></param>/// <param name="price">The price level</param>/// <returns>double</returns>publicstaticdoubleToTicks(thisSymbolsymbol,doubleprice){returnprice*Math.Pow(10,symbol.Digits);}/// <summary>/// Rounds a price level to the number of symbol digits/// </summary>/// <param name="symbol">The symbol</param>/// <param name="price">The price level</param>/// <returns>double</returns>publicstaticdoubleRound(thisSymbolsymbol,doubleprice){returnMath.Round(price,symbol.Digits);}/// <summary>/// Normalize x Pips amount decimal places to something that can be used as a stop loss or take profit for an order./// For example if symbol is EURUSD and you pass to this method 10.456775 it will return back 10.5/// </summary>/// <param name="symbol">The symbol</param>/// <param name="pips">The amount of Pips</param>/// <returns>double</returns>publicstaticdoubleNormalizePips(thisSymbolsymbol,doublepips){varcurrentPrice=Convert.ToDecimal(symbol.Bid);varpipSize=Convert.ToDecimal(symbol.PipSize);varpipsDecimal=Convert.ToDecimal(pips);varpipsAddedToCurrentPrice=Math.Round((pipsDecimal*pipSize)+currentPrice,symbol.Digits);vartickSize=Convert.ToDecimal(symbol.TickSize);varresult=(pipsAddedToCurrentPrice-currentPrice)*tickSize/pipSize*Convert.ToDecimal(Math.Pow(10,symbol.Digits));returndecimal.ToDouble(result);}}}
Transactions chứa các loại cung cấp dữ liệu về nạp tiền và rút tiền cho các tài khoản. Các loại này cho phép bạn truy cập và quản lý chi tiết giao dịch cho tài khoản theo chương trình.
Bạn có thể truy xuất dữ liệu về loại giao dịch (nạp tiền hoặc rút tiền), số tiền, dấu thời gian, ID giao dịch, chi tiết số dư, thuộc tính vốn, v.v.
cTrader cung cấp bộ sưu tập HistoricalOrder để cho phép người dùng truy xuất thông tin về lệnh, bao gồm lệnh thị trường đã hoàn thành và lệnh chờ đã được thực hiện hoặc hủy bỏ. Các chi tiết có thể truy xuất bao gồm ID lệnh, loại lệnh, nhãn, giá mục tiêu, thời gian hết hạn, v.v.
Mã cBot dưới đây cho bạn thấy cách lấy chi tiết cho các lệnh lịch sử:
Khi lập trình cBot, bạn có quyền truy cập vào lịch sử tài khoản của mình. Điều này có nghĩa là bạn có thể lặp qua các giao dịch trong quá khứ của mình và sử dụng dữ liệu của chúng cho bất kỳ mục đích nào bạn có.
Đoạn mã dưới đây tạo một tệp .CSV chứa tất cả các giao dịch trong quá khứ của chúng ta và dữ liệu giao dịch của chúng.
usingSystem;usingcAlgo.API;usingSystem.Text;usingSystem.IO;namespaceSamples{/* We provide the access rights required for reading and writing in locally stored files. */[Robot(AccessRights = AccessRights.FullAccess)]publicclassSample:Robot{protectedoverridevoidOnStart(){varstringBuilder=newStringBuilder();_=stringBuilder.AppendLine($"PositionId,TradeType,SymbolName,VolumeInUnits,EntryTime,EntryPrice,ClosingTime,ClosingPrice,NetProfit,Balance");// All trades are inside the 'History' collectionforeach(vartradeinHistory){_=stringBuilder.AppendLine($"{trade.PositionId},{trade.TradeType},{trade.SymbolName},{trade.VolumeInUnits},{trade.EntryTime:o},{trade.EntryPrice},{trade.ClosingTime:o},{trade.ClosingPrice},{trade.NetProfit},{trade.Balance}");}// We will save the CSV file on our desktopvardesktopPath=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);varfilePath=Path.Combine(desktopPath,$"{Account.Number}_History.csv");File.WriteAllText(filePath,stringBuilder.ToString());}}}
Lấy thông tin về các giao dịch
Trong cTrader, các giao dịch thực hiện lệnh và khiến các vị thế được mở hoặc đóng. Tùy thuộc vào thanh khoản thị trường, một lệnh có thể được khớp hoàn toàn bởi một giao dịch duy nhất hoặc từng phần bởi nhiều giao dịch. Xem Vị thế và giao dịch để tìm hiểu thêm.
Mã cBot dưới đây cho bạn thấy cách truy xuất thông tin về nhiều giao dịch tồn tại trong một vị thế duy nhất:
importclrclr.AddReference("cAlgo.API")# Import cAlgo API typesfromcAlgo.APIimport*fromcAlgo.API.Internalsimport*# Import trading wrapper functionsfromrobot_wrapperimport*classDealsExample():defon_start(self):position=api.ExecuteMarketOrder(TradeType.Buy,"EURUSD",10000)deals=position.Position.Dealsfordealindeals:api.Print(f"{deal.ExecutionTime}{deal.Status}{deal.Id}")api.ClosePosition(position.Position,3000)api.ClosePosition(position.Position,7000)closing_deals=api.History.FindByPositionId(position.Position.Id)forclosing_dealinclosing_deals:api.Print(f"{closing_deal.ClosingDeal.ExecutionTime}{closing_deal.ClosingDeal.VolumeInUnits}")defon_stop(self):pass
Chuyển đổi lot thành đơn vị
Theo mặc định, các thuật toán cTrader tính toán khối lượng bằng đơn vị thay vì lot. Tuy nhiên, trong một số trường hợp, bạn có thể thấy làm việc với lot thuận tiện và quen thuộc hơn.
Bạn có thể chuyển đổi lot thành đơn vị bằng cách sử dụng phương thức Symbol.QuantityToVolumeUnits().
importclrclr.AddReference("cAlgo.API")# Import cAlgo API typesfromcAlgo.APIimport*fromcAlgo.API.Internalsimport*# Import trading wrapper functionsfromrobot_wrapperimport*classSample():defon_start(self):lots=2.5volume_in_units=api.Symbol.QuantityToVolumeInUnits(lots)api.ExecuteMarketOrder(TradeType.Sell,api.SymbolName,volume_in_units)
Ngoài ra, bạn có thể sử dụng phương thức Symbol.VolumeInUnitsToQuantity() để chuyển đổi đơn vị thành lot.
Làm việc với màu sắc
cBot có thể sử dụng màu sắc tùy chỉnh khi thực hiện các thao tác khác nhau (ví dụ: khi hiển thị văn bản trên biểu đồ giao dịch). Để thêm màu sắc như một tham số có thể tùy chỉnh, hãy thêm mã sau vào khai báo tham số của bạn.
Bạn có thể sử dụng cả mã màu thập lục phân và tên màu (như red") khi xác định DefaultValue của tham số như vậy."
Để minh họa cách hoạt động của tham số màu sắc, chúng ta sẽ tạo một cBot đơn giản mà, khi được khởi động, sẽ viết văn bản trên biểu đồ giao dịch mà nó đang hoạt động. Màu sắc của văn bản này sẽ có thể tùy chỉnh thông qua tham số TextColor.
1 2 3 4 5 6 7 8 910111213141516171819202122232425
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingcAlgo.API;usingcAlgo.API.Collections;usingcAlgo.API.Indicators;usingcAlgo.API.Internals;namespacecAlgo.Robots{[Robot(AccessRights = AccessRights.None)]publicclassSampleColorcBot:Robot{[Parameter("Text Color", DefaultValue = "red")]publicColorTextColor{get;set;}protectedoverridevoidOnStart(){varstaticText=Chart.DrawStaticText("static","Sample text to demonstrate how color works",VerticalAlignment.Center,HorizontalAlignment.Center,TextColor);}}}
1 2 3 4 5 6 7 8 91011121314151617181920
importclrclr.AddReference("cAlgo.API")# Import cAlgo API typesfromcAlgo.APIimport*fromcAlgo.API.Internalsimport*# Import trading wrapper functionsfromrobot_wrapperimport*classSampleColorcBot():defon_start(self):api.Chart.DrawStaticText("static","Sample text to demonstrate how color works",VerticalAlignment.Center,HorizontalAlignment.Center,api.TextColor)