Example #1
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            var secret = PwdBox.Password;

            if (!IsConnected)
            {
                if (ConsumerKey.IsEmpty())
                {
                    MessageBox.Show(this, LocalizedStrings.Str3689);
                    return;
                }
                if (secret.IsEmpty())
                {
                    MessageBox.Show(this, LocalizedStrings.Str3690);
                    return;
                }

                if (Trader == null)
                {
                    // create connector
                    Trader = new ETradeTrader();

                    try
                    {
                        Trader.AccessToken = null;

                        var token = OAuthToken.Deserialize(Properties.Settings.Default.AccessToken);
                        if (token != null && token.ConsumerKey.ToLowerInvariant() == ConsumerKey.ToLowerInvariant())
                        {
                            Trader.AccessToken = token;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, LocalizedStrings.Str3691Params.Put(ex));
                    }

                    Trader.LogLevel = LogLevels.Debug;

                    _logManager.Sources.Add(Trader);

                    // subscribe on connection successfully event
                    Trader.Connected += () => this.GuiAsync(() =>
                    {
                        Properties.Settings.Default.AccessToken = Trader.AccessToken.Serialize();
                        OnConnectionChanged(true);
                    });

                    // subscribe on connection error event
                    Trader.ConnectionError += error => this.GuiAsync(() =>
                    {
                        OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected);
                        MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
                    });

                    Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false));

                    // subscribe on error event
                    Trader.Error += error =>
                                    this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));

                    // subscribe on error of market data subscription event
                    Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
                                                           this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));

                    Trader.NewSecurity  += security => _securitiesWindow.SecurityPicker.Securities.Add(security);
                    Trader.NewMyTrade   += trade => _myTradesWindow.TradeGrid.Trades.Add(trade);
                    Trader.NewOrder     += order => _ordersWindow.OrderGrid.Orders.Add(order);
                    Trader.NewStopOrder += order => _stopOrdersWindow.OrderGrid.Orders.Add(order);
                    Trader.NewPortfolio += portfolio =>
                    {
                        _portfoliosWindow.PortfolioGrid.Portfolios.Add(portfolio);

                        // subscribe on portfolio updates
                        Trader.RegisterPortfolio(portfolio);
                    };
                    Trader.NewPosition += position => _portfoliosWindow.PortfolioGrid.Positions.Add(position);

                    // subscribe on error of order registration event
                    Trader.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;
                    // subscribe on error of order cancelling event
                    Trader.OrderCancelFailed += OrderFailed;

                    // subscribe on error of stop-order registration event
                    Trader.StopOrderRegisterFailed += _stopOrdersWindow.OrderGrid.AddRegistrationFail;
                    // subscribe on error of stop-order cancelling event
                    Trader.StopOrderCancelFailed += OrderFailed;

                    Trader.MassOrderCancelFailed += (transId, error) =>
                                                    this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));

                    // set market data provider
                    _securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
                }

                Trader.Sandbox = IsSandbox;
                //Trader.SandboxSecurities = IsSandbox ? GetSandboxSecurities() : null;
                Trader.ConsumerKey    = ConsumerKey;
                Trader.ConsumerSecret = secret;

                Trader.Connect();
            }
            else
            {
                Trader.Disconnect();
            }
        }
Example #2
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            var secret = PwdBox.Password;

            if (!IsConnected)
            {
                if (ConsumerKey.IsEmpty())
                {
                    MessageBox.Show(this, LocalizedStrings.Str3689);
                    return;
                }
                if (secret.IsEmpty())
                {
                    MessageBox.Show(this, LocalizedStrings.Str3690);
                    return;
                }

                if (Trader == null)
                {
                    // создаем подключение
                    Trader = new ETradeTrader();

                    try
                    {
                        Trader.AccessToken = null;

                        var token = OAuthToken.Deserialize(Properties.Settings.Default.AccessToken);
                        if (token != null && token.ConsumerKey.ToLowerInvariant() == ConsumerKey.ToLowerInvariant())
                        {
                            Trader.AccessToken = token;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, LocalizedStrings.Str3691Params.Put(ex));
                    }

                    Trader.LogLevel = LogLevels.Debug;

                    _logManager.Sources.Add(Trader);

                    // подписываемся на событие успешного соединения
                    Trader.Connected += () => this.GuiAsync(() =>
                    {
                        Properties.Settings.Default.AccessToken = Trader.AccessToken.Serialize();
                        OnConnectionChanged(true);

                        Trader.StartExport();
                    });

                    // подписываемся на событие разрыва соединения
                    Trader.ConnectionError += error => this.GuiAsync(() =>
                    {
                        OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected);
                        MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
                    });

                    Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false));

                    // подписываемся на ошибку обработки данных (транзакций и маркет)
                    Trader.ProcessDataError += error =>
                                               this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));

                    // подписываемся на ошибку подписки маркет-данных
                    Trader.MarketDataSubscriptionFailed += (security, type, error) =>
                                                           this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security)));

                    Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities);
                    Trader.NewMyTrades   += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades);
                    Trader.NewOrders     += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders);
                    Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders);
                    Trader.NewPortfolios += portfolios =>
                    {
                        // регистрирует портфели на обновление данных
                        portfolios.ForEach(Trader.RegisterPortfolio);

                        _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios);
                    };
                    Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions);

                    // подписываемся на событие о неудачной регистрации заявок
                    Trader.OrdersRegisterFailed += OrdersFailed;
                    // подписываемся на событие о неудачном снятии заявок
                    Trader.OrdersCancelFailed += OrdersFailed;

                    // подписываемся на событие о неудачной регистрации стоп-заявок
                    Trader.StopOrdersRegisterFailed += OrdersFailed;
                    // подписываемся на событие о неудачном снятии стоп-заявок
                    Trader.StopOrdersCancelFailed += OrdersFailed;

                    // устанавливаем поставщик маркет-данных
                    _securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
                }

                Trader.Sandbox = IsSandbox;
                //Trader.SandboxSecurities = IsSandbox ? GetSandboxSecurities() : null;
                Trader.ConsumerKey    = ConsumerKey;
                Trader.ConsumerSecret = secret;

                Trader.Connect();
            }
            else
            {
                Trader.Disconnect();
            }
        }