示例#1
0
        protected override void OnClosing(CancelEventArgs e)
        {
            _realConnector?.Disconnect();
            _emuConnector?.Disconnect();

            base.OnClosing(e);
        }
示例#2
0
 private void ConnectClick(object sender, RoutedEventArgs e)
 {
     if (!_isConnected)
     {
         ConnectBtn.IsEnabled = false;
         _connector.Connect();
     }
     else
     {
         _connector.Disconnect();
     }
 }
示例#3
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            if (!_isConnected)
            {
                if (_connector == null)
                {
                    if (SmartCom.IsChecked == true)
                    {
                        if (Login.Text.IsEmpty())
                        {
                            MessageBox.Show(this, LocalizedStrings.Str2974);
                            return;
                        }
                        else if (Password.Password.IsEmpty())
                        {
                            MessageBox.Show(this, LocalizedStrings.Str2975);
                            return;
                        }

                        // create real-time emu connector
                        _connector = new RealTimeEmulationTrader <IMessageAdapter>(new SmartComMessageAdapter(new MillisecondIncrementalIdGenerator())
                        {
                            Login    = Login.Text,
                            Password = Password.Password.To <SecureString>(),
                            Address  = Address.SelectedAddress
                        });
                    }
                    else
                    {
                        // create real-time emu connector
                        _connector = new RealTimeEmulationTrader <IMessageAdapter>(new IQFeedMarketDataMessageAdapter(new MillisecondIncrementalIdGenerator())
                        {
                            Level1Address = Level1AddressCtrl.Text.To <EndPoint>(),
                            Level2Address = Level2AddressCtrl.Text.To <EndPoint>(),
                            LookupAddress = LookupAddressCtrl.Text.To <EndPoint>(),
                        });
                    }

                    SecurityEditor.SecurityProvider = new FilterableSecurityProvider(_connector);

                    _candleManager = new CandleManager(_connector);

                    _logManager.Sources.Add(_connector);

                    // clear password for security reason
                    //Password.Clear();

                    // subscribe on connection successfully event
                    _connector.Connected += () =>
                    {
                        // set flag (connection is established)
                        _isConnected = true;

                        // update gui labels
                        this.GuiAsync(() =>
                        {
                            ChangeConnectStatus(true);
                            ConnectBtn.IsEnabled = false;
                        });
                    };

                    // subscribe on connection error event
                    _connector.ConnectionError += error => this.GuiAsync(() =>
                    {
                        // update gui labels
                        ChangeConnectStatus(false);

                        MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
                    });

                    _connector.NewMarketDepths     += OnDepths;
                    _connector.MarketDepthsChanged += OnDepths;

                    _connector.NewPortfolios += PortfolioGrid.Portfolios.AddRange;
                    _connector.NewPositions  += PortfolioGrid.Positions.AddRange;

                    _connector.NewOrders   += OrderGrid.Orders.AddRange;
                    _connector.NewMyTrades += TradeGrid.Trades.AddRange;

                    // subscribe on error of order registration event
                    _connector.OrdersRegisterFailed += OrdersFailed;

                    _candleManager.Processing += (s, candle) =>
                    {
                        if (candle.State == CandleStates.Finished)
                        {
                            _buffer.Add(candle);
                        }
                    };

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

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

                _connector.Connect();
            }
            else
            {
                _connector.Disconnect();
            }
        }
示例#4
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            if (!_isConnected)
            {
                if (_connector == null)
                {
                    if (Login.Text.IsEmpty())
                    {
                        MessageBox.Show(this, LocalizedStrings.Str2974);
                        return;
                    }
                    else if (Password.Password.IsEmpty())
                    {
                        MessageBox.Show(this, LocalizedStrings.Str2975);
                        return;
                    }

                    // создаем подключение
                    _connector = new RealTimeEmulationTrader <Connector>(new SmartTrader
                    {
                        Login    = Login.Text,
                        Password = Password.Password,
                        Address  = Address.SelectedAddress
                    });

                    //_trader = new RealTimeEmulationTrader<Connector>(new StockSharp.Plaza.PlazaTrader
                    //{
                    //	IsCGate = true,
                    //}, portfolio);

                    SecurityEditor.SecurityProvider = new FilterableSecurityProvider(_connector);

                    _logManager.Sources.Add(_connector);

                    // очищаем из текстового поля в целях безопасности
                    //Password.Clear();

                    // подписываемся на событие успешного соединения
                    _connector.Connected += () =>
                    {
                        // возводим флаг, что соединение установлено
                        _isConnected = true;

                        // разблокируем кнопку Экспорт
                        this.GuiAsync(() => ChangeConnectStatus(true));

                        _candleManager = new CandleManager(_connector);

                        _connector.NewMarketDepths     += OnDepths;
                        _connector.MarketDepthsChanged += OnDepths;

                        _connector.NewOrders   += orders => Orders.Orders.AddRange(orders);
                        _connector.NewMyTrades += trades => Trades.Trades.AddRange(trades);

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

                        _candleManager.Processing += (s, candle) =>
                        {
                            if (candle.State == CandleStates.Finished)
                            {
                                _buffer.Add(candle);
                            }
                        };

                        _connector.StartExport();

                        this.GuiAsync(() =>
                        {
                            ConnectBtn.IsEnabled = false;
                        });
                    };

                    // подписываемся на событие разрыва соединения
                    _connector.ConnectionError += error => this.GuiAsync(() =>
                    {
                        // заблокируем кнопку Экспорт (так как соединение было потеряно)
                        ChangeConnectStatus(false);

                        MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
                    });

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

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

                _connector.Connect();
            }
            else
            {
                _connector.Disconnect();
            }
        }
示例#5
0
        private void ConnectClick(object sender, RoutedEventArgs e)
        {
            if (!_isConnected)
            {
                if (_connector == null)
                {
                    if (Login.Text.IsEmpty())
                    {
                        MessageBox.Show(this, LocalizedStrings.Str2974);
                        return;
                    }
                    else if (Password.Password.IsEmpty())
                    {
                        MessageBox.Show(this, LocalizedStrings.Str2975);
                        return;
                    }

                    // create real-time emu connector
                    _connector = new RealTimeEmulationTrader <Connector>(new SmartTrader
                    {
                        Login    = Login.Text,
                        Password = Password.Password,
                        Address  = Address.SelectedAddress
                    });

                    //_connector = new RealTimeEmulationTrader<Connector>(new PlazaTrader
                    //{
                    //	IsCGate = true,
                    //}, portfolio);

                    SecurityEditor.SecurityProvider = new FilterableSecurityProvider(_connector);

                    _logManager.Sources.Add(_connector);

                    // clear password for security reason
                    //Password.Clear();

                    // subscribe on connection successfully event
                    _connector.Connected += () =>
                    {
                        // set flag (connection is established)
                        _isConnected = true;

                        // update gui labels
                        this.GuiAsync(() => ChangeConnectStatus(true));

                        _candleManager = new CandleManager(_connector);

                        _connector.NewMarketDepths     += OnDepths;
                        _connector.MarketDepthsChanged += OnDepths;

                        _connector.NewOrders   += orders => Orders.Orders.AddRange(orders);
                        _connector.NewMyTrades += trades => Trades.Trades.AddRange(trades);

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

                        _candleManager.Processing += (s, candle) =>
                        {
                            if (candle.State == CandleStates.Finished)
                            {
                                _buffer.Add(candle);
                            }
                        };

                        this.GuiAsync(() =>
                        {
                            ConnectBtn.IsEnabled = false;
                        });
                    };

                    // subscribe on connection error event
                    _connector.ConnectionError += error => this.GuiAsync(() =>
                    {
                        // update gui labels
                        ChangeConnectStatus(false);

                        MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
                    });

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

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

                _connector.Connect();
            }
            else
            {
                _connector.Disconnect();
            }
        }
示例#6
0
        static void Main(string[] args)
        {
            _logManager = new LogManager();
            _logManager.Listeners.Add(new FileLogListener("log.log")
            {
                LogDirectory = "Logs"
            });

            BasketMessageAdapter realAdapter = new BasketMessageAdapter(new MillisecondIncrementalIdGenerator());


            // Можно использовать два варианта создания коннектора
            // 1 вариант. Из файла настроек connection.xml. Чтобы создать файл настроек запустите пример
            // SampleRealTimeEmulation из поставочного комплекта s# и создайте соединение для коннектора
            // Quik. Обратите внимание, что нужно добавлять только MarketDataAdapter, т.к. в нашем случае
            // используется специальный эмуляционный TransactionAdapter, который создает сам RealTimeEmulationTrader.
            // 2 вариант. Самостоятельно создаем адаптер
            // В этом примере показаны два варианта.

            if (File.Exists(_settingsFile))
            {
                // Создаем адаптер из файла настроек
                realAdapter.Load(new XmlSerializer <SettingsStorage>().Deserialize(_settingsFile));
                realAdapter.InnerAdapters.ForEach(a => a.RemoveTransactionalSupport());
            }
            else
            {
                // Создаем адаптер "вручную
                realAdapter.AssociatedBoardCode = "ALL";
                realAdapter.LogLevel            = LogLevels.Inherit;

                realAdapter.InnerAdapters.Add(new LuaFixMarketDataMessageAdapter(realAdapter.TransactionIdGenerator)
                {
                    Dialect              = StockSharp.Fix.FixDialects.Default,
                    SenderCompId         = "quik",
                    TargetCompId         = "StockSharpMD",
                    Login                = "******",
                    Password             = "******".To <SecureString>(),
                    Address              = "localhost:5001".To <EndPoint>(),
                    RequestAllPortfolios = false,
                    RequestAllSecurities = true,
                    IsResetCounter       = true,
                    ReadTimeout          = TimeSpan.Zero,
                    WriteTimeout         = TimeSpan.Zero,
                    HeartbeatInterval    = TimeSpan.Zero,
                    SupportedMessages    = new MessageTypes[] { MessageTypes.MarketData, MessageTypes.SecurityLookup, MessageTypes.ChangePassword },
                    AssociatedBoardCode  = "ALL",
                    LogLevel             = LogLevels.Inherit
                });
            }

            // Добавляем адаптер к коннектору
            _connector = new RealTimeEmulationTrader <IMessageAdapter>(realAdapter);
            _connector.EmulationAdapter.Emulator.Settings.TimeZone    = TimeHelper.Est;
            _connector.EmulationAdapter.Emulator.Settings.ConvertTime = true;

            _logManager.Sources.Add(_connector);

            _logManager.Sources.Add(_connector);

            _handler = new AutoResetEvent(false);

            bool isHandlerSet = false;

            var _sendCancelOrders = new List <Order>();

            _connector.Connected += () =>
            {
                Console.WriteLine("Соединение установлено!");
            };

            _connector.Disconnected += () =>
            {
                Console.WriteLine("Соединение разорвано!");
                Console.WriteLine("Для выхода нажмите Q и Enter.");
            };

            _connector.NewPortfolios += portfolios =>
            {
                portfolios.ForEach(portfolio =>
                {
                    Console.WriteLine("Получен портфель: {0}", portfolio.Name);
                    _connector.RegisterPortfolio(portfolio);
                    _portfolio = portfolio;
                });
            };

            _connector.NewSecurities += securities =>
            {
                securities.ForEach(s =>
                {
                    if (s.Id == _securityId)
                    {
                        _security = s;
                        _connector.RegisterSecurity(s);
                        _handler.Set();
                    }
                });
            };

            _connector.ValuesChanged += (security, values, stime, ltime) =>
            {
                //TODO
            };

            _connector.PortfoliosChanged += portfolios =>
            {
                Debug.WriteLine("Изменение состояния портфелей.");

                var sb = new StringBuilder();

                portfolios.ForEach(p =>
                {
                    sb.AppendFormat("Name: {0}{1}", p.Name, Environment.NewLine);
                    sb.AppendFormat("AveragePrice: {0}{1}", p.AveragePrice, Environment.NewLine);
                    sb.AppendFormat("BeginValue: {0}{1}", p.BeginValue, Environment.NewLine);
                    sb.AppendFormat("BlockedValue: {0}{1}", p.BlockedValue, Environment.NewLine);
                    sb.AppendFormat("Board: {0}{1}", p.Board, Environment.NewLine);
                    sb.AppendFormat("Commission: {0}{1}", p.Commission, Environment.NewLine);
                    sb.AppendFormat("CurrentPrice: {0}{1}", p.CurrentPrice, Environment.NewLine);
                    sb.AppendFormat("CurrentValue: {0}{1}", p.CurrentValue, Environment.NewLine);
                    sb.AppendFormat("Leverage: {0}{1}", p.Leverage, Environment.NewLine);
                    sb.AppendFormat("RealizedPnL: {0}{1}", p.RealizedPnL, Environment.NewLine);
                    sb.AppendFormat("UnrealizedPnL: {0}{1}", p.UnrealizedPnL, Environment.NewLine);
                    sb.AppendFormat("VariationMargin: {0}{1}", p.VariationMargin, Environment.NewLine);

                    Debug.WriteLine(sb.ToString());

                    sb.Clear();
                });
            };

            _connector.NewPositions += positions =>
            {
                Debug.WriteLine("Новые позиции.");
                PrintPositions(positions);
            };

            _connector.PositionsChanged += positions =>
            {
                Debug.WriteLine("Изменение позиций.");
                PrintPositions(positions);
            };

            _connector.NewOrders += orders =>
            {
                orders.ForEach(o => Debug.WriteLine(string.Format("NewOrders. {0}", o)));
            };

            _connector.OrdersChanged += orders =>
            {
                orders.ForEach(o =>
                {
                    Debug.WriteLine(string.Format("OrdersChanged. {0}. IsMatched: {1}, IsCanceled : {2}", o, o.IsMatched().ToString(), o.IsCanceled().ToString()));
                });
            };

            _connector.OrdersRegisterFailed += fails =>
            {
                fails.ForEach(f => Debug.WriteLine(string.Format("OrdersRegisterFailed. {0}", f.Error.Message)));
            };

            _connector.OrdersCancelFailed += fails =>
            {
                fails.ForEach(f => Debug.WriteLine(string.Format("OrdersCancelFailed. {0}", f.Error.Message)));
            };

            _connector.NewMyTrades += trades =>
            {
                trades.ForEach(t => Debug.WriteLine(string.Format("NewMyTrades. {0}", t.ToString())));
            };

            _connector.Connect();

            _handler.WaitOne();

            Console.WriteLine("Инструмент и портфель получены");


            var order = new Order()
            {
                Security  = _security,
                Portfolio = _portfolio,
                Type      = OrderTypes.Market,
                Direction = Sides.Buy,
                Volume    = 1
            };

            _connector.RegisterOrder(order);

            Console.WriteLine("ПОСЛАНА ЗАЯВКА");

            Console.Read();

            _connector.Disconnect();

            // Ждет, пока последовательно не будут нажаты клаваши Q и Enter,
            // после чего программа завершит работу
            while (Console.ReadLine().ToUpper() != "Q")
            {
                ;
            }
        }