/// <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 = mSession.getResponseReaderFactory().createOffersTableReader(response); for (int i = 0; i < reader.Count; i++) { O2GOfferRow row = reader.getRow(i); if (mInstrument.Equals(row.Instrument)) { mOffer = new Offer(row.Instrument, row.Time, row.Bid, row.Ask, row.Volume, row.Digits); mSyncOfferEvent.Set(); break; } } if (mOffer == null) { Console.WriteLine("Instrument is not found.\n"); mInitFailed = true; mSyncOfferEvent.Set(); } } }
public OrderObject prepareParamsFromLoginRules(string instrument) { OrderObject orderObject = new OrderObject(); O2GLoginRules loginRules = _session.Session.getLoginRules(); O2GResponseReaderFactory factory = _session.Session.getResponseReaderFactory(); // Gets first account from login. O2GResponse accountsResponse = loginRules.getTableRefeshResponse(O2GTable.Accounts); O2GAccountsTableResponseReader accountsReader = factory.createAccountsTableReader(accountsResponse); O2GAccountRow account = accountsReader.getRow(0); orderObject.AccountID = account.AccountID; // Store base iAmount orderObject.BaseAmount = account.BaseUnitSize; O2GResponse offerResponse = loginRules.getTableRefeshResponse(O2GTable.Offers); O2GOffersTableResponseReader offersReader = factory.createOffersTableReader(offerResponse); for (int i = 0; i < offersReader.Count; i++) { O2GOfferRow offer = offersReader.getRow(i); if (instrument.Equals(offer.Instrument)) { orderObject.OfferID = offer.OfferID; orderObject.Ask = offer.Ask; orderObject.Bid = offer.Bid; orderObject.PointSize = offer.PointSize; orderObject.Symbol = new Symbol(instrument); break; } } return(orderObject); }
/// <summary> /// Print accounts table /// </summary> /// <param name="session"></param> private static void PrintCommissionDetails(O2GSession session, SampleParams sampleParams) { //wait until commissions related information will be loaded O2GCommissionsProvider commissionProvider = session.getCommissionsProvider(); while (commissionProvider.getStatus() == O2GCommissionStatus.CommissionStatusLoading) { System.Threading.Thread.Sleep(1000); } if (commissionProvider.getStatus() != O2GCommissionStatus.CommissionStatusReady) { throw new Exception("Could not calculate the estimated commissions."); } //retrieve the required parameter values from the sampleParams O2GAccountRow account = GetAccount(session, sampleParams.AccountID); O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null || account == null) { throw new Exception("Incorrect input parameters."); } O2GCommissionDescriptionsCollection commList = commissionProvider.getCommissionDescriptions(offer.OfferID, account.ATPID); foreach (O2GCommissionDescription descr in commList) { Console.WriteLine("Commission : {0}, {1}, {2}", descr.Stage, descr.UnitType, descr.CommissionValue); } }
private void Session_TablesUpdates(object sender, TablesUpdatesEventArgs e) { var responseFactory = _session.getResponseReaderFactory(); var responsGTablesUpdatesReader = responseFactory.createTablesUpdatesReader(e.Response); for (int i = 0; i < responsGTablesUpdatesReader.Count; i++) { if (responsGTablesUpdatesReader.getUpdateTable(i) == O2GTableType.Offers) { if (responsGTablesUpdatesReader.getUpdateType(i) == O2GTableUpdateType.Update) { O2GOfferRow offer = responsGTablesUpdatesReader.getOfferRow(i); var _offerID = offer.OfferID; var _currentSymbol = offer.Instrument; PriceUpdate pu = new PriceUpdate { Symbol = offer.Instrument, TradeDateTime = offer.Time, Price = (offer.Bid + offer.Ask) / 2, Volume = offer.Volume, Bid = offer.Bid, Ask = offer.Ask }; priceUpdates.Add(pu); } } } }
/* Prepare Params for Orders */ public void PrepareParamsFromLoginRules(O2GLoginRules loginRules) { O2GResponseReaderFactory factory = m_o2gsession.getResponseReaderFactory(); if (factory == null) { return; } // Gets first account from login. O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsReader = factory.createAccountsTableReader(accountsResponse); O2GAccountRow account = accountsReader.getRow(0); // Store account id m_accountid = account.AccountID; // Store base iAmount m_baseamount = account.BaseUnitSize; // Get offers for eur/usd O2GResponse offerResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers); O2GOffersTableResponseReader offersReader = factory.createOffersTableReader(offerResponse); for (int i = 0; i < offersReader.Count; i++) { O2GOfferRow offer = offersReader.getRow(i); if (string.Compare(offer.Instrument, m_instrument /*"EUR/USD"*/, true) == 0) { m_offerid = offer.OfferID; m_ask = offer.Ask; m_bid = offer.Bid; m_pointsize = offer.PointSize; break; } } }
/// <summary> /// Find valid 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; bool bHasOffer = 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.Offers); O2GOffersTableResponseReader offersResponseReader = readerFactory.createOffersTableReader(response); for (int i = 0; i < offersResponseReader.Count; i++) { offer = offersResponseReader.getRow(i); if (offer.Instrument.Equals(sInstrument)) { if (offer.SubscriptionStatus.Equals("T")) { bHasOffer = true; break; } } } if (!bHasOffer) { return(null); } else { return(offer); } }
/// <summary> /// Find valid offer by instrument name /// </summary> /// <param name="tableManager"></param> /// <param name="sInstrument"></param> /// <returns>offer</returns> private static O2GOfferRow GetOffer(O2GTableManager tableManager, string sInstrument) { bool bHasOffer = false; O2GOfferRow offer = null; O2GOffersTable offersTable = (O2GOffersTable)tableManager.getTable(O2GTableType.Offers); for (int i = 0; i < offersTable.Count; i++) { offer = offersTable.getRow(i); if (offer.Instrument.Equals(sInstrument)) { if (offer.SubscriptionStatus.Equals("T")) { bHasOffer = true; break; } } } if (!bHasOffer) { return(null); } else { return(offer); } }
public void ModelCreateOrder(Session Session, Model CurrentModel, string OrderType, int iAmount, double idRate, double idPointSize, int iAtMarket, string sBuySell) { m_o2gsession = Session.O2GSession; O2GTableManager tableManager = Session.O2GSession.getTableManager(); O2GAccountRow account = GetAccount(tableManager, null); O2GOfferRow offer = GetOffer(tableManager, CurrentModel.Instrument); O2GTradeRow trade = GetTrade(tableManager, account.AccountID, offer.OfferID); switch (OrderType) { case "OpenMarketOrder": CreateTrueMarketOrder(offer.OfferID, account.AccountID, iAmount, sBuySell); break; case "CloseMarketOrder": PrepareParamsAndCallTrueMarketCloseOrder(trade); break; case "OpenLimitOrder": CreateOpenLimitOrder(offer.OfferID, account.AccountID, iAmount, idRate, sBuySell); break; case "CloseLimitOrder": PrepareParamsAndCallLimitCloseOrder(trade); break; case "OpenOpenOrder": CreateMarketOrder(offer.OfferID, account.AccountID, iAmount, idRate, sBuySell); break; case "CloseOpenOrder": // @ here gl PrepareParamsAndCallMarketCloseOrder(trade); break; case "OpenRangeOrder": PrepareParamsAndCallRangeOrder(offer.OfferID, account.AccountID, iAmount, idPointSize, iAtMarket, sBuySell); break; case "CloseRangeOrder": PrepareParamsAndCallRangeCloseOrder(trade, iAtMarket); break; default: break; } }
/// <summary> /// Get and print margin requirements /// </summary> /// <param name="session"></param> /// <param name="account"></param> /// <param name="offer"></param> private static void PrintMargins(O2GSession session, O2GAccountRow account, O2GOfferRow offer) { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettings = loginRules.getTradingSettingsProvider(); double dMmr = 0D; double dEmr = 0D; double lmr = 0D; tradingSettings.getMargins(offer.Instrument, account, ref dMmr, ref dEmr, ref lmr); Console.WriteLine("Margin requirements: mmr={0}, emr={1}, lmr={2}", dMmr, dEmr, lmr); }
/// <summary> /// Print estimates trading commissions /// </summary> private static void printEstimatedTradingCommissions(O2GSession session, O2GOfferRow offer, O2GAccountRow account, int iAmount, string sBuySell) { //wait until commissions related information will be loaded O2GCommissionsProvider commissionProvider = session.getCommissionsProvider(); while (commissionProvider.getStatus() == O2GCommissionStatus.CommissionStatusLoading) { System.Threading.Thread.Sleep(1000); } if (commissionProvider.getStatus() != O2GCommissionStatus.CommissionStatusReady) { throw new Exception("Could not calculate the estimated commissions."); } //calculate commissions Console.WriteLine("Commission for open the position is {0}.", commissionProvider.calcOpenCommission(offer, account, iAmount, sBuySell, 0)); Console.WriteLine("Commission for close the position is {0}.", commissionProvider.calcCloseCommission(offer, account, iAmount, sBuySell, 0)); Console.WriteLine("Total commission for open and close the position is {0}.", commissionProvider.calcTotalCommission(offer, account, iAmount, sBuySell, 0, 0)); }
/// <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); } } }
public void ModelCreateLimitOrder(Session Session, Model CurrentModel, string OrderType, int iAmount, double idRate, double idPointSize, int iAtMarket, string sBuySell, double TakeProfit, double StopLoss) { m_o2gsession = Session.O2GSession; O2GTableManager tableManager = Session.O2GSession.getTableManager(); O2GAccountRow account = GetAccount(tableManager, null); O2GOfferRow offer = GetOffer(tableManager, CurrentModel.Instrument); O2GTradeRow trade = GetTrade(tableManager, account.AccountID, offer.OfferID); switch (OrderType) { case "OpenMarketOrder": CreateTrueMarketLimitOrder(offer.OfferID, account.AccountID, iAmount, sBuySell, TakeProfit, StopLoss); break; default: break; } }
/// <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); }
/// <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); } } }
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); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("GetLastOrderUpdate", loginParams, sampleParams); session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvent() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; O2GRequest request; request = CreateTrueMarketOrderRequest(session, offer.OfferID, account.AccountID, iAmount, sampleParams.BuySell); if (request == null) { throw new Exception("Cannot create request; probably some arguments are missing or incorrect"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } string sOrderID = responseListener.GetOrderID(); if (!string.IsNullOrEmpty(sOrderID)) { Console.WriteLine("You have successfully created a true market order."); Console.WriteLine("Your order ID is {0}", sOrderID); request = GetLastOrderUpdateRequest(session, sOrderID, account.AccountName); if (request == null) { throw new Exception("Cannot create request; probably some arguments are missing or incorrect"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } O2GResponse response = responseListener.GetResponse(); if (response != null && response.Type == O2GResponseType.GetLastOrderUpdate) { O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory(); if (readerFactory != null) { O2GLastOrderUpdateResponseReader reader = readerFactory.createLastOrderUpdateResponseReader(response); Console.WriteLine("Last order update: UpdateType={0}, OrderID={1}, Status={2}, StatusTime={3}", reader.UpdateType.ToString(), reader.Order.OrderID, reader.Order.Status.ToString(), reader.Order.StatusTime.ToString("yyyy-MM-dd HH:mm:ss")); } } Console.WriteLine("Done!"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvent(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; string sInstrument = "EUR/USD"; string sBuySell = Constants.Buy; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("RemoveOrder", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); SessionStatusListener statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { ResponseListener responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sInstrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sInstrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sInstrument, account); int iAmount = iBaseUnitSize * 1; double dRate = offer.Ask - (offer.PointSize * 10); tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateEntryOrderRequest(session, offer.OfferID, account.AccountID, iAmount, dRate, sBuySell, Constants.Orders.LimitEntry); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } string sOrderID = tableListener.GetOrderID(); if (!string.IsNullOrEmpty(sOrderID)) { request = RemoveOrderRequest(session, account.AccountID, sOrderID); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } tableListener.UnsubscribeEvents(tableManager); statusListener.Reset(); session.logout(); statusListener.WaitEvents(); session.unsubscribeResponse(responseListener); } session.unsubscribeSessionStatus(statusListener); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; SessionStatusListener statusListener = null; ResponseListener responseListener = null; try { Console.WriteLine("OpenPositionNetting sample\n"); ArgumentParser argParser = new ArgumentParser(args, "OpenPositionNetting"); argParser.AddArguments(ParserArgument.Login, ParserArgument.Password, ParserArgument.Url, ParserArgument.Connection, ParserArgument.SessionID, ParserArgument.Pin, ParserArgument.Instrument, ParserArgument.BuySell, ParserArgument.Lots, ParserArgument.AccountID); argParser.ParseArguments(); if (!argParser.AreArgumentsValid) { argParser.PrintUsage(); return; } argParser.PrintArguments(); LoginParams loginParams = argParser.LoginParams; SampleParams sampleParams = argParser.SampleParams; session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GTradesTable tradesTable = GetTradesTable(tableManager); if (tradesTable == null) { throw new Exception("Cannot get trades table"); } tableListener.SetTradesTable(tradesTable); O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { System.Threading.Thread.Sleep(1000); // Wait for the balance update Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); if (responseListener != null) { session.unsubscribeResponse(responseListener); } session.unsubscribeSessionStatus(statusListener); } session.Dispose(); } } }
// 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); } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("CreateOrderBySymbol", loginParams, sampleParams); session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; int iCondDistEntryLimit = tradingSettingsProvider.getCondDistEntryLimit(sampleParams.Instrument); int iCondDistEntryStop = tradingSettingsProvider.getCondDistEntryStop(sampleParams.Instrument); string sOrderType = GetEntryOrderType(offer.Bid, offer.Ask, sampleParams.Rate, sampleParams.BuySell, offer.PointSize, iCondDistEntryLimit, iCondDistEntryStop); O2GRequest request = CreateEntryOrderRequest(session, offer.Instrument, sampleParams.AccountID, iAmount, sampleParams.Rate, sampleParams.BuySell, sOrderType); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; int iLots = 10; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("PatrialFill", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } else { if (!account.AccountID.Equals(sampleParams.AccountID)) { sampleParams.AccountID = account.AccountID; Console.WriteLine("AccountID='{0}'", sampleParams.AccountID); } } O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * iLots; tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Thread.Sleep(1000); // Wait for the balance update Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("CreateELS", loginParams, sampleParams); session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvent() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; double dRate; double dRateStop; double dRateLimit; double dBid = offer.Bid; double dAsk = offer.Ask; double dPointSize = offer.PointSize; // For the purpose of this example we will place entry order 8 pips from the current market price // and attach stop and limit orders 10 pips from an entry order price if (sampleParams.OrderType.Equals(Constants.Orders.LimitEntry)) { if (sampleParams.BuySell.Equals(Constants.Buy)) { dRate = dAsk - 8 * dPointSize; dRateLimit = dRate + 10 * dPointSize; dRateStop = dRate - 10 * dPointSize; } else { dRate = dBid + 8 * dPointSize; dRateLimit = dRate - 10 * dPointSize; dRateStop = dRate + 10 * dPointSize; } } else { if (sampleParams.BuySell.Equals(Constants.Buy)) { dRate = dAsk + 8 * dPointSize; dRateLimit = dRate + 10 * dPointSize; dRateStop = dRate - 10 * dPointSize; } else { dRate = dBid - 8 * dPointSize; dRateLimit = dRate - 10 * dPointSize; dRateStop = dRate + 10 * dPointSize; } } O2GRequest request = CreateELSRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, dRate, dRateLimit, dRateStop, sampleParams.BuySell, sampleParams.OrderType); if (request == null) { throw new Exception("Cannot create request; probably some arguments are missing or incorrect"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) session.unsubscribeResponse(responseListener); statusListener.Reset(); session.logout(); statusListener.WaitEvent(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; SessionStatusListener statusListener = null; ResponseListener responseListener = null; string sInstrument = "EUR/USD"; string sBuySell = Constants.Buy; try { Console.WriteLine("CreateOTO sample\n"); ArgumentParser argParser = new ArgumentParser(args, "CloseAllPositions"); argParser.AddArguments(ParserArgument.Login, ParserArgument.Password, ParserArgument.Url, ParserArgument.Connection, ParserArgument.SessionID, ParserArgument.Pin, ParserArgument.AccountID); argParser.ParseArguments(); if (!argParser.AreArgumentsValid) { argParser.PrintUsage(); return; } argParser.PrintArguments(); LoginParams loginParams = argParser.LoginParams; SampleParams sampleParams = argParser.SampleParams; session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sInstrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sInstrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sInstrument, account); int iAmount = iBaseUnitSize * 1; double dRate = offer.Ask - (offer.PointSize * 10); O2GRequest request; request = CreateEntryOrderRequest(session, offer.OfferID, account.AccountID, iAmount, dRate, sBuySell, Constants.Orders.LimitEntry); 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"); } string sOrderID = responseListener.GetOrderID(); if (!string.IsNullOrEmpty(sOrderID)) { request = RemoveOrderRequest(session, account.AccountID, sOrderID); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); if (responseListener != null) { session.unsubscribeResponse(responseListener); } } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
/// <summary> /// Listener: Forex Connect received update for trading tables. /// </summary> /// <param name="data"></param> public void onTablesUpdates(O2GResponse data) { if (data.Type == O2GResponseType.TablesUpdates) { if (mOffer == null) { return; } O2GTablesUpdatesReader reader = mSession.getResponseReaderFactory().createTablesUpdatesReader(data); for (int i = 0; i < reader.Count; i++) { // We are looking only for updates and only for offers // NOTE: in order to support offer subscribtion, the real application also will need // to read add/remove events and change the offer collection correspondingly if (reader.getUpdateType(i) == O2GTableUpdateType.Update && reader.getUpdateTable(i) == O2GTableType.Offers) { // read the offer update O2GOfferRow row = reader.getOfferRow(i); if (!row.isInstrumentValid) { continue; } if (!mInstrument.Equals(row.Instrument)) { continue; } // update latest offer if (row.isTimeValid) { mOffer.LastUpdate = row.Time; } if (row.isBidValid) { mOffer.Bid = row.Bid; } if (row.isAskValid) { mOffer.Ask = row.Ask; } if (row.isVolumeValid) { mOffer.MinuteVolume = row.Volume; } // please note that we send a clone of the offer, // we need it in order to make sure that no ticks // will be lost, if, for example, subscriber doesn't handle the // offer immideatelly if (OnPriceUpdate != null) { OnPriceUpdate(mOffer.Clone()); } } } } }
static private void PrintRollover(O2GRolloverProvider rolloverProvider, O2GAccountRow account, O2GOfferRow offer) { double rolloverBuy; double rolloverSell; rolloverBuy = rolloverProvider.getRolloverBuy(offer, account); rolloverSell = rolloverProvider.getRolloverSell(offer, account); string rolloverInfo = string.Format("Rollover: {0} (buy), {1} (sell)", rolloverBuy, rolloverSell); Console.WriteLine(rolloverInfo); }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("CreateOTO", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; // For the purpose of this example we will place primary order 30 pips below the current market price // and our secondary order 15 pips below the current market price double dRatePrimary = offer.Ask - 30.0 * offer.PointSize; double dRateSecondary = offer.Ask - 15.0 * offer.PointSize; O2GRequest request = CreateOTORequest(session, offer.OfferID, account.AccountID, iAmount, dRatePrimary, dRateSecondary); if (request == null) { throw new Exception("Cannot create request"); } tableListener.SubscribeEvents(tableManager); List <string> requestIDList = new List <string>(); for (int i = 0; i < request.ChildrenCount; i++) { requestIDList.Add(request.getChildRequest(i).RequestID); } responseListener.SetRequestIDs(requestIDList); tableListener.SetRequestIDs(requestIDList); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("PrintRollover", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); SessionStatusListener statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); O2GRolloverProvider rolloverProvider = session.getRolloverProvider(); AutoResetEvent autoEvent = new AutoResetEvent(false); RolloverProviderListener rolloverProviderListener = new RolloverProviderListener(autoEvent); rolloverProvider.subscribe(rolloverProviderListener); if (statusListener.WaitEvents() && statusListener.Connected) { O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } if (autoEvent.WaitOne(10000)) //wait 10s { PrintRollover(rolloverProvider, account, offer); } else { Console.WriteLine("Waiting time expired: Rollover is not available"); } rolloverProvider.unsubscribe(rolloverProviderListener); statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { session.Dispose(); } } }
static void Main(string[] args) { O2GSession session = null; try { LoginParams loginParams = new LoginParams(ConfigurationManager.AppSettings); SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings); PrintSampleParams("ClosePosition", loginParams, sampleParams); session = O2GTransport.createSession(); session.useTableManager(O2GTableManagerMode.Yes, null); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); statusListener.Reset(); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(); TableListener tableListener = new TableListener(responseListener); session.subscribeResponse(responseListener); O2GTableManager tableManager = session.getTableManager(); O2GTableManagerStatus managerStatus = tableManager.getStatus(); while (managerStatus == O2GTableManagerStatus.TablesLoading) { Thread.Sleep(50); managerStatus = tableManager.getStatus(); } if (managerStatus == O2GTableManagerStatus.TablesLoadFailed) { throw new Exception("Cannot refresh all tables of table manager"); } O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(tableManager, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GTradeRow trade = GetTrade(tableManager, sampleParams.AccountID, offer.OfferID); if (trade == null) { throw new Exception(string.Format("There are no opened positions for instrument '{0}'", sampleParams.Instrument)); } tableListener.SubscribeEvents(tableManager); O2GRequest request = CreateCloseMarketOrderRequest(session, sampleParams.Instrument, trade); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); tableListener.SetRequestID(request.RequestID); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } tableListener.UnsubscribeEvents(tableManager); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { if (responseListener != null) { session.unsubscribeResponse(responseListener); } statusListener.Reset(); session.logout(); statusListener.WaitEvents(); } session.unsubscribeSessionStatus(statusListener); session.Dispose(); } } }
public void Run() { try { string sLogin; string sPassword; string sSessionID; string sPin; if (mIsFirstAccount) { sLogin = mLoginParams.Login; sPassword = mLoginParams.Password; sSessionID = mLoginParams.SessionID; sPin = mLoginParams.Pin; } else { sLogin = mLoginParams.Login2; sPassword = mLoginParams.Password2; sSessionID = mLoginParams.SessionID2; sPin = mLoginParams.Pin2; } statusListener = new SessionStatusListener(mSession, sSessionID, sPin); mSession.subscribeSessionStatus(statusListener); statusListener.Reset(); mSession.login(sLogin, sPassword, mLoginParams.URL, mLoginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { if (!mIsFirstAccount) // Disable receiving price updates for the second account { mSession.setPriceUpdateMode(O2GPriceUpdateMode.NoPrice); } responseListener = new ResponseListener(mSession); mSession.subscribeResponse(responseListener); O2GAccountRow account = null; if (mIsFirstAccount) { bool bIsAccountEmpty = String.IsNullOrEmpty(mSampleParams.AccountID); account = GetAccount(mSession, mSampleParams.AccountID); if (account != null) { if (bIsAccountEmpty) { mSampleParams.AccountID = account.AccountID; Console.WriteLine("Account: " + mSampleParams.AccountID); } } else { throw new Exception(string.Format("The account '{0}' is not valid", mSampleParams.AccountID)); } } else { bool bIsAccountEmpty = String.IsNullOrEmpty(mSampleParams.AccountID2); account = GetAccount(mSession, mSampleParams.AccountID2); if (account != null) { if (bIsAccountEmpty) { mSampleParams.AccountID2 = account.AccountID; Console.WriteLine("Account2: " + mSampleParams.AccountID2); } } else { throw new Exception(string.Format("The account2 '{0}' is not valid", mSampleParams.AccountID2)); } } O2GOfferRow offer = GetOffer(mSession, mSampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", mSampleParams.Instrument)); } O2GLoginRules loginRules = mSession.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(mSampleParams.Instrument, account); int iAmount = iBaseUnitSize * mSampleParams.Lots; O2GRequest request; request = CreateTrueMarketOrderRequest(mSession, offer.OfferID, account.AccountID, iAmount, mSampleParams.BuySell); if (request == null) { throw new Exception("Cannot create request"); } responseListener.SetRequestID(request.RequestID); mSession.sendRequest(request); if (!responseListener.WaitEvents()) { throw new Exception("Response waiting timeout expired"); } Console.WriteLine("Done!"); } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (statusListener.Connected) { statusListener.Reset(); mSession.logout(); statusListener.WaitEvents(); mSession.unsubscribeResponse(responseListener); } mSession.subscribeSessionStatus(statusListener); mSession.Dispose(); } }
static void Main(string[] args) { O2GSession session = null; SessionStatusListener statusListener = null; ResponseListener responseListener = null; try { Console.WriteLine("CreateOCO sample\n"); ArgumentParser argParser = new ArgumentParser(args, "CreateOCO"); argParser.AddArguments(ParserArgument.Login, ParserArgument.Password, ParserArgument.Url, ParserArgument.Connection, ParserArgument.SessionID, ParserArgument.Pin, ParserArgument.Instrument, ParserArgument.Lots, ParserArgument.AccountID); argParser.ParseArguments(); if (!argParser.AreArgumentsValid) { argParser.PrintUsage(); return; } argParser.PrintArguments(); LoginParams loginParams = argParser.LoginParams; SampleParams sampleParams = argParser.SampleParams; session = O2GTransport.createSession(); statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin); session.subscribeSessionStatus(statusListener); session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection); if (statusListener.WaitEvents() && statusListener.Connected) { responseListener = new ResponseListener(session); session.subscribeResponse(responseListener); O2GAccountRow account = GetAccount(session, sampleParams.AccountID); if (account == null) { if (string.IsNullOrEmpty(sampleParams.AccountID)) { throw new Exception("No valid accounts"); } else { throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID)); } } sampleParams.AccountID = account.AccountID; O2GOfferRow offer = GetOffer(session, sampleParams.Instrument); if (offer == null) { throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument)); } O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider(); int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account); int iAmount = iBaseUnitSize * sampleParams.Lots; // For the purpose of this example we will place entry orders 30 pips from the current market price double dRateUp = offer.Ask + 30.0 * offer.PointSize; double dRateDown = offer.Bid - 30.0 * offer.PointSize; O2GRequest request = CreateOCORequest(session, offer.OfferID, account.AccountID, iAmount, dRateUp, dRateDown); if (request == null) { throw new Exception("Cannot create request"); } List <string> requestIDList = new List <string>(); for (int i = 0; i < request.ChildrenCount; i++) { requestIDList.Add(request.getChildRequest(i).RequestID); } responseListener.SetRequestIDs(requestIDList); session.sendRequest(request); if (responseListener.WaitEvents()) { Console.WriteLine("Done!"); } else { throw new Exception("Response waiting timeout expired"); } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { if (session != null) { if (statusListener.Connected) { statusListener.Reset(); session.logout(); statusListener.WaitEvents(); if (responseListener != null) { session.unsubscribeResponse(responseListener); } session.unsubscribeSessionStatus(statusListener); } session.Dispose(); } } }