Example #1
0
        /// <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);
            System.Net.WebClient webClient = new System.Net.WebClient();
            for (int i = 0; i < accountsReader.Count; i++)
            {
                O2GAccountRow account = accountsReader.getRow(i);
                string url = session.getReportURL(account, DateTime.Now.AddMonths(-1), DateTime.Now, "html", null, null, 0);

                Console.WriteLine("AccountID={0}; Balance={1}; UsedMargin={2}; Report URL={3}",
                        account.AccountID, account.Balance, account.UsedMargin, url);

                string content = webClient.DownloadString(url);
                string filename = account.AccountID + ".html";
                System.IO.File.WriteAllText(filename, content);
                Console.WriteLine("Report is saved to {0}", filename);
            }
        }
Example #2
0
 /// <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}, Used margin: {2}", accountRow.AccountID, accountRow.Balance, accountRow.UsedMargin);
     }
 }
Example #3
0
 /// <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"))  // 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;
     }
 }
Example #4
0
        /// <summary>
        /// Create close market order request
        /// </summary>
        private static O2GRequest CreateCloseMarketOrderRequest(O2GSession session, string sInstrument, O2GTradeRow tradeRow)
        {
            O2GRequest        request        = null;
            O2GRequestFactory requestFactory = session.getRequestFactory();

            if (requestFactory == null)
            {
                throw new Exception("Cannot create request factory");
            }

            O2GLoginRules        loginRules        = session.getLoginRules();
            O2GPermissionChecker permissionChecker = loginRules.getPermissionChecker();

            O2GValueMap valuemap = requestFactory.createValueMap();

            valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder);

            if (permissionChecker.canCreateMarketCloseOrder(sInstrument) != O2GPermissionStatus.PermissionEnabled)
            {
                valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketOpen); // in USA you need to use "OM" to close a position.
            }
            else
            {
                valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose);
                valuemap.setString(O2GRequestParamsEnum.TradeID, tradeRow.TradeID);
            }

            valuemap.setString(O2GRequestParamsEnum.AccountID, tradeRow.AccountID);
            valuemap.setString(O2GRequestParamsEnum.OfferID, tradeRow.OfferID);
            valuemap.setString(O2GRequestParamsEnum.BuySell, tradeRow.BuySell.Equals(Constants.Buy) ? Constants.Sell : Constants.Buy);
            valuemap.setInt(O2GRequestParamsEnum.Amount, tradeRow.Amount);
            valuemap.setString(O2GRequestParamsEnum.CustomID, "CloseMarketOrder");
            request = requestFactory.createOrderRequest(valuemap);
            if (request == null)
            {
                Console.WriteLine(requestFactory.getLastError());
            }
            return(request);
        }
        /// <summary>
        /// Find 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 (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);
            }
        }
Example #6
0
 /// <summary>
 /// Show permissions for the particular instrument
 /// </summary>
 public static void CheckPermissions(O2GSession session, string sInstrument)
 {
     O2GLoginRules loginRules = session.getLoginRules();
     O2GPermissionChecker permissionChecker = loginRules.getPermissionChecker();
     Console.WriteLine("canCreateMarketOpenOrder = {0}", permissionChecker.canCreateMarketOpenOrder(sInstrument));
     Console.WriteLine("canChangeMarketOpenOrder = {0}", permissionChecker.canChangeMarketOpenOrder(sInstrument));
     Console.WriteLine("canDeleteMarketOpenOrder = {0}", permissionChecker.canDeleteMarketOpenOrder(sInstrument));
     Console.WriteLine("canCreateMarketCloseOrder = {0}", permissionChecker.canCreateMarketCloseOrder(sInstrument));
     Console.WriteLine("canChangeMarketCloseOrder = {0}", permissionChecker.canChangeMarketCloseOrder(sInstrument));
     Console.WriteLine("canDeleteMarketCloseOrder = {0}", permissionChecker.canDeleteMarketCloseOrder(sInstrument));
     Console.WriteLine("canCreateEntryOrder = {0}", permissionChecker.canCreateEntryOrder(sInstrument));
     Console.WriteLine("canChangeEntryOrder = {0}", permissionChecker.canChangeEntryOrder(sInstrument));
     Console.WriteLine("canDeleteEntryOrder = {0}", permissionChecker.canDeleteEntryOrder(sInstrument));
     Console.WriteLine("canCreateStopLimitOrder = {0}", permissionChecker.canCreateStopLimitOrder(sInstrument));
     Console.WriteLine("canChangeStopLimitOrder = {0}", permissionChecker.canChangeStopLimitOrder(sInstrument));
     Console.WriteLine("canDeleteStopLimitOrder = {0}", permissionChecker.canDeleteStopLimitOrder(sInstrument));
     Console.WriteLine("canRequestQuote = {0}", permissionChecker.canRequestQuote(sInstrument));
     Console.WriteLine("canAcceptQuote = {0}", permissionChecker.canAcceptQuote(sInstrument));
     Console.WriteLine("canDeleteQuote = {0}", permissionChecker.canDeleteQuote(sInstrument));
     Console.WriteLine("canJoinToNewContingencyGroup = {0}", permissionChecker.canJoinToNewContingencyGroup(sInstrument));
     Console.WriteLine("canJoinToExistingContingencyGroup = {0}", permissionChecker.canJoinToExistingContingencyGroup(sInstrument));
     Console.WriteLine("canRemoveFromContingencyGroup = {0}", permissionChecker.canRemoveFromContingencyGroup(sInstrument));
     Console.WriteLine("canChangeOfferSubscription = {0}", permissionChecker.canChangeOfferSubscription(sInstrument));
     Console.WriteLine("canCreateNetCloseOrder = {0}", permissionChecker.canCreateNetCloseOrder(sInstrument));
     Console.WriteLine("canChangeNetCloseOrder = {0}", permissionChecker.canChangeNetCloseOrder(sInstrument));
     Console.WriteLine("canDeleteNetCloseOrder = {0}", permissionChecker.canDeleteNetCloseOrder(sInstrument));
     Console.WriteLine("canCreateNetStopLimitOrder = {0}", permissionChecker.canCreateNetStopLimitOrder(sInstrument));
     Console.WriteLine("canChangeNetStopLimitOrder = {0}", permissionChecker.canChangeNetStopLimitOrder(sInstrument));
     Console.WriteLine("canDeleteNetStopLimitOrder = {0}", permissionChecker.canDeleteNetStopLimitOrder(sInstrument));
     Console.WriteLine("canUseDynamicTrailingForStop = {0}", permissionChecker.canUseDynamicTrailingForStop());
     Console.WriteLine("canUseDynamicTrailingForLimit = {0}", permissionChecker.canUseDynamicTrailingForLimit());
     Console.WriteLine("canUseDynamicTrailingForEntryStop = {0}", permissionChecker.canUseDynamicTrailingForEntryStop());
     Console.WriteLine("canUseDynamicTrailingForEntryLimit = {0}", permissionChecker.canUseDynamicTrailingForEntryLimit());
     Console.WriteLine("canUseFluctuateTrailingForStop = {0}", permissionChecker.canUseFluctuateTrailingForStop());
     Console.WriteLine("canUseFluctuateTrailingForLimit = {0}", permissionChecker.canUseFluctuateTrailingForLimit());
     Console.WriteLine("canUseFluctuateTrailingForEntryStop = {0}", permissionChecker.canUseFluctuateTrailingForEntryStop());
     Console.WriteLine("canUseFluctuateTrailingForEntryLimit = {0}", permissionChecker.canUseFluctuateTrailingForEntryLimit());
 }
Example #7
0
        /// <summary>
        /// Create close market order request
        /// </summary>
        private static O2GRequest CreateCloseMarketOrderRequest(O2GSession session, string sInstrument, O2GTradeRow tradeRow)
        {
            O2GRequest request = null;
            O2GRequestFactory requestFactory = session.getRequestFactory();
            if (requestFactory == null)
            {
                throw new Exception("Cannot create request factory");
            }

            O2GLoginRules loginRules = session.getLoginRules();
            O2GPermissionChecker permissionChecker = loginRules.getPermissionChecker();

            O2GValueMap valuemap = requestFactory.createValueMap();
            valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder);

            if (permissionChecker.canCreateMarketCloseOrder(sInstrument) != O2GPermissionStatus.PermissionEnabled)
            {
                valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketOpen); // in USA you need to use "OM" to close a position.
            }
            else
            {
                valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketClose);
                valuemap.setString(O2GRequestParamsEnum.TradeID, tradeRow.TradeID);
            }

            valuemap.setString(O2GRequestParamsEnum.AccountID, tradeRow.AccountID);
            valuemap.setString(O2GRequestParamsEnum.OfferID, tradeRow.OfferID);
            valuemap.setString(O2GRequestParamsEnum.BuySell, tradeRow.BuySell.Equals(Constants.Buy) ? Constants.Sell : Constants.Buy);
            valuemap.setInt(O2GRequestParamsEnum.Amount, tradeRow.Amount);
            valuemap.setString(O2GRequestParamsEnum.CustomID, "CloseMarketOrder");
            request = requestFactory.createOrderRequest(valuemap);
            if (request == null)
            {
                Console.WriteLine(requestFactory.getLastError());
            }
            return request;
        }
Example #8
0
        // Get current prices and calculate order price
        public void GetOfferRate(O2GSession session, string sInstrument, string mBuySell, string mOrderType, int entryPips,int stopPips)
        {
            double dBid = 0.0;
            double dAsk = 0.0;
            double dPointSize = 0.0;
            try
            {
                O2GLoginRules loginRules = session.getLoginRules();
                if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Offers))
                {
                    O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers);
                    O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory();
                    O2GOffersTableResponseReader offersReader = responseFactory.createOffersTableReader(offersResponse);
                    for (int i = 0; i < offersReader.Count; i++)
                    {
                        O2GOfferRow offer = offersReader.getRow(i);
                        if (sInstrument == offer.Instrument)
                        {
                            mOfferID = offer.OfferID;
                            dBid = offer.Bid;
                            dAsk = offer.Ask;
                            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 (mOrderType == Constants.Orders.LimitEntry)
                            {
                                if (mBuySell == Constants.Buy)
                                {
                                    mRate = dAsk - entryPips * dPointSize;
                                   // mRateLimit = mRate + 10 * dPointSize;
                                    mRateStop = mRate - stopPips * dPointSize;
                                    pegStopOffset = stopPips;
                                }
                                else
                                {
                                    mRate = dBid + entryPips * dPointSize;
                                   // mRateLimit = mRate - 10 * dPointSize;
                                    mRateStop = mRate + stopPips * dPointSize;
                                    pegStopOffset = -stopPips;
                                }
                            }
                            else // use StopEntry!
                            {
                                if (mBuySell == Constants.Buy)
                                {
                                    mRate = dAsk + entryPips * dPointSize;
                                    //mRateLimit = mRate + 10 * dPointSize;
                                    mRateStop = mRate - stopPips * dPointSize;
                                    pegStopOffset = -stopPips;
                                }
                                else // Sell
                                {
                                    mRate = dBid - entryPips * dPointSize;
                                    //mRateLimit = mRate - 10 * dPointSize;
                                    mRateStop = mRate + stopPips * dPointSize;
                                    pegStopOffset = stopPips;
                                }
                            }
                            mHasOffer = true;
                            break;
                        }
                    }
                    if (!mHasOffer)
                        log.debug("You specified invalid instrument. No action will be taken.");
                }
            }
            catch (Exception e)
            {
                log.debug("Exception in GetOfferRate().\n\t " + e.Message);
            }
        }
Example #9
0
 // Get account for trade
 public void GetAccount(O2GSession session)
 {
     try
     {
         O2GLoginRules loginRules = session.getLoginRules();
         if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Accounts))
         {
             string sAccountID = string.Empty;
             string sAccountKind = string.Empty;
             O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts);
             O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory();
             O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse);
             for (int i = 0; i < accountsReader.Count; i++)
             {
                 O2GAccountRow account = accountsReader.getRow(i);
                 sAccountID = account.AccountID;
                 sAccountKind = account.AccountKind;
                 if (sAccountKind == "32" || sAccountKind == "36")
                 {
                     mAccountID = sAccountID;
                     mHasAccount = true;
                     break;
                 }
             }
             if (!mHasAccount)
                 log.debug("You don't have any accounts available for trading. No action will be taken.");
         }
     }
     catch (Exception e)
     {
         log.debug("Exception in GetAccounts():\n\t " + e.Message);
     }
 }
        // 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);
            }
        }
Example #11
0
        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();
                }
            }
        }
Example #12
0
 private void GetAccount(O2GSession session)
 {
     try
     {
         O2GLoginRules loginRules = session.getLoginRules();
         if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Accounts))
         {
             string sAccountID = string.Empty;
             string sAccountKind = string.Empty;
             O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts);
             O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory();
             O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse);
             for (int i = 0; i < accountsReader.Count; i++)
             {
                 O2GAccountRow account = accountsReader.getRow(i);
                 sAccountID = account.AccountID;
                 sAccountKind = account.AccountKind;
                 if (sAccountKind == "32" || sAccountKind == "36")
                 {
                     accountID = sAccountID;
                     break;
                 }
             }
         }
     }
     catch (Exception e)
     {
         log.debug("Exception in GetAccounts():\n\t " + e.Message);
     }
 }
Example #13
0
        static void Main(string[] args)
        {
            O2GSession session    = null;
            string     sOrderType = Constants.Orders.LimitEntry;

            try
            {
                LoginParams  loginParams  = new LoginParams(ConfigurationManager.AppSettings);
                SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings);

                PrintSampleParams("FindRowByColumnValue", 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));
                        }
                    }
                    else
                    {
                        if (!sampleParams.AccountID.Equals(account.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 * 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 (sOrderType.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;
                        }
                    }

                    tableListener.SubscribeEvents(tableManager);

                    O2GRequest request = CreateELSRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, dRate, dRateLimit, dRateStop, sampleParams.BuySell, sOrderType);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }

                    string sRequestID = request.RequestID;

                    responseListener.SetRequestID(sRequestID);
                    tableListener.SetRequestID(sRequestID);
                    session.sendRequest(request);
                    if (!responseListener.WaitEvents())
                    {
                        throw new Exception("Response waiting timeout expired");
                    }

                    Console.WriteLine("Search by RequestID:{0}", sRequestID);
                    FindOrders(tableManager, sRequestID);
                    Console.WriteLine("Search by Type:{0} and BuySell:{1}", sOrderType, sampleParams.BuySell);
                    FindOrdersByTypeAndDirection(tableManager, sOrderType, sampleParams.BuySell);
                    Console.WriteLine("Search conditional orders");
                    FindConditionalOrders(tableManager);

                    Console.WriteLine("Done!");

                    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;

            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();
                }
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;

            try
            {
                Console.WriteLine("CreateELS sample\n");

                ArgumentParser argParser = new ArgumentParser(args, "CreateELS");

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin,
                                       ParserArgument.Instrument,
                                       ParserArgument.AccountID,
                                       ParserArgument.BuySell,
                                       ParserArgument.OrderType,
                                       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));
                    }

                    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;
                        }
                    }

                    tableListener.SubscribeEvents(tableManager);

                    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");
                    }

                    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)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                        session.unsubscribeSessionStatus(statusListener);
                    }
                    session.Dispose();
                }
            }
        }
Example #16
0
        static void Main(string[] args)
        {
            O2GSession session = null;

            try
            {
                LoginParams  loginParams  = new LoginParams(ConfigurationManager.AppSettings);
                SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings);

                PrintSampleParams("CreateAndFindEntry", loginParams, sampleParams);

                session = O2GTransport.createSession();
                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(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         = CalculateRate(sampleParams.OrderType, sampleParams.BuySell, offer.Ask, offer.Bid, offer.PointSize);
                    O2GRequest request       = CreateEntryOrderRequest(session, offer.OfferID, account.AccountID, iAmount, dRate, 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())
                    {
                        string sOrderID = responseListener.GetOrderID();
                        if (!string.IsNullOrEmpty(sOrderID))
                        {
                            Console.WriteLine("You have successfully created an entry order for instrument {0}", sampleParams.Instrument);
                            Console.WriteLine("Your order ID is {0}", sOrderID);
                            FindOrder(session, sOrderID, sampleParams.AccountID, responseListener);
                            Console.WriteLine("Done!");
                        }
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                    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();
                }
            }
        }
Example #17
0
 // 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);
     }
 }
Example #18
0
        static void Main(string[] args)
        {
            O2GSession session = null;

            try
            {
                LoginParams  loginParams  = new LoginParams(ConfigurationManager.AppSettings);
                SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings);

                PrintSampleParams("CreateIf-thenELS", loginParams, sampleParams);

                session = O2GTransport.createSession();
                SessionStatusListener 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 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 otoRate    = offer.Bid + 2.0 * offer.PointSize;
                    double dRateELS   = offer.Bid - 30.0 * offer.PointSize;
                    double dRateStop  = offer.Bid - 50.0 * offer.PointSize;
                    double dRateLimit = offer.Bid + 50.0 * offer.PointSize;

                    Console.WriteLine("Bid={0}, Ask={1}, OTO={2}, ELS={3}, Stop={4}, Limit={5}", offer.Bid, offer.Ask, otoRate, dRateELS, dRateStop, dRateLimit);

                    O2GRequest request = CreateOTO_ELSRequest(session, offer.OfferID, account.AccountID, iAmount, otoRate, dRateELS, dRateStop, dRateLimit);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }

                    List <string> requestIDList = new List <string>();
                    FillRequestIDs(requestIDList, request);

                    responseListener.SetRequestIDs(requestIDList);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }

                    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();
                }
            }
        }
Example #19
0
 // Get system properties
 private void getSystemProperties(O2GSession session)
 {
     O2GLoginRules loginRules = session.getLoginRules();
     O2GResponse response = loginRules.getSystemPropertiesResponse();
     O2GResponseReaderFactory factory = session.getResponseReaderFactory();
     if (factory == null)
         return;
     O2GSystemPropertiesReader systemResponseReader = factory.createSystemPropertiesReader(response);
     if (systemResponseReader == null)
         return;
     SystemProperties = systemResponseReader.Properties;
 }
Example #20
0
        static void Main(string[] args)
        {
            O2GSession session = null;

            try
            {
                LoginParams  loginParams  = new LoginParams(ConfigurationManager.AppSettings);
                SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings);

                PrintSampleParams("OpenPositionNetting", loginParams, sampleParams);

                session = O2GTransport.createSession();
                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(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));
                    }

                    O2GTradesTableResponseReader tradesTable = GetTradesTable(session, sampleParams.AccountID, responseListener);
                    if (tradesTable == null)
                    {
                        throw new Exception("Cannot get trades table");
                    }
                    responseListener.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;

                    O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.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");
                    }

                    session.unsubscribeResponse(responseListener);
                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvents();
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
        void IO2GSessionStatus.onSessionStatusChanged(O2GSessionStatusCode status)
        {
            bool   connected;
            string name;

            switch (status)
            {
            case O2GSessionStatusCode.Connected:
                connected      = true;
                mTimeConverter = mSession.getTimeConverter();
                O2GLoginRules rules = mSession.getLoginRules();
                if (rules.isTableLoadedByDefault(O2GTableType.Offers))
                {
                    O2GResponse offers = rules.getTableRefreshResponse(O2GTableType.Offers);
                    ReadOffers(offers);
                    mReady = true;
                }
                else
                {
                    O2GRequestFactory reqFactory = mSession.getRequestFactory();
                    O2GRequest        request    = reqFactory.createRefreshTableRequest(O2GTableType.Offers);
                    mSession.sendRequest(request);
                    mReady = false;
                }
                name = "connected";
                break;

            case O2GSessionStatusCode.Connecting:
                connected = false;
                name      = "connecting";
                break;

            case O2GSessionStatusCode.Disconnected:
                connected = false;
                name      = "disconnected";
                break;

            case O2GSessionStatusCode.Disconnecting:
                connected = false;
                name      = "disconnecting";
                break;

            case O2GSessionStatusCode.PriceSessionReconnecting:
                connected = false;
                name      = "price channel reconnecting";
                break;

            case O2GSessionStatusCode.SessionLost:
                connected = false;
                name      = "session has been lost";
                break;

            default:
                connected = false;
                name      = "unknown";
                break;
            }

            if (!connected)
            {
                mReady         = false;
                mTimeConverter = null;
            }

            if (OnSessionStatusChanged != null)
            {
                SessionStatusEventArgs args = new SessionStatusEventArgs(connected, name);
                OnSessionStatusChanged(this, args);
            }
        }
Example #22
0
 /// <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;
     }
 }
        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();
                }
            }
        }
Example #24
0
        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();
                }
            }
        }
        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();
                }
            }
        }
Example #26
0
        static void Main(string[] args)
        {
            O2GSession session = null;

            try
            {
                LoginParams  loginParams  = new LoginParams(ConfigurationManager.AppSettings);
                SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings);

                PrintSampleParams("CalculateTradingCommissions", loginParams, sampleParams);

                session = O2GTransport.createSession();
                session.useTableManager(O2GTableManagerMode.Yes, null);
                statusListener = new SessionStatusListener(session);
                session.subscribeSessionStatus(statusListener);
                statusListener.Reset();
                session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
                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");
                    }
                    O2GAccountTableRow account = GetAccount(tableManager, sampleParams.AccountID);
                    if (account == null)
                    {
                        throw new Exception(string.IsNullOrEmpty(sampleParams.AccountID) ? "No valid accounts" : string.Format("The account '{0}' is not valid", sampleParams.AccountID));
                    }

                    O2GOfferTableRow 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;

                    printEstimatedTradingCommissions(session, offer, account, iAmount, sampleParams.BuySell);
                    Console.WriteLine("Done!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
Example #27
0
        /// <summary>
        /// Listener: When Trading session status is changed
        /// </summary>
        /// <param name="status"></param>
        public void onSessionStatusChanged(O2GSessionStatusCode status)
        {
            switch (status)
            {
            case    O2GSessionStatusCode.TradingSessionRequested:
                // If the trading session requires the session name or pin code...
                if (OnErrorEvent != null)
                {
                    OnErrorEvent("Multi-session connectors aren't supported by this example\n");
                }
                mTradingSession.logout();
                break;

            case    O2GSessionStatusCode.Connected:
                // login is completed

                // now we need collect data about the system properties
                O2GLoginRules loginRules = mTradingSession.getLoginRules();
                mTZConverter = mTradingSession.getTimeConverter();
                // get the trading day offset.
                O2GResponse response;
                response = loginRules.getSystemPropertiesResponse();
                O2GSystemPropertiesReader reader = mTradingSession.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;
                }

                // ...and now get the list of the offers to which the user is subscribed
                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      = mTradingSession.getRequestFactory();
                    O2GRequest        offerRequest = factory.createRefreshTableRequest(O2GTableType.Offers);
                    mTradingSession.sendRequest(offerRequest);
                }
                break;

            default:
                if (OnStateChange != null)
                {
                    OnStateChange(false);
                }
                break;
            }
        }
Example #28
0
        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();
                }
            }
        }
Example #29
0
        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();
                }
            }
        }
Example #30
0
        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;

            try
            {
                LoginParams  loginParams  = new LoginParams(ConfigurationManager.AppSettings);
                SampleParams sampleParams = new SampleParams(ConfigurationManager.AppSettings);

                PrintSampleParams("GetOffers", loginParams, sampleParams);

                session = O2GTransport.createSession();
                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(session);
                    responseListener.SetInstrument(sampleParams.Instrument);
                    session.subscribeResponse(responseListener);

                    O2GLoginRules loginRules = session.getLoginRules();
                    if (loginRules == null)
                    {
                        throw new Exception("Cannot get login rules");
                    }

                    O2GResponse response;
                    if (loginRules.isTableLoadedByDefault(O2GTableType.Offers))
                    {
                        response = loginRules.getTableRefreshResponse(O2GTableType.Offers);
                        if (response != null)
                        {
                            responseListener.PrintOffers(session, response, null);
                        }
                    }
                    else
                    {
                        O2GRequestFactory requestFactory = session.getRequestFactory();
                        if (requestFactory != null)
                        {
                            O2GRequest offersRequest = requestFactory.createRefreshTableRequest(O2GTableType.Offers);
                            responseListener.SetRequestID(offersRequest.RequestID);
                            session.sendRequest(offersRequest);
                            if (!responseListener.WaitEvents())
                            {
                                throw new Exception("Response waiting timeout expired");
                            }
                            response = responseListener.GetResponse();
                            if (response != null)
                            {
                                responseListener.PrintOffers(session, response, null);
                            }
                        }
                    }

                    // Do nothing 10 seconds, let offers print
                    Thread.Sleep(100000);
                    Console.WriteLine("Done!");

                    session.unsubscribeResponse(responseListener);
                    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;
            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();
                }
            }
        }
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;
            int iLots = 10;

            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.Instrument,
                                       ParserArgument.BuySell,
                                       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));
                        }
                    }
                    else
                    {
                        if (!account.AccountID.Equals(sampleParams.AccountID))
                        {
                            sampleParams.AccountID = account.AccountID;
                            Console.WriteLine("AccountID='{0}'",
                                              sampleParams.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 * iLots;

                    O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.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");
                    }
                }
            }
            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();
                }
            }
        }
Example #34
0
        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();
            }
        }
Example #35
0
        // Get current prices and calculate order price
        private void GetOfferRate(O2GSession session, string sInstrument, string mBuySell, string mOrderType,
            int stopPips, int limitPips)
        {
            double dBid = 0.0;
            double dAsk = 0.0;
            double dPointSize = 0.0;
            try
            {
                O2GLoginRules loginRules = session.getLoginRules();
                O2GTradingSettingsProvider tsp = loginRules.getTradingSettingsProvider();
                condDistEntryLimit = tsp.getCondDistEntryLimit(sInstrument);
                condDistLimitTrade = tsp.getCondDistLimitForTrade(sInstrument);

                if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Offers))
                {
                    O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers);
                    O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory();
                    O2GOffersTableResponseReader offersReader = responseFactory.createOffersTableReader(offersResponse);
                    for (int i = 0; i < offersReader.Count; i++)
                    {
                        O2GOfferRow offer = offersReader.getRow(i);
                        if (sInstrument == offer.Instrument)
                        {
                            if (offer.InstrumentType != 1)
                            {  // validity check, TODO-what else?
                                log.debug("Instrument type = " + offer.InstrumentType + " for " + sInstrument);
                                //return;
                            }
                            // TODO--sometimes pointsize is zero, but since not doing limits, it doesn't matter
                            //      returning at this point is causing other failures!!!
                            //
                            if (offer.PointSize == 0.0)
                            {  // validity check, TODO-what else?
                                log.debug("PointSize = " + offer.PointSize + " for " + sInstrument);
                                //return;
                            }

                            mOfferID = offer.OfferID;
                            dBid = offer.Bid;
                            dAsk = offer.Ask;
                            dPointSize = offer.PointSize;
                            mBid = dBid;
                            mAsk = dAsk;
                            mPointSize = dPointSize;

                            // limit -- The offset must be negative for a sell position and positive for a buy position.
                            if (mBuySell == Constants.Buy)
                            {
                                //mRateLimit = dBid + limitPips * dPointSize;
                                pegStopOffset = -stopPips;
                                pegLimitOffset = limitPips;
                            }
                            else if (mBuySell == Constants.Sell)
                            {
                                //mRateLimit = dAsk - limitPips * dPointSize;
                                pegStopOffset = stopPips;
                                pegLimitOffset = -limitPips;
                            }
                            mHasOffer = true;
                            break;
                        }
                    }
                }
                if (!mHasOffer)
                    log.debug("You specified invalid instrument. No action will be taken.");
            }
            catch (Exception e)
            {
                log.debug("Exception in GetOfferRate().\n\t " + e.Message);
            }
        }