Beispiel #1
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("PrintTable", loginParams);

                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)
                {
                    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);
                    if (account == null)
                        throw new Exception("No valid accounts");

                    PrintOrders(tableManager, account.AccountID);
                    Console.WriteLine("Done!");

                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvents();
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
        public async Task<User> Login(LoginParams loginParams)
        {
            Utils.CheckNullOrEmpty(new List<string> { "Email", "Token" }, loginParams.Email, loginParams.Token);

            using (AppDbContext context = new AppDbContext())
            {
                User user = await context.Users.FirstOrDefaultAsync(p => p.Email == loginParams.Email &&
                                                                         p.AccountType == loginParams.AccountType &&
                                                                         p.UserType == loginParams.UserType);

                if (user == null)
                {
                    throw new UserException(ErrorCode.INVALID.ToString());
                }

                if (!user.IsActivated)
                {
                    throw new UserException(ErrorCode.USER_NOT_VERIFIED_YET.ToString());
                }

                if (loginParams.AccountType == AccountType.Email)
                {
                    if (!UtilsCryptography.VerifyBCryptPassword(loginParams.Token, user.Password))
                    {
                        throw new UserException(ErrorCode.INVALID.ToString());
                    }
                }
                else if (loginParams.AccountType == AccountType.Facebook)
                {
                    try
                    {
                        FacebookClient facebookClient = new FacebookClient(loginParams.Token);
                        await facebookClient.GetTaskAsync("me?fields=id");
                    }
                    catch (Exception)
                    {
                        throw new UserException(ErrorCode.FACEBOOK_INVALID.ToString());
                    }
                }
                else
                {
                    try
                    {
                        string query = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + loginParams.Token;
                        HttpClient client = new HttpClient();
                        await client.GetStringAsync(query);
                    }
                    catch (Exception)
                    {
                        throw new UserException(ErrorCode.GOOGLE_INVALID.ToString());
                    }
                }

                return user;
            }
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("PrintTable", loginParams);

                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.subscribeResponse(responseListener);
                    O2GAccountRow account = GetAccount(session);
                    if (account != null)
                    {
                        PrintOrders(session, account.AccountID, responseListener);
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        throw new Exception("No valid accounts");
                    }
                    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 #4
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("CheckPermissions", 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)
                {
                    CheckPermissions(session, sampleParams.Instrument);
                    Console.WriteLine("Done!");
                    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 #5
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 #6
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: Instrument='{1}', Lots='{2}', AccountID='{3}'", procName, prm.Instrument, prm.Lots, prm.AccountID);
 }
Beispiel #7
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("CreateOTOCO", loginParams, sampleParams);

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

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

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

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

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

                    double dRatePrimary   = offer.Ask - 30.0 * offer.PointSize;
                    double dRateOcoFirst  = offer.Ask + 15.0 * offer.PointSize;
                    double dRateOcoSecond = offer.Ask - 15.0 * offer.PointSize;

                    O2GRequest request = CreateOTOCORequest(session, offer.OfferID, account.AccountID, iAmount, dRatePrimary, dRateOcoFirst, dRateOcoSecond);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }

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

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

                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvents();
                    session.unsubscribeResponse(responseListener);
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
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("OpenPosition", 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, 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;

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

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

                PrintSampleParams("NetStopLimit", 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, sampleParams.Instrument);
                    if (offer == null)
                    {
                        throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument));
                    }

                    O2GTradeRow trade = GetTrade(tableManager, sampleParams.AccountID, offer.OfferID);
                    if (trade == null)
                    {
                        throw new Exception(string.Format("There are no opened positions for instrument '{0}'", sampleParams.Instrument));
                    }

                    O2GRequest request;
                    string sBuySell = trade.BuySell.Equals(Constants.Buy) ? Constants.Sell : Constants.Buy;

                    tableListener.SubscribeEvents(tableManager);

                    request = CreateNetEntryOrderRequest(session, offer.OfferID, sampleParams.AccountID, sampleParams.RateStop, sBuySell, Constants.Orders.StopEntry);
                    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");
                    }

                    request = CreateNetEntryOrderRequest(session, offer.OfferID, sampleParams.AccountID, sampleParams.RateLimit, 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");
                    }

                    Console.WriteLine("Done!");

                    tableListener.UnsubscribeEvents(tableManager);

                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvents();
                    session.unsubscribeResponse(responseListener);
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
Beispiel #10
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: Instrument='{1}', Timeframe='{2}', DateFrom='{3}', DateTo='{4}'", procName, prm.Instrument, prm.Timeframe, prm.DateFrom.ToString("MM.dd.yyyy HH:mm:ss"), prm.DateTo.ToString("MM.dd.yyyy HH:mm:ss"));
 }
Beispiel #11
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("ClosePosition", loginParams, sampleParams);

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

                    O2GTradeRow trade = GetTrade(session, sampleParams.AccountID, offer.OfferID, responseListener);
                    if (trade == null)
                    {
                        throw new Exception(string.Format("There are no opened positions for instrument '{0}'", sampleParams.Instrument));
                    }

                    O2GRequest request = CreateCloseMarketOrderRequest(session, sampleParams.Instrument, trade);
                    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();
                }
            }
        }
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: Instrument='{1}', Timeframe='{2}', DateFrom='{3}', QuotesCount='{4}'",
                       procName, prm.Instrument, prm.Timeframe, prm.DateFrom.ToString("MM.dd.yyyy HH:mm:ss"), prm.QuotesCount);
 }
        static void Main(string[] args)
        {
            O2GSession session = null;
            IPriceHistoryCommunicator communicator   = null;
            SessionStatusListener     statusListener = null;
            bool loggedIn = false;

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

                PrintSampleParams("GetLivePrices", loginParams, sampleParams);

                // use the application module path as a base path for quotes storage
                string storagePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "History");

                // create the ForexConnect trading session
                session        = O2GTransport.createSession();
                statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin);
                // subscribe IO2GSessionStatus interface implementation for the status events
                session.subscribeSessionStatus(statusListener);
                statusListener.Reset();

                // create an instance of IPriceHistoryCommunicator
                communicator = PriceHistoryCommunicatorFactory.createCommunicator(session, storagePath);

                // log in to ForexConnect
                session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
                if (statusListener.WaitEvents() && statusListener.Connected)
                {
                    loggedIn = true;

                    CommunicatorStatusListener communicatorStatusListener = new CommunicatorStatusListener();
                    communicator.addStatusListener(communicatorStatusListener);

                    // wait until the communicator signals that it is ready
                    if (communicator.isReady() ||
                        (communicatorStatusListener.WaitEvents() && communicatorStatusListener.Ready))
                    {
                        // attach the instance of the class that implements the IPriceHistoryCommunicatorListener
                        // interface to the communicator
                        ResponseListener responseListener = new ResponseListener();
                        communicator.addListener(responseListener);

                        GetLivePrices(communicator, sampleParams.Instrument, sampleParams.Timeframe,
                                      sampleParams.DateFrom, sampleParams.DateTo, sampleParams.QuotesCount, responseListener,
                                      session, statusListener);
                        Console.WriteLine("Done!");

                        communicator.removeListener(responseListener);
                    }

                    communicator.removeStatusListener(communicatorStatusListener);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (communicator != null)
                {
                    communicator.Dispose();
                }
                if (session != null)
                {
                    if (loggedIn)
                    {
                        try
                        {
                            statusListener.Reset();
                            session.logout();
                            statusListener.WaitEvents();
                        }
                        catch (Exception ee)
                        {
                        }
                    }

                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: AccountID='{1}'", procName, prm.AccountID);
 }
Beispiel #15
0
 public LtiAdvantageLoginRedirectValueProvider(LoginParams loginParams)
 {
     _loginParams = loginParams;
 }
        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();
                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)
                    {
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;

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

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

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin,
                                       ParserArgument.Instrument,
                                       ParserArgument.BuySell,
                                       ParserArgument.Rate,
                                       ParserArgument.Lots,
                                       ParserArgument.AccountID,
                                       ParserArgument.ExpireData);

                argParser.ParseArguments();

                if (!argParser.AreArgumentsValid)
                {
                    argParser.PrintUsage();
                    return;
                }

                argParser.PrintArguments();

                LoginParams  loginParams  = argParser.LoginParams;
                SampleParams sampleParams = argParser.SampleParams;

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

                    O2GTableManager       tableManager  = session.getTableManager();
                    O2GTableManagerStatus managerStatus = tableManager.getStatus();
                    while (managerStatus == O2GTableManagerStatus.TablesLoading)
                    {
                        Thread.Sleep(50);
                        managerStatus = tableManager.getStatus();
                    }

                    if (managerStatus == O2GTableManagerStatus.TablesLoadFailed)
                    {
                        throw new Exception("Cannot refresh all tables of table manager");
                    }
                    O2GAccountRow account = GetAccount(tableManager, sampleParams.AccountID);
                    if (account == null)
                    {
                        if (string.IsNullOrEmpty(sampleParams.AccountID))
                        {
                            throw new Exception("No valid accounts");
                        }
                        else
                        {
                            throw new Exception(string.Format("The account '{0}' is not valid", sampleParams.AccountID));
                        }
                    }
                    sampleParams.AccountID = account.AccountID;

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

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

                    tableListener.SubscribeEvents(tableManager);

                    O2GRequest request = CreateEntryOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.Rate, sampleParams.BuySell, sOrderType, sampleParams.ExpireDate);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    tableListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }

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

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

                PrintSampleParams("PrintTableListener", loginParams);

                session = O2GTransport.createSession();
                TableManagerListener managerListener = new TableManagerListener();
                session.useTableManager(O2GTableManagerMode.Yes, managerListener);
                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)
                {
                    O2GTableManager tableManager = session.getTableManager();
                    if (managerListener.WaitEvents() && managerListener.IsLoaded)
                    {
                        Console.WriteLine("All tables are loaded");
                    }
                    else
                    {
                        throw new Exception("Cannot refresh all tables of table manager");
                    }

                    O2GAccountRow account = GetAccount(tableManager);
                    if (account == null)
                    {
                        throw new Exception("No valid accounts");
                    }

                    managerListener.Reset();
                    O2GTableManager tableManagerByAccount = session.getTableManagerByAccount(account.AccountID);
                    if (managerListener.WaitEvents() && managerListener.IsLoaded)
                    {
                        Console.WriteLine(string.Format("All tables are loaded (account {0})", account.AccountID));
                    }
                    else
                    {
                        throw new Exception(string.Format("Cannot refresh all tables of table manager (account {0})", account.AccountID));
                    }

                    PrintOrders(tableManagerByAccount, account.AccountID);
                    Console.WriteLine("Done!");

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

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

                PrintSampleParams("ClosePosition", loginParams, sampleParams);

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

                    O2GTradeRow trade = GetTrade(session, sampleParams.AccountID, offer.OfferID, responseListener);
                    if (trade == null)
                    {
                        throw new Exception(string.Format("There are no opened positions for instrument '{0}'", sampleParams.Instrument));
                    }

                    O2GRequest request = CreateCloseMarketOrderRequest(session, sampleParams.Instrument, trade);
                    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();
                }
            }
        }
Beispiel #20
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();
                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, sampleParams.Instrument);
                    if (offer == null)
                    {
                        throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument));
                    }

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

                    double dRate;
                    double dRateStop;
                    double dRateLimit;
                    double dBid       = offer.Bid;
                    double dAsk       = offer.Ask;
                    double dPointSize = offer.PointSize;

                    // For the purpose of this example we will place entry order 8 pips from the current market price
                    // and attach stop and limit orders 10 pips from an entry order price
                    if (sampleParams.OrderType.Equals(Constants.Orders.LimitEntry))
                    {
                        if (sampleParams.BuySell.Equals(Constants.Buy))
                        {
                            dRate      = dAsk - 8 * dPointSize;
                            dRateLimit = dRate + 10 * dPointSize;
                            dRateStop  = dRate - 10 * dPointSize;
                        }
                        else
                        {
                            dRate      = dBid + 8 * dPointSize;
                            dRateLimit = dRate - 10 * dPointSize;
                            dRateStop  = dRate + 10 * dPointSize;
                        }
                    }
                    else
                    {
                        if (sampleParams.BuySell.Equals(Constants.Buy))
                        {
                            dRate      = dAsk + 8 * dPointSize;
                            dRateLimit = dRate + 10 * dPointSize;
                            dRateStop  = dRate - 10 * dPointSize;
                        }
                        else
                        {
                            dRate      = dBid - 8 * dPointSize;
                            dRateLimit = dRate - 10 * dPointSize;
                            dRateStop  = dRate + 10 * dPointSize;
                        }
                    }

                    tableListener.SubscribeEvents(tableManager);

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

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

                    tableListener.UnsubscribeEvents(tableManager);

                    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 #21
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: Instrument='{1}'", procName, prm.Instrument);
 }
Beispiel #22
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: Instrument='{1}', BuySell='{2}', Lots='{3}', AccountID='{4}', OrderType='{5}'", procName, prm.Instrument, prm.BuySell, prm.Lots, prm.AccountID, prm.OrderType);
 }
Beispiel #23
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: PrimaryID='{1}', SecondaryID='{2}', AccountID='{3}'", procName, prm.PrimaryID, prm.SecondaryID, prm.AccountID);
 }
        static void Main(string[] args)
        {
            O2GSession session       = null;
            O2GSession secondSession = null;

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

                PrintSampleParams("Login", loginParams);

                session        = O2GTransport.createSession();
                statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin, "PrimarySessionStatus");
                session.subscribeSessionStatus(statusListener);
                statusListener.Reset();
                session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
                if (statusListener.WaitEvents() && statusListener.Connected)
                {
                    string token = session.getToken();
                    Console.WriteLine("Token obtained: {0}", token);
                    secondSession        = O2GTransport.createSession();
                    secondStatusListener = new SessionStatusListener(secondSession, loginParams.SessionID, loginParams.Pin, "SecondarySessionStatus");
                    secondSession.subscribeSessionStatus(secondStatusListener);
                    secondStatusListener.Reset();
                    secondSession.loginWithToken(loginParams.Login, token, loginParams.URL, loginParams.Connection);
                    if (secondStatusListener.WaitEvents() && secondStatusListener.Connected)
                    {
                        Console.WriteLine("Done!");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (secondSession != null)
                {
                    if (secondStatusListener.Connected)
                    {
                        secondStatusListener.Reset();
                        secondSession.logout();
                        secondStatusListener.WaitEvents();
                    }
                    secondSession.unsubscribeSessionStatus(secondStatusListener);
                    secondSession.Dispose();
                }
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
Beispiel #25
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();
                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));
                        }
                    }
                    else
                    {
                        if(!sampleParams.AccountID.Equals(account.AccountID))
                        {
                            sampleParams.AccountID = account.AccountID;
                            Console.WriteLine("AccountID='{0}'",
                                    sampleParams.AccountID);
                        }
                    }

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

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

                    O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        Thread.Sleep(1000); // Wait for the balance update
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }

                    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();
                }
            }
        }
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm)
 {
     Console.WriteLine("{0}", procName);
 }
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: VoiceTest.exe [firstname] [lastname] [password]");
                return;
            }

            string firstName = args[0];
            string lastName  = args[1];
            string password  = args[2];


            GridClient client = new GridClient();

            client.Settings.MULTIPLE_SIMS          = false;
            Settings.LOG_LEVEL                     = Helpers.LogLevel.None;
            client.Settings.LOG_RESENDS            = false;
            client.Settings.STORE_LAND_PATCHES     = true;
            client.Settings.ALWAYS_DECODE_OBJECTS  = true;
            client.Settings.ALWAYS_REQUEST_OBJECTS = true;
            client.Settings.SEND_AGENT_UPDATES     = true;

            string loginURI = client.Settings.LOGIN_SERVER;

            if (4 == args.Length)
            {
                loginURI = args[3];
            }

            VoiceManager voice = new VoiceManager(client);

            voice.OnProvisionAccount += voice_OnProvisionAccount;
            voice.OnParcelVoiceInfo  += voice_OnParcelVoiceInfo;

            client.Network.EventQueueRunning += client_OnEventQueueRunning;

            try {
                if (!voice.ConnectToDaemon())
                {
                    throw new VoiceException("Failed to connect to the voice daemon");
                }

                List <string> captureDevices = voice.CaptureDevices();

                Console.WriteLine("Capture Devices:");
                for (int i = 0; i < captureDevices.Count; i++)
                {
                    Console.WriteLine(String.Format("{0}. \"{1}\"", i, captureDevices[i]));
                }
                Console.WriteLine();

                List <string> renderDevices = voice.RenderDevices();

                Console.WriteLine("Render Devices:");
                for (int i = 0; i < renderDevices.Count; i++)
                {
                    Console.WriteLine(String.Format("{0}. \"{1}\"", i, renderDevices[i]));
                }
                Console.WriteLine();


                // Login
                Console.WriteLine("Logging into the grid as " + firstName + " " + lastName + "...");
                LoginParams loginParams =
                    client.Network.DefaultLoginParams(firstName, lastName, password, "Voice Test", "1.0.0");
                loginParams.URI = loginURI;
                if (!client.Network.Login(loginParams))
                {
                    throw new VoiceException("Login to SL failed: " + client.Network.LoginMessage);
                }
                Console.WriteLine("Logged in: " + client.Network.LoginMessage);


                Console.WriteLine("Creating voice connector...");
                int    status;
                string connectorHandle = voice.CreateConnector(out status);
                if (String.IsNullOrEmpty(connectorHandle))
                {
                    throw new VoiceException("Failed to create a voice connector, error code: " + status, true);
                }
                Console.WriteLine("Voice connector handle: " + connectorHandle);


                Console.WriteLine("Waiting for OnEventQueueRunning");
                if (!EventQueueRunningEvent.WaitOne(45 * 1000, false))
                {
                    throw new VoiceException("EventQueueRunning event did not occur", true);
                }
                Console.WriteLine("EventQueue running");


                Console.WriteLine("Asking the current simulator to create a provisional account...");
                if (!voice.RequestProvisionAccount())
                {
                    throw new VoiceException("Failed to request a provisional account", true);
                }
                if (!ProvisionEvent.WaitOne(120 * 1000, false))
                {
                    throw new VoiceException("Failed to create a provisional account", true);
                }
                Console.WriteLine("Provisional account created. Username: "******", Password: "******"Logging in to voice server " + voice.VoiceServer);
                string accountHandle = voice.Login(VoiceAccount, VoicePassword, connectorHandle, out status);
                if (String.IsNullOrEmpty(accountHandle))
                {
                    throw new VoiceException("Login failed, error code: " + status, true);
                }
                Console.WriteLine("Login succeeded, account handle: " + accountHandle);


                if (!voice.RequestParcelVoiceInfo())
                {
                    throw new Exception("Failed to request parcel voice info");
                }
                if (!ParcelVoiceInfoEvent.WaitOne(45 * 1000, false))
                {
                    throw new VoiceException("Failed to obtain parcel info voice", true);
                }


                Console.WriteLine("Parcel Voice Info obtained. Region name {0}, local parcel ID {1}, channel URI {2}",
                                  VoiceRegionName, VoiceLocalID, VoiceChannelURI);

                client.Network.Logout();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                if (e is VoiceException && (e as VoiceException).LoggedIn)
                {
                    client.Network.Logout();
                }
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            O2GSession            session        = null;
            SessionStatusListener statusListener = null;

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

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

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin);

                argParser.ParseArguments();

                if (!argParser.AreArgumentsValid)
                {
                    argParser.PrintUsage();
                    return;
                }

                argParser.PrintArguments();

                LoginParams loginParams = argParser.LoginParams;

                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)
                {
                    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);
                    if (account == null)
                    {
                        throw new Exception("No valid accounts");
                    }

                    PrintOrders(tableManager, account.AccountID);
                    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();
                }
            }
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;

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

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

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin,
                                       ParserArgument.Instrument,
                                       ParserArgument.BuySell,
                                       ParserArgument.OrderType,
                                       ParserArgument.Lots,
                                       ParserArgument.AccountID);

                argParser.ParseArguments();

                if (!argParser.AreArgumentsValid)
                {
                    argParser.PrintUsage();
                    return;
                }

                argParser.PrintArguments();

                LoginParams  loginParams  = argParser.LoginParams;
                SampleParams sampleParams = argParser.SampleParams;

                session        = O2GTransport.createSession();
                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;
                    double     dRate         = CalculateRate(sampleParams.OrderType, sampleParams.BuySell, offer.Ask, offer.Bid, offer.PointSize);
                    O2GRequest request       = CreateEntryOrderRequest(session, offer.OfferID, account.AccountID, iAmount, dRate, sampleParams.BuySell, sampleParams.OrderType);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request; probably some arguments are missing or incorrect");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        string sOrderID = responseListener.GetOrderID();
                        if (!string.IsNullOrEmpty(sOrderID))
                        {
                            Console.WriteLine("You have successfully created an entry order for instrument {0}", sampleParams.Instrument);
                            Console.WriteLine("Your order ID is {0}", sOrderID);
                            FindOrder(session, sOrderID, sampleParams.AccountID, responseListener);
                            Console.WriteLine("Done!");
                        }
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                }
            }
            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 #30
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: ContingencyID='{1}', OrderID='{2}', AccountID='{3}'", procName, prm.ContingencyID, prm.OrderID, prm.AccountID);
 }
Beispiel #31
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();
                SessionStatusListener statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin);
                session.subscribeSessionStatus(statusListener);
                statusListener.Reset();
                session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
                if (statusListener.WaitEvents() && statusListener.Connected)
                {
                    ResponseListener responseListener = new ResponseListener(session);
                    session.subscribeResponse(responseListener);

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

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

                    O2GLoginRules loginRules = session.getLoginRules();
                    if (loginRules == null)
                    {
                        throw new Exception("Cannot get login rules");
                    }
                    O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider();
                    int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account);
                    int iAmount = iBaseUnitSize * sampleParams.Lots;
                    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");
                    }
                    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 #32
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("PrintTable", 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)
                {
                    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);
                    if (account == null)
                    {
                        throw new Exception("No valid accounts");
                    }

                    O2GResponseType responseType = string.Equals(sampleParams.TableType, SampleParams.OrdersTable) == true ?
                                                   O2GResponseType.GetOrders : O2GResponseType.GetTrades;

                    if (responseType == O2GResponseType.GetOrders)
                    {
                        PrintOrders(tableManager, account.AccountID);
                    }
                    else
                    {
                        PrintTrades(tableManager, account.AccountID);
                    }

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

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

                PrintSampleParams("PrintTableListener", loginParams);

                session = O2GTransport.createSession();
                TableManagerListener managerListener = new TableManagerListener();
                session.useTableManager(O2GTableManagerMode.Yes, managerListener);
                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)
                {
                    O2GTableManager tableManager = session.getTableManager();
                    if (managerListener.WaitEvents() && managerListener.IsLoaded)
                    {
                        Console.WriteLine("All tables are loaded");
                    }
                    else
                    {
                        throw new Exception("Cannot refresh all tables of table manager");
                    }

                    O2GAccountRow account = GetAccount(tableManager);
                    if (account == null)
                        throw new Exception("No valid accounts");

                    managerListener.Reset();
                    O2GTableManager tableManagerByAccount = session.getTableManagerByAccount(account.AccountID);
                    if (managerListener.WaitEvents() && managerListener.IsLoaded)
                    {
                        Console.WriteLine(string.Format("All tables are loaded (account {0})", account.AccountID));
                    }
                    else
                    {
                        throw new Exception(string.Format("Cannot refresh all tables of table manager (account {0})", account.AccountID));
                    }

                    PrintOrders(tableManagerByAccount, account.AccountID);
                    Console.WriteLine("Done!");

                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvents();
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("Exception: {0}", e.ToString()));
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
Beispiel #34
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0} : Table='{1}'", procName, prm.TableType);
 }
Beispiel #35
0
        /// <summary>
        /// Begins login sequence using the parameters defined in .LoginParams
        /// </summary>
        public void Login()
        {
            if (_Client == null) return;

            if (_LoginParams.MethodName == null)
                _LoginParams = Client.Network.DefaultLoginParams("", "", "", "", "");

            SetText(btnLogin, "Logout");
            SetText(listNames, _LoginParams.FirstName + " " + _LoginParams.LastName);
            SetText(txtPass, _LoginParams.Password);

            if (LoginThread != null)
            {
                LoginThread.Abort();
                LoginThread = null;
            }
            LoginThread = new Thread(new ThreadStart(delegate() { _Client.Network.Login(_LoginParams); }));
            LoginThread.Start();
        }
Beispiel #36
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();
                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;

                    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!");
                    }
                    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 #37
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();
                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)
                {
                    TableListener tableListener = new TableListener();

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

                    tableListener.SetInstrument(sampleParams.Instrument);
                    tableListener.SubscribeEvents(tableManager);

                    O2GOffersTable offers = null;
                    offers = (O2GOffersTable)tableManager.getTable(O2GTableType.Offers);
                    tableListener.PrintOffers(offers, null);

                    // Do nothing 10 seconds, let offers print
                    Thread.Sleep(10000);

                    Console.WriteLine("Done!");

                    tableListener.UnsubscribeEvents(tableManager);

                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvents();
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
        public TestClient Login(LoginDetails account)
        {
            // Check if this client is already logged in
            foreach (TestClient c in Clients.Values)
            {
                if (c.Self.FirstName == account.FirstName && c.Self.LastName == account.LastName)
                {
                    Logout(c);
                    break;
                }
            }

            ++PendingLogins;

            TestClient client = new TestClient(this);

            client.Network.LoginProgress +=
                delegate(object sender, LoginProgressEventArgs e)
            {
                Logger.Log(String.Format("Login {0}: {1}", e.Status, e.Message), Helpers.LogLevel.Info, client);

                if (e.Status == LoginStatus.Success)
                {
                    Clients[client.Self.AgentID] = client;

                    if (client.MasterKey.IsZero())
                    {
                        UUID query = UUID.Zero;
                        EventHandler <DirPeopleReplyEventArgs> peopleDirCallback =
                            delegate(object sender2, DirPeopleReplyEventArgs dpe)
                        {
                            if (dpe.QueryID == query)
                            {
                                if (dpe.MatchedPeople.Count != 1)
                                {
                                    Logger.Log("Unable to resolve master key from " + client.MasterName, Helpers.LogLevel.Warning);
                                }
                                else
                                {
                                    client.MasterKey = dpe.MatchedPeople[0].AgentID;
                                    Logger.Log("Master key resolved to " + client.MasterKey, Helpers.LogLevel.Info);
                                }
                            }
                        };

                        client.Directory.DirPeopleReply += peopleDirCallback;
                        query = client.Directory.StartPeopleSearch(client.MasterName, 0);
                    }

                    Logger.Log("Logged in " + client.ToString(), Helpers.LogLevel.Info);
                    --PendingLogins;
                }
                else if (e.Status == LoginStatus.Failed)
                {
                    Logger.Log("Failed to login " + account.FirstName + " " + account.LastName + ": " +
                               client.Network.LoginMessage, Helpers.LogLevel.Warning);
                    --PendingLogins;
                }
            };

            // Optimize the throttle
            client.Throttle.Wind  = 0;
            client.Throttle.Cloud = 0;
            client.Throttle.Land  = 1000000;
            client.Throttle.Task  = 1000000;

            client.GroupCommands     = account.GroupCommands;
            client.MasterName        = account.MasterName;
            client.MasterKey         = account.MasterKey;
            client.AllowObjectMaster = client.MasterKey != UUID.Zero; // Require UUID for object master.

            LoginParams loginParams = client.Network.DefaultLoginParams(
                account.FirstName, account.LastName, account.Password, "TestClient", VERSION);

            if (!String.IsNullOrEmpty(account.StartLocation))
            {
                loginParams.Start = account.StartLocation;
            }

            if (!String.IsNullOrEmpty(account.URI))
            {
                loginParams.URI = account.URI;
            }

            client.Network.BeginLogin(loginParams);
            return(client);
        }
Beispiel #39
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 #40
0
        static void Main(string[] args)
        {
            O2GSession            session        = null;
            SessionStatusListener statusListener = null;

            try
            {
                ArgumentParser argParser = new ArgumentParser(args, "PrintTableListener");

                argParser.AddArguments(ParserArgument.Login,
                                       ParserArgument.Password,
                                       ParserArgument.Url,
                                       ParserArgument.Connection,
                                       ParserArgument.SessionID,
                                       ParserArgument.Pin);

                argParser.ParseArguments();

                if (!argParser.AreArgumentsValid)
                {
                    argParser.PrintUsage();
                    return;
                }

                argParser.PrintArguments();

                LoginParams loginParams = argParser.LoginParams;

                session = O2GTransport.createSession();
                TableManagerListener managerListener = new TableManagerListener();
                session.useTableManager(O2GTableManagerMode.Yes, managerListener);
                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)
                {
                    O2GTableManager tableManager = session.getTableManager();
                    if (managerListener.WaitEvents() && managerListener.IsLoaded)
                    {
                        Console.WriteLine("All tables are loaded");
                    }
                    else
                    {
                        throw new Exception("Cannot refresh all tables of table manager");
                    }

                    O2GAccountRow account = GetAccount(tableManager);
                    if (account == null)
                    {
                        throw new Exception("No valid accounts");
                    }

                    managerListener.Reset();
                    O2GTableManager tableManagerByAccount = session.getTableManagerByAccount(account.AccountID);
                    if (managerListener.WaitEvents() && managerListener.IsLoaded)
                    {
                        Console.WriteLine(string.Format("All tables are loaded (account {0})", account.AccountID));
                    }
                    else
                    {
                        throw new Exception(string.Format("Cannot refresh all tables of table manager (account {0})", account.AccountID));
                    }

                    PrintOrders(tableManagerByAccount, account.AccountID);
                    Console.WriteLine("Done!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("Exception: {0}", e.ToString()));
            }
            finally
            {
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                        session.unsubscribeSessionStatus(statusListener);
                    }
                    session.Dispose();
                }
            }
        }
Beispiel #41
0
        static void Main(string[] args)
        {
            O2GSession session = null;
            int iContingencyGroupType = 1; // OCO group

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

                PrintSampleParams("JoinNewGroup", 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;

                    O2GRequest request = JoinToNewGroupRequest(session, sampleParams.AccountID, sampleParams.PrimaryID, sampleParams.SecondaryID, iContingencyGroupType);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }

                    List<string> orderIDList = new List<string>();
                    orderIDList.Add(sampleParams.PrimaryID);
                    orderIDList.Add(sampleParams.SecondaryID);
                    foreach (string sOrderID in orderIDList)
                    {
                        if (!IsOrderExists(session, sampleParams.AccountID, sOrderID, responseListener))
                        {
                            throw new Exception(string.Format("Order '{0}' does not exist", sOrderID));
                        }
                    }
                    responseListener.SetOrderIDs(orderIDList);
                    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 #42
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 #43
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();
                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, sampleParams.Instrument);
                    if (offer == null)
                    {
                        throw new Exception(string.Format("The instrument '{0}' is not valid", sampleParams.Instrument));
                    }

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

                    double dRate;
                    double dRateStop;
                    double dRateLimit;
                    double dBid = offer.Bid;
                    double dAsk = offer.Ask;
                    double dPointSize = offer.PointSize;

                    // For the purpose of this example we will place entry order 8 pips from the current market price
                    // and attach stop and limit orders 10 pips from an entry order price
                    if (sampleParams.OrderType.Equals(Constants.Orders.LimitEntry))
                    {
                        if (sampleParams.BuySell.Equals(Constants.Buy))
                        {
                            dRate = dAsk - 8 * dPointSize;
                            dRateLimit = dRate + 10 * dPointSize;
                            dRateStop = dRate - 10 * dPointSize;
                        }
                        else
                        {
                            dRate = dBid + 8 * dPointSize;
                            dRateLimit = dRate - 10 * dPointSize;
                            dRateStop = dRate + 10 * dPointSize;
                        }
                    }
                    else
                    {
                        if (sampleParams.BuySell.Equals(Constants.Buy))
                        {
                            dRate = dAsk + 8 * dPointSize;
                            dRateLimit = dRate + 10 * dPointSize;
                            dRateStop = dRate - 10 * dPointSize;
                        }
                        else
                        {
                            dRate = dBid - 8 * dPointSize;
                            dRateLimit = dRate - 10 * dPointSize;
                            dRateStop = dRate + 10 * dPointSize;
                        }
                    }

                    tableListener.SubscribeEvents(tableManager);

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

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

                    tableListener.UnsubscribeEvents(tableManager);

                    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 #44
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("CloseAllPositions", 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;

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

                    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 #45
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

                PrintSampleParams("CreateAndFindEntry", loginParams, sampleParams);

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

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

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

                    O2GLoginRules loginRules = session.getLoginRules();
                    if (loginRules == null)
                    {
                        throw new Exception("Cannot get login rules");
                    }
                    O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider();
                    int iBaseUnitSize = tradingSettingsProvider.getBaseUnitSize(sampleParams.Instrument, account);
                    int iAmount = iBaseUnitSize * sampleParams.Lots;
                    double dRate = CalculateRate(sampleParams.OrderType, sampleParams.BuySell, offer.Ask, offer.Bid, offer.PointSize);
                    O2GRequest request = CreateEntryOrderRequest(session, offer.OfferID, account.AccountID, iAmount, dRate, sampleParams.BuySell, sampleParams.OrderType);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request; probably some arguments are missing or incorrect");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        string sOrderID = responseListener.GetOrderID();
                        if (!string.IsNullOrEmpty(sOrderID))
                        {
                            Console.WriteLine("You have successfully created an entry order for instrument {0}", sampleParams.Instrument);
                            Console.WriteLine("Your order ID is {0}", sOrderID);
                            FindOrder(session, sOrderID, sampleParams.AccountID, responseListener);
                            Console.WriteLine("Done!");
                        }
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                    statusListener.Reset();
                    session.logout();
                    statusListener.WaitEvents();
                    session.unsubscribeResponse(responseListener);
                }
                session.unsubscribeSessionStatus(statusListener);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
        }
Beispiel #46
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: OrderID='{1}', AccountID='{2}'", procName, prm.OrderID, prm.AccountID);
 }
Beispiel #47
0
        public async Task Login(LoginParams loginParameters)
        {
            await localStorage.SetItem("token", await authorizationApi.Login(loginParameters));

            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
        }
Beispiel #48
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm)
 {
     Console.WriteLine("{0}", procName);
 }
Beispiel #49
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: Instrument='{1}', BuySell='{2}', Lots='{3}', AccountID='{4}'", procName, prm.Instrument, prm.BuySell, prm.Lots, prm.AccountID);
 }
Beispiel #50
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();
                }
            }
        }
Beispiel #51
0
        static void Main(string[] args)
        {
            O2GSession session = null;

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

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

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

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

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

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

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

                PrintSampleParams("CloseAllPositionsByInstrument", 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, 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);

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

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

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

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

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

                    O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        Thread.Sleep(1000); // Wait for the balance update
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
Beispiel #55
0
        public void Login()
        {
            loggingIn = true;

            // Report crashes only once and not on relogs/reconnects
            LastExecStatus execStatus = instance.GetLastExecStatus();

            if (!instance.AnotherInstanceRunning() && execStatus != LastExecStatus.Normal && (!instance.ReportedCrash))
            {
                instance.ReportedCrash     = true;
                loginOptions.LastExecEvent = execStatus;
                Logger.Log("Reporting crash of the last application run to the grid login service", Helpers.LogLevel.Warning);
            }
            else
            {
                loginOptions.LastExecEvent = LastExecStatus.Normal;
                Logger.Log("Reporting normal shutdown of the last application run to the grid login service", Helpers.LogLevel.Info);
            }
            instance.MarkStartExecution();

            OverrideEventArgs ea = new OverrideEventArgs();

            OnClientLoggingIn(ea);

            if (ea.Cancel)
            {
                loggingIn = false;
                return;
            }

            if (string.IsNullOrEmpty(loginOptions.FirstName) ||
                string.IsNullOrEmpty(loginOptions.LastName) ||
                string.IsNullOrEmpty(loginOptions.Password))
            {
                OnClientLoginStatus(
                    new LoginProgressEventArgs(LoginStatus.Failed, "One or more fields are blank.", string.Empty));
            }

            string startLocation = string.Empty;

            switch (loginOptions.StartLocation)
            {
            case StartLocationType.Home: startLocation = "home"; break;

            case StartLocationType.Last: startLocation = "last"; break;

            case StartLocationType.Custom:
                startLocation = loginOptions.StartLocationCustom.Trim();

                StartLocationParser parser = new StartLocationParser(startLocation);
                startLocation = NetworkManager.StartLocation(parser.Sim, parser.X, parser.Y, parser.Z);

                break;
            }

            string password;

            if (LoginOptions.IsPasswordMD5(loginOptions.Password))
            {
                password = loginOptions.Password;
            }
            else
            {
                if (loginOptions.Password.Length > 16)
                {
                    password = Utils.MD5(loginOptions.Password.Substring(0, 16));
                }
                else
                {
                    password = Utils.MD5(loginOptions.Password);
                }
            }

            LoginParams loginParams = client.Network.DefaultLoginParams(
                loginOptions.FirstName, loginOptions.LastName, password,
                loginOptions.Channel, loginOptions.Version);

            grid = loginOptions.Grid;
            loginParams.Start         = startLocation;
            loginParams.AgreeToTos    = AgreeToTos;
            loginParams.URI           = grid.LoginURI;
            loginParams.LastExecEvent = loginOptions.LastExecEvent;
            client.Network.BeginLogin(loginParams);
        }
Beispiel #56
0
        static void Main(string[] args)
        {
            O2GSession            session          = null;
            SessionStatusListener statusListener   = null;
            ResponseListener      responseListener = null;

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

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

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

                    O2GRequest request = CreateTrueMarketOrderRequest(session, offer.OfferID, sampleParams.AccountID, iAmount, sampleParams.BuySell);
                    if (request == null)
                    {
                        throw new Exception("Cannot create request");
                    }
                    responseListener.SetRequestID(request.RequestID);
                    session.sendRequest(request);
                    if (responseListener.WaitEvents())
                    {
                        Thread.Sleep(1000); // Wait for the balance update
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        throw new Exception("Response waiting timeout expired");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
            finally
            {
                if (session != null)
                {
                    if (statusListener.Connected)
                    {
                        if (responseListener != null)
                        {
                            session.unsubscribeResponse(responseListener);
                        }
                        statusListener.Reset();
                        session.logout();
                        statusListener.WaitEvents();
                    }
                    session.unsubscribeSessionStatus(statusListener);
                    session.Dispose();
                }
            }
        }
Beispiel #57
0
 /// <summary>
 /// Print process name and sample parameters
 /// </summary>
 /// <param name="procName"></param>
 /// <param name="loginPrm"></param>
 /// <param name="prm"></param>
 private static void PrintSampleParams(string procName, LoginParams loginPrm, SampleParams prm)
 {
     Console.WriteLine("{0}: Instrument='{1}', RateStop='{2}', RateLimit='{3}', AccountID='{4}'", procName, prm.Instrument, prm.RateStop, prm.RateLimit, prm.AccountID);
 }
Beispiel #58
0
        // Someone wants connect.kat.
        public void OnFileRequested(HttpRequest request, IDirectory directory)
        {
            request.Response.ResponseContent = new MemoryStream();
            StreamWriter textWriter = new StreamWriter(request.Response.ResponseContent);

            try
            {
                // Grab various bits of data from the User object.
                // If we can't do that, complain.
                // While we're at it, decode the post data.
                User         user;
                GridClient   client;
                StreamReader reader  = new StreamReader(request.PostData);
                string       qstring = reader.ReadToEnd();
                reader.Dispose();
                Dictionary <string, string> POST = AjaxLife.PostDecode(qstring);
                Guid key = new Guid(POST["session"]);
                // The session doesn't exist. Get upset.
                if (!this.users.ContainsKey(key))
                {
                    this.invalidSessionID(key, textWriter);
                    return;
                }
                lock (this.users)
                {
                    user = users[key];
                }
                user.LastRequest = DateTime.Now;
                client           = user.GetClient();

                string first = "";
                string last  = "";
                string pass  = "";
                // Decrypt the incoming login data
                string decrypted = StringHelper.ASCIIBytesToString(AjaxLife.RSA.Decrypt(StringHelper.HexStringToBytes(POST["logindata"])));
                // Split it into its component parts.
                string[] data = decrypted.Split('\\');
                // Get upset if the challenge was incorrect.
                if (data[0] == null || data[0] != user.Challenge)
                {
                    throw new Exception("Invalid request.");
                }
                // Decode the login data.
                first          = StringHelper.ASCIIBytesToString(StringHelper.FromBase64(data[1]));
                last           = StringHelper.ASCIIBytesToString(StringHelper.FromBase64(data[2]));
                pass           = data[3];
                user.Signature = data[4];
                // Check if they're banned first.
                if (AjaxLife.BannedUsers.IsBanned(first, last))
                {
                    textWriter.WriteLine("{success: false, message: \"You have been banned from AjaxLife by the administrator.\"}");
                    textWriter.Flush();
                    return;
                }
                LoginParams login = client.Network.DefaultLoginParams(first, last, pass, "AjaxLife", "Katharine Berry <*****@*****.**>");
                login.Platform = "web";
                login.Channel  = "AjaxLife Release; original IP: " + request.Client.RemoteAddress;
                login.MAC      = AjaxLife.MAC_ADDRESS;
                login.ID0      = AjaxLife.ID0;
                login.Start    = (POST["location"] != "arbitrary") ? POST["location"] : NetworkManager.StartLocation(POST["sim"], 128, 128, 20);
                // Pick the correct loginuri.
                lock (AjaxLife.LOGIN_SERVERS) login.URI = AjaxLife.LOGIN_SERVERS[POST["grid"]];
                client.Settings.LOGIN_SERVER = login.URI;
                user.LindenGrid = POST["grid"].EndsWith("(Linden Lab)");
                Console.WriteLine(login.FirstName + " " + login.LastName + " is attempting to log into " + POST["grid"] + " (" + login.URI + ")");
                if (client.Network.Login(login))
                {
                    // Ensure that the challenge isn't matched by another request with the same SID.
                    // We don't do this until after successful login because otherwise a second attempt will always fail.
                    user.Challenge = null;
                    AvatarTracker avatars = new AvatarTracker(client);
                    Events        events  = new Events(user);
                    user.Events  = events;
                    user.Avatars = avatars;
                    // Register event handlers
                    this.RegisterCallbacks(user);
                    // Pythagoras says that 181.0193m is the optimal view distance to see the whole sim.
                    client.Self.Movement.Camera.Far = 181.0193f;

                    // This doesn't seem to work.
                    // client.Self.Movement.Camera.SetPositionOrientation(new Vector3(128, 128, 0), 0, 0, 0);

                    // Everything's happy. Log the requested message list, if any.
                    if (POST.ContainsKey("events"))
                    {
                        user.ParseRequestedEvents(POST["events"]);
                    }

                    // If we got this far, it worked. Announce this.
                    textWriter.WriteLine("{\"success\": 1}");
                }
                else
                {
                    // Return whatever errors may have transpired.
                    textWriter.WriteLine("{success: false, message: " + AjaxLife.StringToJSON(client.Network.LoginMessage) + "}");
                }
            }
            catch (Exception exception)
            {
                request.Response.ContentType = "text/plain";
                textWriter.WriteLine(exception.Message);
            }
            textWriter.Flush();
        }