private List <UserPaymentSystem> GetUserWallets() { WalletError error; List <UserPaymentSystem> paySystWallets = null; try { paySystWallets = TradeSharpWalletManager.Instance.proxy.GetUserRegistredPaymentSystemWallets( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountStatus.Instance.Login, "", // !! pwrd out error); } catch (Exception ex) { Logger.Error("GetWalletsWebMoney() error", ex); error = WalletError.CommonError; } if (error != WalletError.OK) { MessageBox.Show("Невозможно получить данные кошельков:\n" + EnumFriendlyName <WalletError> .GetString(error), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } // показать данные кошелька return(paySystWallets); }
private void UpdateOrRemoveSubscription(Contract.Entity.Subscription sub, bool remove) { var isOk = false; var error = WalletError.CommonError; try { isOk = MainForm.serverProxyTrade.proxy.SubscribeOnService( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountStatus.Instance.Login, sub.Service, sub.RenewAuto, remove, sub.AutoTradeSettings, out error); } catch (Exception ex) { Logger.ErrorFormat("GridSubscriptionOnUserHitCell - ошибка в GridSubscriptionOnUserHitCell({0}): {1}", sub.Service, ex); } if (!isOk) { MessageBox.Show((remove ? "Ошибка при отключении подписки: " : "Ошибка обновления подписки: ") + EnumFriendlyName <WalletError> .GetString(error), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { // обновить состояние подписки и кошелька SubscriptionModel.Instance.LoadSubscribedCategories(); InitiateAsynchLoad(); } }
public static Account SelectTerminalUserAccount(bool realAccountsOnly) { // проверить наличие реального счета, если их несколько - дать выбор List <Account> accounts = null; AuthenticationResponse status; try { status = MainForm.serverProxyTrade.proxy.GetUserOwnedAccountsWithActualBalance( AccountStatus.Instance.Login, CurrentProtectedContext.Instance.MakeProtectedContext(), false, out accounts); } catch (Exception ex) { Logger.Error("Error in BtnMakeSignalServiceClick().GetUserOwnedAccountsWithActualBalance", ex); status = AuthenticationResponse.ServerError; } if (status != AuthenticationResponse.OK) { dialogBoxProvider.ShowMessageBox(EnumFriendlyName <AuthenticationResponse> .GetString(status), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } if (accounts == null || accounts.Count == 0) { dialogBoxProvider.ShowMessageBox("У вас нет открытых торговых счетов", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } var accountsReal = realAccountsOnly ? accounts.Where(a => DalAccountGroup.Instance.Groups.First(g => g.Code == a.Group).IsReal).ToList() : accounts; if (accountsReal.Count == 0) { dialogBoxProvider.ShowMessageBox("Среди ваших торговых счетов нет действительного (не виртуального) счета", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } // дать пользователю выбор среди счетов var accountSelected = accountsReal[0]; if (accountsReal.Count > 1) { object selected; string inputText; if (!dialogBoxProvider.ShowComboDialog("Укажите торговый счет", accountsReal.Cast <object>().ToList(), out selected, out inputText, true)) { return(null); } accountSelected = (Account)selected; } return(accountSelected); }
public SoundEventTag(VocalizedEvent evt, string fileName) { VocEvent = evt; EventName = EnumFriendlyName <VocalizedEvent> .GetString(evt); FileName = fileName; }
public void Setup() { // настроить фейковую БД из файлов CSV SetupDatabase(); // получить из БД десяток счетов и их владельцев using (var ctx = DatabaseContext.Instance.Make()) { var accounts = (from account in ctx.ACCOUNT select(int?) account.ID).Take(5).ToList(); accountIds = accounts.Concat(Enumerable.Range(0, 10).Select(r => (int?)null)).OrderBy(a => rnd.Next()).ToArray(); targetUsers = (from us in ctx.PLATFORM_USER select us).Take(10).ToArray(); } const int eventsCount = 1000; var timeStart = DateTime.Now.AddSeconds(-eventsCount); sampleUserEvents = new List <UserEvent>(); for (var i = 0; i < eventsCount; i++) { var evt = new UserEvent { AccountId = accountIds[i % accountIds.Length], Action = AccountEventAction.DefaultAction, Time = timeStart.AddSeconds(i), User = targetUsers[i % targetUsers.Length].ID }; evt.Code = evt.AccountId.HasValue ? AccountEventCode.TradeSignal : AccountEventCode.AccountModified; evt.Text = evt.Code + " " + i; evt.Title = EnumFriendlyName <AccountEventCode> .GetString(evt.Code); sampleUserEvents.Add(evt); } }
private void Subscribe(object sender, EventArgs e) { RequestStatus status; try { if (isSubsribed) { status = AccountModel.Instance.ServerProxy.UnsubscribePortfolio( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountModel.Instance.GetUserLogin(), true, true); } else { var complete = new CompleteSubscribeOnPortfolioDlg(portfolio).ShowDialog() == DialogResult.OK; if (!complete) { return; } var tradeSettings = new AutoTradeSettings(); // открыть диалог настройки авто-торговли var dlg = new AutoTradeSettingsForm(); if (dlg.ShowDialog(this) == DialogResult.OK) { tradeSettings = dlg.sets; } status = AccountModel.Instance.ServerProxy.SubscribeOnPortfolio( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountModel.Instance.GetUserLogin(), portfolio, null, tradeSettings); } } catch (Exception ex) { //4 debug MessageBox.Show(this, "Операция выполнена с ошибкой:" + Environment.NewLine + ex.Message, Localizer.GetString("TitleWarning"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Logger.Info("TopPortfolioControl.Subscribe: error calling SubscribeOnPortfolio/UnsubscribePortfolio", ex); return; } if (status == RequestStatus.OK) { MessageBox.Show(this, "Операция выполнена успешно", Localizer.GetString("TitleInformation"), MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(this, "Операция выполнена с ошибкой:" + Environment.NewLine + EnumFriendlyName <RequestStatus> .GetString(status), Localizer.GetString("TitleWarning"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } IsSubsribed = !isSubsribed; if (SubscriptionChanged != null) { SubscriptionChanged(this, new EventArgs()); } }
private string ProcessFormattedRequestBalance(List <HttpParameter> ptrs) { if (ptrs.Count != 1 || ptrs[0] is ChangeAccountBalanceQuery == false) { return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = false, Comment = "Список параметров (JSON) - ожидается один параметр типа ChangeAccountBalanceQuery" } })); } var queryPtr = (ChangeAccountBalanceQuery)ptrs[0]; // пополнить счет или произвести списания var status = accountRepository.ChangeBalance(queryPtr.AccountId, queryPtr.Amount, queryPtr.Description, queryPtr.ValueDate, queryPtr.ChangeType); return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = status == RequestStatus.OK, Comment = EnumFriendlyName <RequestStatus> .GetString(status) } })); }
/// <summary> /// отключить услугу /// </summary> private void DeregisterTradeSignals(PaidService service) { if (service == null) { return; } // отписаться от услуги WalletError error; try { TradeSharpWalletManager.Instance.proxy.DisableService( CurrentProtectedContext.Instance.MakeProtectedContext(), service.Id, out error); } catch (Exception ex) { Logger.ErrorFormat("TradeSharpWalletManager.DisableService({0}) error: {1}", service.Id, ex); error = WalletError.CommonError; } if (error == WalletError.OK) { MessageBox.Show(Localizer.GetString("MessageServiceIsTurnedOff"), Localizer.GetString("TitleConfirmation"), MessageBoxButtons.OK, MessageBoxIcon.Asterisk); ShowSignallerOptions(editedUser); } else { MessageBox.Show(EnumFriendlyName <WalletError> .GetString(error), Localizer.GetString("TitleError"), MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void ShowOrderParams() { // заголовок окна Text = order.ToString(); // параметры сделки cbStatus.SelectedIndex = cbStatus.Items.IndexOf(EnumFriendlyName <PositionState> .GetString(order.State)); if (order.State == PositionState.Closed) { cbExitReason.SelectedIndex = cbExitReason.Items.IndexOf(EnumFriendlyName <PositionExitReason> .GetString(order.ExitReason)); } else { cbExitReason.Visible = false; } tbPriceEnter.Text = FormatPrice(order.PriceEnter); dpEnter.Value = order.TimeEnter; if (order.PriceExit.HasValue) { tbPriceExit.Text = FormatPrice(order.PriceExit.Value); } if (order.TimeExit.HasValue) { dpExit.Value = order.TimeExit.Value; } if (order.StopLoss.HasValue && order.StopLoss.Value > 0) { tbSL.Text = FormatPrice(order.StopLoss.Value); } if (order.TakeProfit.HasValue && order.TakeProfit.Value > 0) { tbTP.Text = FormatPrice(order.TakeProfit.Value); } if (order.Magic.HasValue) { tbMagic.Text = order.Magic.Value.ToString(); } tbVolume.Text = order.Volume.ToStringUniformMoneyFormat(); var sbTrailing = new StringBuilder(); for (var i = 0; i < order.trailingLevels.Length; i++) { if ((!order.trailingLevels[i].HasValue) || order.trailingLevels[i] == 0 || (!order.trailingTargets[i].HasValue)) { break; } sbTrailing.AppendFormat("[{0} - {1}]", FormatPrice(order.trailingLevels[i].Value), FormatPrice(order.trailingTargets[i].Value)); } tbTrailing.Text = sbTrailing.ToString(); tbComment.Text = string.IsNullOrEmpty(order.Comment) && string.IsNullOrEmpty(order.ExpertComment) ? "" : string.IsNullOrEmpty(order.Comment) ? "[R] " + order.ExpertComment : string.IsNullOrEmpty(order.ExpertComment) ? order.Comment : order.Comment + ", [R] " + order.ExpertComment; }
private void TrendLineTypeDialogLoad(object sender, EventArgs e) { // заполнить список линий var w = imageListLarge.ImageSize.Width; var h = imageListLarge.ImageSize.Height; var rectWorld = new RectangleD(0, 0, w, h); var rectCanvas = new Rectangle(0, 0, w, h); var colors = new [] { Color.BlanchedAlmond, Color.GreenYellow, Color.PaleTurquoise }; var colorIndex = 0; foreach (TrendLine.TrendLineStyle lineType in Enum.GetValues(typeof(TrendLine.TrendLineStyle))) { var bmp = new Bitmap(w, h); var line = new TrendLine(); line.AddPoint(h * 0.23, w - 5); line.AddPoint(h * 0.77, 5); if (lineType == TrendLine.TrendLineStyle.Отрезок || lineType == TrendLine.TrendLineStyle.Окружность || lineType == TrendLine.TrendLineStyle.ЛинияСМаркерами || lineType == TrendLine.TrendLineStyle.ОтрезокСМаркерами) { line.linePoints[1] = new PointD(h * 0.32, w - 16); line.linePoints[0] = new PointD(h * 0.68, 16); } line.LineColor = Color.Black; line.ShapeFillColor = colors[colorIndex]; line.LineStyle = lineType; colorIndex++; if (colorIndex == colors.Length) { colorIndex = 0; } using (var gr = Graphics.FromImage(bmp)) using (var brushes = new BrushesStorage()) using (var pens = new PenStorage()) { gr.SmoothingMode = SmoothingMode.AntiAlias; line.Draw(gr, rectWorld, rectCanvas, pens, brushes); } imageListLarge.Images.Add(bmp); var item = listView.Items.Add(lineType.ToString(), EnumFriendlyName <TrendLine.TrendLineStyle> .GetString(lineType), imageListLarge.Images.Count - 1); item.Tag = lineType; if (lineType == selectedStyle) { item.Selected = true; } } // привязать картинки к списку listView.LargeImageList = imageListLarge; listView.SmallImageList = imageListLarge; }
private void WithdrawOrDepositFromAccount(Account account, decimal sum, bool withdraw) { WalletError error; try { var walletResulted = withdraw ? TradeSharpWalletManager.Instance.proxy.TransferToWallet( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountStatus.Instance.Login, account.ID, sum, out error) : TradeSharpWalletManager.Instance.proxy.TransferToTradingAccount( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountStatus.Instance.Login, account.ID, sum, out error); if (error == WalletError.OK) { if (UserSettings.Instance.GetAccountEventAction(AccountEventCode.WalletModified) != AccountEventAction.DoNothing) { var deltaMoney = walletResulted.Balance - walletExplicitDetail.wallet.Balance; var msg = string.Format("Баланс кошелька изменен: {0} {1} {2}", deltaMoney >= 0 ? "внесено" : "выведено", deltaMoney.ToStringUniformMoneyFormat(true), walletResulted.Currency); bool repeatNotification; NotificationBox.Show(msg, "Операция выполнена", out repeatNotification); if (!repeatNotification) { UserSettings.Instance.SwitchAccountEventAction(AccountEventCode.WalletModified); UserSettings.Instance.SaveSettings(); } } // обновить данные кошелька и счетов InitiateAsynchLoad(); return; } } catch { error = WalletError.CommonError; } if (error != WalletError.OK) { var errorString = EnumFriendlyName <WalletError> .GetString(error); Logger.ErrorFormat("WithdrawFromAccount() error: {0}", errorString); MessageBox.Show("Ошибка выполнения операции:\n" + errorString, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); //return; } }
/// <summary> /// сохранить данные кошельков WM /// </summary> private void BtnSaveWebMoneyClick(object sender, EventArgs e) { var wmId = cbWMID.Text; var isValid = WebMoneyValidator.WmidIsValid(wmId); if (!isValid) { MessageBox.Show("WMID введен некорректно.\n" + WebMoneyValidator.GetCorrectWMIDSampleStringWithSpecs(), "Ошибка ввода", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // взять все purseId bool errorExists; var purses = webMoneyPursePanelControl.GetPurseIds(out errorExists); if (errorExists) { MessageBox.Show("ID кошелька введен некорректно.\n" + WebMoneyValidator.GetCorrectPurseIdSampleStringWithSpecs(), "Ошибка ввода", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // забить на сервер кошельки / WMID WalletError error; try { error = TradeSharpWalletManager.Instance.proxy.SetPaymentWalletsBySystem( CurrentProtectedContext.Instance.MakeProtectedContext(), PaymentSystem.WebMoney, purses.Select(p => new UserPaymentSystem { RootId = wmId, PurseId = p, SystemPayment = PaymentSystem.WebMoney }).ToList(), AccountStatus.Instance.Login, ""); // wallet pwrd } catch (Exception ex) { Logger.Error("BtnSaveWebMoneyClick() error", ex); error = WalletError.CommonError; } if (error == WalletError.OK) { MessageBox.Show("Данные платежной системы обновлены"); GetUserWalletsWebMoney(); return; } MessageBox.Show("Ошибка обновления данных:\n" + EnumFriendlyName <WalletError> .GetString(error), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); }
private void UpdateDealLineStatusUnsafe(int index, RequestStatus status) { var lines = tbDeals.Lines; if (lines.Length <= index) { return; } lines[index] = lines[index] + ": " + EnumFriendlyName <RequestStatus> .GetString(status); tbDeals.Text = string.Join(Environment.NewLine, lines); }
private void SetupForm() { foreach (PositionState state in Enum.GetValues(typeof(PositionState))) { cbStatus.Items.Add(EnumFriendlyName <PositionState> .GetString(state)); } foreach (PositionExitReason reason in Enum.GetValues(typeof(PositionExitReason))) { cbExitReason.Items.Add(EnumFriendlyName <PositionExitReason> .GetString(reason)); } }
private void UpdateSubscriptionUnsafe() { var login = AccountStatus.Instance.Login; if (string.IsNullOrEmpty(login)) { return; } try { summaryFlowLayoutPanel.Hide(); topSubscriptionControl.Hide(); var subscribedPortfolioId = TradeSharpAccountStatistics.Instance.proxy.GetSubscribedTopPortfolioId(login); if (subscribedPortfolioId == -1) { var services = TradeSharpAccount.Instance.proxy.GetPaidServices(AccountStatus.Instance.Login); if (services == null) { MessageBox.Show(this, Localizer.GetString("MessageUnableToGetSubscriptions"), Localizer.GetString("TitleWarning"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { summaryLabel.Text = string.Format( Localizer.GetString("MessageYourAreSubscribedOnSignalsFmt"), services.Count, services.Select(s => s.FixedPrice).Sum(), PerformerStat.FeeCurrency); } summaryFlowLayoutPanel.Show(); } else { AccountEfficiency userAccountEfficiency; topSubscriptionControl.Portfolio = TradeSharpAccountStatistics.Instance.proxy.GetTopPortfolio(subscribedPortfolioId, out userAccountEfficiency); topSubscriptionControl.Show(); } if (SubscriptionModel.Instance.getActionOnSignal != null) { cbActionOnSignal.SelectedItem = EnumFriendlyName <ActionOnSignal> .GetString(SubscriptionModel.Instance.getActionOnSignal()); } grid.DataBind(SubscriptionModel.Instance.SubscribedCategories); grid.Invalidate(); } catch (Exception ex) { Logger.Error("SubscriptionFastGrid.UpdateSubscriptionUnsafe", ex); } }
public override string ToString() { var parts = new List <string> { EnumFriendlyName <PaidServiceType> .GetString(ServiceType) }; if (!string.IsNullOrEmpty(comment)) { parts.Add(Comment); } return(string.Join(", ", parts)); }
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); }
/// <summary> /// Формирует список типов сделки (покупка / продажа) для выпадающего списка фильтра /// </summary> public static List <SelectListItem> DealTypeList() { var result = Enum.GetValues(typeof(DealType)).Cast <DealType>().Select(x => new SelectListItem { Text = EnumFriendlyName <DealType> .GetString(x), Value = ((int)x).ToString(CultureInfo.InvariantCulture) }).ToList(); result.Insert(0, new SelectListItem { Text = Resource.TitleWithoutFilter, Value = null, Selected = true }); return(result); }
public static bool RegisterOrUpdateService(PaidService service) { // получить кошелек пользователя Wallet wallet; try { wallet = TradeSharpWalletManager.Instance.proxy.GetUserWallet( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountStatus.Instance.Login); if (wallet == null) { throw new Exception("Кошелек не заведен"); } } catch (Exception ex) { Logger.ErrorFormat("GetUserWallet({0}) error: {1}", AccountStatus.Instance.Login, ex); dialogBoxProvider.ShowMessageBox("Не удалось получить данные о кошельке", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } // отправить на сервер запрос service.User = wallet.User; WalletError error; try { TradeSharpWalletManager.Instance.proxy.RegisterOrUpdateService( CurrentProtectedContext.Instance.MakeProtectedContext(), service, out error); } catch (Exception ex) { Logger.ErrorFormat("TradeSharpWalletManager.RegisterOrUpdateService({0}) error: {1}", AccountStatus.Instance.Login, ex); error = WalletError.CommonError; } if (error == WalletError.OK) { dialogBoxProvider.ShowMessageBox("Сервис зарегистрирован в системе", "Подтверждение", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return(true); } dialogBoxProvider.ShowMessageBox(EnumFriendlyName <WalletError> .GetString(error), "Ошибка регистрации сервера", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); }
private void BtnUpdateClick(object sender, EventArgs e) { var ctx = CurrentProtectedContext.Instance.MakeProtectedContext(); if (ctx == null) { MessageBox.Show("Необходимо авторизоваться для смены пароля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); return; } // проверка ввода if (string.IsNullOrEmpty(tbNewPassword.Text)) { MessageBox.Show("Пароль не может быть пустой строкой", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (tbNewPassword.Text.Length < PlatformUser.PasswordLenMin) { MessageBox.Show(string.Format("Длина пароля не может быть меньше {0} символов", PlatformUser.PasswordLenMin), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (tbNewPassword.Text.Length > PlatformUser.PasswordLenMax) { MessageBox.Show(string.Format("Длина пароля не может быть больше {0} символов", PlatformUser.PasswordLenMax), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { var status = MainForm.serverProxyTrade.proxy.ChangePassword(ctx, AccountStatus.Instance.Login, tbNewPassword.Text); if (status != AuthenticationResponse.OK) { MessageBox.Show(EnumFriendlyName <AuthenticationResponse> .GetString(status), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } catch (Exception ex) { Logger.Error("Ошибка в ChangePassword", ex); MessageBox.Show("Ошибка исполнения команды", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show("Пароль изменен", "Выполнено"); UserSettings.Instance.StoreLogin(UserSettings.Instance.Login, tbNewPassword.Text); Close(); }
/// <summary> /// если счет подписан на "топ" - обновить состав участников топа /// </summary> public void UpdatePortfolio() { var sets = RobotFarm.Instance.portfolioTradeSettings; if (sets == null) { return; } int?subscribedPortfolioId = 0; try { // получить информацию по портфелю var portfolioId = TradeSharpAccountStatistics.Instance.proxy.GetSubscribedTopPortfolioId(UserLogin); subscribedPortfolioId = portfolioId > 0 ? portfolioId : (int?)null; } catch (Exception ex) { RobotFarm.Instance.AppendLogMessage(string.Format("Невозможно получить информацию по портфелю ({0}): {1}", UserLogin, ex.Message)); Logger.Error("GetSubscribedTopPortfolio() error", ex); } if (!subscribedPortfolioId.HasValue) { return; } var status = RequestStatus.ServerError; try { status = proxyTrade.proxy.SubscribeOnPortfolio(protectedContext.MakeProtectedContext(), UserLogin, new TopPortfolio { Id = subscribedPortfolioId.Value }, null, sets); } catch (Exception ex) { Logger.ErrorFormat("UpdatePortfolio(\"{0}\", {1}): {2}", UserLogin, subscribedPortfolioId, ex); } RobotFarm.Instance.AppendLogMessage(string.Format("Обновление портфеля (\"{0}\", {1}) {2}: {3}", UserLogin, subscribedPortfolioId, status == RequestStatus.OK ? "произведено" : "неуспешно", EnumFriendlyName <RequestStatus> .GetString(status))); }
public HotKeySetForm(ApplicationMessageBinding objHotKey) { InitializeComponent(); Localizer.LocalizeControl(this); ObjHotKey = objHotKey; txtActionName.Text = EnumFriendlyName <ApplicationMessage> .GetString(ObjHotKey.Message); txtbxHotKeyNewValue.Text = ObjHotKey.Key; mainForm = Application.OpenForms[0] as MainForm; if (mainForm != null) { mainForm.KeyPressedEvent += MainFormKeyPressedEvent; } }
private void ConfiguringNotificationsClick(object sender, EventArgs e) { // в строках ниже из AccountEventCode формируется Dictionary из локализованных строк, // а затем эти строки обратно преобразуются в AccountEventCode var pageState = currentMessageCodes.Distinct().ToDictionary(x => (object)EnumFriendlyName <AccountEventCode> .GetString(x), x => { AccountEventSettings accountEventSettings; try { accountEventSettings = UserSettings.Instance.AccountEventAction.Single(y => y.EventCode == x); } catch (Exception ex) { Logger.Error("ConfiguringNotificationsClick()", ex); return(true); } return(accountEventSettings.EventAction != AccountEventAction.DoNothing); }); if (CheckedListBoxDialog.Show(pageState, this, Localizer.GetString("TitleCustomizeNotifications")) != DialogResult.OK) { return; } foreach (var state in pageState) { AccountEventCode accountEventCode; try { accountEventCode = EnumItem <AccountEventCode> .items.Single(x => EnumFriendlyName <AccountEventCode> .GetString(x.Value) == (string)state.Key).Value; } catch (Exception ex) { Logger.Error("ConfiguringNotificationsClick()", ex); continue; } var updateAction = UserSettings.Instance.AccountEventAction.FirstOrDefault(a => a.EventCode == accountEventCode); if (updateAction == null) { continue; } updateAction.EventAction = state.Value ? AccountEventAction.DefaultAction : AccountEventAction.DoNothing; } UserSettings.Instance.SaveSettings(); }
private static string ProcessFormattedRequestRegister(List <HttpParameter> ptrs) { if (ptrs.Count != 1 || ptrs[0] is RegisterAccountQuery == false) { return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = false, Comment = "Список параметров (JSON) - ожидается один параметр типа RegisterAccountQuery" } })); } var queryPtr = (RegisterAccountQuery)ptrs[0]; var status = ManagerAccount.Instance.RegisterAccount( new PlatformUser { Login = queryPtr.UserLogin, Password = queryPtr.UserPassword, Name = queryPtr.UserName, Surname = queryPtr.UserSurname, Patronym = queryPtr.UserPatronym, Description = queryPtr.UserDescription, Title = queryPtr.UserLogin, Email = queryPtr.UserEmail, Phone1 = queryPtr.UserPhone1, Phone2 = queryPtr.UserPhone2, RegistrationDate = DateTime.Now, RightsMask = queryPtr.UserRightsMask, RoleMask = queryPtr.UserRoleMask }, queryPtr.Currency, (int)queryPtr.Balance, (decimal)queryPtr.MaxLeverage, queryPtr.UserPassword, // пароль задан заранее, автоматом не сочиняем false); // не подписывать автоматом на торговые сигналы лучших в мире трейдеров return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = status == AccountRegistrationStatus.OK, Comment = EnumFriendlyName <AccountRegistrationStatus> .GetString(status) } })); }
public AccountRegistrationResponse RegisterAccount( string login, string password, string email, string firstName, string lastName, string patronym, string phone, string currency, int startBalance) { var usr = new PlatformUser { Login = login, Password = password, Email = email, Name = firstName, Surname = lastName, Patronym = patronym, Phone1 = phone, RegistrationDate = DateTime.Now }; var resp = new AccountRegistrationResponse(); if (currency != "USD") { resp.errors.Add("Поддерживаемые валюты: " + "USD"); } //if (!PlatformUser.CheckLoginSpelling(usr.Login)) // resp.errors.Add("Логин задан некорректно"); if (resp.errors.Count > 0) { return(resp); } var status = ManagerAccount.Instance.RegisterAccount(usr, currency, startBalance < 1000 ? 1000 : startBalance, 0, usr.Password, false); resp.status = status; resp.statusName = EnumFriendlyName <AccountRegistrationStatus> .GetString(status); return(resp); }
private void CheckVersionCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Result == null) { versionLabel.Text = EnumFriendlyName <AccountConnectionStatus> .GetString(AccountConnectionStatus.ConnectionError); versionLabel.ForeColor = Color.Red; return; } var typedResult = (Cortege2 <List <string>, List <string> >)e.Result; var missingFiles = typedResult.a; var olderFiles = typedResult.b; // показать сообщение о новой версии if (missingFiles.Count <= 0 && olderFiles.Count <= 0) { return; } versionLabel.Text = string.Format(Localizer.GetString("MessageVersionOutdatedNFilesFmt"), missingFiles.Count + olderFiles.Count); versionLabel.ForeColor = Color.Red; versionLabel.Cursor = Cursors.Hand; // собрать детальную информацию var msgUpdate = new StringBuilder(); if (missingFiles.Count > 0) { msgUpdate.Append(Localizer.GetString("TitleMissedMany") + ":" + Environment.NewLine + string.Join(Environment.NewLine, missingFiles) + Environment.NewLine + Environment.NewLine); } if (olderFiles.Count > 0) { msgUpdate.Append(Localizer.GetString("TitleStaleMany") + ": " + Environment.NewLine + string.Join(Environment.NewLine, olderFiles) + Environment.NewLine + Environment.NewLine); } msgUpdate.Append(Localizer.GetString("MessageTerminalRestartRecommended")); versionLabel.Click += (ea, s) => MessageBox.Show(msgUpdate.ToString(), Localizer.GetString("TitleStatus")); }
private static RequestStatus SendEditPendingRequestUnsafe(PendingOrder ord) { try { var res = serverProxyTrade.proxy.SendEditPendingRequest(CurrentProtectedContext.Instance.MakeProtectedContext(), ord); if (res != RequestStatus.OK) { Instance.ShowMsgWindowSafe(new AccountEvent( Localizer.GetString("MessageErrorExecutingOrder"), EnumFriendlyName <RequestStatus> .GetString(res), AccountEventCode.ServerMessage)); } return(res); } catch (Exception ex) { Logger.Error("SendEditPendingRequest ошибка выполнения: ", ex); return(RequestStatus.NoConnection); } }
private void ReadOnlyAccountFormLoad(object sender, EventArgs e) { // подставить данные существующего пользователя lblStatus.Text = Localizer.GetString("TitleNotAuthorized"); btnMake.Text = Localizer.GetString("TitleCreate"); var ctx = CurrentProtectedContext.Instance.MakeProtectedContext(); if (ctx == null || AccountStatus.Instance.accountID <= 0) { return; } PlatformUser user; RequestStatus status; try { status = MainForm.serverProxyTrade.proxy.QueryReadonlyUserForAccount(ctx, AccountStatus.Instance.accountID, out user); lblStatus.Text = EnumFriendlyName <RequestStatus> .GetString(status); } catch (Exception ex) { lblStatus.Text = "Данные не получены"; Logger.Error("Ошибка в QueryReadonlyUserForAccount()", ex); return; } if (status != RequestStatus.OK) { lblStatus.Text = "Данные не получены"; return; } if (user != null) { tbLogin.Text = user.Login; tbPassword.Text = user.Password; btnMake.Text = Localizer.GetString("TitleEdit"); } }
public void InvestInPAMM(PerformerStat performer, decimal amount, bool investNotWithdraw, bool withdrawAll) { var accountData = AccountStatus.Instance.AccountData; if (accountData == null) { return; } var status = investNotWithdraw ? TradeSharpWalletManager.Instance.proxy.InvestInPAMM( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountStatus.Instance.Login, performer.Account, amount) : TradeSharpWalletManager.Instance.proxy.WithdrawFromPAMM( CurrentProtectedContext.Instance.MakeProtectedContext(), AccountStatus.Instance.Login, performer.Account, amount, withdrawAll); if (status == RequestStatus.OK) { var msg = investNotWithdraw ? "Сумма {0} {1} зачислена на счет №{2}" : "Сумма {0} {1} списана со счета №{2}"; MessageBox.Show(string.Format(msg, amount.ToStringUniformMoneyFormat(), accountData.Currency, performer.Account), investNotWithdraw ? "Зачисление проведено" : "Списание проведено", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } var opStatusName = EnumFriendlyName <RequestStatus> .GetString(status); var msgFail = investNotWithdraw ? "Сумма {0} {1} не зачислена на счет: {2}" : "Сумма {0} {1} не списана со счета: {2}"; MessageBox.Show(string.Format(msgFail, amount.ToStringUniformMoneyFormat(), accountData.Currency, opStatusName), investNotWithdraw ? "Зачисление не проведено" : "Списание не проведено", MessageBoxButtons.OK, MessageBoxIcon.Warning); }
private static RequestStatus SendCloseRequestUnsafe(int accountId, int orderId, PositionExitReason reason) { try { var res = serverProxyTrade.proxy.SendCloseRequest(CurrentProtectedContext.Instance.MakeProtectedContext(), accountId, orderId, reason); if (res != RequestStatus.OK) { Instance.ShowMsgWindowSafe(new AccountEvent( Localizer.GetString("MessageErrorExecutingOrder"), EnumFriendlyName <RequestStatus> .GetString(res), AccountEventCode.ServerMessage)); } return(res); } catch (Exception ex) { Logger.Error("SendCloseRequest", ex); return(RequestStatus.NoConnection); } }