GetSeries Asynchronously
Created at 15 Jan 2018, 14:03
GetSeries Asynchronously
15 Jan 2018, 14:03
Hi, I am trying to get multiple series asynchronously using multi-threading but it gets stuck when the cBot is finding more than one symbol at the same time. See the code below which I used.
using System; using System.Threading; using cAlgo.API; namespace cAlgo { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class SampleAsyncGetSeries : Robot { private readonly string[] _symbolCodes = { "EURJPY", "GBPJPY", "AUDJPY", "NZDJPY", "USDJPY", "CADJPY", "CHFJPY", "EURCHF", "GBPCHF", "AUDCHF", "NZDCHF", "USDCHF", "CADCHF", "EURCAD", "GBPCAD", "AUDCAD", "NZDCAD", "USDCAD", "EURUSD", "GBPUSD", "AUDUSD", "NZDUSD", "EURNZD", "GBPNZD", "AUDNZD", "EURAUD", "GBPAUD", "EURGBP", }; protected override void OnStart() { try { foreach (var symbolCode in _symbolCodes) { var thread = new Thread(() => GetSeriesAsync(symbolCode)); thread.SetApartmentState(ApartmentState.STA); thread.IsBackground = true; thread.Start(); //thread.Join(); } } catch (Exception e) { Print(e); Stop(); } } [STAThread] private void GetSeriesAsync(string symbolCode) { try { var series = MarketData.GetSeries(symbolCode, TimeFrame); Print("{0} : {1}", series.SymbolCode, series.Close.LastValue); } catch (Exception e) { Print(e); Stop(); } } } }
You can try to uncomment thread.Join() which will make the new thread to wait for the previous one to finish, then it gets all the series correctly but not asynchronously.
Any advice how to fix that highly appreciated.
PanagiotisCharalampous
17 Jan 2018, 17:20
Hi tmc.
API functions are not thread safe therefore they should be called in the main thread of a cBot. Therefore parallelization of this functionality is currently not possible.
Best Regards,
Panagiotis
@PanagiotisCharalampous