예제 #1
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));
                }
            }
        }
예제 #2
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))));
            }
        }
예제 #3
0
        private IEnumerable <BaseRow> GetGenericResponse(O2GMarketDataSnapshotResponseReader reader, string requestID)
        {
            var rows = new List <MarketDataRow>();

            // Try to obtain the instrument from a saved list of market data requests.
            var instrument = this.MarketDataInstrumentGetter(requestID);

            for (var i = 0; i < reader.Count; i++)
            {
                var row = new MarketDataRow();

                row.Instrument = instrument;

                if (reader.isBar)
                {
                    row.AskClose = reader.getAskClose(i);
                    row.AskHigh  = reader.getAskHigh(i);
                    row.AskLow   = reader.getAskLow(i);
                    row.AskOpen  = reader.getAskOpen(i);
                    row.BidClose = reader.getBidClose(i);
                    row.BidHigh  = reader.getBidHigh(i);
                    row.BidLow   = reader.getBidLow(i);
                    row.BidOpen  = reader.getBidOpen(i);
                }
                else
                {
                    row.Ask = reader.getAsk(i);
                    row.Bid = reader.getBid(i);
                }

                row.IsBar  = reader.isBar;
                row.Time   = reader.getDate(i);
                row.Volume = reader.getVolume(i);

                rows.Add(row);
            }

            return(rows);
        }
예제 #4
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);
                }
            }
        }
예제 #5
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));
                    }
                }
            }
        }
        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);
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Print history data from response.
        /// </summary>
        /// <param name="communicator">The price history communicator.</param>
        /// <param name="response">The response. Cannot be null.</param>
        public static void PrintPrices(IPriceHistoryCommunicator communicator, IPriceHistoryCommunicatorResponse response)
        {
            // use O2GMarketDataSnapshotResponseReader to extract price data from the response object
            O2GMarketDataSnapshotResponseReader reader = communicator.createResponseReader(response);

            for (int i = 0; i < reader.Count; i++)
            {
                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(i), 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));
                }
                else
                {
                    Console.WriteLine("DateTime={0}, Bid={1}, Ask={2}", reader.getDate(i), reader.getBid(i), reader.getAsk(i));
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Listener: Price history request is completed
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void onRequestCompleted(IPriceHistoryCommunicatorRequest request, IPriceHistoryCommunicatorResponse response)
        {
            // try to find the collection (must be created at the moment when the request is sent)
            PeriodCollection coll = null;

            mHistories.TryGetValue(request, out coll);
            if (coll != null)
            {
                // create a reader for the price history data
                O2GMarketDataSnapshotResponseReader reader = mPriceHistoryCommunicator.createResponseReader(response);
                // and read all bars
                for (int i = 0; i < reader.Count; i++)
                {
                    coll.Add(reader.getDate(i), 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));
                }
                // finally notify the collection that all bars are added, so it can
                // add all ticks collected while the request was being executed
                // and start update the data by forthcoming ticks (for alive collections)
                coll.Finish(reader.getLastBarTime(), reader.getLastBarVolume());
            }
            // now we can remove collection from our cache and send it to the application
            mHistories.Remove(request);
            if (coll != null && OnCollectionLoaded != null)
            {
                OnCollectionLoaded(coll);
            }
        }
예제 #9
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);
            }
        }
예제 #10
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();
        }
예제 #11
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");
            }
        }