How to get historic prices

Brief

The article discusses how to get historic prices in Java.

Details

To get historic prices in your Java application, you should:

  1. Create a session, a session status listener, subscribe the listener to the session status (see this article).

  2. Implement the IO2GResponseListener interface in a response listener class:

    public class ResponseListener implements IO2GResponseListener{...}
  3. Subscribe an object of this class to the session response:

    ResponseListener responseListener = new ResponseListener(...);
    session.subscribeResponse(new myResponseListener());
  4. Log in (see this article).

  5. Use the listener onSessionStatusChanged function to capture the CONNECTED event:

  6. Create O2GRequestFactory:

    O2GRequestFactory factory = mSession.getRequestFactory();
  7. Get O2GTimeframeCollection:

    O2GTimeframeCollection timeFrames = factory.getTimeFrameCollection();
  8. Get the O2GTimeframe you need:

    O2GTimeframe timeFrame = timeFrames.get(0);

    or

    O2GTimeframe timeFrame = timeFrames.get("m1");
  9. Create a market data snapshot request (O2GRequest), using the instrument, time frame, and maximum number of bars as arguments:

    O2GRequest marketDataRequest = factory.createMarketDataSnapshotRequestInstrument("EUR/USD", timeFrame, 300);
  10. Fill the market data snapshot request, using the request, date and time "from", and date and time "to" as arguments (use null for date and time "from" to get maximum number of bars; use null for date and time "to" to get history till now):

    factory.fillMarketDataSnapshotRequestTime(marketDataRequest, null, null);
  11. Send the request:

    mSession.sendRequest(marketDataRequest);
  12. Finally capture O2GResponse in the onRequestCompleted function of a response listener class.
    If the type of response is MARKET_DATA_SNAPSHOT, process the response to extract necessary information.

  13. Get O2GResponseReaderFactory:

    O2GResponseReaderFactory factory = mSession.getResponseReaderFactory();
  14. Create O2GMarketDataSnapshotResponseReader:

    O2GMarketDataSnapshotResponseReader marketSnapshotReader = factory.createMarketDataSnapshotReader(response);
  15. Process row by row:

    for (int i = 0; i < marketSnapshotReader.size(); i++) {
    {
        // information like marketSnapshotReader.getDate(i), marketSnapshotReader.getBidOpen(i), marketSnapshotReader.getBidHigh(i), marketSnapshotReader.getBidLow(i), marketSnapshotReader.getBidClose(i), marketSnapshotReader.getVolume(i) is now available
    }
    
  16. Unsubscribe the session from the response listener.

  17. Log out.

Get historic prices example [show]

See also the simplified request/response sequence diagram.

back