public WalletError UnsubscribeFromTradeSignal(string hash, string userLogin, long localTime, int serviceId)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        return(WalletError.AuthenticationError);
                    }

                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        return(WalletError.AuthenticationError);
                    }

                    WalletError error;
                    walletRepository.SubscribeOnService(ctx, user.ID, serviceId, false, true,
                                                        new AutoTradeSettings(), out error);
                    return(error);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error in UnsubscribeFromTradeSignal()", ex);
                return(WalletError.ServerError);
            }
        }
        public string AuthoriseUserWithAccountDetail(string userLogin, string password, long localTime,
                                                     out Account[] userAccounts)
        {
            userAccounts = new Account[0];
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin && u.Password == password);
                    if (user == null)
                    {
                        return(string.Empty);
                    }

                    var hash = CredentialsHash.MakeCredentialsHash(userLogin, password, localTime);
                    userAccounts = ctx.PLATFORM_USER_ACCOUNT.Where(pa => pa.PlatformUser == user.ID).Select(pa =>
                                                                                                            pa.ACCOUNT1).ToArray().Select(LinqToEntity.DecorateAccount).ToArray();
                    return(hash);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("AuthoriseUserWithAccountDetail", ex);
                return(string.Empty);
            }
        }
        public RequestStatus UnsubscribePortfolio(string hash, string userLogin, long localTime,
                                                  bool deleteSubscriptions)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        return(RequestStatus.Unauthorized);
                    }

                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        return(RequestStatus.Unauthorized);
                    }

                    Logger.InfoFormat("UnsubscribePortfolio({0}) in progress", userLogin);

                    return(walletRepository.UnsubscribeUserFromPortfolio(ctx, userLogin, true, deleteSubscriptions));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в UnsubscribePortfolio()", ex);
                return(RequestStatus.ServerError);
            }
        }
        public Wallet GetUserWalletSubscriptionAndLastPayments(string hash, string userLogin,
                                                               long localTime, int maxPaymentsQuery,
                                                               out int paymentsTotalCount, out List <Subscription> subscriptions,
                                                               out List <Transfer> transfers, out WalletError error)
        {
            paymentsTotalCount = 0;
            subscriptions      = null;
            transfers          = null;

            PLATFORM_USER user;

            using (var ctx = DatabaseContext.Instance.Make())
            {
                user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                if (user == null)
                {
                    error = WalletError.AuthenticationError;
                    return(null);
                }
            }

            var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);

            if (hash != userHash)
            {
                error = WalletError.AuthenticationError;
                return(null);
            }

            return(walletRepository.GetUserWalletSubscriptionAndLastPaymentsInner(userLogin, maxPaymentsQuery,
                                                                                  out paymentsTotalCount, out subscriptions,
                                                                                  out transfers, out error));
        }
        public void TestGetClosedOrders()
        {
            var account = conn.ACCOUNT.First(a => a.POSITION_CLOSED.Count > 50);
            var ownerId = account.PLATFORM_USER_ACCOUNT.First().PlatformUser;
            var user    = conn.PLATFORM_USER.First(u => u.ID == ownerId);

            const long magic = 1;
            var        hash  = CredentialsHash.MakeCredentialsHash(user.Login, user.Password, magic);

            var orders = platformManager.GetClosedOrders(hash, user.Login, magic, account.ID,
                                                         string.Empty, 0, 45);

            Assert.IsNotNull(orders, "GetClosedOrders - список ордеров не должен быть null");
            Assert.AreEqual(45, orders.Count, "GetClosedOrders - список ордеров должен содержать 45 значений (45 запрошено)");

            var totalOrdersInDbCount = account.POSITION_CLOSED.Count;

            orders = platformManager.GetClosedOrders(hash, user.Login, magic, account.ID,
                                                     string.Empty, orders[orders.Count - 1].ID, 100000);
            var totalCount = orders.Count + 45;

            Assert.AreEqual(totalOrdersInDbCount, totalCount,
                            "GetClosedOrders - список ордеров должен содержать все значения после 2-го запроса");

            var ticker = orders[1].Symbol;
            var ordersByTickerCount = account.POSITION_CLOSED.Count(a => a.Symbol == ticker);

            orders = platformManager.GetClosedOrders(hash, user.Login, magic, account.ID,
                                                     ticker, 0, 100000);
            Assert.AreEqual(ordersByTickerCount, orders.Count, "GetClosedOrders - количество ордеров " + ticker +
                            " должно совпадать");
        }
        private RequestStatus GetUserSubscribedCats(TradeSharpConnection ctx,
                                                    string userLogin, string hash, long localTime,
                                                    out List <Subscription> categories)
        {
            categories = new List <Subscription>();
            try
            {
                var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                if (user == null)
                {
                    return(RequestStatus.Unauthorized);
                }

                var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                if (userHash != hash)
                {
                    return(RequestStatus.Unauthorized);
                }

                // получить подписку на торг. сигналы и собственные сигналы пользователя
                categories = (from uc in ctx.SUBSCRIPTION_V
                              where uc.User == user.ID
                              select uc).ToList().Select(LinqToEntity.DecorateSubscription).ToList();
                return(RequestStatus.OK);
            }
            catch (Exception ex)
            {
                Logger.Error("Error in GetUserSubscribedCats()", ex);
                return(RequestStatus.ServerError);
            }
        }
        public string LoadUserSettingsString(string hash, string userLogin, long localTime)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        return(string.Empty);
                    }

                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        return(string.Empty);
                    }

                    return(userSettingsStorage.LoadUserSettings(user.ID));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в LoadUserSettingsString()", ex);
            }
            return(string.Empty);
        }
        public Account GetAccountDetail(string hash, string userLogin, long localTime,
                                        int accountId, bool calculateEquity,
                                        out decimal brokerLeverage, out decimal exposure)
        {
            brokerLeverage = 0;
            exposure       = 0;

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        return(null);
                    }

                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        return(null);
                    }

                    // авторизован?
                    if (!PlatformUser.IsManager(user.RoleMask) && !PlatformUser.IsAdmin(user.RoleMask))
                    {
                        if (!ctx.PLATFORM_USER_ACCOUNT.Any(pa => pa.PlatformUser == user.ID && pa.Account == accountId))
                        {
                            return(null);
                        }
                    }

                    var account = LinqToEntity.DecorateAccount(ctx.ACCOUNT.First(a => a.ID == accountId));
                    if (!calculateEquity)
                    {
                        return(account);
                    }

                    // получить открытые ордера по счету
                    var orders = ctx.POSITION.Where(p => p.AccountID == accountId && p.State ==
                                                    (int)PositionState.Opened).ToList().Select(LinqToEntity.DecorateOrder).ToList();

                    // посчитать открытый результат и экспозицию в валюте депо
                    var quotes = QuoteStorage.Instance.ReceiveAllData();
                    var errors = new List <string>();
                    exposure = DalSpot.Instance.CalculateExposure(orders, quotes, account.Currency, errors);
                    var group = ctx.ACCOUNT_GROUP.First(g => g.Code == account.Group);
                    brokerLeverage     = group.BrokerLeverage;
                    account.UsedMargin = exposure / brokerLeverage;
                    return(account);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в GetAccountDetail()", ex);
                return(null);
            }
        }
        public List <Account> GetUserAccounts(string hash, string userLogin, long localTime, out RequestStatus error)
        {
            var accounts = new List <Account>();

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        error = RequestStatus.Unauthorized;
                        return(accounts);
                    }

                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        error = RequestStatus.Unauthorized;
                        return(accounts);
                    }

                    // получить счета пользователя
                    var query = from pa in ctx.PLATFORM_USER_ACCOUNT
                                join ac in ctx.ACCOUNT on pa.Account equals ac.ID
                                where pa.RightsMask == (int)AccountRights.Управление && pa.PlatformUser == user.ID
                                select new Account
                    {
                        ID          = ac.ID,
                        Group       = ac.AccountGroup,
                        Balance     = ac.Balance,
                        Currency    = ac.Currency,
                        MaxLeverage = (float)ac.MaxLeverage,
                        Status      = (Account.AccountStatus)ac.Status
                    };
                    // ReSharper disable LoopCanBeConvertedToQuery
                    foreach (var ac in query)
                    {
                        accounts.Add(ac);
                    }
                    // ReSharper restore LoopCanBeConvertedToQuery
                    error = RequestStatus.OK;
                    return(accounts);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error in GetUserAccounts()", ex);
                error = RequestStatus.ServerError;
                return(accounts);
            }
        }
Beispiel #10
0
        public bool Authenticate(string login, string password,
                                 out AuthenticationResponse response, out string authStatusString)
        {
            AccountStatus.Instance.connectionStatus = AccountConnectionStatus.NotConnected;
            AccountStatus.Instance.Login            = login;
            try
            {
                var localTime = DateTime.Now.Ticks;
                var hash      = CredentialsHash.MakeCredentialsHash(login, password, localTime);
                int sessionTag;
                response = serverProxyTrade.proxy.Authenticate(login, hash, terminalVersion,
                                                               UserSettings.Instance.TerminalId, localTime,
                                                               out sessionTag);
                // обновить контекст безопасности
                if (response == AuthenticationResponse.OK)
                {
                    CurrentProtectedContext.Instance.OnAuthenticated(sessionTag);
                }
                else
                {
                    CurrentProtectedContext.Instance.OnAuthenticateFaulted();
                }
            }
            catch (Exception ex)
            {
                response = AuthenticationResponse.ServerError;
                Logger.ErrorFormat("Ошибка аутентификации {0}", ex);
                authStatusString = EnumFriendlyName <AuthenticationResponse> .GetString(response);

                AccountStatus.Instance.connectionStatus = AccountConnectionStatus.ConnectionError;
                AccountStatus.Instance.isAuthorized     = false;
                return(false);
            }
            authStatusString = EnumFriendlyName <AuthenticationResponse> .GetString(response);

            if (new[] { AuthenticationResponse.AccountInactive, AuthenticationResponse.InvalidAccount,
                        AuthenticationResponse.ServerError, AuthenticationResponse.WrongPassword, AuthenticationResponse.NotAuthorized }.Contains(response))
            {
                AccountStatus.Instance.isAuthorized     = false;
                AccountStatus.Instance.connectionStatus = AccountConnectionStatus.ConnectionError;
                return(false);
            }

            // аутентификация успешна
            MainWindowTitle.Instance.UserTitle      = login;
            AccountStatus.Instance.connectionStatus = AccountConnectionStatus.Connected;
            AccountStatus.Instance.isAuthorized     = true;
            authStatusString = "Connected";
            // выполнить ряд действий, доступных после подключения
            OnAuthenticated();
            return(true);
        }
        public WalletError SubscribeOnTradeSignal(
            string hash, string userLogin, long localTime, int serviceId,
            bool tradeAuto, bool enableHedgingOrders, int percentLeverage,
            int maxVolume, int minVolume,
            int volumeStep, double maxLeverage)
        {
            var tradeSets = new AutoTradeSettings
            {
                TradeAuto            = tradeAuto,
                HedgingOrdersEnabled = enableHedgingOrders,
                PercentLeverage      = percentLeverage,
                MaxVolume            = maxVolume,
                MinVolume            = minVolume,
                StepVolume           = volumeStep,
                MaxLeverage          = maxLeverage
            };

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        Logger.InfoFormat("PlatformManager.SubscribeOnTradeSignal(usr={0} not found)",
                                          userLogin);
                        return(WalletError.InvalidData);
                    }
                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        return(WalletError.AuthenticationError);
                    }

                    WalletError error;
                    walletRepository.SubscribeOnService(ctx, user.ID, serviceId, true,
                                                        false, tradeSets, out error);
                    if (error != WalletError.OK)
                    {
                        Logger.InfoFormat("PlatformManager.SubscribeOnTradeSignal(usr={0}, login={1}, srv={2}): {3}",
                                          user.ID, userLogin, serviceId, error);
                    }
                    return(error);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error in SubscribeOnTradeSignal()", ex);
                return(WalletError.ServerError);
            }
        }
        public void TestGetUserAccounts()
        {
            var usr  = conn.PLATFORM_USER.First(u => u.PLATFORM_USER_ACCOUNT.Count > 1);
            var hash = CredentialsHash.MakeCredentialsHash(usr.Login, usr.Password, 100);

            RequestStatus status;
            var           accounts = platformManager.GetUserAccounts(hash, usr.Login, 100, out status);

            Assert.AreEqual(RequestStatus.OK, status, "GetUserAccounts() - не отработал");
            Assert.AreEqual(usr.PLATFORM_USER_ACCOUNT.Count, accounts.Count(a => a.ID > 0),
                            "GetUserAccounts() - не вернул нужное количество счетов");
            platformManager.GetUserAccounts(hash + "X", usr.Login, 100, out status);
            Assert.AreEqual(status, RequestStatus.Unauthorized, "GetUserAccounts(wrong hash) - не должен отработать отработать");
        }
        public void TestGetOpenOrders()
        {
            var account = conn.ACCOUNT.First(a => a.POSITION.Count > 1);
            var ownerId = account.PLATFORM_USER_ACCOUNT.First().PlatformUser;
            var user    = conn.PLATFORM_USER.First(u => u.ID == ownerId);

            const long magic = 1;
            var        hash  = CredentialsHash.MakeCredentialsHash(user.Login, user.Password, magic);

            var orders = platformManager.GetOpenOrdersByAccount(hash, user.Login, magic, account.ID,
                                                                string.Empty, 0, 10);

            Assert.IsNotNull(orders, "GetOpenOrdersByAccount - список ордеров не должен быть null");
            Assert.Greater(orders.Count, 1, "GetOpenOrdersByAccount - список ордеров должен содержать 45 значений (45 запрошено)");
        }
        public void TestGetAccountDetail()
        {
            var account = conn.ACCOUNT.First(a => a.POSITION.Count > 1);
            var group   = conn.ACCOUNT_GROUP.First(g => g.Code == account.AccountGroup);
            var ownerId = account.PLATFORM_USER_ACCOUNT.First().PlatformUser;
            var user    = conn.PLATFORM_USER.First(u => u.ID == ownerId);

            const long magic = 1;
            var        hash  = CredentialsHash.MakeCredentialsHash(user.Login, user.Password, magic);

            decimal brokerLeverage, exposure;
            var     accountResulted = platformManager.GetAccountDetail(hash, user.Login, magic, account.ID, true,
                                                                       out brokerLeverage, out exposure);

            Assert.IsNotNull(accountResulted, "GetAccountDetail - счет не должен быть null");
            Assert.AreEqual(group.BrokerLeverage, brokerLeverage, "GetAccountDetail - плечо брокера определено неверно");
            Assert.Greater(exposure, 0, "GetAccountDetail - экспозиция должна быть больше 0");
        }
Beispiel #15
0
        public List <MarketOrder> GetClosedOrOpenedOrdersCheckCredentials(string hash, string userLogin, long localTime,
                                                                          int accountId, string optionalSymbolFilter, int startId, int maxCount, bool checkCredentials,
                                                                          bool needClosedOrders)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    if (checkCredentials)
                    {
                        var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                        if (user == null)
                        {
                            return(null);
                        }

                        var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                        if (userHash != hash)
                        {
                            return(null);
                        }

                        if (!ctx.PLATFORM_USER_ACCOUNT.Any(pa => pa.PlatformUser == user.ID && pa.Account == accountId))
                        {
                            return(null);
                        }
                    }

                    return(needClosedOrders
                               ? ctx.POSITION_CLOSED.Where(p => p.AccountID == accountId && p.ID > startId &&
                                                           (string.IsNullOrEmpty(optionalSymbolFilter) || p.Symbol == optionalSymbolFilter)).OrderBy(p =>
                                                                                                                                                     p.ID).Take(maxCount).ToList().Select(LinqToEntity.DecorateOrder).ToList()
                               : ctx.POSITION.Where(p => p.AccountID == accountId && p.ID > startId &&
                                                    (string.IsNullOrEmpty(optionalSymbolFilter) || p.Symbol == optionalSymbolFilter)).OrderBy(p =>
                                                                                                                                              p.ID).Take(maxCount).ToList().Select(LinqToEntity.DecorateOrder).ToList());
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в GetClosedOrOpenedOrdersCheckCredentials()", ex);
                return(null);
            }
        }
        private RequestStatus SubscribeOnUserOrCustomPortfolio(string hash, string userLogin, long localTime,
                                                               TopPortfolio portfolio,
                                                               AutoTradeSettings tradeAutoSettings)
        {
            if (portfolio == null)
            {
                Logger.Error("SubscribeOnUserOrCustomPortfolio(null)");
                return(RequestStatus.BadRequest);
            }

            Logger.InfoFormat("SubscribeOnUserOrCustomPortfolio({0}, портфель {1})", userLogin,
                              portfolio.Id > 0 ? "#" + portfolio.Id : portfolio.Criteria);
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        return(RequestStatus.Unauthorized);
                    }

                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        return(RequestStatus.Unauthorized);
                    }

                    var status = walletRepository.SubscribeUserOnPortfolio(ctx, userLogin, portfolio, null, tradeAutoSettings);
                    if (status != RequestStatus.OK)
                    {
                        Logger.Info("SubscribeOnUserOrCustomPortfolio: status: " + status);
                    }
                    return(status);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в SubscribeOnUserOrCustomPortfolio()", ex);
                return(RequestStatus.ServerError);
            }
        }
        private RequestStatus CheckCredentials(string hash, string userLogin, long localTime, int accountId, bool checkTradeRights,
                                               TradeSharpConnection connection = null)
        {
            try
            {
                var ctx = connection ?? DatabaseContext.Instance.Make();
                try
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        return(RequestStatus.IncorrectData);
                    }

                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        return(RequestStatus.IncorrectData);
                    }

                    if (!ctx.PLATFORM_USER_ACCOUNT.Any(pa => pa.PlatformUser == user.ID && pa.Account == accountId &&
                                                       (!checkTradeRights ||
                                                        pa.RightsMask == (int)AccountRights.Управление)))
                    {
                        return(RequestStatus.Unauthorized);
                    }
                }
                finally
                {
                    if (connection == null)
                    {
                        ctx.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в CheckCredentials()", ex);
                return(RequestStatus.ServerError);
            }
            return(RequestStatus.OK);
        }
        public void TestClosePosition()
        {
            var account = conn.ACCOUNT.First(a => a.POSITION.Any());
            var ownerId = account.PLATFORM_USER_ACCOUNT.First().PlatformUser;
            var user    = conn.PLATFORM_USER.First(u => u.ID == ownerId);
            var pos     = conn.POSITION.First(p => p.AccountID == account.ID);

            const long localTime = 13;
            var        hash      = CredentialsHash.MakeCredentialsHash(user.Login, user.Password, localTime);
            var        status    = platformManager.ClosePosition(hash, user.Login, localTime,
                                                                 account.ID, pos.ID);
            // попытка закрыть ордер может не пройти - торговый контекст не настроен
            var isOk = status == RequestStatus.GroupUnsupported || status == RequestStatus.OK;

            Assert.IsTrue(isOk, "ClosePosition - должно быть ОК || (GroupUnsupported)");

            status = platformManager.ClosePosition(hash, user.Login, localTime,
                                                   account.ID + 1, pos.ID);
            Assert.AreEqual(RequestStatus.NotFound, status, "ClosePosition - должно быть NotFound");
        }
        public void TestOpenPosition()
        {
            var account = conn.ACCOUNT.First(a => a.POSITION.Any());
            var ownerId = account.PLATFORM_USER_ACCOUNT.First().PlatformUser;
            var user    = conn.PLATFORM_USER.First(u => u.ID == ownerId);
            var pos     = conn.POSITION.First(p => p.AccountID == account.ID);

            const long localTime = 13;
            var        hash      = CredentialsHash.MakeCredentialsHash(user.Login, user.Password, localTime);
            var        status    = platformManager.EditPosition(hash, user.Login, localTime,
                                                                account.ID, pos.ID, (float)(pos.Stoploss ?? 0),
                                                                (float)pos.PriceEnter + pos.Side * 0.009f, 0, "comment");
            // попытка редактировать ордер может не пройти - торговый контекст не настроен
            var isOk = status == RequestStatus.GroupUnsupported || status == RequestStatus.OK;

            Assert.IsTrue(isOk, "EditPosition - должно быть ОК || (GroupUnsupported)");

            status = platformManager.EditPosition(hash, user.Login, localTime,
                                                  account.ID + 1, pos.ID, (float)(pos.Stoploss ?? 0),
                                                  (float)pos.PriceEnter + pos.Side * 0.009f, 0, "comment");
            Assert.AreEqual(RequestStatus.IncorrectData, status, "EditPosition - должно быть IncorrectData");
        }
        public string AuthoriseUser(string userLogin, string password, long localTime)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin && u.Password == password);
                    if (user == null)
                    {
                        return(string.Empty);
                    }

                    var hash = CredentialsHash.MakeCredentialsHash(userLogin, password, localTime);
                    return(hash);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("AuthoriseUser", ex);
                return(string.Empty);
            }
        }
 public PlatformUser GetUserFullInfo(string hash, string userLogin, long localTime, out List <Account> accounts)
 {
     using (var ctx = DatabaseContext.Instance.Make())
     {
         var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
         if (user == null)
         {
             accounts = null;
             return(null);
         }
         var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
         if (hash != userHash)
         {
             accounts = null;
             return(null);
         }
         accounts =
             (from pua in ctx.PLATFORM_USER_ACCOUNT where pua.PlatformUser == user.ID select pua.ACCOUNT1).ToList
                 ().Select(LinqToEntity.DecorateAccount).ToList();
         return(LinqToEntity.DecoratePlatformUser(user));
     }
 }
        public void TestGetTickersTraded()
        {
            var account = conn.ACCOUNT.First(a => a.POSITION.Any() && a.POSITION_CLOSED.Any());
            var ownerId = account.PLATFORM_USER_ACCOUNT.First().PlatformUser;
            var user    = conn.PLATFORM_USER.First(u => u.ID == ownerId);

            const long magic = 1;
            var        hash  = CredentialsHash.MakeCredentialsHash(user.Login, user.Password, magic);

            var tickers = platformManager.GetTickersTraded(hash, user.Login, account.ID, magic);

            Assert.IsNotNull(tickers, "GetTickersTraded - список тикеров не должен быть null");
            Assert.Greater(tickers.Count, 1, "GetTickersTraded - торгуемые инструменты получены");

            tickers = platformManager.GetTickersTraded(hash + "x", user.Login, account.ID, magic);
            Assert.IsNull(tickers, "GetTickersTraded - список тикеров таки должен быть null - хеш не подходит");

            account = conn.ACCOUNT.First(a => a.POSITION.Any() && a.POSITION_CLOSED.Any() &&
                                         a.PLATFORM_USER_ACCOUNT.All(pa => pa.PlatformUser != user.ID));

            tickers = platformManager.GetTickersTraded(hash, user.Login, account.ID, magic);
            Assert.IsNull(tickers, "GetTickersTraded - список тикеров должен быть null - не тот пользователь");
        }
        public void TestGetUserPortfolioAndSubscriptions()
        {
            var        user  = conn.PLATFORM_USER.First(u => u.SUBSCRIPTION.Count > 1 && u.USER_TOP_PORTFOLIO.Count == 1);
            const long magic = 1;
            var        hash  = CredentialsHash.MakeCredentialsHash(user.Login, user.Password, magic);

            List <Contract.Entity.Subscription> subscriptions;
            TopPortfolio portfolio;
            var          status = platformManager.GetUserPortfolioAndSubscriptions(hash, user.Login, magic, out subscriptions, out portfolio);

            Assert.AreEqual(RequestStatus.OK, status, "GetUserPortfolioAndSubscriptions() - завершен успешно");
            var userSubsCount = conn.SUBSCRIPTION.Count(s => s.User == user.ID);

            // !! тест невозможен из-за обращения к VIEW
            //Assert.AreEqual(userSubsCount, subscriptions.Count(s => s.User == user.ID), "GetUserPortfolioAndSubscriptions() - получены все подписки");
            Assert.IsNotNull(portfolio, "GetUserPortfolioAndSubscriptions() - портфель получен");
            var portfolioOrig = conn.TOP_PORTFOLIO.First(p => p.USER_TOP_PORTFOLIO.Any(u => u.User == user.ID));

            Assert.AreEqual(portfolioOrig.Criteria, portfolio.Criteria, "GetUserPortfolioAndSubscriptions() - портфель прочитан верно");

            status = platformManager.GetUserPortfolioAndSubscriptions("wrongHash", user.Login, magic, out subscriptions, out portfolio);
            Assert.AreEqual(RequestStatus.Unauthorized, status, "GetUserPortfolioAndSubscriptions() - левая авторизация не прошла");
        }
Beispiel #24
0
        public List <string> GetTickersTradedCheckCredentials(string hash, string userLogin, int accountId,
                                                              long localTime, bool checkCredentials)
        {
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    if (checkCredentials)
                    {
                        var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                        if (user == null)
                        {
                            return(null);
                        }

                        var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                        if (userHash != hash)
                        {
                            return(null);
                        }

                        if (!ctx.PLATFORM_USER_ACCOUNT.Any(pa => pa.PlatformUser == user.ID && pa.Account == accountId))
                        {
                            return(null);
                        }
                    }

                    return(ctx.POSITION.Where(p => p.AccountID == accountId).Select(p => p.Symbol).Distinct().Union(
                               ctx.POSITION_CLOSED.Where(p => p.AccountID == accountId).Select(p => p.Symbol).Distinct()).ToList());
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в GetTickersTraded()", ex);
                return(null);
            }
        }
Beispiel #25
0
 public static string CheckCredentials(FarmAccountArg e)
 {
     try
     {
         var proxyTrade = new TradeSharpServerTrade(new TradeServerCallbackProcessor());
         var localTime  = DateTime.Now.Ticks;
         var hash       = CredentialsHash.MakeCredentialsHash(e.Login, e.Password, localTime);
         int sessionTag;
         var response = proxyTrade.proxy.Authenticate(e.Login, hash, "robot_farm",
                                                      TestTerminalId, localTime, out sessionTag);
         if (response != AuthenticationResponse.OK)
         {
             return(EnumFriendlyName <AuthenticationResponse> .GetString(response));
         }
         Account account;
         var     status = TradeSharpAccount.Instance.proxy.GetAccountInfo(e.AccountId, false, out account);
         // !! logout here
         return(EnumFriendlyName <RequestStatus> .GetString(status));
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
        public bool SetBalance(string hash, string userLogin, long localTime,
                               int accountId, decimal newBalance, string comment, out string errorString)
        {
            errorString = string.Empty;
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        errorString = "Unauthorised (not found)";
                        return(false);
                    }

                    var userHash = CredentialsHash.MakeCredentialsHash(userLogin, user.Password, localTime);
                    if (userHash != hash)
                    {
                        errorString = "Unauthorised (wrong credentials)";
                        return(false);
                    }

                    if (!PlatformUser.IsAdmin(user.RoleMask) &&
                        !PlatformUser.IsManager(user.RoleMask))
                    {
                        errorString = "Unauthorised (insufficient rights)";
                        return(false);
                    }

                    var account = ctx.ACCOUNT.FirstOrDefault(a => a.ID == accountId);
                    if (account == null)
                    {
                        errorString = "Account " + accountId + " was not found";
                        return(false);
                    }

                    var delta = newBalance - account.Balance;
                    if (delta == 0)
                    {
                        return(true);
                    }

                    // сформировать транзакцию и поправить баланс
                    var sign   = Math.Sign(delta);
                    var amount = Math.Abs(delta);
                    var trans  = new BALANCE_CHANGE
                    {
                        AccountID   = accountId,
                        ChangeType  = sign > 0 ? (int)BalanceChangeType.Deposit : (int)BalanceChangeType.Withdrawal,
                        Amount      = amount,
                        ValueDate   = DateTime.Now,
                        Description = comment
                    };
                    account.Balance = newBalance;
                    ctx.BALANCE_CHANGE.Add(trans);
                    ctx.SaveChanges();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в SetBalance()", ex);
            }
            return(false);
        }
Beispiel #27
0
 public static string GetUserHash(string login, string pwrd, long magic)
 {
     return(CredentialsHash.MakeCredentialsHash(login, pwrd, magic));
 }
Beispiel #28
0
        public bool SetupLiveContext()
        {
            context          = null;
            protectedContext = new CurrentProtectedContext();

            try
            {
                protectedContext.Initialize(TerminalId);
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка инициализации защищенного контекста", ex);
                throw;
            }

            // создать объект proxy
            try
            {
                if (proxyTrade == null)
                {
                    proxyTrade = new TradeSharpServerTrade(callbackProcessor);
                }
            }
            catch (Exception ex)
            {
                RobotFarm.Instance.AppendLogMessage("Ошибка создания TradeSharpServerTrade: " + ex);
                return(false);
            }

            // залогиниться и
            // получить актуальную информацию по счету
            Account account;

            try
            {
                var localTime = DateTime.Now.Ticks;
                var hash      = CredentialsHash.MakeCredentialsHash(UserLogin, UserPassword, localTime);
                int sessionTag;
                var response = proxyTrade.proxy.Authenticate(UserLogin, hash,
                                                             TerminalVersionString, TerminalId, localTime, out sessionTag);
                if (response != AuthenticationResponse.OK)
                {
                    protectedContext.OnAuthenticateFaulted();
                    RobotFarm.Instance.AppendLogMessage(string.Format("Ошибка аутентификации ({0}-{1}): {2}",
                                                                      UserLogin, UserPassword, response));
                    return(false);
                }
                protectedContext.OnAuthenticated(sessionTag);

                var opRst = TradeSharpAccount.Instance.proxy.GetAccountInfo(AccountId, false, out account);
                if (account == null)
                {
                    RobotFarm.Instance.AppendLogMessage(string.Format("Невозможно получить информацию по счету {0}: {1}",
                                                                      AccountId, opRst));
                    return(false);
                }
                Logger.InfoFormat("User {0} authenticated on #{1}", UserLogin, AccountId);
            }
            catch (Exception ex)
            {
                RobotFarm.Instance.AppendLogMessage(
                    string.Format("Ошибка аутентификации ({0}-{1}): {2}",
                                  UserLogin, UserPassword, ex));
                return(false);
            }

            // инициализировать киборгов
            var countSuccess = robots == null ? 0 : robots.Count;

            if (robots != null && robots.Count > 0)
            {
                // контекст для роботов
                context = new RobotContextLiveFarm(proxyTrade, account, () => UserLogin, accountData,
                                                   () =>
                {
                    return(robots.SelectMany(r => r.Graphics).Distinct().ToList());
                })
                {
                    robotContextMode = RobotContext.ContextMode.Realtime
                };
                context.OnRobotMessage += (robot, time, messages) =>
                {
                    foreach (var msg in messages)
                    {
                        RobotFarm.Instance.AppendLogMessage(
                            "#" + AccountId + ": [" +
                            robot.GetUniqueName() + "] said \"" + msg + "\"");
                    }
                };

                // включить каждого робота в контекст
                foreach (var robot in robots)
                {
                    try
                    {
                        robot.Initialize(context, protectedContext);
                        context.SubscribeRobot(robot);
                    }
                    catch (Exception ex)
                    {
                        countSuccess--;
                        RobotFarm.Instance.AppendLogMessage("Ошибка инициализации робота " +
                                                            robot.GetUniqueName() + ": " + ex);
                    }
                }
            }

            // создать объект - обработчик торговых сигалов
            callbackProcessor.SignalProcessor = new TradeSignalProcessor(
                () => accountData.GetActualAccount(true),
                s => RobotFarm.Instance.AppendLogMessage(s),
                () => accountData.GetActualOrderList(),
                () => VolumeRoundType.Ближайшее,
                proxyTrade.proxy, protectedContext, this);

            return((robots == null || robots.Count <= 0) || countSuccess > 0);
        }
Beispiel #29
0
        /// <summary>
        /// вернуть тег сессии клиента, передаваемый затем в последующих запросах
        /// </summary>
        public AuthenticationResponse Authenticate(string login, string hashString,
                                                   string terminalVersion,
                                                   long clientLocalTime, long terminalId, string address, ITradeSharpServerCallback callback,
                                                   out int sessionTag)
        {
            sessionTag = 0;

            // проверка параметров
            if (string.IsNullOrEmpty(login))
            {
                return(AuthenticationResponse.InvalidAccount);
            }
            if (string.IsNullOrEmpty(hashString))
            {
                return(AuthenticationResponse.WrongPassword);
            }
            if (terminalId == 0)
            {
                Logger.Info("AuthenticationResponse usr (" + login + "): terminal Id is 0");
                return(AuthenticationResponse.InvalidAccount);
            }
            if (clientLocalTime == 0)
            {
                Logger.Info("AuthenticationResponse usr (" + login + "): clientLocalTime is 0");
                return(AuthenticationResponse.InvalidAccount);
            }

            // получить пользователя и его роль по логину
            string password;
            int    userId;
            var    response = CheckCredentials(login, out password, out userId);

            if (response != AuthenticationResponse.OK)
            {
                return(response);
            }

            // проверить хеш из логина, пароля и локального времени клиента
            var userHash = CredentialsHash.MakeCredentialsHash(login, password, clientLocalTime);

            if (hashString != userHash)
            {
                return(AuthenticationResponse.WrongPassword);
            }

            // проверить наличие сессии
            try
            {
                sessionLocker.AcquireWriterLock(SessionLockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("Authenticate - unable to get writer lock to session storage");
                return(AuthenticationResponse.ServerError);
            }
            try
            {
                UserSession session;
                sessions.TryGetValue(terminalId, out session);
                // сессия еще жива
                if (session != null)
                {
                    session.lastRequestClientTime = clientLocalTime;
                    session.callback        = callback;
                    sessionTag              = session.sessionTag;
                    session.enabledAccounts = GetUserAccounts(userId);
                    return(AuthenticationResponse.OK);
                }
                // создать новую сессию
                session = new UserSession
                {
                    ip = address,
                    lastRequestClientTime = clientLocalTime,
                    login           = login,
                    loginTime       = DateTime.Now,
                    sessionTag      = (int)(DateTime.Now.Ticks / 3),
                    terminalId      = terminalId,
                    callback        = callback,
                    enabledAccounts = GetUserAccounts(userId),
                    terminalVersion = terminalVersion,
                    userId          = userId
                };
                sessions.Add(terminalId, session);
                sessionTag = session.sessionTag;
                return(AuthenticationResponse.OK);
            }
            catch (Exception ex)
            {
                Logger.Error("UserSessionStorage - error in Authenticate", ex);
                return(AuthenticationResponse.ServerError);
            }
            finally
            {
                sessionLocker.ReleaseWriterLock();
            }
        }