static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;

            try
            {
                Console.WriteLine("CloseAllPositions 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;

                    Dictionary <string, CloseOrdersData> closeOrdersData = GetCloseOrdersData(session, sampleParams.AccountID, responseListener);
                    if (closeOrdersData.Values.Count == 0)
                    {
                        throw new Exception("There are no opened positions");
                    }

                    O2GRequest request = CreateCloseAllRequest(session, closeOrdersData);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request; probably some arguments are missing or incorrect");
                    }
                    List <string> requestIDs = new List <string>();
                    for (int i = 0; i < request.ChildrenCount; i++)
                    {
                        requestIDs.Add(request.getChildRequest(i).RequestID);
                    }
                    responseListener.SetRequestIDs(requestIDs);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        Thread.Sleep(1000); // Wait for the balance update
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                        session.unsubscribeSessionStatus(statusListener);
                    }
                    session.Dispose();
                }
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("If-Then", loginParams, sampleParams);

                session = O2GTransport.createSession();
                SessionStatusListener statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin);
                session.subscribeSessionStatus(statusListener);
                session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
                if (statusListener.WaitEvents() && statusListener.Connected)
                {
                    ResponseListener responseListener = new ResponseListener(session);
                    session.subscribeResponse(responseListener);

                    O2GAccountRow account = GetAccount(session, sampleParams.AccountID);
                    if (account == null)
                    {
                        if (string.IsNullOrEmpty(sampleParams.AccountID))
                        {
                            throw new Exception("No valid accounts");
                        }
                        else
                        {
                            throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID));
                        }
                    }
                    sampleParams.AccountID = account.AccountID;

                    O2GOfferRow offer = GetOffer(session, sampleParams.Instrument);
                    if (offer == null)
                    {
                        throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument));
                    }

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

                    O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider();
                    int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account);
                    int iAmount       = iBaseUnitSize * sampleParams.Lots;

                    // For the purpose of this example we will place IF-THEN order 30 pips below the current market price
                    // and our stop entry order 15 pips below the current market price
                    double dRateIf   = offer.Ask - 30.0 * offer.PointSize;
                    double dRateStop = offer.Ask - 15.0 * offer.PointSize;

                    O2GRequest request = CreateIfThenRequest(session, offer.OfferID, account.AccountID, iAmount, dRateIf, dRateStop);
                    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");
                    }

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

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

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

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

                    CloseOrdersData closeOrdersData;
                    if (!GetCloseOrdersData(tableManager, sampleParams.AccountID, offer.OfferID, out closeOrdersData))
                    {
                        throw new Exception("There are no opened positions");
                    }

                    tableListener.SubscribeEvents(tableManager);

                    O2GRequest request = CreateCloseMarketNettingOrderRequest(session, closeOrdersData);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request; probably some arguments are missing or incorrect");
                    }
                    List <string> requestIDs = new List <string>();
                    for (int i = 0; i < request.ChildrenCount; i++)
                    {
                        requestIDs.Add(request.getChildRequest(i).RequestID);
                    }
                    responseListener.SetRequestIDs(requestIDs);
                    tableListener.SetRequestIDs(requestIDs);
                    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)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                        session.unsubscribeSessionStatus(statusListener);
                    }
                    session.Dispose();
                }
            }
        }
Beispiel #4
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); }));
                            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);

            // 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);

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

            this.Invoke(new MethodInvoker(delegate { actiBox.AppendText("Connection Established.... Monitoring Pairs..." + Environment.NewLine); }));
            pastTimer.Start();
        }
Beispiel #5
0
        /// <summary>
        /// Listener: When Trading session status is changed
        /// </summary>
        /// <param name="status"></param>
        public void onSessionStatusChanged(O2GSessionStatusCode status)
        {
            switch (status)
            {
            case    O2GSessionStatusCode.TradingSessionRequested:
                // If the trading session requires the session name or pin code...
                if (OnErrorEvent != null)
                {
                    OnErrorEvent("Multi-session connectors aren't supported by this example\n");
                }
                mTradingSession.logout();
                break;

            case    O2GSessionStatusCode.Connected:
                // login is completed

                // now we need collect data about the system properties
                O2GLoginRules loginRules = mTradingSession.getLoginRules();
                mTZConverter = mTradingSession.getTimeConverter();
                // get the trading day offset.
                O2GResponse response;
                response = loginRules.getSystemPropertiesResponse();
                O2GSystemPropertiesReader reader = mTradingSession.getResponseReaderFactory().createSystemPropertiesReader(response);
                string   eod  = reader.Properties["END_TRADING_DAY"];
                DateTime time = DateTime.ParseExact("01.01.1900_" + eod, "MM.dd.yyyy_HH:mm:ss", CultureInfo.InvariantCulture);
                // convert Trading day start to EST time because the trading day is always closed by New York time
                // so to avoid handling different hour depending on daylight saying time - use EST always
                // for candle calculations
                time = mTZConverter.convert(time, O2GTimeConverterTimeZone.UTC, O2GTimeConverterTimeZone.EST);
                // here we have the date when trading day begins, e.g. 17:00:00
                // please note that if trading day begins before noon - it begins AFTER calendar date is started,
                // so the offset is positive (e.g. 03:00 is +3 offset).
                // if trading day begins after noon, it begins BEFORE calendar date is istarted,
                // so the offset is negative (e.g. 17:00 is -7 offset).
                if (time.Hour <= 12)
                {
                    mTradingDayOffset = time.Hour;
                }
                else
                {
                    mTradingDayOffset = time.Hour - 24;
                }

                // ...and now get the list of the offers to which the user is subscribed
                if (loginRules.isTableLoadedByDefault(O2GTableType.Offers))
                {
                    // if it is already loaded - just handle them
                    response = loginRules.getTableRefreshResponse(O2GTableType.Offers);
                    onRequestCompleted(null, response);
                }
                else
                {
                    // otherwise create the request to get offers from the server
                    O2GRequestFactory factory      = mTradingSession.getRequestFactory();
                    O2GRequest        offerRequest = factory.createRefreshTableRequest(O2GTableType.Offers);
                    mTradingSession.sendRequest(offerRequest);
                }
                break;

            default:
                if (OnStateChange != null)
                {
                    OnStateChange(false);
                }
                break;
            }
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("GetOffers", loginParams, sampleParams);

                session = O2GTransport.createSession();
                SessionStatusListener statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin);
                session.subscribeSessionStatus(statusListener);
                statusListener.Reset();
                session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
                if (statusListener.WaitEvents() && statusListener.Connected)
                {
                    ResponseListener responseListener = new ResponseListener(session);
                    responseListener.SetInstrument(sampleParams.Instrument);
                    session.subscribeResponse(responseListener);

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

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

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

                    session.unsubscribeResponse(responseListener);
                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvents();
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;

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

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

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin,
                                       ParserArgument.Instrument,
                                       ParserArgument.BuySell,
                                       ParserArgument.Rate,
                                       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);
                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)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
Beispiel #8
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();
                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.WaitEvent() && statusListener.Connected)
                {
                    ResponseListener responseListener = new ResponseListener(session);
                    session.subscribeResponse(responseListener);

                    O2GAccountRow account = GetAccount(session, sampleParams.AccountID);
                    if (account == null)
                    {
                        if (string.IsNullOrEmpty(sampleParams.AccountID))
                        {
                            throw new Exception("No valid accounts");
                        }
                        else
                        {
                            throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID));
                        }
                    }
                    sampleParams.AccountID = account.AccountID;

                    O2GOfferRow offer = GetOffer(session, sampleParams.Instrument);
                    if (offer == null)
                    {
                        throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument));
                    }

                    O2GLoginRules loginRules = session.getLoginRules();
                    if (loginRules == null)
                    {
                        throw new Exception("Cannot get login rules");
                    }
                    O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider();
                    int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account);
                    int iAmount       = iBaseUnitSize * sampleParams.Lots;

                    double dRate;
                    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");
                    }
                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvent();
                    session.unsubscribeResponse(responseListener);
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
Beispiel #9
0
        private void GetHistoryPrices(O2GSession O2GSession, string Instrument, string Interval, DateTime DtFrom, DateTime DtTo)
        {
            m_responseListener = new ResponseListener(O2GSession);
            O2GSession.subscribeResponse(m_responseListener);

            O2GRequestFactory factory = O2GSession.getRequestFactory();

            O2GTimeframeCollection timeframecollection = factory.Timeframes;
            O2GTimeframe           Timeframe           = timeframecollection[Interval];

            if (Timeframe == null)
            {
                throw new Exception(string.Format("Timeframe '{0}' is incorrect!", Timeframe));
            }

            O2GRequest request  = factory.createMarketDataSnapshotRequestInstrument(Instrument, Timeframe, 300);
            DateTime   DtFirst  = DtTo;
            DateTime   DatePrec = System.DateTime.MinValue;

            //TimeSpan PricesTimeSpan = System.TimeSpan.MinValue;

            //if (Interval == "m5")
            //{
            //    PricesTimeSpan = new TimeSpan(0, 0, 5, 0, 0);
            //}

            do // cause there is limit for returned candles amount
            {
                factory.fillMarketDataSnapshotRequestTime(request, DtFrom, DtFirst, false);
                m_responseListener.SetRequestID(request.RequestID);
                O2GSession.sendRequest(request);

                if (!m_responseListener.WaitEvents())
                {
                    throw new Exception("Response waiting timeout expired");
                }
                // shift "to" bound to oldest datetime of returned data
                O2GResponse response = m_responseListener.GetResponse();
                if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
                {
                    O2GResponseReaderFactory readerFactory = O2GSession.getResponseReaderFactory();
                    if (readerFactory != null)
                    {
                        O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response);
                        if (reader.Count > 0)
                        {
                            if (DateTime.Compare(DtFirst, reader.getDate(0)) != 0)
                            {
                                DtFirst = reader.getDate(0); // earliest datetime of returned data

                                for (int nData = reader.Count - 1; nData > -1; nData--)
                                {
                                    if (reader.getDate(nData) != DatePrec)
                                    {
                                        m_datetime.Add(reader.getDate(nData));

                                        m_ask.Add(reader.getAsk(nData));
                                        m_askopen.Add(reader.getAskOpen(nData));
                                        m_askclose.Add(reader.getAskClose(nData));
                                        m_askhigh.Add(reader.getAskHigh(nData));
                                        m_asklow.Add(reader.getAskLow(nData));

                                        m_bid.Add(reader.getBid(nData));
                                        m_bidopen.Add(reader.getBidOpen(nData));
                                        m_bidclose.Add(reader.getBidClose(nData));
                                        m_bidhigh.Add(reader.getBidHigh(nData));
                                        m_bidlow.Add(reader.getBidLow(nData));
                                    }
                                    //else
                                    //{
                                    //    break;
                                    //}

                                    DatePrec = reader.getDate(nData);
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            Console.WriteLine("0 rows received");
                            break;
                        }
                    }
                    // PrintPrices(session, response);
                }
                else
                {
                    break;
                }
            } while (DtFirst > DtFrom);

            m_datetime.Reverse();

            m_ask.Reverse();
            m_askopen.Reverse();
            m_askclose.Reverse();
            m_askhigh.Reverse();
            m_asklow.Reverse();

            m_bid.Reverse();
            m_bidopen.Reverse();
            m_bidclose.Reverse();
            m_bidhigh.Reverse();
            m_bidlow.Reverse();
        }
        public static bool CreateMarketOrder(this FxcmBroker fxcm, string instrument, int lotsAmount, TradeDirection direction, out string orderId, double?rateStop = null, double?rateLimit = null)
        {
            orderId = string.Empty;

            if (fxcm.Status != ConnectStatus.Connected)
            {
                Log.Error("FXCM not connected");

                return(false);
            }

            O2GOfferRow offer = GetOffer(fxcm.Session, instrument);

            if (offer == null)
            {
                throw new Exception(string.Format("The instrument '{0}' is not valid", instrument));
            }

            O2GRequest        request        = null;
            O2GRequestFactory requestFactory = fxcm.Session.getRequestFactory();

            if (requestFactory == null)
            {
                throw new Exception("Cannot create request factory");
            }
            var         account  = GetAccount(fxcm.Session);
            O2GValueMap valuemap = requestFactory.createValueMap();

            valuemap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder);
            valuemap.setString(O2GRequestParamsEnum.OrderType, Constants.Orders.TrueMarketOpen);
            valuemap.setString(O2GRequestParamsEnum.AccountID, account.AccountID);
            valuemap.setString(O2GRequestParamsEnum.OfferID, offer.OfferID);
            valuemap.setString(O2GRequestParamsEnum.BuySell, direction == TradeDirection.Long ? "B" : "S");

            if (rateStop != null)
            {
                valuemap.setDouble(O2GRequestParamsEnum.RateStop, rateStop.Value);
            }

            if (rateLimit != null)
            {
                valuemap.setDouble(O2GRequestParamsEnum.RateLimit, rateLimit.Value);
            }

            // Get account
            var loginRules = fxcm.Session.getLoginRules();
            var tradingSettingsProvider = loginRules.getTradingSettingsProvider();
            int iBaseUnitSize           = tradingSettingsProvider.getBaseUnitSize(instrument, account);
            int iAmount = iBaseUnitSize * lotsAmount;

            valuemap.setInt(O2GRequestParamsEnum.Amount, iAmount);
            valuemap.setString(O2GRequestParamsEnum.CustomID, "TrueMarketOrder");
            request = requestFactory.createOrderRequest(valuemap);

            if (request == null)
            {
                Log.Error($"Unable to process request - {requestFactory.getLastError()}");
                return(false);
            }

            var ret = ProcessOrderRequest(fxcm, request, out orderId);

            return(ret);
        }
        private static bool ProcessOrderRequest(FxcmBroker fxcm, O2GRequest request, out string orderId)
        {
            var ret       = string.Empty;
            var waitOrder = new ManualResetEvent(false);

            var responseListener = new ResponseListener(
                fxcm.Session,
                data =>
            {
                O2GResponseReaderFactory factory = fxcm.Session.getResponseReaderFactory();
                if (factory != null)
                {
                    O2GTablesUpdatesReader reader = factory.createTablesUpdatesReader(data);
                    for (int ii = 0; ii < reader.Count; ii++)
                    {
                        if (reader.getUpdateTable(ii) == O2GTableType.Orders)
                        {
                            O2GOrderRow orderRow = reader.getOrderRow(ii);
                            if (reader.getUpdateType(ii) == O2GTableUpdateType.Insert)
                            {
                                ret = orderRow.OrderID;
                                waitOrder.Set();
                                break;
                            }
                        }
                    }
                }
            });

            fxcm.Session.subscribeResponse(responseListener);

            try
            {
                responseListener.SetRequestID(request.RequestID);
                fxcm.Session.sendRequest(request);
                if (responseListener.WaitEvents())
                {
                    if (!string.IsNullOrEmpty(responseListener.Error))
                    {
                        Log.Error($"Unable to process request - {responseListener.Error}");
                        orderId = ret;
                        return(false);
                    }

                    // Get order ID
                    waitOrder.WaitOne();

                    orderId = ret;
                    return(true);
                }
                else
                {
                    Log.Error($"Unable to process request");
                    orderId = ret;
                    return(false);
                }
            }
            finally
            {
                fxcm.Session.unsubscribeResponse(responseListener);
            }
        }
        /// <summary>
        /// Fetches historical data from FXCM server
        /// </summary>
        /// <param name="historicDataRequest"></param>
        public void GetHistoricalData(HistoricDataRequest historicDataRequest)
        {
            // Create a new factory
            O2GRequestFactory factory = _session.getRequestFactory();

            // Get time frame
            O2GTimeframe timeframe = factory.Timeframes[GetFxcmTimeFrame(historicDataRequest)];

            if (timeframe == null)
            {
                _logger.Error("Invalid time format", _type.FullName, "GetHistoricalData");

                return;
            }

            // Clear any existing data
            _barCollection.Clear();

            // Request historical snapshot
            O2GRequest request = factory.createMarketDataSnapshotRequestInstrument(historicDataRequest.Security.Symbol, timeframe, 300);

            DateTime endTime = historicDataRequest.EndTime;

            do // cause there is limit for returned candles amount
            {
                factory.fillMarketDataSnapshotRequestTime(request, historicDataRequest.StartTime, endTime, false);

                SetRequestId(request.RequestID);

                _session.sendRequest(request);

                if (!WaitEvents())
                {
                    _logger.Error("Response waiting timeout expired", _type.FullName, "GetHistoricalData");

                    return;
                }

                // Shift "to" bound to oldest datetime of returned data
                O2GResponse response = GetResponse();
                if (response != null && response.Type == O2GResponseType.MarketDataSnapshot)
                {
                    O2GResponseReaderFactory readerFactory = _session.getResponseReaderFactory();
                    if (readerFactory != null)
                    {
                        O2GMarketDataSnapshotResponseReader reader = readerFactory.createMarketDataSnapshotReader(response);
                        if (reader.Count > 0)
                        {
                            if (DateTime.Compare(endTime, reader.getDate(0)) != 0)
                            {
                                endTime = reader.getDate(0); // earliest datetime of returned data
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            if (_logger.IsInfoEnabled)
                            {
                                _logger.Info("Response waiting timeout expired", _type.FullName, "GetHistoricalData");
                            }
                            break;
                        }
                    }
                    ExtractPrices(_session, response, historicDataRequest);
                }
                else
                {
                    break;
                }
            } while (endTime > historicDataRequest.StartTime);

            if (_barCollection.Count > 0)
            {
                if (_historicalDataEvent != null)
                {
                    _barCollection.Reverse();

                    // Create historical data object
                    var historicalData = new HistoricBarData(historicDataRequest.Security, historicDataRequest.MarketDataProvider, DateTime.UtcNow);
                    historicalData.Bars  = _barCollection.ToArray();
                    historicalData.ReqId = historicDataRequest.Id;

                    // Raise Event
                    _historicalDataEvent(historicalData);
                }

                _barCollection.Clear();
            }
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;
            int iContingencyGroupType = 1; // OCO group

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

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

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin,
                                       ParserArgument.ContingencyID,
                                       ParserArgument.OrderID,
                                       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;

                    O2GRequest request = AddOrderIntoGroupRequest(session, sampleParams.AccountID, sampleParams.ContingencyID, sampleParams.OrderID, iContingencyGroupType);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }

                    List <string> orderIDList = new List <string>();
                    orderIDList.Add(sampleParams.OrderID);
                    foreach (string sOrderID in orderIDList)
                    {
                        if (!IsOrderExists(session, sampleParams.AccountID, sOrderID, responseListener))
                        {
                            throw new Exception(string.Format("Order '{0}' does not exist", sOrderID));
                        }
                    }
                    if (!IsContingencyExists(session, sampleParams.AccountID, sampleParams.ContingencyID, responseListener))
                    {
                        throw new Exception(string.Format("Contingency group '{0}' does not exist", sampleParams.ContingencyID));
                    }
                    responseListener.SetOrderIDs(orderIDList);
                    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
            {
                Console.ReadLine();
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                        session.unsubscribeResponse(responseListener);
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("SubscriptionStatus", 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.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));
                    }

                    O2GRequest request = CreateSetSubscriptionStatusRequest(session, offer.OfferID, sampleParams.Status, responseListener);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (!responseListener.WaitEvents())
                    {
                        throw new Exception("Response waiting timeout expired");
                    }

                    O2GResponse response = responseListener.GetResponse();
                    if (response != null && response.Type == O2GResponseType.CommandResponse)
                    {
                        Console.WriteLine("Subscription status for '{0}' is set to '{1}'", sampleParams.Instrument, sampleParams.Status);
                    }

                    PrintMargins(session, account, offer);
                    UpdateMargins(session, responseListener);
                    PrintMargins(session, account, offer);
                    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.WaitEvents();
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }