public void onTablesUpdates(O2GResponse data) { O2GResponseReaderFactory factory = mSession.getResponseReaderFactory(); if (factory != null) { O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data); for (int ii = 0; ii < reader.Count; ii++) { if (reader.getUpdateTable(ii) == O2GTableType.Orders) { O2GOrderRow orderRow = reader.getOrderRow(ii); if (reader.getUpdateType(ii) == O2GTableUpdateType.Update) { if (mOrderIDs.Contains(orderRow.OrderID)) { Console.WriteLine("The order has been updated. OrderID={0}, ContingentOrderID={1}, ContingencyType={2}", orderRow.OrderID, orderRow.ContingentOrderID, orderRow.ContingencyType); mOrderIDs.Remove(orderRow.OrderID); } if (mOrderIDs.Count == 0) { mSyncResponseEvent.Set(); } } } } } }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mRequestID = string.Empty; mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mSession = session; }
/// <summary> /// Store offers data from response and print it /// </summary> /// <param name="session"></param> /// <param name="response"></param> /// <param name="sInstrument"></param> public void PrintOffers(O2GSession session, O2GResponse response, string sInstrument) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GOffersTableResponseReader responseReader = readerFactory.createOffersTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GOfferRow offerRow = responseReader.getRow(i); Offer offer; if (mOffers.FindOffer(offerRow.OfferID, out offer)) { if (offerRow.isTimeValid && offerRow.isBidValid && offerRow.isAskValid) { offer.Date = offerRow.Time; offer.Bid = offerRow.Bid; offer.Ask = offerRow.Ask; } } else { offer = new Offer(offerRow.OfferID, offerRow.Instrument, offerRow.Digits, offerRow.PointSize, offerRow.Time, offerRow.Bid, offerRow.Ask); mOffers.AddOffer(offer); } if (string.IsNullOrEmpty(sInstrument) || offerRow.Instrument.Equals(sInstrument)) { Console.WriteLine("{0}, {1}, Bid={2}, Ask={3}", offer.OfferID, offer.Instrument, offer.Bid, offer.Ask); } } }
public void onRequestCompleted(string sRequestId, O2GResponse response) { if (mRequestID.Equals(response.RequestID)) { mResponse = response; } }
public void onTablesUpdates(O2GResponse data) { O2GResponseReaderFactory factory = mSession.getResponseReaderFactory(); if (factory != null) { O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data); for (int ii = 0; ii < reader.Count; ii++) { if (reader.getUpdateTable(ii) == O2GTableType.Orders) { O2GOrderRow orderRow = reader.getOrderRow(ii); if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert) { if (mRequestID.Equals(orderRow.RequestID)) { Console.WriteLine("The order has been added. OrderID={0}, Type={1}, BuySell={2}, Rate={3}, TimeInForce={4}", orderRow.OrderID, orderRow.Type, orderRow.BuySell, orderRow.Rate, orderRow.TimeInForce); mSyncResponseEvent.Set(); break; } } } } } }
public void onTablesUpdates(O2GResponse response) { if (response.Type == O2GResponseType.TablesUpdates) { PrintOffers(mSession, response, mInstrument); } }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mSession = session; mRequestID = string.Empty; mInstrument = string.Empty; mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mOffers = new OfferCollection(); }
/// <summary> /// ctor /// </summary> /// <param name="session"></param> public ResponseListener(O2GSession session) { mSession = session; mRequestID = string.Empty; mRequestIDs = new List<string>(); mResponse = null; mSyncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mBatchOrderMonitor = null; }
public void onRequestCompleted(string sRequestId, O2GResponse response) { if (mRequestID.Equals(response.RequestID)) { mResponse = response; if (response.Type != O2GResponseType.CreateOrderResponse) { mSyncResponseEvent.Set(); } } }
// Implementation of IO2GResponseListener interface public method onRequestCompleted public void onRequestCompleted(String requestID, O2GResponse response) { // if need to capture response, send to log! //log.debug("Request completed.\nrequestID= " + requestID); mError = false; mErrorDescription = ""; O2GOrderResponseReader reader = mSession.getResponseReaderFactory().createOrderResponseReader(response); this.OrderId = reader.OrderID; manualEvent.Set(); CtrlTimer.getInstance().stopTimer("MarketRequest"); }
public void onRequestCompleted(string sRequestId, O2GResponse response) { if (mRequestID.Equals(response.RequestID) || mRequestIDs.Contains(response.RequestID)) { mResponse = response; if (response.Type != O2GResponseType.CreateOrderResponse) { mSyncResponseEvent.Set(); } } //real order execution is processed by Order monitor }
// Implementation of IO2GResponseListener interface public method onRequestCompleted public void onRequestCompleted(String requestID, O2GResponse response) { // if need to capture response, send to log! //log.debug("Request completed.\nrequestID= " + requestID); mError = false; mErrorDescription = ""; O2GOrderResponseReader reader = mSession.getResponseReaderFactory().createOrderResponseReader(response); this.OrderId = reader.OrderID; // TODO: API change dropped these properties //mError = !reader.isSuccessful; //if (mError) // mErrorDescription = reader.ErrorDescription; manualEvent.Set(); CtrlTimer.getInstance().stopTimer("ELSRequest"); }
public void onRequestFailed(string sRequestID, string sError) { if (mRequestID.Equals(sRequestID)) { mResponse = null; if (string.IsNullOrEmpty(sError)) { Console.WriteLine("There is no more data"); } else { Console.WriteLine("Request failed: " + sError); } mSyncResponseEvent.Set(); } }
public void onRequestCompleted(string s, O2GResponse response) { Console.WriteLine(s); switch (response.Type) { case O2GResponseType.CommandResponse: case O2GResponseType.CreateOrderResponse: case O2GResponseType.GetAccounts: case O2GResponseType.GetClosedTrades: case O2GResponseType.GetMessages: case O2GResponseType.GetOffers: case O2GResponseType.GetOrders: case O2GResponseType.GetSystemProperties: case O2GResponseType.GetTrades: { try { AccountInformationEventArg data = AccountInformationEventArg.ProcessData(_connection, response); } catch (Exception e) { Console.WriteLine(e); } break; } case O2GResponseType.MarketDataSnapshot: { try { MarketDataEventArg mData = MarketDataEventArg.ProcessMarketData(_connection, response); OnResponseReceived(mData); } catch (Exception e) { Console.WriteLine(e); } break; } case O2GResponseType.ResponseUnknown: case O2GResponseType.TablesUpdates: break; } }
/// <summary> /// Print accounts table /// </summary> /// <param name="session"></param> private static void PrintAccounts(O2GSession session) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsResponseReader = readerFactory.createAccountsTableReader(response); for (int i = 0; i < accountsResponseReader.Count; i++) { O2GAccountRow accountRow = accountsResponseReader.getRow(i); Console.WriteLine("AccountID: {0}, Balance: {1}", accountRow.AccountID, accountRow.Balance); } }
/// <summary> /// Find order by ID and print information about it /// </summary> /// <param name="session"></param> /// <param name="sOrderID"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> private static void FindOrder(O2GSession session, string sOrderID, string sAccountID, ResponseListener responseListener) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Orders, sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GOrdersTableResponseReader ordersReader = responseFactory.createOrdersTableReader(response); for (int i = 0; i < ordersReader.Count; i++) { O2GOrderRow order = ordersReader.getRow(i); if (sOrderID.Equals(order.OrderID)) { Console.WriteLine("Information for OrderID = {0}", sOrderID); Console.WriteLine("Account: {0}", order.AccountID); Console.WriteLine("Amount: {0}", order.Amount); Console.WriteLine("Rate: {0}", order.Rate); Console.WriteLine("Type: {0}", order.Type); Console.WriteLine("Buy/Sell: {0}", order.BuySell); Console.WriteLine("Stage: {0}", order.Stage); Console.WriteLine("Status: {0}", order.Status); } } } else { throw new Exception("Cannot get response"); } }
public bool ExistsPositionFor(string symbol) { O2GResponseReaderFactory factory = session.Session.getResponseReaderFactory(); // Gets first account from login. O2GLoginRules loginRules = session.Session.getLoginRules(); O2GResponse response = loginRules.getTableRefeshResponse(O2GTable.ClosedTrades); O2GTradesTableResponseReader tradesReader = factory.createTradesTableReader(response); for (int i = 0; i < tradesReader.Count; i++) { O2GTradeRow tradeRow = tradesReader.getRow(i); Console.WriteLine("Trades---"); Console.WriteLine(tradeRow.OpenQuoteID); Console.WriteLine(tradeRow.OfferID); } return(false); }
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); }
/// <summary> /// Find valid account by ID or get the first valid account /// </summary> /// <param name="session"></param> /// <returns>account</returns> private static O2GAccountRow GetAccount(O2GSession session, string sAccountID) { O2GAccountRow account = null; bool bHasAccount = false; O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsResponseReader = readerFactory.createAccountsTableReader(response); for (int i = 0; i < accountsResponseReader.Count; i++) { account = accountsResponseReader.getRow(i); string sAccountKind = account.AccountKind; if (!account.MaintenanceType.Equals("0")) // not netting account { if (sAccountKind.Equals("32") || sAccountKind.Equals("36")) { if (account.MarginCallFlag.Equals("N")) { if (string.IsNullOrEmpty(sAccountID) || sAccountID.Equals(account.AccountID)) { bHasAccount = true; break; } } } } } if (!bHasAccount) { return(null); } else { return(account); } }
/// <summary> /// Listener: Forex Connect request handled /// </summary> /// <param name="requestId"></param> /// <param name="response"></param> public void onRequestCompleted(string requestId, O2GResponse response) { // we need only offer table refresh for our example if (response.Type == O2GResponseType.GetOffers) { // so simply read and store offers O2GOffersTableResponseReader reader = mTradingSession.getResponseReaderFactory().createOffersTableReader(response); mOffers.Clear(); for (int i = 0; i < reader.Count; i++) { O2GOfferRow row = reader.getRow(i); mOffers.Add(row.OfferID, row.Instrument, row.Time, row.Bid, row.Ask, row.Volume, row.Digits); } // if price history communicator has been initialized before we get offer - notify that we're ready. if (mPriceHistoryCommunicator.isReady() && OnStateChange != null) { OnStateChange(true); } } }
void IO2GResponseListener.onRequestCompleted(string requestId, O2GResponse response) { if (response.Type == O2GResponseType.GetOffers) { ReadOffers(response); mReady = true; } else if (response.Type == O2GResponseType.MarketDataSnapshot) { TransportHistoryRequest req; if (mHistoryRequests.TryGetValue(requestId, out req)) { ReadSnapshot(requestId, response); if (OnRequestCompleted != null) { OnRequestCompleted(this, new RequestCompletedEventArgs(req.ID)); } } } }
/// <summary> /// Get the latest offer to which the user is subscribed /// </summary> private void GetLatestOffer() { // get the list of the offers to which the user is subscribed O2GLoginRules loginRules = mSession.getLoginRules(); O2GResponse response = loginRules.getSystemPropertiesResponse(); if (loginRules.isTableLoadedByDefault(O2GTableType.Offers)) { // if it is already loaded - just handle them response = loginRules.getTableRefreshResponse(O2GTableType.Offers); onRequestCompleted(null, response); } else { // otherwise create the request to get offers from the server O2GRequestFactory factory = mSession.getRequestFactory(); O2GRequest offerRequest = factory.createRefreshTableRequest(O2GTableType.Offers); mSession.sendRequest(offerRequest); } }
/// <summary> /// Get reports for all accounts /// </summary> /// <param name="session"></param> public static void GetReports(O2GSession session) { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse); using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient()) { for (int i = 0; i < accountsReader.Count; i++) { O2GAccountRow account = accountsReader.getRow(i); Uri url = new Uri(session.getReportURL(account.AccountID, DateTime.Now.AddMonths(-1), DateTime.Now, "html", null)); Console.WriteLine("AccountID={0}; Balance={1}; BaseUnitSize={2}; Report URL={3}", account.AccountID, account.Balance, account.BaseUnitSize, url); var response = httpClient.GetAsync(url).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; // by calling .Result you are synchronously reading the result string content = responseContent.ReadAsStringAsync().Result; string filename = account.AccountID + ".html"; string prefix = url.Scheme + "://" + url.Host + "/"; string report = O2GHtmlContentUtils.ReplaceRelativePathWithAbsolute(content, prefix); System.IO.File.WriteAllText(filename, report); Console.WriteLine("Report is saved to {0}", filename); } else { throw new Exception("Report is not received."); } } } }
/// <summary> /// Print offers and find offer by instrument name /// </summary> /// <param name="session"></param> /// <param name="sInstrument"></param> /// <returns>offer</returns> private static O2GOfferRow GetOffer(O2GSession session, string sInstrument) { O2GOfferRow offer = null; O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.Offers); O2GOffersTableResponseReader offersResponseReader = readerFactory.createOffersTableReader(response); for (int i = 0; i < offersResponseReader.Count; i++) { O2GOfferRow offerRow = offersResponseReader.getRow(i); if (offerRow.Instrument.Equals(sInstrument)) { offer = offerRow; } switch (offerRow.SubscriptionStatus) { case Constants.SubscriptionStatuses.ViewOnly: Console.WriteLine("{0} : [V]iew only", offerRow.Instrument); break; case Constants.SubscriptionStatuses.Disable: Console.WriteLine("{0} : [D]isabled", offerRow.Instrument); break; case Constants.SubscriptionStatuses.Tradable: Console.WriteLine("{0} : Available for [T]rade", offerRow.Instrument); break; default: Console.WriteLine("{0} : {1}", offerRow.Instrument, offerRow.SubscriptionStatus); break; } } return(offer); }
public void onTablesUpdates(O2GResponse data) { O2GResponseReaderFactory factory = mSession.getResponseReaderFactory(); if (factory != null) { O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data); for (int ii = 0; ii < reader.Count; ii++) { if (reader.getUpdateTable(ii) == O2GTableType.Orders) { O2GOrderRow orderRow = reader.getOrderRow(ii); if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert) { mOrderID = orderRow.OrderID; mSyncResponseEvent.Set(); break; } } } } }
public void onTablesUpdates(O2GResponse response) { //Console.WriteLine(response.ToString()); switch (response.Type) { case O2GResponseType.CommandResponse: case O2GResponseType.CreateOrderResponse: case O2GResponseType.GetAccounts: case O2GResponseType.GetClosedTrades: case O2GResponseType.GetMessages: case O2GResponseType.GetOffers: case O2GResponseType.GetOrders: case O2GResponseType.GetSystemProperties: case O2GResponseType.GetTrades: case O2GResponseType.MarketDataSnapshot: case O2GResponseType.ResponseUnknown: case O2GResponseType.TablesUpdates: break; } }
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))); } }
/// <summary> /// Print trades table for account /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="responseListener"></param> private static void PrintTrades(O2GSession session, string sAccountID, ResponseListener responseListener) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); if (request != null) { Console.WriteLine("Trades table for account {0}", sAccountID); responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null) { O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); O2GTradesTableResponseReader responseReader = responseReaderFactory.createTradesTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GTradeRow tradeRow = responseReader.getRow(i); Console.WriteLine("TradeID: {0}, Amount: {1}, Dividends: {2}", tradeRow.TradeID, tradeRow.Amount, tradeRow.Dividends); } } else { throw new Exception("Cannot get response"); } } else { throw new Exception("Cannot create request"); } }
/// <summary> /// Constructor. /// </summary> public PriceUpdateController(O2GSession session, string instrument) { mSyncOfferEvent = new EventWaitHandle(false, EventResetMode.AutoReset); mInstrument = instrument; mSession = session; mInitFailed = false; mSession.subscribeResponse(this); mTZConverter = session.getTimeConverter(); // get the trading day offset O2GLoginRules loginRules = session.getLoginRules(); O2GResponse response = loginRules.getSystemPropertiesResponse(); O2GSystemPropertiesReader reader = session.getResponseReaderFactory().createSystemPropertiesReader(response); string eod = reader.Properties["END_TRADING_DAY"]; DateTime time = DateTime.ParseExact("01.01.1900_" + eod, "MM.dd.yyyy_HH:mm:ss", CultureInfo.InvariantCulture); // convert Trading day start to EST time because the trading day is always closed by New York time // so to avoid handling different hour depending on daylight saying time - use EST always // for candle calculations time = mTZConverter.convert(time, O2GTimeConverterTimeZone.UTC, O2GTimeConverterTimeZone.EST); // here we have the date when trading day begins, e.g. 17:00:00 // please note that if trading day begins before noon - it begins AFTER calendar date is started, // so the offset is positive (e.g. 03:00 is +3 offset). // if trading day begins after noon, it begins BEFORE calendar date is istarted, // so the offset is negative (e.g. 17:00 is -7 offset). if (time.Hour <= 12) { mTradingDayOffset = time.Hour; } else { mTradingDayOffset = time.Hour - 24; } // get latest offer for the instrument GetLatestOffer(); }
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)))); } }
/// <summary> /// Store offers data from response and print it /// </summary> /// <param name="session"></param> /// <param name="response"></param> /// <param name="sInstrument"></param> public void PrintOffers(O2GSession session, O2GResponse response, string sInstrument) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory == null) { throw new Exception("Cannot create response reader factory"); } O2GOffersTableResponseReader responseReader = readerFactory.createOffersTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GOfferRow offerRow = responseReader.getRow(i); Offer offer; if (mOffers.FindOffer(offerRow.OfferID, out offer)) { if (offerRow.isTimeValid && offerRow.isBidValid && offerRow.isAskValid) { offer.Date = offerRow.Time; offer.Bid = offerRow.Bid; offer.Ask = offerRow.Ask; } } else { offer = new Offer(offerRow.OfferID, offerRow.Instrument, offerRow.Digits, offerRow.PointSize, offerRow.Time, offerRow.Bid, offerRow.Ask); mOffers.AddOffer(offer); } if (string.IsNullOrEmpty(sInstrument) || offerRow.Instrument.Equals(sInstrument)) { if (offer.Instrument.Equals("Copper")) { //Console.WriteLine("{0}, {1}, Bid={2}, Ask={3}", offer.OfferID, offer.Instrument, offer.Bid, offer.Ask); } Console.WriteLine("{0}, {1}, Bid={2}, Ask={3}", offer.OfferID, offer.Instrument, offer.Bid, offer.Ask); } } }
/// <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)); } } } }
public void onTablesUpdates(O2GResponse data) { O2GResponseReaderFactory factory = mSession.getResponseReaderFactory(); if (factory != null) { O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data); for (int ii = 0; ii < reader.Count; ii++) { if (reader.getUpdateTable(ii) == O2GTableType.Orders) { O2GOrderRow orderRow = reader.getOrderRow(ii); if (orderRow.RequestID.Equals(mRequestID)) { switch (reader.getUpdateType(ii)) { case O2GTableUpdateType.Insert: if (IsLimitEntryOrder(orderRow) && string.IsNullOrEmpty(mOrderID)) { mOrderID = orderRow.OrderID; Console.WriteLine("The order has been added. Order ID: {0}, Rate: {1}, Time In Force: {2}", orderRow.OrderID, orderRow.Rate, orderRow.TimeInForce); mSyncResponseEvent.Set(); } break; case O2GTableUpdateType.Delete: Console.WriteLine("The order has been deleted. Order ID: {0}", orderRow.OrderID); mSyncResponseEvent.Set(); break; } } } } } }
/// <summary> /// Get trade by order ID /// </summary> private static O2GTradeRow FindPosition(O2GSession session, string sAccountID, string sOrderID, ResponseListener responseListener) { O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Trades, sAccountID); if (request != null) { responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse tradeResponse = responseListener.GetResponse(); if (tradeResponse != null) { if (tradeResponse.Type == O2GResponseType.GetTrades) { O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); O2GTradesTableResponseReader responseReader = responseReaderFactory.createTradesTableReader(tradeResponse); for (int i = 0; i < responseReader.Count; i++) { O2GTradeRow tradeRow = responseReader.getRow(i); if (sOrderID.Equals(tradeRow.OpenOrderID)) { return(tradeRow); } } } } } return(null); }
private void ProcessResponse(O2GResponse response) { if (response == null) { // No response. return; } if (this.DataReceived == null) { // No listeners. return; } foreach (var item in this.ResponseReader.ReadResponse(response)) { this.DataReceived(this, new EventArgs <DataReceived>(new DataReceived() { RequestID = response.RequestID, Row = item, })); } }
void ReadOffers(O2GResponse offers) { O2GResponseReaderFactory factory = mSession.getResponseReaderFactory(); if (factory != null) { O2GOffersTableResponseReader reader = factory.createOffersTableReader(offers); mOffers.Clear(); mOffersList.Clear(); for (int i = 0; i < reader.Count; i++) { O2GOfferRow row = reader.getRow(i); //mTimeConverter.convert(row.Time, O2GTimeConverterTimeZone.UTC, mTimezone) //DateTime dt = mTimeConverter.convert(row.Time, O2GTimeConverterTimeZone.Server, O2GTimeConverterTimeZone.UTC); DateTime dt = row.Time; Offer offer = new Offer(row.Instrument, dt, row.Bid, row.Ask, row.Volume, row.Digits, row.PointSize); mOffers[row.OfferID] = offer; mOffersList.Add(offer); SendTick(offer); } } }
public void onRequestFailed(string requestId, string errorMessage) { if (this.requestId.Equals(requestId)) { response = null; if (string.IsNullOrEmpty(errorMessage)) { errorMessage = "There is no more data"; } if (errorMessage.StartsWith( "Reason='unsupported scope', Description=No data found for symbolID=")) { OnNoTicks?.Invoke(this, EventArgs.Empty); } else { OnRequestFailed?.Invoke(this, new RequestFailedArgs(errorMessage)); } syncResponseEvent.Set(); } }
/// <summary> /// Check if order exists /// </summary> /// <param name="session"></param> /// <param name="sAccountID"></param> /// <param name="sOrderID"></param> /// <param name="responseListener"></param> /// <returns></returns> private static bool IsOrderExists(O2GSession session, string sAccountID, string sOrderID, ResponseListener responseListener) { bool bHasOrder = false; O2GRequestFactory requestFactory = session.getRequestFactory(); if (requestFactory == null) { throw new Exception("Cannot create request factory"); } O2GRequest request = requestFactory.createRefreshTableRequestByAccount(O2GTableType.Orders, sAccountID); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); O2GResponseReaderFactory responseReaderFactory = session.getResponseReaderFactory(); O2GOrdersTableResponseReader responseReader = responseReaderFactory.createOrdersTableReader(response); for (int i = 0; i < responseReader.Count; i++) { O2GOrderRow orderRow = responseReader.getRow(i); if (sOrderID.Equals(orderRow.OrderID)) { bHasOrder = true; break; } } return(bHasOrder); }
public void SetRequestID(string sRequestID) { mResponse = null; mRequestID = sRequestID; }
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); } } }
public void SetRequestIDs(List<string> requestIDs) { mResponse = null; mRequestIDs.Clear(); foreach (string sOrderID in requestIDs) { mRequestIDs.Add(sOrderID); } }
public void onTablesUpdates(O2GResponse data) { }
// Implementation of IO2GResponseListener interface public method onRequestCompleted public void onRequestCompleted(string sRequestID, O2GResponse response) { }
public static AccountInformationEventArg ProcessData(FXSession connection, O2GResponse response) { return new AccountInformationEventArg(); }
public void onTablesUpdates(O2GResponse data) { O2GResponseReaderFactory factory = mSession.getResponseReaderFactory(); if (factory != null) { O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data); for (int ii = 0; ii < reader.Count; ii++) { switch (reader.getUpdateTable(ii)) { case O2GTableType.Accounts: O2GAccountRow account = reader.getAccountRow(ii); //Show balance updates Console.WriteLine("Balance: {0}", account.Balance); break; case O2GTableType.Orders: O2GOrderRow order = reader.getOrderRow(ii); switch (reader.getUpdateType(ii)) { case O2GTableUpdateType.Insert: if ((OrderMonitorNetting.IsClosingOrder(order) || OrderMonitorNetting.IsOpeningOrder(order)) && mOrderMonitor == null) { Console.WriteLine("The order has been added. Order ID: {0}, Rate: {1}, Time In Force: {2}", order.OrderID, order.Rate, order.TimeInForce); O2GTradeRow tradeRow = null; string sTradeID = order.TradeID; if (mTradesTable != null) { for (int j = 0; j < mTradesTable.Count; j++) { if (sTradeID.Equals(mTradesTable.getRow(j).TradeID)) { tradeRow = mTradesTable.getRow(j); break; } } } if (tradeRow == null) { mOrderMonitor = new OrderMonitorNetting(order); } else { mOrderMonitor = new OrderMonitorNetting(order, tradeRow.Amount); } } break; case O2GTableUpdateType.Delete: if (mOrderMonitor != null) { Console.WriteLine("The order has been deleted. Order ID: {0}", order.OrderID); mOrderMonitor.OnOrderDeleted(order); if (mOrderMonitor.IsOrderCompleted) { PrintResult(); mSyncResponseEvent.Set(); } } break; } break; case O2GTableType.Trades: O2GTradeRow trade = reader.getTradeRow(ii); switch (reader.getUpdateType(ii)) { case O2GTableUpdateType.Insert: if (mOrderMonitor != null) { mOrderMonitor.OnTradeAdded(trade); if (mOrderMonitor.IsOrderCompleted) { PrintResult(); mSyncResponseEvent.Set(); } } break; case O2GTableUpdateType.Update: if (mOrderMonitor != null) { mOrderMonitor.OnTradeUpdated(trade); if (mOrderMonitor.IsOrderCompleted) { PrintResult(); mSyncResponseEvent.Set(); } } break; } break; case O2GTableType.ClosedTrades: O2GClosedTradeRow closedTrade = reader.getClosedTradeRow(ii); if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert) { if (mOrderMonitor != null) { mOrderMonitor.OnClosedTradeAdded(closedTrade); if (mOrderMonitor.IsOrderCompleted) { PrintResult(); mSyncResponseEvent.Set(); } } } break; case O2GTableType.Messages: O2GMessageRow message = reader.getMessageRow(ii); if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert) { if (mOrderMonitor != null) { mOrderMonitor.OnMessageAdded(message); if (mOrderMonitor.IsOrderCompleted) { PrintResult(); mSyncResponseEvent.Set(); } } } break; } } } }
public void onRequestCompleted(string requestId, O2GResponse response) { if (this.requestId == requestId) { manualEvent.Set(); log.debug("Ordering STE for tradeId=" + tradeId); } }
// Implementation of IO2GResponseListener interface public method onRequestCompleted public void onRequestCompleted(String requestID, O2GResponse response) { if (response.Type != O2GResponseType.MarketDataSnapshot) return; // if need to capture response, send to log! //log.debug("Request completed.\nrequestID= " + requestID); mError = false; O2GResponseReaderFactory factory = mSession.getResponseReaderFactory(); O2GMarketDataSnapshotResponseReader mReader = factory.createMarketDataSnapshotReader(response); for (int i = 0; i < mReader.Count; i++) { map.Add(mReader.getDate(i), new Dictionary<PriceComponent, object>()); map[mReader.getDate(i)].Add(PriceComponent.BidClose, mReader.getBidClose(i)); map[mReader.getDate(i)].Add(PriceComponent.AskClose, mReader.getAskClose(i)); map[mReader.getDate(i)].Add(PriceComponent.BidHigh, mReader.getBidHigh(i)); map[mReader.getDate(i)].Add(PriceComponent.BidLow, mReader.getBidLow(i)); map[mReader.getDate(i)].Add(PriceComponent.BidOpen, mReader.getBidOpen(i)); map[mReader.getDate(i)].Add(PriceComponent.AskHigh, mReader.getAskHigh(i)); map[mReader.getDate(i)].Add(PriceComponent.AskLow, mReader.getAskLow(i)); map[mReader.getDate(i)].Add(PriceComponent.AskOpen, mReader.getAskOpen(i)); // information like reader.getDate(i), reader.getBidOpen(i), reader.getBidHigh(i), reader.getBidLow(i), reader.getBidClose(i), reader.getVolume(i) is now available } manualEvent.Set(); CtrlTimer.getInstance().stopTimer("HistoryRequest"); }
// Implementation of IO2GResponseListener interface public method onTablesUpdates public void onTablesUpdates(O2GResponse response) { }
public void onRequestCompleted(string requestId, O2GResponse response) { if (this.requestId == requestId) { manualEvent.Set(); log.debug("Closing, tradeId=" + tradeId); } if (this.OrderDeleteRequestId == requestId) { manualEvent.Set(); log.debug("SLE order deleted, orderId=" + orderId); } }
public ResponseListener() { requestId = string.Empty; response = null; syncResponseEvent = new EventWaitHandle(false, EventResetMode.AutoReset); }
// Print trading settings of the first account private static void PrintTradingSettings(O2GSession session) { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts); if (accountsResponse == null) { throw new Exception("Cannot get response"); } O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers); if (offersResponse == null) { throw new Exception("Cannot get response"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); O2GResponseReaderFactory factory = session.getResponseReaderFactory(); if (factory == null) { throw new Exception("Cannot create response reader factory"); } O2GAccountsTableResponseReader accountsReader = factory.createAccountsTableReader(accountsResponse); O2GOffersTableResponseReader instrumentsReader = factory.createOffersTableReader(offersResponse); O2GAccountRow account = accountsReader.getRow(0); for (int i = 0; i < instrumentsReader.Count; i++) { O2GOfferRow instrumentRow = instrumentsReader.getRow(i); string instrument = instrumentRow.Instrument; int condDistStopForTrade = tradingSettingsProvider.getCondDistStopForTrade(instrument); int condDistLimitForTrade = tradingSettingsProvider.getCondDistLimitForTrade(instrument); int condDistEntryStop = tradingSettingsProvider.getCondDistEntryStop(instrument); int condDistEntryLimit = tradingSettingsProvider.getCondDistEntryLimit(instrument); int minQuantity = tradingSettingsProvider.getMinQuantity(instrument, account); int maxQuantity = tradingSettingsProvider.getMaxQuantity(instrument, account); int baseUnitSize = tradingSettingsProvider.getBaseUnitSize(instrument, account); O2GMarketStatus marketStatus = tradingSettingsProvider.getMarketStatus(instrument); int minTrailingStep = tradingSettingsProvider.getMinTrailingStep(); int maxTrailingStep = tradingSettingsProvider.getMaxTrailingStep(); double mmr = tradingSettingsProvider.getMMR(instrument, account); double mmr2 = 0, emr = 0, lmr = 0; bool threeLevelMargin = tradingSettingsProvider.getMargins(instrument, account, ref mmr2, ref emr, ref lmr); string sMarketStatus = "unknown"; switch (marketStatus) { case O2GMarketStatus.MarketStatusOpen: sMarketStatus = "Market Open"; break; case O2GMarketStatus.MarketStatusClosed: sMarketStatus = "Market Close"; break; } Console.WriteLine("Instrument: {0}, Status: {1}", instrument, sMarketStatus); Console.WriteLine("Cond.Dist: ST={0}; LT={1}", condDistStopForTrade, condDistLimitForTrade); Console.WriteLine("Cond.Dist entry stop={0}; entry limit={1}", condDistEntryStop, condDistEntryLimit); Console.WriteLine("Quantity: Min={0}; Max={1}. Base unit size={2}; MMR={3}", minQuantity, maxQuantity, baseUnitSize, mmr); if (threeLevelMargin) { Console.WriteLine("Three level margin: MMR={0}; EMR={1}; LMR={2}", mmr2, emr, lmr); } else { Console.WriteLine("Single level margin: MMR={0}; EMR={1}; LMR={2}", mmr2, emr, lmr); } Console.WriteLine("Trailing step: {0}-{1}", minTrailingStep, maxTrailingStep); } }
public void SetRequestID(string requestId) { response = null; this.requestId = requestId; }
public void onTablesUpdates(O2GResponse data) { O2GResponseReaderFactory factory = mSession.getResponseReaderFactory(); if (factory != null) { O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data); for (int ii = 0; ii < reader.Count; ii++) { switch (reader.getUpdateTable(ii)) { case O2GTableType.Accounts: O2GAccountRow account = reader.getAccountRow(ii); //Show balance updates Console.WriteLine("Balance: {0}", account.Balance); break; case O2GTableType.Orders: O2GOrderRow order = reader.getOrderRow(ii); switch (reader.getUpdateType(ii)) { case O2GTableUpdateType.Insert: if (mBatchOrderMonitor != null) { Console.WriteLine("The order has been added. Order ID: {0}, Rate: {1}, Time In Force: {2}", order.OrderID, order.Rate, order.TimeInForce); mBatchOrderMonitor.OnOrderAdded(order); } break; case O2GTableUpdateType.Delete: if (mBatchOrderMonitor != null) { Console.WriteLine("The order has been deleted. Order ID: {0}", order.OrderID); mBatchOrderMonitor.OnOrderDeleted(order); if (mBatchOrderMonitor.IsBatchExecuted()) { PrintResult(); mSyncResponseEvent.Set(); } } break; } break; case O2GTableType.Trades: O2GTradeRow trade = reader.getTradeRow(ii); if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert) { if (mBatchOrderMonitor != null) { mBatchOrderMonitor.OnTradeAdded(trade); if (mBatchOrderMonitor.IsBatchExecuted()) { PrintResult(); mSyncResponseEvent.Set(); } } } break; case O2GTableType.ClosedTrades: O2GClosedTradeRow closedTrade = reader.getClosedTradeRow(ii); if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert) { if (mBatchOrderMonitor != null) { mBatchOrderMonitor.OnClosedTradeAdded(closedTrade); if (mBatchOrderMonitor.IsBatchExecuted()) { PrintResult(); mSyncResponseEvent.Set(); } } } break; case O2GTableType.Messages: O2GMessageRow message = reader.getMessageRow(ii); if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert) { if (mBatchOrderMonitor != null) { mBatchOrderMonitor.OnMessageAdded(message); if (mBatchOrderMonitor.IsBatchExecuted()) { PrintResult(); mSyncResponseEvent.Set(); } } } break; } } } }