Example #1
0
        private void OnQueryPosition(AccountVM acctVm)
        {
            string viewName     = acctVm.InvestorId;
            var    existingPane = RegionManager.GetExistingPane <PositionContentPane>(viewName);

            if (existingPane != null)
            {
                existingPane.Activate();
                PositionView positionView = existingPane.Content as PositionView;
                if (positionView != null)
                {
                    positionView.ViewModel.RefreshPositionCommand.Execute();
                }
            }
            else
            {
                PositionContentPane pane = new PositionContentPane();
                pane.ViewName = viewName;
                var positionView = ServiceLocator.Current.GetInstance <PositionView>();
                positionView.ViewModel.SetAccount(acctVm);
                positionView.ViewModel.RefreshPositionCommand.Execute();
                pane.Content = positionView;
                //pane.CloseAction = Infragistics.Windows.DockManager.PaneCloseAction.RemovePane;
                pane.Closed += new EventHandler <Infragistics.Windows.DockManager.Events.PaneClosedEventArgs>(pane_Closed);

                RegionManager.RegisterViewWithRegion(RegionNames.PortfolioViewRegion,
                                                     () => pane);
                pane.Activate();
            }
        }
Example #2
0
 private void OnDetachHost(AccountVM acct)
 {
     EventLogger.Write(string.Format("正在将{0}从交易终端断开连接...", acct.InvestorId));
     _client.Disconnect();
     EventLogger.Write(string.Format("{0}已断开", acct.InvestorId));
     Status = "未连接";
 }
        private void xamDataTreeAccount_NodeDragEnd(object sender, Infragistics.DragDrop.DragDropEventArgs e)
        {
            if (e.OperationType != null && e.OperationType == OperationType.Copy)
            {
                XamDataTreeNode origNode = e.Data as XamDataTreeNode;
                if (origNode == null)
                {
                    return;
                }
                PortfolioVM porfVm = origNode.Data as PortfolioVM;
                if (porfVm == null)
                {
                    return;
                }

                XamDataTreeNodeControl treeNodeCtrl = e.DropTarget as XamDataTreeNodeControl;
                if (treeNodeCtrl == null)
                {
                    return;
                }
                AccountVM acctVm = treeNodeCtrl.Node.Data as AccountVM;
                if (acctVm == null)
                {
                    return;
                }

                XElement portfElem = porfVm.Persist();
                var      cloned    = PortfolioVM.Load(acctVm, portfElem);
                acctVm.AddPorfolio(cloned);

                ViewModel.Persist();
            }
        }
Example #4
0
 public AccountInfoVM(AccountVM parentAcct)
 {
     QueryAccountCommand  = new DelegateCommand(OnQueryAccount);
     QueryPositionCommand = new DelegateCommand(OnQueryPosition);
     CurrentAccount       = parentAcct;
     EventAggregator      = ServiceLocator.Current.GetInstance <IEventAggregator>();
 }
Example #5
0
 private void OnDisconnectHost(AccountVM acct)
 {
     EventLogger.Write(string.Format("正在将{0}关闭交易终端连接...", acct.InvestorId));
     Close();
     EventLogger.Write(string.Format("{0}已断开", acct.InvestorId));
     Status = "未连接";
 }
Example #6
0
        private void OnAddPortfolio(AccountVM acct)
        {
            PortfolioVM portf = new PortfolioVM(this);

            portf.Id = NextPortfId();

            EditPortfolioDlg dlg = new EditPortfolioDlg();

            dlg.Owner     = System.Windows.Application.Current.MainWindow;
            dlg.Portfolio = portf;
            bool?res = dlg.ShowDialog();

            if (res ?? false)
            {
                portf.SetHedgeFlag(HedgeFlag);
                PTEntity.PortfolioItem portfolioItem = dlg.Portfolio.GetEntity();
                AddPorfolio(portf);
                if (_client.IsConnected)
                {
                    _client.AddPortfolio(portfolioItem);
                }

                PublishChanged();
            }
        }
        private void xamDataTreeAccount_ActiveNodeChanged(object sender, Infragistics.Controls.Menus.ActiveNodeChangedEventArgs e)
        {
            AccountVM acctVm = e.NewActiveTreeNode.Data as AccountVM;

            if (acctVm != null)
            {
                EventAggregator.GetEvent <AccountSelectedEvent>().Publish(acctVm);
            }
        }
Example #8
0
        private void OnClosePosition(CloseMlOrderArgs closeArgs)
        {
            AccountVM acct = _accounts.FirstOrDefault(a => a.Id == closeArgs.AccountId);

            if (acct != null)
            {
                acct.Host.PortfClosePosition(closeArgs.MlOrder.PortfolioId, closeArgs.MlOrder.OrderId, closeArgs.LegOrderRef);
            }
            EventLogger.Write("组合委托{0} 平仓", closeArgs.MlOrder.OrderId);
        }
Example #9
0
 public PortfolioVM(AccountVM accountVm)
 {
     _accountVm              = accountVm;
     OpenPositionCommand     = new DelegateCommand(OnOpenPosition);
     OpenQtyPositionCommand  = new DelegateCommand(OnOpenQtyPosition);
     ClosePositionCommand    = new DelegateCommand(OnClosePosition);
     CloseQtyPositionCommand = new DelegateCommand(OnCloseQtyPosition);
     ModifyQtyCommand        = new DelegateCommand(OnModifyQuantity);
     StartCommand            = new DelegateCommand(OnStart);
     StopCommand             = new DelegateCommand(OnStop);
 }
Example #10
0
        private void OnCancelOrder(CancelOrderEventArgs cxlArgs)
        {
            AccountVM acct = _accounts.FirstOrDefault(a => a.Id == cxlArgs.AccountId);

            if (acct != null)
            {
                acct.Host.CancelOrder(cxlArgs.OrderToCancel);
            }
            EventLogger.Write("{0}: 撤单({1} - {2})", cxlArgs.AccountId,
                              cxlArgs.OrderToCancel.OrderRef,
                              cxlArgs.OrderToCancel.InstrumentID);
        }
Example #11
0
        private void OnConnectHost(AccountVM acct)
        {
            ChangeStatus("连接中...", true);

            UIContext = SynchronizationContext.Current;

            TradeStationConnector connector = new TradeStationConnector(_client, _clientHandler, UIContext,
                                                                        () => new ServerLoginParam
            {
                TradeAddress = AddressRepo.EffectiveTrading.Address,
                QuoteAddress = AddressRepo.EffectiveMarket.Address,
                BrokerId     = acct.BrokerId,
                InvestorId   = acct.InvestorId,
                UserId       = acct.UserId,
                Password     = acct.Password
            }
                                                                        );

            //string localHostIP = NativeHost.GetLocalIP();
            //string host = ConfigurationHelper.GetAppSettingValue("tradeHostIP", localHostIP);
            //HostPort = ConfigurationHelper.GetAppSettingValue("tradeHostPort", 16181);

            string effectiveTradeStation = AddressRepo.EffectiveTradeStation.Address;

            string[] addr_port = effectiveTradeStation.Split(':');
            string   host      = addr_port[0];

            HostPort = int.Parse(addr_port[1]);

            _client.SetPseudo(acct.Id);
            EventLogger.Write(string.Format("正在为{0}建立交易终端...", acct.InvestorId));
            connector.Login(host, HostPort,
                            (succ, error) =>
            {
                if (succ)
                {
                    ChangeStatus("已连接", false);
                    EventLogger.Write("连接交易终端成功");
                    SyncToHost();
                }
                else
                {
                    ChangeStatus("未连接", false);
                    EventLogger.Write("连接交易终端失败 : {0}", error);
                }
            },
                            status => EventLogger.Write(status));
        }
Example #12
0
        public static AccountVM Load(XElement xmlElement)
        {
            AccountVM acct = new AccountVM();

            XAttribute attrBrokerId = xmlElement.Attribute("brokerId");

            if (attrBrokerId != null)
            {
                acct.BrokerId = attrBrokerId.Value;
            }

            XAttribute attrInvestorId = xmlElement.Attribute("investorId");

            if (attrInvestorId != null)
            {
                acct.InvestorId = attrInvestorId.Value;
            }

            XAttribute attrPwd = xmlElement.Attribute("password");

            if (attrPwd != null)
            {
                acct.Password = attrPwd.Value;
            }

            XAttribute attrMaxSubmit = xmlElement.Attribute("maxSubmit");

            if (attrMaxSubmit != null)
            {
                acct.MaxSubmit = int.Parse(attrMaxSubmit.Value);
            }

            XAttribute attrMaxCancel = xmlElement.Attribute("maxCancel");

            if (attrMaxCancel != null)
            {
                acct.MaxCancel = int.Parse(attrMaxCancel.Value);
            }

            foreach (var portfElem in xmlElement.Element("portfolios").Elements("portfolio"))
            {
                PortfolioVM porfVm = PortfolioVM.Load(acct, portfElem);
                acct.AddPorfolio(porfVm);
            }

            return(acct);
        }
Example #13
0
        private void OnAddAccount()
        {
            EditAccountDlg addAcctDlg = new EditAccountDlg(true);

            addAcctDlg.Owner = Application.Current.MainWindow;
            AccountVM acct = new AccountVM();

            addAcctDlg.ViewModel = acct;
            bool?ret = addAcctDlg.ShowDialog();

            if (ret ?? false)
            {
                _accounts.Add(acct);
                //CheckCanExecute();

                Persist();
            }
        }
Example #14
0
        private void OnRemoveAccount(XamDataTree dataTree)
        {
            AccountVM acct = GetSelectedAcccount(dataTree);

            if (acct == null)
            {
                return;
            }

            string           prompt = string.Format("你确定要删除 {0} ?", acct.InvestorId);
            MessageBoxResult res    = MessageBox.Show(System.Windows.Application.Current.MainWindow,
                                                      prompt, "删除帐户", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (res == MessageBoxResult.Yes)
            {
                this._accounts.Remove(acct);
                Persist();
            }
        }
Example #15
0
        private void OnEditAccount(XamDataTree dataTree)
        {
            AccountVM acct = GetSelectedAcccount(dataTree);

            if (acct == null)
            {
                return;
            }

            EditAccountDlg addAcctDlg = new EditAccountDlg();

            addAcctDlg.Owner     = Application.Current.MainWindow;
            addAcctDlg.ViewModel = acct;
            bool?ret = addAcctDlg.ShowDialog();

            if (ret ?? false)
            {
                Persist();
            }
        }
Example #16
0
        private void Load()
        {
            string filePath = PeristFilePath;

            if (File.Exists(filePath))
            {
                XElement acctsElem      = XElement.Load(filePath);
                var      attr           = acctsElem.Attribute("marketData");
                string   marketDataName = attr != null ? attr.Value : "";
                ServerAddrRepoVM.SelectMarket(marketDataName);
                attr = acctsElem.Attribute("trading");
                string tradingName = attr != null ? attr.Value : "";
                ServerAddrRepoVM.SelectTrading(tradingName);
                attr = acctsElem.Attribute("tradeStation");
                string tradeStationName = attr != null ? attr.Value : "";
                ServerAddrRepoVM.SelectTradeStation(tradeStationName);

                foreach (var acctElem in acctsElem.Elements("account"))
                {
                    AccountVM acctVm = AccountVM.Load(acctElem);
                    _accounts.Add(acctVm);
                }
            }
        }
Example #17
0
        private bool HaveTradeStationReady(AccountVM acct)
        {
            EventLogger.Write("正在连接交易服务器: " + AddressRepo.EffectiveTrading.Name);
            OperationResult tradeConnResult = _client.TradeConnect(AddressRepo.EffectiveTrading.Address,
                                                                   acct.InvestorId);

            if (tradeConnResult.Success)
            {
                EventLogger.Write("交易连接成功");
            }
            else
            {
                EventLogger.Write("交易连接失败 (" + tradeConnResult.ErrorMessage + ")");
                return(false);
            }

            OperationResult tradeLoginResult = _client.TradeLogin(acct.BrokerId,
                                                                  acct.InvestorId, acct.Password, new entity.AccountSettings
            {
                MaxSubmit = acct.MaxSubmit,
                MaxCancel = acct.MaxCancel
            });

            if (tradeLoginResult.Success)
            {
                EventLogger.Write("交易登录成功");
            }
            else
            {
                EventLogger.Write("交易登录失败 (" + tradeLoginResult.ErrorMessage + ")");
                return(false);
            }

            EventLogger.Write("正在连接行情服务器: " + AddressRepo.EffectiveMarket.Name);
            OperationResult quoteConnResult = _client.QuoteConnect(AddressRepo.EffectiveMarket.Address,
                                                                   acct.InvestorId);

            if (quoteConnResult.Success)
            {
                EventLogger.Write("行情连接成功");
            }
            else
            {
                EventLogger.Write("行情连接失败 (" + quoteConnResult.ErrorMessage + ")");
                return(false);
            }

            OperationResult quoteLoginResult = _client.QuoteLogin(acct.BrokerId,
                                                                  acct.InvestorId, acct.Password);

            if (quoteLoginResult.Success)
            {
                EventLogger.Write("行情登录成功");
            }
            else
            {
                EventLogger.Write("行情登录失败 (" + quoteLoginResult.ErrorMessage + ")");
                return(false);
            }

            return(true);
        }
Example #18
0
        private void OnConnectHost(AccountVM acct)
        {
            ChangeStatus("连接中...", true);

            SynchronizationContext uiContext = SynchronizationContext.Current;

            HostPort = ConfigurationHelper.GetAppSettingValue("tradeHostPort", 16181);;

            EventLogger.Write(string.Format("正在为{0}建立交易终端...", acct.InvestorId));

            Func <int, bool, bool> funcLaunch = new Func <int, bool, bool>(_host.Startup);

            funcLaunch.BeginInvoke(HostPort, true,
                                   delegate(IAsyncResult arLaunch)
            {
                bool succ = funcLaunch.EndInvoke(arLaunch);

                if (!succ)
                {
                    LogManager.Logger.Warn("Launch trade station failed");
                    return;
                }

                LogManager.Logger.InfoFormat("TradeStaion started up.");

                Action <int> actionLoopConnect = null;
                _connectTimes = 1;

                Action <bool, string, bool> actionClntConnectDone = null;
                actionClntConnectDone = (b, t, attach) =>
                {
                    string txt = string.Format("连接交易终端(第{0}次)", _connectTimes);
                    if (b)
                    {
                        txt += "成功";
                    }
                    else
                    {
                        txt += "失败 (" + t + ")";
                    }
                    EventLogger.Write(txt);

                    if (b)
                    {
                        if (attach)
                        {
                            uiContext.Send(o => ChangeStatus("已连接", false), null);
                            EventLogger.Write("恢复连接到交易终端");
                        }
                        else
                        {
                            Func <AccountVM, bool> actionReady = new Func <AccountVM, bool>(HaveTradeStationReady);
                            actionReady.BeginInvoke(
                                acct,
                                new AsyncCallback(
                                    delegate(IAsyncResult ar)
                            {
                                try
                                {
                                    bool ok = actionReady.EndInvoke(ar);
                                    if (ok)
                                    {
                                        uiContext.Send(o => ChangeStatus("已连接", false), null);
                                        EventLogger.Write(string.Format("{0}准备就绪", acct.InvestorId));
                                        SyncToHost();
                                    }
                                    else
                                    {
                                        uiContext.Send(o => ChangeStatus("连接失败", false), null);
                                        EventLogger.Write(string.Format("{0}发生错误", acct.InvestorId));
                                        _client.Disconnect();
                                        _host.Exit();
                                    }
                                }
                                catch (System.Exception ex)
                                {
                                    EventLogger.Write("初始化交易终端发生错误");
                                    LogManager.Logger.Error(ex.Message);
                                    _host.Exit();
                                }
                            }),
                                null);
                            LogManager.Logger.Info(txt);
                        }
                    }
                    else
                    {
                        LogManager.Logger.Warn(txt);
                        if ("交易终端拒绝连接" != t &&
                            _connectTimes < MaxRetryConnectTimes &&
                            actionLoopConnect != null)
                        {
                            actionLoopConnect.Invoke(++_connectTimes);
                        }
                        else
                        {
                            uiContext.Send(o => ChangeStatus("连接失败", false), null);
                            EventLogger.Write(string.Format("为{0}尝试{1}次连接均发生错误"
                                                            , acct.InvestorId, _connectTimes));
                            _client.Disconnect();
                        }
                    }
                };

                actionLoopConnect = new Action <int>(delegate(int times)
                {
                    if (times > 1)
                    {
                        Thread.Sleep(1000);
                    }

                    string effectiveTradeStation = AddressRepo.EffectiveTradeStation.Address;
                    EventLogger.Write("Connect to {0}", effectiveTradeStation);
                    LogManager.Logger.InfoFormat("Connect to {0}", effectiveTradeStation);
                    _client.AuthClientId = this.Id;

                    try
                    {
                        _client.ConnectAsync(effectiveTradeStation, actionClntConnectDone);
                    }
                    catch (System.Exception ex)
                    {
                        LogManager.Logger.ErrorFormat("Error connecting host due to : {0}", ex.Message);
                        if (actionClntConnectDone != null)
                        {
                            actionClntConnectDone(false, "交易终端拒绝连接", false);
                        }
                    }
                });

                actionLoopConnect.Invoke(_connectTimes);
            }, null);

            //_host.Startup(HostPort);
        }
Example #19
0
 private void OnCertainAccountChanged(AccountVM acctVm)
 {
     Persist();
 }
Example #20
0
        public static PortfolioVM Load(AccountVM acct, XElement xmlElement)
        {
            PortfolioVM portf = new PortfolioVM(acct);

            portf.IsLoading = true;
            XAttribute attr = xmlElement.Attribute("id");

            if (attr != null)
            {
                portf.Id = attr.Value;
            }

            attr = xmlElement.Attribute("quantity");
            if (attr != null)
            {
                portf.Quantity = int.Parse(attr.Value);
            }

            attr = xmlElement.Attribute("currentPosition");
            if (attr != null)
            {
                int currPos = int.Parse(attr.Value);
                portf.Position  = currPos;
                portf.OpenTimes = currPos;
            }

            attr = xmlElement.Attribute("avgCost");
            if (attr != null)
            {
                double avgCost = double.Parse(attr.Value);
                portf.AvgCost = avgCost;
            }

            attr = xmlElement.Attribute("maxPosition");
            if (attr != null)
            {
                portf.MaxPosition = int.Parse(attr.Value);
            }

            attr = xmlElement.Attribute("autoOpen");
            if (attr != null)
            {
                portf.AutoOpen = attr.Value == bool.TrueString;
            }

            attr = xmlElement.Attribute("autoStopGain");
            if (attr != null)
            {
                portf.AutoStopGain = attr.Value == bool.TrueString;
            }

            attr = xmlElement.Attribute("autoStopLoss");
            if (attr != null)
            {
                portf.AutoStopLoss = attr.Value == bool.TrueString;
            }

            attr = xmlElement.Attribute("autoTracking");
            if (attr != null)
            {
                portf.AutoTracking = attr.Value == bool.TrueString;
            }

            attr = xmlElement.Attribute("enablePrefer");
            if (attr != null)
            {
                portf.EnablePrefer = attr.Value == bool.TrueString;
            }

            foreach (var legElem in xmlElement.Element("legs").Elements("leg"))
            {
                LegVM legVm = LegVM.Load(legElem);
                portf.AddLeg(legVm);
            }

            XElement xmlSetting      = xmlElement.Element("setting");
            string   strategyName    = xmlSetting.Attribute("name").Value;
            string   strategyXmlText = xmlSetting.Value;

            portf.StrategySetting = StrategySetting.Load(strategyName, strategyXmlText);
            portf.IsLoading       = false;
            return(portf);
        }
Example #21
0
 private void OnStopAllPortfolio(AccountVM acct)
 {
     StartAccountPortfolios(false);
 }
Example #22
0
 private void OnStartAllPortfolio(AccountVM acct)
 {
     StartAccountPortfolios(true);
 }
Example #23
0
 public void OnAccountSelected(AccountVM accountVm)
 {
     AccountId      = accountVm.InvestorId;
     CurrentAccount = accountVm;
     OnQueryAccount();
 }
 private void OnAccountSelected(AccountVM accountVm)
 {
     this.DataContext = accountVm.AccountInfo;
 }