Ejemplo n.º 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);
            }
        }
Ejemplo n.º 2
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);
                Uri           url     = new Uri(session.getReportURL(account.AccountID, DateTime.Now.AddMonths(-1), DateTime.Now, "html", null));

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

                string content = webClient.DownloadString(url);

                string prefix = url.Scheme + Uri.SchemeDelimiter + url.Host;
                string report = O2GHtmlContentUtils.ReplaceRelativePathWithAbsolute(content, prefix);

                string filename = account.AccountID + ".html";
                System.IO.File.WriteAllText(filename, report);
                Console.WriteLine("Report is saved to {0}", filename);
            }
        }
Ejemplo n.º 3
0
        /* Prepare Params for Orders */
        public void PrepareParamsFromLoginRules(O2GLoginRules loginRules)
        {
            O2GResponseReaderFactory factory = m_o2gsession.getResponseReaderFactory();

            if (factory == null)
            {
                return;
            }
            // Gets first account from login.
            O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts);
            O2GAccountsTableResponseReader accountsReader = factory.createAccountsTableReader(accountsResponse);
            O2GAccountRow account = accountsReader.getRow(0);

            // Store account id
            m_accountid = account.AccountID;
            // Store base iAmount
            m_baseamount = account.BaseUnitSize;
            // Get offers for eur/usd
            O2GResponse offerResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers);
            O2GOffersTableResponseReader offersReader = factory.createOffersTableReader(offerResponse);

            for (int i = 0; i < offersReader.Count; i++)
            {
                O2GOfferRow offer = offersReader.getRow(i);
                if (string.Compare(offer.Instrument, m_instrument /*"EUR/USD"*/, true) == 0)
                {
                    m_offerid   = offer.OfferID;
                    m_ask       = offer.Ask;
                    m_bid       = offer.Bid;
                    m_pointsize = offer.PointSize;
                    break;
                }
            }
        }
Ejemplo n.º 4
0
        public OrderObject prepareParamsFromLoginRules(string instrument)
        {
            OrderObject              orderObject = new OrderObject();
            O2GLoginRules            loginRules  = _session.Session.getLoginRules();
            O2GResponseReaderFactory factory     = _session.Session.getResponseReaderFactory();
            // Gets first account from login.
            O2GResponse accountsResponse = loginRules.getTableRefeshResponse(O2GTable.Accounts);
            O2GAccountsTableResponseReader accountsReader = factory.createAccountsTableReader(accountsResponse);
            O2GAccountRow account = accountsReader.getRow(0);

            orderObject.AccountID = account.AccountID;
            // Store base iAmount
            orderObject.BaseAmount = account.BaseUnitSize;

            O2GResponse offerResponse = loginRules.getTableRefeshResponse(O2GTable.Offers);
            O2GOffersTableResponseReader offersReader = factory.createOffersTableReader(offerResponse);

            for (int i = 0; i < offersReader.Count; i++)
            {
                O2GOfferRow offer = offersReader.getRow(i);
                if (instrument.Equals(offer.Instrument))
                {
                    orderObject.OfferID   = offer.OfferID;
                    orderObject.Ask       = offer.Ask;
                    orderObject.Bid       = offer.Bid;
                    orderObject.PointSize = offer.PointSize;
                    orderObject.Symbol    = new Symbol(instrument);
                    break;
                }
            }

            return(orderObject);
        }
Ejemplo n.º 5
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);
            }
        }
Ejemplo n.º 6
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 (string.IsNullOrEmpty(sAccountID) || sAccountID.Equals(account.AccountID))
                {
                    bHasAccount = true;
                    break;
                }
            }
            if (!bHasAccount)
            {
                return(null);
            }
            else
            {
                return(account);
            }
        }
Ejemplo n.º 7
0
        public LoginRulesProvider(O2GLoginRules rules, ResponseReader reader, ILoginRulesProviderValidator validator = null)
        {
            if (rules == null)
            {
                throw new ArgumentNullException("rules");
            }

            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            this.Rules     = rules;
            this.Reader    = reader;
            this.Validator = validator ?? new LoginRulesProviderValidator();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Get and print margin requirements
        /// </summary>
        /// <param name="session"></param>
        /// <param name="account"></param>
        /// <param name="offer"></param>
        private static void PrintMargins(O2GSession session, O2GAccountRow account, O2GOfferRow offer)
        {
            O2GLoginRules loginRules = session.getLoginRules();

            if (loginRules == null)
            {
                throw new Exception("Cannot get login rules");
            }
            O2GTradingSettingsProvider tradingSettings = loginRules.getTradingSettingsProvider();
            double dMmr = 0D;
            double dEmr = 0D;
            double lmr  = 0D;

            tradingSettings.getMargins(offer.Instrument, account, ref dMmr, ref dEmr, ref lmr);
            Console.WriteLine("Margin requirements: mmr={0}, emr={1}, lmr={2}", dMmr, dEmr, lmr);
        }
Ejemplo n.º 9
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}", accountRow.AccountID, accountRow.Balance);
            }
        }
Ejemplo n.º 10
0
        public bool ExistsPositionFor(string symbol)
        {
            O2GResponseReaderFactory factory = session.Session.getResponseReaderFactory();
            // Gets first account from login.
            O2GLoginRules loginRules = session.Session.getLoginRules();
            O2GResponse   response   = loginRules.getTableRefeshResponse(O2GTable.ClosedTrades);

            O2GTradesTableResponseReader tradesReader = factory.createTradesTableReader(response);

            for (int i = 0; i < tradesReader.Count; i++)
            {
                O2GTradeRow tradeRow = tradesReader.getRow(i);
                Console.WriteLine("Trades---");
                Console.WriteLine(tradeRow.OpenQuoteID);
                Console.WriteLine(tradeRow.OfferID);
            }

            return(false);
        }
        /// <summary>
        /// Get the latest offer to which the user is subscribed
        /// </summary>
        private void GetLatestOffer()
        {
            // get the list of the offers to which the user is subscribed
            O2GLoginRules loginRules = mSession.getLoginRules();
            O2GResponse   response   = loginRules.getSystemPropertiesResponse();

            if (loginRules.isTableLoadedByDefault(O2GTableType.Offers))
            {
                // if it is already loaded - just handle them
                response = loginRules.getTableRefreshResponse(O2GTableType.Offers);
                onRequestCompleted(null, response);
            }
            else
            {
                // otherwise create the request to get offers from the server
                O2GRequestFactory factory      = mSession.getRequestFactory();
                O2GRequest        offerRequest = factory.createRefreshTableRequest(O2GTableType.Offers);
                mSession.sendRequest(offerRequest);
            }
        }
Ejemplo n.º 12
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);

            using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
            {
                for (int i = 0; i < accountsReader.Count; i++)
                {
                    O2GAccountRow account = accountsReader.getRow(i);
                    Uri           url     = new Uri(session.getReportURL(account.AccountID, DateTime.Now.AddMonths(-1), DateTime.Now, "html", null));

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

                    var response = httpClient.GetAsync(url).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = response.Content;
                        // by calling .Result you are synchronously reading the result
                        string content  = responseContent.ReadAsStringAsync().Result;
                        string filename = account.AccountID + ".html";
                        string prefix   = url.Scheme + "://" + url.Host + "/";
                        string report   = O2GHtmlContentUtils.ReplaceRelativePathWithAbsolute(content, prefix);
                        System.IO.File.WriteAllText(filename, report);
                        Console.WriteLine("Report is saved to {0}", filename);
                    }
                    else
                    {
                        throw new Exception("Report is not received.");
                    }
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Print offers and find offer by instrument name
        /// </summary>
        /// <param name="session"></param>
        /// <param name="sInstrument"></param>
        /// <returns>offer</returns>
        private static O2GOfferRow GetOffer(O2GSession session, string sInstrument)
        {
            O2GOfferRow offer = null;
            O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory();

            if (readerFactory == null)
            {
                throw new Exception("Cannot create response reader factory");
            }
            O2GLoginRules loginRules = session.getLoginRules();
            O2GResponse   response   = loginRules.getTableRefreshResponse(O2GTableType.Offers);
            O2GOffersTableResponseReader offersResponseReader = readerFactory.createOffersTableReader(response);

            for (int i = 0; i < offersResponseReader.Count; i++)
            {
                O2GOfferRow offerRow = offersResponseReader.getRow(i);
                if (offerRow.Instrument.Equals(sInstrument))
                {
                    offer = offerRow;
                }
                switch (offerRow.SubscriptionStatus)
                {
                case Constants.SubscriptionStatuses.ViewOnly:
                    Console.WriteLine("{0} : [V]iew only", offerRow.Instrument);
                    break;

                case Constants.SubscriptionStatuses.Disable:
                    Console.WriteLine("{0} : [D]isabled", offerRow.Instrument);
                    break;

                case Constants.SubscriptionStatuses.Tradable:
                    Console.WriteLine("{0} : Available for [T]rade", offerRow.Instrument);
                    break;

                default:
                    Console.WriteLine("{0} : {1}", offerRow.Instrument, offerRow.SubscriptionStatus);
                    break;
                }
            }
            return(offer);
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public PriceUpdateController(O2GSession session, string instrument)
        {
            mSyncOfferEvent = new EventWaitHandle(false, EventResetMode.AutoReset);

            mInstrument = instrument;
            mSession    = session;
            mInitFailed = false;

            mSession.subscribeResponse(this);

            mTZConverter = session.getTimeConverter();

            // get the trading day offset
            O2GLoginRules             loginRules = session.getLoginRules();
            O2GResponse               response   = loginRules.getSystemPropertiesResponse();
            O2GSystemPropertiesReader reader     = session.getResponseReaderFactory().createSystemPropertiesReader(response);
            string   eod  = reader.Properties["END_TRADING_DAY"];
            DateTime time = DateTime.ParseExact("01.01.1900_" + eod, "MM.dd.yyyy_HH:mm:ss", CultureInfo.InvariantCulture);

            // convert Trading day start to EST time because the trading day is always closed by New York time
            // so to avoid handling different hour depending on daylight saying time - use EST always
            // for candle calculations
            time = mTZConverter.convert(time, O2GTimeConverterTimeZone.UTC, O2GTimeConverterTimeZone.EST);
            // here we have the date when trading day begins, e.g. 17:00:00
            // please note that if trading day begins before noon - it begins AFTER calendar date is started,
            // so the offset is positive (e.g. 03:00 is +3 offset).
            // if trading day begins after noon, it begins BEFORE calendar date is istarted,
            // so the offset is negative (e.g. 17:00 is -7 offset).
            if (time.Hour <= 12)
            {
                mTradingDayOffset = time.Hour;
            }
            else
            {
                mTradingDayOffset = time.Hour - 24;
            }

            // get latest offer for the instrument
            GetLatestOffer();
        }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
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());
        }
Ejemplo n.º 17
0
        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();
                }
            }
        }
Ejemplo n.º 18
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);
            }
        }
Ejemplo n.º 19
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();
                }
            }
        }
Ejemplo n.º 20
0
        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();
                }
            }
        }
Ejemplo n.º 21
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();
                }
            }
        }
Ejemplo n.º 22
0
        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();
                }
            }
        }
Ejemplo n.º 23
0
        // **AFTER LOG IN**
        // Background worker for table listeners
        private void priceBW_DoWork(object sender, DoWorkEventArgs e)
        {
            Console.WriteLine("Entered BW");

            mSession.useTableManager(O2GTableManagerMode.Yes, null);

            tableManager  = mSession.getTableManager();
            managerStatus = tableManager.getStatus();

            while (managerStatus == O2GTableManagerStatus.TablesLoading)
            {
                Thread.Sleep(50);
                managerStatus = tableManager.getStatus();
            }
            if (managerStatus == O2GTableManagerStatus.TablesLoadFailed)
            {
                this.Invoke(new MethodInvoker(delegate { actiBox.AppendText("WARNING: LOADING TABLES FAILED!" + Environment.NewLine); }));
                return;
            }
            // Check Accounts Table and Grab Information
            try
            {
                O2GLoginRules loginRules = mSession.getLoginRules();
                Console.WriteLine("Tables are loaded!");
                // Check if Accounts table is loaded automatically
                if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Accounts))
                {
                    // If table is loaded, use getTableRefreshResponse method
                    O2GResponse accountsResponse             = loginRules.getTableRefreshResponse(O2GTableType.Accounts);
                    O2GResponseReaderFactory responseFactory = mSession.getResponseReaderFactory();
                    if (responseFactory != null)
                    {
                        O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse);

                        for (int i = 0; i < accountsReader.Count; i++)
                        {
                            account      = accountsReader.getRow(i);
                            accountValue = account.Balance;
                            this.Invoke(new MethodInvoker(delegate { accountValueBox.Text = "$" + Convert.ToString(accountValue); }));
                            acctEq = account.Balance;
                            this.Invoke(new MethodInvoker(delegate { accountLevBox.Text = "$" + Convert.ToString(acctEq); }));
                            this.Invoke(new MethodInvoker(delegate { accountEquityBox.Text = "$" + Convert.ToString(acctEq); }));
                            sAccountID  = account.AccountID.ToString();
                            amountLimit = account.AmountLimit;
                            baseSize    = account.BaseUnitSize;
                            if (account.MaintenanceType == "Y")
                            {
                                this.Invoke(new MethodInvoker(delegate { hedgingBox.Text = "Yes"; }));
                                hedgingLong = true;
                                Settings.Default.hedgeLong = true;
                                hedgingShort = true;
                                Settings.Default.hedgeShort = true;
                                this.Invoke(new MethodInvoker(delegate { longCheckBox.Checked = true; }));
                                this.Invoke(new MethodInvoker(delegate { shortCheckBox.Checked = true; }));
                            }
                            else
                            {
                                this.Invoke(new MethodInvoker(delegate { hedgingBox.Text = "No"; }));
                                if (hedgingShort == false)
                                {
                                    hedgingLong = true;
                                    this.Invoke(new MethodInvoker(delegate { longCheckBox.Checked = true; }));
                                    this.Invoke(new MethodInvoker(delegate { shortCheckBox.Checked = false; }));
                                }
                                else
                                {
                                    hedgingShort = true;
                                    this.Invoke(new MethodInvoker(delegate { longCheckBox.Checked = false; }));
                                    this.Invoke(new MethodInvoker(delegate { shortCheckBox.Checked = true; }));
                                }
                            }
                        }
                    }
                }
                else
                {
                    // If table is not loaded, use createRefreshTableRequest method
                    O2GRequestFactory requestFactory = mSession.getRequestFactory();
                    if (requestFactory != null)
                    {
                        O2GRequest request = requestFactory.createRefreshTableRequest(O2GTableType.Accounts);
                        mSession.sendRequest(request);
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception acctErr)
            {
                Console.WriteLine(acctErr);
            }

            // Check if all 20 pairs needed are subscribed to on the account.
            try
            {
                O2GLoginRules loginRules = mSession.getLoginRules();

                if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Offers))
                {
                    O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers);
                    O2GResponseReaderFactory responseFactory = mSession.getResponseReaderFactory();
                    if (responseFactory != null)
                    {
                        O2GOffersTableResponseReader offersReader = responseFactory.createOffersTableReader(offersResponse);

                        for (int i = 0; i < offersReader.Count; i++)
                        {
                            O2GOfferRow offers = offersReader.getRow(i);

                            string checkOffer = offers.OfferID;
                        }
                    }
                }
            }
            catch (Exception mmrErr)
            {
                Console.WriteLine(mmrErr);
            }

            Console.WriteLine("Initializing needed table events.");
            // Initiate Table Getters
            O2GOffersTable offersTable = (O2GOffersTable)tableManager.getTable(O2GTableType.Offers);

            accountsTable = (O2GAccountsTable)tableManager.getTable(O2GTableType.Accounts);
            O2GSummaryTable      summaryTable = (O2GSummaryTable)tableManager.getTable(O2GTableType.Summary);
            O2GClosedTradesTable closedTable  = (O2GClosedTradesTable)tableManager.getTable(O2GTableType.ClosedTrades);

            // Trigger Table Events for Subscription
            offersTable.RowChanged   += new EventHandler <RowEventArgs>(offersTable_RowChanged);
            accountsTable.RowChanged += new EventHandler <RowEventArgs>(accountsTable_RowChanged);
            summaryTable.RowChanged  += new EventHandler <RowEventArgs>(summaryTable_RowChanged);
            closedTable.RowChanged   += new EventHandler <RowEventArgs>(closedTable_RowChanged);

            // Check pair subscription status, and add if needed.

            this.Invoke(new MethodInvoker(delegate { actiBox.AppendText("Connection Established.... Monitoring Pairs..." + Environment.NewLine); }));
            pastTimer.Start();
        }
Ejemplo n.º 24
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();
                }
            }
        }
Ejemplo n.º 25
0
        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();
                }
            }
        }
Ejemplo n.º 26
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();
                }
            }
        }
Ejemplo n.º 27
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();
                }
            }
        }
Ejemplo n.º 28
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();
                }
            }
        }
Ejemplo n.º 29
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();
            }
        }
Ejemplo n.º 30
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();
                }
            }
        }