public WalletWithdrawForm(Wallet wallet, 
            List<Account> realAccounts,
            Account account, 
            bool deposit)
            : this()
        {
            this.wallet = wallet;
            this.account = account;
            this.realAccounts = realAccounts;

            Text = "Счет №" + account.ID;
            tabControl.SelectedTab = deposit ? tabPageDeposit : tabPageWithdraw;

            // вкладка Пополнить
            lblDepositWalletCurrency.Text = wallet.Currency;
            tbDepositAmount.Text = wallet.Balance.ToStringUniformMoneyFormat(true);
            lblAccountAmount.Text = account.Equity.ToStringUniformMoneyFormat(true) +
                " " + account.Currency;

            // вкладка Вывести
            tbWithdraw.Text = "0";
            lblWithdrawCurrency.Text = account.Currency;
            lblMargin.Text = account.UsedMargin.ToStringUniformMoneyFormat(true) + " " + account.Currency;
            lblAccountRemains.Text = account.Equity.ToStringUniformMoneyFormat(true) + " " + account.Currency;
        }
Esempio n. 2
0
        public virtual RequestStatus SendNewOrderRequest(Account account,
            MarketOrder order,
            OrderType orderType,
            decimal requestedPrice,
            decimal slippagePoints)
        {
            order.State = PositionState.Opened;
            order.TimeEnter = DateTime.Now;

            //if (magic.HasValue)
            //    order.ExpertComment = comment;
            //else
            //    order.Comment = comment;
            // подставить текущую цену
            var quote = QuoteStorage.Instance.ReceiveValue(order.Symbol);
            if (quote == null)
                return RequestStatus.NoPrice;
            order.PriceEnter = order.Side > 0 ? quote.ask : quote.bid;
            // проверить проскальзывание
            if (slippagePoints != 0)
            {
                var slippageAbs = DalSpot.Instance.GetAbsValue(order.Symbol, slippagePoints);
                var delta = Math.Abs(order.PriceEnter - (float)requestedPrice);
                if (delta > (float)slippageAbs) return RequestStatus.Slippage;
            }

            int posID;
            // сохранить ордер (и уведомить клиента)
            var result = ServerInterface.SaveOrderAndNotifyClient(order, out posID);
            return result ? RequestStatus.OK : RequestStatus.SerializationError;
        }
Esempio n. 3
0
 public RobotContextLive(TradeSharpServerTrade proxyTrade, Account accountInfo, Func<string> getUserLogin)
 {
     this.proxyTrade = proxyTrade;
     this.AccountInfo = accountInfo;
     this.getUserLogin = getUserLogin;
     quotesStorage = Contract.Util.BL.QuoteStorage.Instance;
 }
Esempio n. 4
0
 public static void DecorateAccount(Account dest, ACCOUNT src)
 {
     dest.ID = src.ID;
     dest.Currency = src.Currency;
     dest.Group = src.AccountGroup;
     dest.MaxLeverage = (float) src.MaxLeverage;
     dest.Balance = src.Balance;
     dest.TimeCreated = src.TimeCreated;
     dest.TimeBlocked = src.TimeBlocked;
     dest.Status = (Account.AccountStatus) src.Status;
 }
Esempio n. 5
0
        /// <summary>
        /// Конструктор, в который передаётся GetAllAccountsUserDetail_Result.
        /// словарь "OwnersNameId" заполняется соответствиями "уникальный идентификатор пользователя - имя пользователя"
        /// </summary>
        public AccountTag(GetAllAccountsUserDetail_Result ac)
        {
            if (ac == null)
            {
                account = new Account();
            }
            else
            {
                account = new Account
                {
                    Balance = ac.Balance,
                    Currency = ac.Currency,
                    Group = ac.AccountGroup,
                    ID = ac.ID,
                };

                OwnersNameId = new Dictionary<int, string>();
                OwnersName = string.Empty;

                if (ac.UserNames != null)
                {
                    OwnersName = ac.UserNames;

                    int[] idArray = null;
                    try
                    {
                        idArray = ac.UserId.Split(',').Select(x => Convert.ToInt32(x)).ToArray();
                    }
                    catch (FormatException ex)
                    {
                        Logger.Info("Ошибка в конструкторе AccountTag. Хранимая процедура GetAllAccountsUserDetail вернула из таблици PLATFORM_USER значение Id не являющееся int", ex);
                    }
                    catch (ArgumentNullException ex)
                    {
                        Logger.Info("Ошибка в конструкторе AccountTag. Строка UserId не корректна или равна null", ex);
                    }
                    catch (Exception ex)
                    {
                        Logger.Info("Ошибка в конструкторе AccountTag. Не удалось разбить строку UserId в массив целых чисел", ex);
                    }

                    var nameArray = ac.UserNames.Split(',');
                    if (idArray != null && idArray.Count() == nameArray.Count())
                    {
                        //TODO Тут возможна неоднозначноасть. Тут возможный источник ошибки
                        for (var i = 0; i < nameArray.Count(); i++)
                        {
                            OwnersNameId.Add(idArray[i], nameArray[i]);
                        }
                    }
                }
            }
        }
Esempio n. 6
0
 public Account(Account acc)
 {
     ID = acc.ID;
     Group = acc.Group;
     Balance = acc.Balance;
     Equity = acc.Equity;
     UsedMargin = acc.UsedMargin;
     Currency = acc.Currency;
     MaxLeverage = acc.MaxLeverage;
     TimeCreated = acc.TimeCreated;
     TimeBlocked = acc.TimeBlocked;
     Status = acc.Status;
 }
Esempio n. 7
0
 public bool GetAccountData(string login, string pwrd, int accountId,
     out Account account, out List<MarketOrder> openedOrders)
 {
     if (channel == null) throw new Exception("RobotFarmProxy: связь не установлена");
     try
     {
         return channel.GetAccountData(login, pwrd, accountId, out account, out openedOrders);
     }
     catch (Exception)
     {
         RenewFactory();
         return channel.GetAccountData(login, pwrd, accountId, out account, out openedOrders);
     }
 }
Esempio n. 8
0
        /// <summary>
        /// добавить маркапы и прочее шкурилово
        /// 
        /// вызывается на открытии рыночного ордера, срабатывании отложенного
        /// (для всех - единая точка входа - SaveOrder & Notify Client)
        /// </summary>
        public static OrderBill ProcessOrderOpening(MarketOrder order, Account account)
        {
            AccountGroup.MarkupType markType;
            var spreadDelta = AcccountMarkupDictionary.GetMarkupAbs(account.Group, order.Symbol, out markType);
            var bill = new OrderBill(0, markType, 0);
            if (spreadDelta > 0 && markType != AccountGroup.MarkupType.NoMarkup)
            {
                if (markType == AccountGroup.MarkupType.Markup)
                    order.PriceEnter += spreadDelta * order.Side;
                bill.MarkupEnter = spreadDelta;
            }

            return bill;
        }
Esempio n. 9
0
 public static Account DecorateAccount(ACCOUNT ac)
 {
     var account = new Account
     {
         ID = ac.ID,
         Currency = ac.Currency,
         Group = ac.AccountGroup,
         MaxLeverage = (float)ac.MaxLeverage,
         Balance = ac.Balance,
         TimeCreated = ac.TimeCreated,
         TimeBlocked = ac.TimeBlocked,
         Status = (Account.AccountStatus)ac.Status
     };
     return account;
 }
Esempio n. 10
0
 /// <summary>
 /// Конструктор, в который передаётся GetAllAccounts_Result, не содержащий сведений о соответствии "уникальный идентификатор пользователя - имя пользователя" и
 /// не заполняющий словарь "OwnersNameId"
 /// </summary>
 public AccountTag(GetAllAccounts_Result ac)
 {
     if (ac == null)
     {
         account = new Account();
     }
     else
     {
         account = new Account
         {
             Balance = ac.Balance,
             Currency = ac.Currency,
             Group = ac.AccountGroup,
             ID = ac.ID,
         };
         OwnersName = ac.UserNames ?? string.Empty;
         OwnersNameId = new Dictionary<int, string>();
     }
 }
Esempio n. 11
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;
            }
        }
 private IDealer GetDealerByAccount(int accountId, out Account accountTyped)
 {
     accountTyped = accountRepository.GetAccount(accountId);
     if (accountTyped == null) return null;
     var dealer = GetDealerByGroup(accountTyped.Group);
     return dealer;
 }
Esempio n. 13
0
        public static ORDER_BILL ProcessPriceForOrderClosing(MarketOrder order, Account account,
            TradeSharpConnection ctx)
        {
            AccountGroup.MarkupType markType;
            var spreadDelta = AcccountMarkupDictionary.GetMarkupAbs(account.Group, order.Symbol, out markType);
            var markupExit = 0f;
            if (spreadDelta > 0 && markType != AccountGroup.MarkupType.NoMarkup)
            {
                markupExit = spreadDelta;
                if (markType == AccountGroup.MarkupType.Markup)
                    order.PriceExit -= spreadDelta * order.Side;
            }

            var bill = ctx.ORDER_BILL.FirstOrDefault(b => b.Position == order.ID);
            if (bill != null)
                bill.MarkupExit = markupExit;
            //else
            //    Logger.Debug("Markup: ProcessPriceForOrderClosing - can not find the bill for pos " + order.ID);

            return bill;
        }
Esempio n. 14
0
        /// <summary>
        /// преобразовать запрос на вход / выход из рынка в отложенный ордер
        /// </summary>        
        private bool MakeMarketRequest(Account account, string symbol, int? magic,
            int volume, int side,
            OrderType orderPricing,
            decimal requestedPrice, decimal slippagePoints,  
            string description,
            int? closingPositionId, string comment, string expertComment, float? trailingLevel, float? trailingGoal,
            out RequestStatus error,
            out TradeSharp.ProviderProxyContract.Entity.MarketOrder req)
        {
            Logger.InfoFormat("Dealer [{0}, account: {1}]: MakeMarketRequest({2} {3})",
                DealerCode, account.ID, side > 0 ? "BUY" : "SELL", symbol);
            error = RequestStatus.OK;
            req = new TradeSharp.ProviderProxyContract.Entity.MarketOrder(new BrokerOrder());

            if (orderPricing == OrderType.Instant && slippagePoints != 0)
            {
                var slipAbs = DalSpot.Instance.GetAbsValue(symbol, slippagePoints);
                if (slipAbs == 0)
                {
                    Logger.ErrorFormat("Ошибка в FixDealer - нет информации по символу {0} (пересчет проскальзывания)", symbol);
                    errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                        string.Format("Ошибка в FixDealer - нет информации по символу {0} (пересчет проскальзывания)", symbol),
                        null));
                    error = RequestStatus.ServerError;
                    return false;
                }
                req.brokerOrder.Slippage = slipAbs;
            }
            int posId = 0;
            if (closingPositionId == null || closingPositionId == 0)
            {
                var order = new MarketOrder
                                {
                                    AccountID = account.ID,
                                    Side = side,
                                    ID = 0,
                                    Volume = volume,
                                    Symbol = symbol,
                                    Comment = comment,
                                    ExpertComment = expertComment,
                                    Magic = magic,
                                    TimeEnter = DateTime.Now,
                                    TrailLevel1 = trailingLevel,
                                    TrailTarget1 = trailingGoal,
                                    PriceEnter = (float) requestedPrice,
                                    State = PositionState.StartOpened,
                                };

                // создание позы - обработано
                ServerInterface.SaveOrderAndNotifyClient(order, out posId);
                if (posId <= 0)
                {
                    Logger.ErrorFormat("Ошибка в FixDealer - ошибка создания открытой позиции в БД по {0}", symbol);
                    errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                                                             string.Format(
                                                                 "Ошибка в FixDealer - ошибка создания открытой позиции в БД по {0}",
                                                                 symbol),
                                                             null));
                    error = RequestStatus.ServerError;
                    return false;
                }
            }
            else
            {// закрытие позы
                MarketOrder order;
                ServerInterface.GetMarketOrder(closingPositionId.Value, out order);
                if (order == null)
                {
                    error = RequestStatus.ServerError;
                    Logger.ErrorFormat("FixDealer - MakeMarketRequest - order {0} not found", closingPositionId.Value);
                    return false;
                }
                order.State = PositionState.StartClosed;
                if (!ServerInterface.ModifyMarketOrder(order))
                {
                    error = RequestStatus.ServerError;
                    Logger.ErrorFormat("FixDealer - MakeMarketRequest - cannot modify order {0}", closingPositionId.Value);
                    return false;
                }
            }

            req.AccountGroupCode = account.Group;
            req.brokerOrder.Instrument = Instrument.Spot;
            req.brokerOrder.OrderPricing = orderPricing == OrderType.Instant ? OrderPricing.Instant : OrderPricing.Market;
            if (req.brokerOrder.OrderPricing == OrderPricing.Instant)
                req.brokerOrder.RequestedPrice = requestedPrice == 0 ? (decimal?)null : requestedPrice;
            req.brokerOrder.Side = side;
            req.brokerOrder.Volume = volume;
            req.brokerOrder.Ticker = symbol;
            req.brokerOrder.RequestId = posId != 0 ? posId : (int)RequestUniqueId;
            req.brokerOrder.DealerCode = DealerCode;
            req.brokerOrder.TimeCreated = DateTime.Now;
            req.brokerOrder.ClosingPositionID = closingPositionId;
            req.brokerOrder.AccountID = account.ID;
            req.brokerOrder.Magic = magic;
            req.brokerOrder.Comment = comment;
            req.brokerOrder.ExpertComment = expertComment;

            requestWatchdog.AddRequest(new RequestWatchdogItem
                { requestId = req.brokerOrder.RequestId, requestTime = DateTime.Now,
                    requestSymbol = symbol, requestType = (DealType)side });

            // сохранить сообщение в БД
            try
            {
                ServerInterface.SaveProviderMessage(req.brokerOrder);
            }
            catch (Exception ex)
            {
                error = RequestStatus.SerializationError;
                Logger.ErrorFormat("Дилер {0}: ошибка сохранения запроса брокеру: {1}",
                    DealerCode, ex);
                errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                        string.Format("Дилер {0}: ошибка сохранения запроса брокеру", DealerCode), ex));
                return false;
            }

            return true;
        }
Esempio n. 15
0
        private static void CalculateAccountEquity(Account account, List<MarketOrder> orders)
        {
            var quotes = QuoteStorage.Instance.ReceiveAllData();
            if (quotes.Count == 0) return;

            var profit = DalSpot.Instance.CalculateOpenedPositionsCurrentResult(orders, quotes, account.Currency);
            account.Equity = account.Balance + (decimal)profit;
        }
 public void AccountDataUpdated(Account account)
 {
 }
Esempio n. 17
0
        public RequestStatus SendNewOrderRequest(Account account,
            MarketOrder order,
            OrderType orderType,
            decimal requestedPrice,
            decimal slippagePoints)
        {
            TradeSharp.ProviderProxyContract.Entity.MarketOrder request;
            RequestStatus error;
            if (!MakeMarketRequest(account, order.Symbol, order.Magic, order.Volume, order.Side,
                orderType,
                requestedPrice, slippagePoints,
                string.Format("open for acc#{0}", account.ID),
                null, order.Comment, order.ExpertComment, order.trailingLevels[0], order.trailingTargets[0],
                out error, out request)) return error;

            // отправить запрос на вход в рынок в соотв сессию
            if (!request.SendToQueue(false))
            {
                errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                    "Невозможно отправить сообщение (NewOrder) в очередь MQ", null));
                return RequestStatus.DealerError;
            }
            return RequestStatus.OK;
        }
 public RobotContextLiveFarm(TradeSharpServerTrade proxyTrade, Account accountInfo, Func<string> getUserLogin,
     ActualAccountData accountData)
     : base(proxyTrade, accountInfo, getUserLogin)
 {
     this.accountData = accountData;
 }
 public AccountForSelectList(Account account)
 {
     this.account = account;
 }
Esempio n. 20
0
        public void OpenInvestInPAMMDialog(PerformerStat performer, bool invest)
        {
            ScheduleTaskOnSynchronizationCompleted(state =>
                {
                    if (walletExplicitDetail == null || performer == null) return;

                    var performerAccount = new Account
                        {
                            ID = performer.Account,
                            Currency = performer.DepoCurrency,
                            Balance = (decimal) performer.Equity,
                            Equity = (decimal) performer.Equity
                        };

                    // сколько можно вывести средств?
                    var userShare = walletExplicitDetail.realAccounts.FirstOrDefault(a => a.AccountId == performer.Account);
                    performerAccount.Balance = userShare == null ? 0 : userShare.ShareMoneyWallet;

                    // окно пополнения - снятия
                    var dlg = new WalletWithdrawForm(walletExplicitDetail.wallet,
                                                     gridAccount.GetRowValues<AccountShared>(false)
                                                                .Select(a => a.Account)
                                                                .ToList(),
                                                     performerAccount, true);
                    if (dlg.ShowDialog() != DialogResult.OK) return;

                    if (dlg.TargetWithdrawal > 0)
                        InvestInPAMM(performer, dlg.TargetWithdrawal, false, dlg.WithdrawAll);
                    if (dlg.TargetDespoit > 0)
                        InvestInPAMM(performer, dlg.TargetDespoit, true, dlg.WithdrawAll);
                });
        }
Esempio n. 21
0
        private void InitContextAccountSettings()
        {
            if (robotContext.AccountInfo != null) return;
            Account account;
            if (AccountStatus.Instance.AccountData != null)
            {
                account = new Account(AccountStatus.Instance.AccountData)
                              {
                                  Balance = DefaultStartBalance,
                                  Equity = DefaultStartBalance,
                                  UsedMargin = 0
                              };
            }
            else
                account = new Account
                    {
                        Group = DalAccountGroup.Instance.Groups.Length == 0
                                    ? "Demo" : DalAccountGroup.Instance.Groups[0].Code,
                        Balance = 100000,
                        Equity = 100000,
                        Currency = "USD",
                        ID = 0,
                        MaxLeverage = 50,
                        UsedMargin = 0
                    };

            robotContext.AccountInfo = new Account(account);
        }
Esempio n. 22
0
        private void LoadWalletAsynch(object sender, DoWorkEventArgs ea)
        {
            var details = new WalletExplicitResponse();

            // запросить средства в кошельке, средства на счете
            var error = WalletError.CommonError;

            try
            {
                details.wallet = TradeSharpWalletManager.Instance.proxy.GetUserWalletSubscriptionAndLastPayments(
                    CurrentProtectedContext.Instance.MakeProtectedContext(),
                    AccountStatus.Instance.Login,
                    0,
                    out details.transfersTotal,
                    out details.subscriptions,
                    out details.transfers,
                    out error);
                /*details.wallet = TradeSharpWalletManager.Instance.proxy.GetUserWalletSubscriptionAndLastPayments(
                    CurrentProtectedContext.Instance.MakeProtectedContext(),
                    AccountStatus.Instance.Login,
                    details.transfersTotal,
                    out details.transfersTotal,
                    out details.subscriptions,
                    out details.transfers,
                    out error);*/
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("GetUserWalletSubscriptionAndLastPayments({0}) error: {1}",
                    AccountStatus.Instance.Login, ex);
            }
            if (error != WalletError.OK)
            {
                Logger.ErrorFormat("GetUserWalletSubscriptionAndLastPayments({0}) error: {1}",
                    AccountStatus.Instance.Login, EnumFriendlyName<WalletError>.GetString(error));
            }
            if (details.wallet == null)
                return;

            lastAccountDataProcessed = AccountStatus.Instance.AccountData;

            // запросить актуальные данные по реальным счетам пользователя
            try
            {
                TradeSharpAccount.Instance.proxy.GetUserOwnAndSharedAccounts(
                    AccountStatus.Instance.Login, CurrentProtectedContext.Instance.MakeProtectedContext(),
                    out details.realAccounts);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("GetUserOwnAndSharedAccounts({0}) error: {1}", AccountStatus.Instance.Login, ex);
            }

            try
            {
                details.transfersSummary = TradeSharpAccount.Instance.proxy.GetTransfersSummary(
                    CurrentProtectedContext.Instance.MakeProtectedContext(), AccountStatus.Instance.Login);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("GetTransfersSummary({0}) error: {1}", AccountStatus.Instance.Login, ex);
            }

            ea.Result = details;
        }
Esempio n. 23
0
 public AccountTag(Account ac)
 {
     account = ac;
 }
Esempio n. 24
0
        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;
            }
        }
Esempio n. 25
0
        public RequestStatus SendNewOrderRequest(Account account,
            MarketOrder order,
            OrderType orderType,
            decimal requestedPrice,
            decimal slippagePoints)
        {
            var quote = QuoteStorage.Instance.ReceiveValue(order.Symbol);
            if (quote == null)
                return RequestStatus.NoPrice;

            var slippageAbs = slippagePoints;
            if (slippageAbs > 0)
                slippageAbs = DalSpot.Instance.GetAbsValue(order.Symbol, slippageAbs);
            var status = MakeMarketRequest(new TradeTransactionRequest
            {
                Account = account.ID,
                ClosingPositionId = null,
                Comment = order.Comment,
                ExpertComment = order.ExpertComment,
                Id = RequestUniqueId, // !!
                Magic = order.Magic,
                RequestedPrice = (decimal)(order.Side > 0 ? quote.ask : quote.bid),
                SlippageAbs = slippageAbs,
                Side = order.Side,
                Symbol = order.Symbol,
                Volume = order.Volume
            }, order);
            return status;
        }
Esempio n. 26
0
 public void AccountDataUpdated(Account account)
 {
     AccountStatus.Instance.OnAccountUpdated(account);
 }
Esempio n. 27
0
        /// <summary>
        /// обновить заголовок окна (в потокобезопасном режиме)
        /// </summary>
        private void OnAccountInfoUpdated(Account account)
        {
            MainWindowTitle.Instance.Account = account;

            // обновить контекст для роботов
            RobotFarm.UpdateRobotContext(account);
        }
Esempio n. 28
0
        public RequestStatus SendNewOrderRequest(Account account, 
            MarketOrder order,
            OrderType orderType,
            decimal requestedPrice,
            decimal slippagePoints)
        {
            order.TimeEnter = DateTime.Now;
            order.State = PositionState.Opened;

            // подставить текущую цену
            var quote = QuoteStorage.Instance.ReceiveValue(order.Symbol);
            if (quote == null)
                return RequestStatus.NoPrice;
            order.PriceEnter = order.Side > 0 ? quote.ask : quote.bid;

            // проверить проскальзывание
            if (slippagePoints != 0)
            {
                var slippageAbs = DalSpot.Instance.GetAbsValue(order.Symbol, slippagePoints);
                var delta = Math.Abs(order.PriceEnter - (float)requestedPrice);
                if (delta > (float)slippageAbs) return RequestStatus.Slippage;
            }

            if (account.Balance <= 0)
            {
                Logger.ErrorFormat("SendNewOrderRequest (счет {0}) - баланс счета равен 0", account.ID);
                return RequestStatus.DealerError;
            }
            // получить уникальный Id сигнала, он же - Magic для ордера
            // посчитать плечо, пересчитав объем в валюту депо
            bool areEqual, inverse;
            var baseTicker = DalSpot.Instance.FindSymbol(order.Symbol, true, account.Currency,
                out inverse, out areEqual);
            if (!areEqual && string.IsNullOrEmpty(baseTicker))
            {
                Logger.ErrorFormat("SendNewOrderRequest - неизвестный сивол пересчета базовой валюты ({0})",
                    order.Symbol);
                return RequestStatus.DealerError;
            }
            var rateDepo = 1f;
            if (!areEqual)
            {
                var baseQuote = QuoteStorage.Instance.ReceiveValue(baseTicker);
                if (baseQuote == null)
                {
                    Logger.ErrorFormat("SendNewOrderRequest - нет котировки {0} для пересчета базовой валюты",
                                       baseQuote);
                    return RequestStatus.DealerError;
                }
                rateDepo = inverse ? 1/quote.ask : quote.bid;
            }
            var volumeDepo = order.Volume * rateDepo;
            var leverage = (decimal) volumeDepo / account.Balance;

            // отправить сигнал
            var signal = new ManagerSignal
            {
                Id = DateTime.Now.Ticks.ToString(),
                Price = (decimal)order.PriceEnter,
                Side = order.Side,
                Symbol = order.Symbol,
                Leverage = (decimal)leverage,
                Category = signalCategoryCode
            };

            // !!!
            // переделал ID сигнала в запись поля expertComment вместо comment
            //order.Comment = signal.Id;
            order.ExpertComment = signal.Id;

            // отправка сигнала успешна?)
            var timeExec = new ThreadSafeTimeStamp();
            timeExec.Touch();
            if (!SendSignal(signal, true)) return RequestStatus.DealerError;
            int posID;
            // сохранить ордер (и уведомить клиента)
            var endTime = DateTime.Now - timeExec.GetLastHit();
            Logger.InfoFormat("Время исполнения SendNewOrderRequest SendSignal: {0} секунд, {1} миллисекунд", endTime.TotalSeconds, endTime.TotalMilliseconds);
            timeExec.Touch();
            var result = ServerInterface.SaveOrderAndNotifyClient(order, out posID);
            endTime = DateTime.Now - timeExec.GetLastHit();
            Logger.InfoFormat("Время исполнения SendNewOrderRequest - SaveOrderAndNotifyClient: {0} секунд, {1} миллисекунд", endTime.TotalSeconds, endTime.TotalMilliseconds);
            return result ? RequestStatus.OK : RequestStatus.SerializationError;
        }
Esempio n. 29
0
 public virtual void UpdateAccountInfo(Account accountInfo)
 {
     robotContext.AccountInfo = accountInfo;
 }
 public TerminalLiveRobotContext(TradeSharpServerTrade proxyTrade, Account accountInfo, Func<string> getUserLogin)
     : base(proxyTrade, accountInfo, getUserLogin)
 {
 }