Пример #1
0
        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);
            }
        }
Пример #2
0
        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);
            }
        }
Пример #3
0
        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));
        }
Пример #4
0
        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);
        }
Пример #5
0
        /// <summary>
        /// клиент выполнил логаут
        /// </summary>
        public void Logout(ProtectedOperationContext ctx)
        {
            // проверить контекст
            var userHash = CredentialsHash.MakeOperationParamsHash(ctx.clientLocalTime, ctx.sessionTag, ctx.terminalId);

            if (ctx.hash != userHash)
            {
                return;
            }

            // найти сессию
            try
            {
                sessionLocker.AcquireWriterLock(SessionLockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("Logout read timout");
                return;
            }
            try
            {
                sessions.Remove(ctx.terminalId);
            }
            catch (Exception ex)
            {
                Logger.Error("Logout error", ex);
                return;
            }
            finally
            {
                sessionLocker.ReleaseLock();
            }
        }
Пример #6
0
        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 +
                            " должно совпадать");
        }
Пример #7
0
        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);
            }
        }
Пример #8
0
        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);
            }
        }
Пример #9
0
        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);
            }
        }
Пример #10
0
        public string InternalsToString()
        {
            string str1 = string.Format("SRP {0} Internals:\n", IsServer ? "server" : "client") +
                          string.Format("G      = {0}\n", Generator.ToHexString()) +
                          string.Format("K      = {0}\n", Multiplier.ToHexString()) +
                          string.Format("N      = {0}\n", Modulus.ToHexString()) +
                          string.Format("I      = '{0}'\n", Credentials) +
                          string.Format("Hash(I)= {0}\n",
                                        Hash((HashUtilities.HashDataBroker)Credentials).ToHexString()) +
                          string.Format("X      = {0}\n", CredentialsHash.ToHexString()) +
                          string.Format("V      = {0}\n", Verifier.ToHexString());

            if (m_salt != null)
            {
                str1 += string.Format("Salt   = {0}\n", Salt.ToHexString());
            }
            if (null != m_publicEphemeralValueA && null != m_publicEphemeralValueB)
            {
                str1 = str1 + string.Format("u      = {0}\n", ScramblingParameter.ToHexString()) +
                       string.Format("h(A)   = {0}\n",
                                     Hash((HashUtilities.HashDataBroker)PublicEphemeralValueA)
                                     .ToHexString()) + string.Format("h(B)   = {0}\n",
                                                                     Hash((HashUtilities.HashDataBroker)PublicEphemeralValueB.GetBytes())
                                                                     .ToHexString());
            }
            if (!IsServer || PublicEphemeralValueA != null)
            {
                str1 += string.Format("A      = {0}\n", PublicEphemeralValueA.ToHexString());
            }
            if (IsServer || PublicEphemeralValueB != null)
            {
                string     str2        = str1 + string.Format("B      = {0}\n", PublicEphemeralValueB.ToHexString());
                BigInteger bigInteger1 = Multiplier * Generator.ModPow(CredentialsHash, Modulus);
                string     str3        = str2 + string.Format("kg^x   = {0}\n", bigInteger1.ToHexString());
                BigInteger bigInteger2 = PublicEphemeralValueB - bigInteger1 % Modulus;
                if (bigInteger2 < 0)
                {
                    bigInteger2 += Modulus;
                }
                str1 = str3 + string.Format("B-kg^x = {0}\n", bigInteger2.ToHexString());
            }

            string str4;

            try
            {
                str4 = str1 + string.Format("S.key  = {0}\n", SessionKey.ToHexString());
            }
            catch
            {
                str4 = str1 + "S.key  = empty\n";
            }

            return(str4);
        }
Пример #11
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);
        }
Пример #12
0
        public string InternalsToString()
        {
            string type = IsServer ? "server" : "client";
            string str  = string.Format("SRP {0} Internals:\n", type);

            str += string.Format("G      = {0}\n", Generator.ToHexString());
            str += string.Format("K      = {0}\n", Multiplier.ToHexString());
            str += string.Format("N      = {0}\n", Modulus.ToHexString());

            str += string.Format("I      = '{0}'\n", Credentials);
            str += string.Format("Hash(I)= {0}\n", Hash(Credentials).ToHexString());
            str += string.Format("X      = {0}\n", CredentialsHash.ToHexString());
            str += string.Format("V      = {0}\n", Verifier.ToHexString());
            if (m_salt != null)
            {
                str += string.Format("Salt   = {0}\n", Salt.ToHexString());
            }
            if (null != m_publicEphemeralValueA && null != m_publicEphemeralValueB)
            {
                str += string.Format("u      = {0}\n", ScramblingParameter.ToHexString());
                str += string.Format("h(A)   = {0}\n", Hash(PublicEphemeralValueA).ToHexString());
                str += string.Format("h(B)   = {0}\n", Hash(PublicEphemeralValueB.GetBytes()).ToHexString());
            }

            if (IsServer == false || PublicEphemeralValueA != null)
            {
                str += string.Format("A      = {0}\n", PublicEphemeralValueA.ToHexString());
            }
            if (IsServer || PublicEphemeralValueB != null)
            {
                str += string.Format("B      = {0}\n", PublicEphemeralValueB.ToHexString());
                BigInteger tmp = Multiplier * Generator.ModPow(CredentialsHash, Modulus);
                str += string.Format("kg^x   = {0}\n", tmp.ToHexString());
                tmp  = PublicEphemeralValueB - tmp % Modulus;
                if (tmp < 0)
                {
                    tmp += Modulus;
                }
                str += string.Format("B-kg^x = {0}\n", tmp.ToHexString());
            }

            try
            {
                str += string.Format("S.key  = {0}\n", SessionKey.ToHexString());
            }
            catch
            {
                str += "S.key  = empty\n";
            }

            return(str);
        }
Пример #13
0
        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);
            }
        }
Пример #14
0
        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);
            }
        }
Пример #15
0
        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) - не должен отработать отработать");
        }
Пример #16
0
        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 запрошено)");
        }
Пример #17
0
        public ProtectedOperationContext MakeProtectedContext()
        {
            if (sessionTag == 0)
            {
                return(null);
            }
            var context = new ProtectedOperationContext
            {
                sessionTag      = sessionTag,
                terminalId      = terminalId,
                clientLocalTime = DateTime.Now.Ticks,
                userMachineName = shortMachineName
            };

            context.hash = CredentialsHash.MakeOperationParamsHash(context.clientLocalTime, sessionTag, terminalId);
            return(context);
        }
Пример #18
0
        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");
        }
Пример #19
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);
            }
        }
Пример #20
0
        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);
        }
Пример #21
0
        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);
            }
        }
Пример #22
0
        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");
        }
Пример #23
0
 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));
     }
 }
Пример #24
0
        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);
            }
        }
Пример #25
0
        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");
        }
Пример #26
0
        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() - левая авторизация не прошла");
        }
Пример #27
0
        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 - не тот пользователь");
        }
Пример #28
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);
            }
        }
Пример #29
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);
     }
 }
Пример #30
0
 public static string GetUserHash(string login, string pwrd, long magic)
 {
     return(CredentialsHash.MakeCredentialsHash(login, pwrd, magic));
 }