void ReadSnapshot(string requestId, O2GResponse response)
        {
            TransportHistoryRequest request = null;

            mHistoryRequests.TryGetValue(requestId, out request);
            if (request != null)
            {
                O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();
                if (factory != null)
                {
                    O2GMarketDataSnapshotResponseReader reader   = factory.createMarketDataSnapshotReader(response);
                    ITransportHistoryReader             consumer = request.Reader;
                    for (int i = 0; i < reader.Count; i++)
                    {
                        //mTimeConverter.convert(reader.getDate(i), O2GTimeConverterTimeZone.UTC, mTimezone)
                        DateTime dt = reader.getDate(i);
                        consumer.onHistoryRow(requestId, dt,
                                              reader.getBidOpen(i), reader.getBidHigh(i), reader.getBidLow(i), reader.getBidClose(i),
                                              reader.getAskOpen(i), reader.getAskHigh(i), reader.getAskLow(i), reader.getAskClose(i),
                                              reader.getVolume(i), i);
                    }
                    //mTimeConverter.convert(reader.getLastBarTime(), O2GTimeConverterTimeZone.UTC, mTimezone)
                    DateTime dt1 = reader.getLastBarTime();
                    consumer.setLastBar(dt1, reader.getLastBarVolume());
                    mHistoryRequests.Remove(requestId);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Request historical prices for the specified timeframe of the specified period
        /// </summary>
        /// <param name="session"></param>
        /// <param name="sInstrument"></param>
        /// <param name="sTimeframe"></param>
        /// <param name="dtFrom"></param>
        /// <param name="dtTo"></param>
        /// <param name="responseListener"></param>
        public void GetHistoryPrices(O2GSession session, string sInstrument, string sTimeframe, DateTime dtFrom, DateTime dtTo, ResponseListener responseListener)
        {
            O2GRequestFactory factory   = session.getRequestFactory();
            O2GTimeframe      timeframe = factory.Timeframes[sTimeframe];

            if (timeframe == null)
            {
                throw new Exception(string.Format("Timeframe '{0}' is incorrect!", sTimeframe));
            }
            O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(sInstrument, timeframe, 300);
            DateTime   dtFirst = dtTo;

            do // cause there is limit for returned candles amount
            {
                factory.fillMarketDataSnapshotRequestTime(request, dtFrom, dtFirst, false);
                responseListener.SetRequestID(request.RequestID);
                session.sendRequest(request);
                if (!responseListener.WaitEvents())
                {
                    throw new Exception("Response waiting timeout expired");
                }
                // shift "to" bound to oldest datetime of returned data
                O2GResponse response = responseListener.GetResponse();
                if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
                {
                    O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory();
                    if (readerFactory != null)
                    {
                        O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response);
                        if (reader.Count > 0)
                        {
                            if (DateTime.Compare(dtFirst, reader.getDate(0)) != 0)
                            {
                                dtFirst = reader.getDate(0); // earliest datetime of returned data
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            //  Console.WriteLine("0 rows received");
                            updateLogDelegate(string.Format("0 rows received"));
                            break;
                        }
                    }
                    // PrintPrices(session, response);
                    storeHistoryPriceToDataTable(session, response, sInstrument);
                    // DateTime.Subtraction(dtTo, dtFirst)/ Subtraction
                    long percent = (dtTo.Ticks - dtFirst.Ticks) * 100 / (dtTo.Ticks - dtFrom.Ticks);

                    updateProcessDelegate((int)percent, this.InstrumentDT.Rows.Count);
                }
                else
                {
                    break;
                }
            } while (dtFirst > dtFrom);
        }
Ejemplo n.º 3
0
        public void storeHistoryPriceToDataTable(O2GSession session, O2GResponse response, string sInstrument)
        {
            //   string ss = string.Format("Request with RequestID={0} is completed:", response.RequestID);
            //    updateLogDelegate(ss);
            DataTable tmpTable = InstrumentDT.Clone();
            O2GResponseReaderFactory factory = session.getResponseReaderFactory();

            if (factory != null)
            {
                O2GMarketDataSnapshotResponseReader reader = factory.createMarketDataSnapshotReader(response);

                for (int ii = reader.Count - 1; ii >= 0; ii--)
                {
                    if (reader.isBar)
                    {
                        InstrumentDT.Rows.Add(reader.getDate(ii), reader.getBidOpen(ii), reader.getBidHigh(ii), reader.getBidLow(ii), reader.getBidClose(ii),
                                              reader.getAskOpen(ii), reader.getAskHigh(ii), reader.getAskLow(ii), reader.getAskClose(ii), reader.getVolume(ii));
                        tmpTable.Rows.Add(reader.getDate(ii), reader.getBidOpen(ii), reader.getBidHigh(ii), reader.getBidLow(ii), reader.getBidClose(ii),
                                          reader.getAskOpen(ii), reader.getAskHigh(ii), reader.getAskLow(ii), reader.getAskClose(ii), reader.getVolume(ii));
                    }
                    else
                    {
                        InstrumentDT.Rows.Add(reader.getDate(ii), reader.getBidClose(ii), reader.getAskClose(ii));
                        tmpTable.Rows.Add(reader.getDate(ii), reader.getBidClose(ii), reader.getAskClose(ii));
                    }
                }
                SaveDataToFile(tmpTable, sInstrument);
            }
        }
        /// <summary>
        /// Print history data from response
        /// </summary>
        /// <param name="session"></param>
        /// <param name="response"></param>
        /// <param name="request"></param>
        private void ExtractPrices(O2GSession session, O2GResponse response, HistoricDataRequest request)
        {
            O2GResponseReaderFactory factory = session.getResponseReaderFactory();

            if (factory != null)
            {
                O2GMarketDataSnapshotResponseReader reader = factory.createMarketDataSnapshotReader(response);
                for (int decrement = reader.Count - 1; decrement >= 0; decrement--)
                {
                    if (reader.isBar)
                    {
                        // Extract Time
                        var dateTime = reader.getDate(decrement);

                        // Create new Bar object
                        Bar bar = new Bar(request.Security, request.MarketDataProvider, request.Id, dateTime);

                        // Set bar fields
                        bar.High  = Convert.ToDecimal(reader.getBidHigh(decrement));
                        bar.Low   = Convert.ToDecimal(reader.getBidLow(decrement));
                        bar.Open  = Convert.ToDecimal(reader.getBidOpen(decrement));
                        bar.Close = Convert.ToDecimal(reader.getBidClose(decrement));

                        bar.Volume = reader.getVolume(decrement);

                        // Add to local collection
                        _barCollection.Add(bar);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private void Session_RequestCompleted(object sender, RequestCompletedEventArgs e)
        {
            switch (e.Response.Type)
            {
            case O2GResponseType.GetLastOrderUpdate:
                break;

            case O2GResponseType.MarginRequirementsResponse:
                break;

            case O2GResponseType.CommandResponse:
                break;

            case O2GResponseType.GetSystemProperties:
                break;

            case O2GResponseType.CreateOrderResponse:
                break;

            case O2GResponseType.GetMessages:
                break;

            case O2GResponseType.GetClosedTrades:
                break;

            case O2GResponseType.GetTrades:
                break;

            case O2GResponseType.GetOrders:
                break;

            case O2GResponseType.GetOffers:
                break;

            case O2GResponseType.GetAccounts:
                var accountsReader = _factory.createAccountsTableReader(e.Response);
                //_accountRow = GetAccountRow(accountsReader);
                _syncResponseEvent.Set();
                break;

            case O2GResponseType.MarketDataSnapshot:
                var readerFactory = _session.getResponseReaderFactory();
                _marketDataSnapshotResponse = _factory.createMarketDataSnapshotReader(e.Response);
                _syncHistoryEvent.Set();
                break;

            case O2GResponseType.TablesUpdates:
                _session.TablesUpdates += Session_TablesUpdates;
                break;

            case O2GResponseType.ResponseUnknown:
                Stop();
                break;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Request historical prices for the specified timeframe of the specified period
        /// </summary>
        /// <param name="session"></param>
        /// <param name="sInstrument"></param>
        /// <param name="sTimeframe"></param>
        /// <param name="dtFrom"></param>
        /// <param name="dtTo"></param>
        /// <param name="responseListener"></param>
        public static void GetHistoryPrices(O2GSession session, string sInstrument, string sTimeframe, DateTime dtFrom, DateTime dtTo, ResponseListener responseListener)
        {
            O2GRequestFactory factory   = session.getRequestFactory();
            O2GTimeframe      timeframe = factory.Timeframes[sTimeframe];

            if (timeframe == null)
            {
                throw new Exception(string.Format("Timeframe '{0}' is incorrect!", sTimeframe));
            }
            O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(sInstrument, timeframe, 300);
            DateTime   dtFirst = dtTo;

            do // cause there is limit for returned candles amount
            {
                factory.fillMarketDataSnapshotRequestTime(request, dtFrom, dtFirst, false, O2GCandleOpenPriceMode.PreviousClose);
                responseListener.SetRequestID(request.RequestID);
                session.sendRequest(request);
                if (!responseListener.WaitEvents())
                {
                    throw new Exception("Response waiting timeout expired");
                }
                // shift "to" bound to oldest datetime of returned data
                O2GResponse response = responseListener.GetResponse();
                if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
                {
                    O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory();
                    if (readerFactory != null)
                    {
                        O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response);
                        if (reader.Count > 0)
                        {
                            if (DateTime.Compare(dtFirst, reader.getDate(0)) != 0)
                            {
                                dtFirst = reader.getDate(0); // earliest datetime of returned data
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            Console.WriteLine("0 rows received");
                            break;
                        }
                    }
                    PrintPrices(session, response);
                }
                else
                {
                    break;
                }
            } while (dtFirst > dtFrom);
        }
Ejemplo n.º 7
0
        private List <FxBar> getHistoryPrices(O2GSession session, string instrument, Resolution resolution, DateTime startDateTime, DateTime endDateTime, int maxBars, GetHistoricalDataResponseListener responseListener)
        {
            O2GRequestFactory factory = session.getRequestFactory();
            var          tf           = convert_Resolution_To_string(resolution);
            O2GTimeframe timeframe    = factory.Timeframes[tf];

            if (timeframe == null)
            {
                throw new TimeframeNotFoundException($"Timeframe '{resolution.TimeFrame}:{resolution.Size}' is incorrect!");
            }

            O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(instrument, timeframe, maxBars);

            factory.fillMarketDataSnapshotRequestTime(request, startDateTime, endDateTime, false);

            responseListener.SetRequestID(request.RequestID);
            session.sendRequest(request);

            if (!responseListener.WaitEvents())
            {
                throw new Exception($"{responseListener.Error}");
            }

            O2GResponse response = responseListener.GetResponse();

            List <FxBar> barList = new List <FxBar>();

            if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
            {
                O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory();
                if (readerFactory != null)
                {
                    O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response);
                    if (reader.Count > 0)
                    {
                        for (int i = 0; i < reader.Count; i++)
                        {
                            barList.Add(new FxBar
                            {
                                Open     = reader.getBidOpen(i),
                                High     = reader.getBidHigh(i),
                                Low      = reader.getBidLow(i),
                                Close    = reader.getBidClose(i),
                                Volume   = reader.getVolume(i),
                                DateTime = reader.getDate(i)
                            });
                        }
                    }
                }
            }

            return(barList);
        }
Ejemplo n.º 8
0
        public string PrintPrices(O2GSession session, O2GResponse response, string newPast)
        {
            Console.WriteLine();
            O2GResponseReaderFactory factory = session.getResponseReaderFactory();

            if (factory != null)
            {
                O2GMarketDataSnapshotResponseReader reader = factory.createMarketDataSnapshotReader(response);
                for (int ii = 0; ii < reader.Count; ii++)
                {
                }
            }
            return(newPast);
        }
Ejemplo n.º 9
0
        public void onRequestCompleted(String requestID, O2GResponse response)
        {
            O2GResponseReaderFactory responseFactory = mSession.getResponseReaderFactory();

            if (responseFactory != null)
            {
                O2GMarketDataSnapshotResponseReader reader = responseFactory.createMarketDataSnapshotReader(response);
                for (int i = 0; i < reader.Count; i++)
                {
                    System.Console.WriteLine("\n\tAskOpen =" + reader.getAskOpen(i) +
                                             "\n\tAskHigh = " + reader.getAskHigh(i) +
                                             "\n\tAskLow = " + reader.getAskLow(i) +
                                             "\n\tAskClose =" + reader.getAskClose(i));
                }
            }
        }
Ejemplo n.º 10
0
        public string PrintPrices(O2GSession session, O2GResponse response, string newPast)
        {
            Console.WriteLine();
            O2GResponseReaderFactory factory = session.getResponseReaderFactory();

            if (factory != null)
            {
                O2GMarketDataSnapshotResponseReader reader = factory.createMarketDataSnapshotReader(response);
                for (int ii = 0; ii < reader.Count; ii++)
                {
                    newPast = Convert.ToString(reader.getAskOpen(ii));
                    double newDouble = reader.getAskOpen(ii);
                    gbpnzdPast         = newDouble;
                    gbpnzdPastBox.Text = newPast;
                    Console.WriteLine(newPast);
                }
            }
            return(newPast);
        }
Ejemplo n.º 11
0
        public static MarketDataEventArg ProcessMarketData(FXSession connection, O2GResponse response)
        {
            try
            {
                O2GResponseReaderFactory            rrfactory = connection.Session.getResponseReaderFactory();
                O2GMarketDataSnapshotResponseReader mReader   = rrfactory.createMarketDataSnapshotReader(response);

                var d = new SortedList <DateTime, Tick>(mReader.Count);

                for (int i = 0; i < mReader.Count; i++)
                {
                    // information like reader.getDate(i), reader.getBidOpen(i), reader.getBidHigh(i), reader.getBidLow(i), reader.getBidClose(i), reader.getVolume(i) is now available
                    //Console.WriteLine(i + ":" + mReader.getDate(i).ToString() + ":" + mReader.getBidOpen(i));
                    //create a quantum of ticks for the market data
                    var tick = new Tick(
                        mReader.getBid(i),
                        mReader.getBidOpen(i),
                        mReader.getBidHigh(i),
                        mReader.getBidLow(i),
                        mReader.getBidClose(i),
                        mReader.getAsk(i),
                        mReader.getAskOpen(i),
                        mReader.getAskHigh(i),
                        mReader.getAskLow(i),
                        mReader.getAskClose(i),
                        mReader.getVolume(i),
                        mReader.getDate(i));

                    d.Add(mReader.getDate(i), tick);
                }

                var q = new Quantum(d);
                return(new MarketDataEventArg(q));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(new MarketDataEventArg(new Quantum(new SortedList <DateTime, Tick>(300))));
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Print history data from response
        /// </summary>
        /// <param name="session"></param>
        /// <param name="response"></param>
        public static void PrintPrices(O2GSession session, O2GResponse response)
        {
            Console.WriteLine("Request with RequestID={0} is completed:", response.RequestID);
            O2GResponseReaderFactory factory = session.getResponseReaderFactory();

            if (factory != null)
            {
                O2GMarketDataSnapshotResponseReader reader = factory.createMarketDataSnapshotReader(response);
                for (int ii = reader.Count - 1; ii >= 0; ii--)
                {
                    if (reader.isBar)
                    {
                        Console.WriteLine("DateTime={0}, BidOpen={1}, BidHigh={2}, BidLow={3}, BidClose={4}, AskOpen={5}, AskHigh={6}, AskLow={7}, AskClose={8}, Volume={9}",
                                          reader.getDate(ii), reader.getBidOpen(ii), reader.getBidHigh(ii), reader.getBidLow(ii), reader.getBidClose(ii),
                                          reader.getAskOpen(ii), reader.getAskHigh(ii), reader.getAskLow(ii), reader.getAskClose(ii), reader.getVolume(ii));
                    }
                    else
                    {
                        Console.WriteLine("DateTime={0}, Bid={1}, Ask={2}", reader.getDate(ii), reader.getBidClose(ii), reader.getAskClose(ii));
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private static void GetHistoryPrices(O2GSession session, string sInstrument, string sTimeframe, DateTime dtFrom, DateTime dtTo, ResponseListener responseListener)
        {
            try
            {
                StreamWriter m_data = new StreamWriter(OutData);

                string m_string_to_write = "";

                O2GRequestFactory factory   = session.getRequestFactory();
                O2GTimeframe      timeframe = factory.Timeframes[sTimeframe];
                if (timeframe == null)
                {
                    throw new Exception(string.Format("Timeframe '{0}' is incorrect!", sTimeframe));
                }
                O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(sInstrument, timeframe, 300);
                DateTime   dtFirst = dtTo;
                do // cause there is limit for returned candles amount
                {
                    factory.fillMarketDataSnapshotRequestTime(request, dtFrom, dtFirst, false);
                    responseListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (!responseListener.WaitEvents())
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                    // shift "to" bound to oldest datetime of returned data
                    O2GResponse response = responseListener.GetResponse();
                    if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
                    {
                        O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory();
                        if (readerFactory != null)
                        {
                            O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response);
                            if (reader.Count > 0)
                            {
                                if (DateTime.Compare(dtFirst, reader.getDate(0)) != 0)
                                {
                                    dtFirst = reader.getDate(0); // earliest datetime of returned data

                                    for (int nData = reader.Count - 1; nData > -1; nData--)
                                    {
                                        // reader.getDate(0);

                                        m_string_to_write = reader.getDate(nData).ToString() + ";" +
                                                            reader.getAsk(nData).ToString() + ";" +
                                                            reader.getAskOpen(nData).ToString() + ";" +
                                                            reader.getAskClose(nData).ToString() + ";" +
                                                            reader.getAskLow(nData).ToString() + ";" +
                                                            reader.getAskHigh(nData).ToString() + ";" +

                                                            reader.getBid(nData).ToString() + ";" +
                                                            reader.getBidOpen(nData).ToString() + ";" +
                                                            reader.getBidClose(nData).ToString() + ";" +
                                                            reader.getBidLow(nData).ToString() + ";" +
                                                            reader.getBidHigh(nData).ToString() + ";" +

                                                            reader.getVolume(nData).ToString() + ";" +

                                                            reader.getLastBarTime().ToString() + ";" +
                                                            reader.getLastBarVolume().ToString();


                                        m_data.WriteLine(m_string_to_write);
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else
                            {
                                Console.WriteLine("0 rows received");
                                break;
                            }
                        }
                        // PrintPrices(session, response);
                    }
                    else
                    {
                        break;
                    }
                } while (dtFirst > dtFrom);

                m_data.Close();
            }
            catch (Exception e)
            {
                int ErrorCounter = 0;

                if (ErrorCounter > 5)
                {
                    LogDirector.DoAction(4, e);
                }
                else
                {
                    ErrorCounter++;
                    LogDirector.DoAction(2, e);
                    GetHistoryPrices(session, sInstrument, sTimeframe, dtFrom, dtTo, responseListener);
                }
            }
        }
Ejemplo n.º 14
0
        private void GetHistoryPrices(O2GSession O2GSession, string Instrument, string Interval, DateTime DtFrom, DateTime DtTo)
        {
            m_responseListener = new ResponseListener(O2GSession);
            O2GSession.subscribeResponse(m_responseListener);

            O2GRequestFactory factory = O2GSession.getRequestFactory();

            O2GTimeframeCollection timeframecollection = factory.Timeframes;
            O2GTimeframe           Timeframe           = timeframecollection[Interval];

            if (Timeframe == null)
            {
                throw new Exception(string.Format("Timeframe '{0}' is incorrect!", Timeframe));
            }

            O2GRequest request  = factory.createMarketDataSnapshotRequestInstrument(Instrument, Timeframe, 300);
            DateTime   DtFirst  = DtTo;
            DateTime   DatePrec = System.DateTime.MinValue;

            //TimeSpan PricesTimeSpan = System.TimeSpan.MinValue;

            //if (Interval == "m5")
            //{
            //    PricesTimeSpan = new TimeSpan(0, 0, 5, 0, 0);
            //}

            do // cause there is limit for returned candles amount
            {
                factory.fillMarketDataSnapshotRequestTime(request, DtFrom, DtFirst, false);
                m_responseListener.SetRequestID(request.RequestID);
                O2GSession.sendRequest(request);

                if (!m_responseListener.WaitEvents())
                {
                    throw new Exception("Response waiting timeout expired");
                }
                // shift "to" bound to oldest datetime of returned data
                O2GResponse response = m_responseListener.GetResponse();
                if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
                {
                    O2GResponseReaderFactory readerFactory = O2GSession.getResponseReaderFactory();
                    if (readerFactory != null)
                    {
                        O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response);
                        if (reader.Count > 0)
                        {
                            if (DateTime.Compare(DtFirst, reader.getDate(0)) != 0)
                            {
                                DtFirst = reader.getDate(0); // earliest datetime of returned data

                                for (int nData = reader.Count - 1; nData > -1; nData--)
                                {
                                    if (reader.getDate(nData) != DatePrec)
                                    {
                                        m_datetime.Add(reader.getDate(nData));

                                        m_ask.Add(reader.getAsk(nData));
                                        m_askopen.Add(reader.getAskOpen(nData));
                                        m_askclose.Add(reader.getAskClose(nData));
                                        m_askhigh.Add(reader.getAskHigh(nData));
                                        m_asklow.Add(reader.getAskLow(nData));

                                        m_bid.Add(reader.getBid(nData));
                                        m_bidopen.Add(reader.getBidOpen(nData));
                                        m_bidclose.Add(reader.getBidClose(nData));
                                        m_bidhigh.Add(reader.getBidHigh(nData));
                                        m_bidlow.Add(reader.getBidLow(nData));
                                    }
                                    //else
                                    //{
                                    //    break;
                                    //}

                                    DatePrec = reader.getDate(nData);
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            Console.WriteLine("0 rows received");
                            break;
                        }
                    }
                    // PrintPrices(session, response);
                }
                else
                {
                    break;
                }
            } while (DtFirst > DtFrom);

            m_datetime.Reverse();

            m_ask.Reverse();
            m_askopen.Reverse();
            m_askclose.Reverse();
            m_askhigh.Reverse();
            m_asklow.Reverse();

            m_bid.Reverse();
            m_bidopen.Reverse();
            m_bidclose.Reverse();
            m_bidhigh.Reverse();
            m_bidlow.Reverse();
        }
Ejemplo n.º 15
0
        public void processData(O2GResponse response, HddMainFormBasic hdd, DataSetup dataSetup)
        {
            bool     outOfRangeDateFound = false;
            DateTime tempEndDate         = new DateTime();

            try
            {
                //Exit thread if the value is false
                if (!keepThreadRunning)
                {
                    return;
                }

                var query1 = HddMainFormBasic.threadDictionary.Keys.FirstOrDefault(t => t == response.RequestID);
                if (query1 != null)
                {
                    HddMainFormBasic.threadDictionary[query1].CallBack = true;
                }


                O2GResponseReaderFactory readerfactory = tss.Session.getResponseReaderFactory();

                O2GMarketDataSnapshotResponseReader reader = readerfactory.createMarketDataSnapshotReader(response);

                DateTime from = new DateTime();
                DateTime to   = new DateTime();
                if (reader.Count > 0)
                {
                    from = reader.getDate(0);
                    to   = reader.getDate(reader.Count - 1);
                }
                Console.WriteLine("Market data received from " + from.ToString("MM/dd/yyyy HH:mm:ss") + " to " + to.ToString("MM/dd/yyyy HH:mm:ss"));

                //insert data into price list
                for (int j = reader.Count - 1; j > -1; j--)
                {
                    prices.Add(new Data(reader.getAskOpen(j), reader.getAskHigh(j), reader.getAskLow(j), reader.getAskClose(j), reader.getBidOpen(j), reader.getBidHigh(j), reader.getBidLow(j), reader.getBidClose(j), reader.getDate(j), reader.getVolume(j)));
                }
                //if less rates are obtained then it means we reached the end.
                //Nothing came back for the timeframe specified means, nothing exist in the remaining timeframe.
                if (reader.Count < 300 || reader.Count == 0)
                {
                    outOfRangeDateFound = true;
                    tempEndDate         = endDate;
                }

                if (!outOfRangeDateFound)
                {
                    removeLastDate(prices[prices.Count - 1].StartTime, prices);

                    tempEndDate = prices[prices.Count - 1].StartTime;
                }
                if (prices.Count > 3000)
                {
                    DataBaseHandler.getInstance().addEntries(prices);
                    prices.Clear();
                    if (timeInterval.Equals("t1"))
                    {
                        Thread.Sleep(2000);
                    }
                }

                //Get total ticks between end date and start date
                long totalTicks = tempEndDate.Ticks - dataSetup.StartDate.Ticks;

                currentStep           = 0;
                currentStep           = ((double)(totalTicks * maxIterations)) / initialTotalTicks;
                dataSetup.currentStep = currentStep;
                tick = reader.Count;
                Time = sw.Elapsed;

                #region repeat process OR quit
                if (outOfRangeDateFound == false)
                {
                    try
                    {
                        //Call HDD function to calculate more data
                        DataSetup ds = new DataSetup();
                        ds = dataSetup;

                        ds.EndDate = tempEndDate;
                        hdd.sendRequest(startDate, tempEndDate, ds);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Error: " + e.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Done");

                    #region Final flushing to database
                    try
                    {
                        if (prices.Count > 0)
                        {
                            //Finally write to database
                            DataBaseHandler.getInstance().addEntries(prices);
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Error in writing data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        logger.Debug(e.Message);
                        logger.Debug(e.StackTrace);
                    }
                    finally
                    {
                        prices.Clear();
                    }
                    #endregion

                    #region Writing to a File
                    long rows = 0;
                    rows = DataBaseHandler.getInstance().getNumberOfRows();

                    //Calculate the levels first before requesting data.
                    long        templevel = 0;
                    List <long> levels    = new List <long>();
                    levels.Add(0);
                    while (true)
                    {
                        if (templevel + 5000 < rows)
                        {
                            templevel += 5000;
                            levels.Add(templevel);
                        }
                        else
                        {
                            levels.Add(rows);
                            break;
                        }
                    }
                    logger.Debug("Levels of data to be requested from database: " + levels.ToString());
                    dataSetup.isAlive = false;
                    #endregion
                }
                #endregion
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n" + e.Source, "Error");
            }
        }
        /// <summary>
        /// Fetches historical data from FXCM server
        /// </summary>
        /// <param name="historicDataRequest"></param>
        public void GetHistoricalData(HistoricDataRequest historicDataRequest)
        {
            // Create a new factory
            O2GRequestFactory factory = _session.getRequestFactory();

            // Get time frame
            O2GTimeframe timeframe = factory.Timeframes[GetFxcmTimeFrame(historicDataRequest)];

            if (timeframe == null)
            {
                _logger.Error("Invalid time format", _type.FullName, "GetHistoricalData");

                return;
            }

            // Clear any existing data
            _barCollection.Clear();

            // Request historical snapshot
            O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(historicDataRequest.Security.Symbol, timeframe, 300);

            DateTime endTime = historicDataRequest.EndTime;

            do // cause there is limit for returned candles amount
            {
                factory.fillMarketDataSnapshotRequestTime(request, historicDataRequest.StartTime, endTime, false);

                SetRequestId(request.RequestID);

                _session.sendRequest(request);

                if (!WaitEvents())
                {
                    _logger.Error("Response waiting timeout expired", _type.FullName, "GetHistoricalData");

                    return;
                }

                // Shift "to" bound to oldest datetime of returned data
                O2GResponse response = GetResponse();
                if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
                {
                    O2GResponseReaderFactory readerFactory = _session.getResponseReaderFactory();
                    if (readerFactory != null)
                    {
                        O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response);
                        if (reader.Count > 0)
                        {
                            if (DateTime.Compare(endTime, reader.getDate(0)) != 0)
                            {
                                endTime = reader.getDate(0); // earliest datetime of returned data
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            if (_logger.IsInfoEnabled)
                            {
                                _logger.Info("Response waiting timeout expired", _type.FullName, "GetHistoricalData");
                            }
                            break;
                        }
                    }
                    ExtractPrices(_session, response, historicDataRequest);
                }
                else
                {
                    break;
                }
            } while (endTime > historicDataRequest.StartTime);

            if (_barCollection.Count > 0)
            {
                if (_historicalDataEvent != null)
                {
                    _barCollection.Reverse();

                    // Create historical data object
                    var historicalData = new HistoricBarData(historicDataRequest.Security, historicDataRequest.MarketDataProvider, DateTime.UtcNow);
                    historicalData.Bars  = _barCollection.ToArray();
                    historicalData.ReqId = historicDataRequest.Id;

                    // Raise Event
                    _historicalDataEvent(historicalData);
                }

                _barCollection.Clear();
            }
        }