I am using a BarsRequest to call on specific exchange rates. I have used the BarsREquest within a method so that I can call it whenever I want. I have a problem in that the BarsREquest code provided in the help guide does not perform the BarsREquest in a syncronised fashion and therefore the method returns zero because the method returns before the BarsRequest has had time to complete. I can work around this by using initiating a while loop however this is bad practice and I am aware of all the negative issues sleeping the ui thread brings so I am looking for a way to code the the barsRequest in a synchronous fashion so that the method will not complete until the BarsRequest has completed and in a way that I do not have to rely on the while loop to hold up the thread.
My code is as follows:
private double GetGBPUSD()
{
double gbpUsdClose=0;
barsRequest2= new BarsRequest(Instrument.GetInstrument("GBPUSD"), 1);
barsRequest2.BarsPeriod.BarsPeriodType = BarsPeriodType.Day;
barsRequest2.BarsPeriod.Value = 1;
barsRequest2.TradingHours = TradingHours.Get(Bars.Instrument.MasterInstrument. TradingHours.ToString());
// Request the bars
barsRequest2.Request(new Action<BarsRequest, ErrorCode, string>((bars, errorCode, errorMessage) =>
{
if (errorCode != ErrorCode.NoError)
{
// Handle any errors in requesting bars here
Print(string.Format("Error on requesting bars: {0}, {1}",errorCode, errorMessage));
return;
}
for (int i = 0; i < bars.Bars.Count; i++)
{
// Output the bars
gbpUsdClose=bars.Bars.GetClose(i);
//Print("GBPInsodemethod "+ gbpUsdClose);
if(gbpUsdClose!=0) break;
}
}));
while(gbpUsdClose==0)
{
Print("Getting the rate...");
}
barsRequest2.Dispose();
return gbpUsdClose;
}
Many thanks
Comment