The article discusses how to get historic prices in .Net.
Create a session, a session status listener, subscribe the listener to the session status
(see this article
).
Implement the IO2GResponseListener
interface
in a response listener class:
public class MyResponseListener : IO2GResponseListener{...}
Subscribe an object of this class to the session response:
MyResponseListener responseListener = new MyResponseListener();
mSession.subscribeResponse(responseListener);
Log in (see this article
).
Use the listener onSessionStatusChanged
function to capture the Connected
event:
Create O2GRequestFactory
:
O2GRequestFactory factory = mSession.getRequestFactory();
Get O2GTimeframeCollection
:
O2GTimeframeCollection timeframes = factory.Timeframes;
Get the O2GTimeframe
you need:
O2GTimeframe tfo = timeframes["m1"];
Create a market data snapshot request (O2GRequest
), using the instrument, time frame, and maximum number of bars as arguments:
O2GRequest request = factory.createMarketDataSnapshotRequestInstrument("EUR/USD", tfo, 300);
Fill the market data snapshot request, using the request, date and time "from", and date and time "to" as arguments:
factory.fillMarketDataSnapshotRequestTime(request, from, to);
Send the request:
mSession.sendRequest(request);
Finally capture O2GResponse
in the
onRequestCompleted
function of a response listener class.
If the type of response is
MarketDataSnapshot
,
process the response to extract necessary information.
Get O2GResponseReaderFactory
:
O2GResponseReaderFactory readerFactory = mSession.getResponseReaderFactory();
Create O2GMarketDataSnapshotResponseReader
:
O2GMarketDataSnapshotResponseReader mReader = readerFactory.createMarketDataSnapshotReader(response);
Process row by row:
for (int i = 0; i < reader.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
}
Unsubscribe the session from the response listener.
mSession.unsubscribeResponse(responseListener);
Log out.
mSession.logout();
Get history prices example: [hide]
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using fxcore2;
namespace GetHistPrices
{
class Program
{
private static string sSessionID = "";
public static string SessionID
{
get { return sSessionID; }
}
private static string sPin = "";
public static string Pin
{
get { return sPin; }
}
private static string sTimeframeName;
public static string TimeframeName
{
get { return sTimeframeName; }
}
private static string sInstrument;
public static string Instrument
{
get { return sInstrument; }
}
public const int MAX_BARS = 300;
private static O2GSession session = null;
public static O2GSession Session
{
get { return session; }
}
private static SessionStatusListener sessionStatusListener;
private static ResponseListener responseListener;
static void Main(string[] args)
{
try
{
if (args.Length < 8)
{
Console.WriteLine("Not Enough Parameters!");
Console.WriteLine("USAGE: [application].exe [instrument (default \"EUR/USD\"] [time frame (default \"m1\")] [datetime \"from\" or empty string for \"from now\" (default)] [datetime \"to\" or empty string for \"to now\" (default)] [user ID] [password] [URL] [connection] [session ID (if needed) or empty string] [pin (if needed) or empty string] ");
Console.WriteLine("\nPress enter to close the program");
Console.ReadLine();
return;
}
sInstrument = "EUR/USD"; // default
sInstrument = args[0];
sTimeframeName = "m1"; // default
sTimeframeName = args[1];
string sDateTimeFrom = "";
sDateTimeFrom = args[2];
string sDateTimeTo = "";
sDateTimeTo = args[3];
string sUserID = args[4];
string sPassword = args[5];
string sURL = args[6];
string sConnection = args[7];
if (args.Length > 8)
sSessionID = args[8];
if (args.Length > 9)
sPin = args[9];
Console.WriteLine("Getting price history for instrument {0}; timeframe {1}; from {2}; to {3}", sInstrument, sTimeframeName, sDateTimeFrom, sDateTimeTo);
session = O2GTransport.createSession();
sessionStatusListener = new SessionStatusListener(session);
session.subscribeSessionStatus(sessionStatusListener);
sessionStatusListener.login(sUserID, sPassword, sURL, sConnection); //wait until login or fail
if (sessionStatusListener.Connected)
{
responseListener = new ResponseListener(session);
session.subscribeResponse(responseListener);
GetHistoryPrices(session, responseListener, sInstrument, sTimeframeName, sDateTimeFrom, sDateTimeTo);
session.unsubscribeResponse(responseListener);
session.logout();
while (!sessionStatusListener.Disconnected)
Thread.Sleep(50);
}
session.unsubscribeSessionStatus(sessionStatusListener);
Console.WriteLine("Press enter to exit");
Console.ReadLine();
session.Dispose();
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
public static void GetHistoryPrices(O2GSession session, ResponseListener listener, string instrument, string timeframeName, string sFrom, string sTo)
{
O2GRequestFactory factory = session.getRequestFactory();
O2GTimeframe tf = factory.Timeframes[timeframeName];
O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(sInstrument, tf, MAX_BARS);
DateTime dtFrom;
DateTime dtTo;
dtFrom = string.IsNullOrEmpty(sFrom) ? factory.ZERODATE : DateTime.Parse(sFrom);
dtTo = string.IsNullOrEmpty(sTo) ? factory.ZERODATE : DateTime.Parse(sTo);
factory.fillMarketDataSnapshotRequestTime(request, dtFrom, dtTo, false);
session.sendRequest(request);
responseListener.ResponseHandle.WaitOne(30000); //30 seconds timeout
}
public static void PrintPrices(O2GSession session, O2GResponse response)
{
Console.WriteLine();
O2GResponseReaderFactory factory = session.getResponseReaderFactory();
if (factory != null)
{
O2GMarketDataSnapshotResponseReader reader = factory.createMarketDataSnapshotReader(response);
for (int ii = 0; ii < reader.Count; 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));
}
}
}
}
}
internal class ResponseListener : IO2GResponseListener
{
private O2GSession mSession = null;
public WaitHandle ResponseHandle
{
get { return mResponseHandle; }
}
private EventWaitHandle mResponseHandle;
public ResponseListener(O2GSession session)
{
mSession = session;
mResponseHandle = new AutoResetEvent(false);
}
public void onRequestCompleted(string requestId, O2GResponse response)
{
if (response.Type == O2GResponseType.MarketDataSnapshot)
{
Program.PrintPrices(mSession, response);
Console.WriteLine("\nDone!");
}
mResponseHandle.Set();
}
public void onRequestFailed(string requestId, string error)
{
if (String.IsNullOrEmpty(error)) // not an error - we are finished - no more candles
{
Console.WriteLine("\n There is no history data for the specified period!");
}
else
{
Console.WriteLine("Request failed requestID={0} error={1}", requestId, error);
}
mResponseHandle.Set();
}
public void onTablesUpdates(O2GResponse data)
{
//STUB
}
}
internal class SessionStatusListener : IO2GSessionStatus
{
private bool mConnected = false;
private bool mDisconnected = false;
private bool mError = false;
private O2GSession mSession;
private object mEvent = new object();
public SessionStatusListener(O2GSession session)
{
mSession = session;
}
public bool Connected
{
get
{
return mConnected;
}
}
public bool Disconnected
{
get
{
return mDisconnected;
}
}
public bool Error
{
get
{
return mError;
}
}
public void onSessionStatusChanged(O2GSessionStatusCode status)
{
Console.WriteLine("Status: " + status.ToString());
if (status == O2GSessionStatusCode.Connected)
mConnected = true;
else
mConnected = false;
if (status == O2GSessionStatusCode.Disconnected)
mDisconnected = true;
else
mDisconnected = false;
if (status == O2GSessionStatusCode.TradingSessionRequested)
{
if (Program.SessionID == "")
Console.WriteLine("Argument for trading session ID is missing");
else
mSession.setTradingSession(Program.SessionID, Program.Pin);
}
else if (status == O2GSessionStatusCode.Connected)
{
lock (mEvent)
Monitor.PulseAll(mEvent);
}
}
public void onLoginFailed(string error)
{
Console.WriteLine("Login error: " + error);
mError = true;
lock (mEvent)
Monitor.PulseAll(mEvent);
}
public void login(string sUserID, string sPassword, string sURL, string sConnection)
{
Program.Session.login(sUserID, sPassword, sURL, sConnection);
lock (mEvent)
Monitor.Wait(mEvent, 60000);
}
}
}