Example #1
0
        public async Task InitializeAsync()
        {
            Debug.WriteLine("init start");
            Client = await InterReactClient.Builder.BuildAsync().ConfigureAwait(false);

            Debug.WriteLine("init end");
        }
Example #2
0
        private async void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                client = await InterReactClient.Builder.BuildAsync();
            }
            catch (Exception exception)
            {
                ShowMessage(exception.Message, close: true);
                return;
            }

            // Write all incoming messages to the debug window to see what's happening.
            // Also observe any exceptions.
            client.Response.Stringify().Subscribe(Console.WriteLine, exception => ShowMessage(exception.Message));

            SymbolLabel.Visible = Symbol.Visible = true;

            // Listen for textbox TextChanged messages to determine the symbol.
            Observable.FromEventPattern(Symbol, "TextChanged")
            .Select(ea => ((TextBox)ea.Sender).Text)
            .Throttle(TimeSpan.FromSeconds(1))
            .DistinctUntilChanged()
            .ObserveOn(synchronizationContext)
            .Subscribe(UpdateSymbol);
        }
Example #3
0
    public async Task Test()
    {
        // Create the InterReact client by first connecting to TWS/Gateway on the local host.
        IInterReactClient interReact = await new InterReactClientConnector().ConnectAsync();

        // Create a contract object.
        Contract contract = new()
        {
            SecurityType = SecurityType.Stock,
            Symbol       = "SPY",
            Currency     = "USD",
            Exchange     = "SMART"
        };

        // Create and then subscribe to the observable which can observe ticks for the contract.
        IDisposable subscription = interReact
                                   .Services
                                   .CreateTickObservable(contract)
                                   .OfTickClass(selector => selector.PriceTick)
                                   .Subscribe(onNext: priceTick => Console.WriteLine($"Price = {priceTick.Price}"));

        Console.WriteLine(Environment.NewLine + "press a key to exit...");
        Console.ReadKey();
        Console.Clear();

        // Dispose the subscription to stop receiving ticks.
        subscription.Dispose();

        // Disconnect from TWS/Gateway.
        await interReact.DisposeAsync();
    }
}
Example #4
0
    protected async Task TestClient(IInterReactClient client)
    {
        client.Response.Select(x => x.Stringify()).Subscribe(s => Write($"response: {s}"));
        var instant = await client.Services.CurrentTimeObservable;

        Write($"Test calling CurrentTimeObservable: {instant}");
        await Task.Delay(500);
    }
Example #5
0
 protected BaseSystemTest(SystemTestFixture fixture, ITestOutputHelper output)
 {
     Client = fixture.Client;
     Write  = output.WriteLine;
     Id     = Client.Request.NextId();
     Write($"BaseSystemTest: Id = {Id}.");
     subscription = Client.Response.Spy(Write).Subscribe(Responses.Add);
 }
Example #6
0
    public TestCollectionBase(ITestOutputHelper output, TestFixture fixture)
    {
        Write = output.WriteLine;

        Logger = new LoggerFactory().AddMXLogger(Write, LogLevel.Debug).CreateLogger("Test");
        fixture.DynamicLogger.Add(Logger, true);

        Client = fixture.Client ?? throw new Exception("Client");
    }
Example #7
0
        protected BaseSystemTest(SystemTestFixture fixture, ITestOutputHelper output)
        {
            if (fixture.Client == null)
            {
                throw new NullReferenceException(nameof(fixture.Client));
            }

            var provider = new MXLoggerProvider(output.WriteLine);

            LoggerFactory = new LoggerFactory(new[] { provider });
            Logger        = LoggerFactory.CreateLogger("SystemTest");

            Client = fixture.Client;
            Id     = Client.Request.NextId();
            Logger.LogDebug($"BaseSystemTest: Id = {Id}.");
            subscription = Client.Response.Spy(Logger).Subscribe(Responses.Add);
        }
Example #8
0
        public async void Init()
        {
            Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(1)).Subscribe(x => Date.Value = DateTime.Now);
            try
            {
                interReactClient = await InterReactClient.BuildAsync();
            }
            catch (Exception exception)
            {
                await SyncMessageBox.Show(exception.Message, terminate : true);

                return;
            }
            CoreApplication.Suspending += (x, y) => { interReactClient.Dispose(); };

            // TickRedundantRealtimeVolumeFilter removes redundant messages (LastPrice, LastSize, Volume and Time ticks).
            // Display a message box for any errors. Write messages to the Debug window.
            interReactClient.Response
            .Subscribe(async message =>
            {
                Debug.WriteLine(message.Stringify());
                if (message is Alert alert &&
                    (alert.AlertType == AlertType.ConnectionLost || alert.AlertType == AlertType.ConnectionRestored))
                {
                    await SyncMessageBox.Show(alert.Message);
                }
            }, async exception => await SyncMessageBox.Show(exception.Message, terminate: true));

            // Note that Symbol is an observable.
            Symbol.Throttle(TimeSpan.FromSeconds(1))
            .DistinctUntilChanged()
            .Subscribe(async symbol =>
            {
                try
                {
                    await FindContract(symbol);
                }
                catch (Exception exception)
                {
                    await SyncMessageBox.Show(exception.Message);
                }
            });
        }
Example #9
0
        public async Task Initialize()
        {
            try
            {
                client = await InterReactClient.Builder.BuildAsync();
            }
            catch (Exception exception)
            {
                Utilities.MessageBoxShow(exception.Message, "InterReact", terminate: true);
                return;
            }

            // Create a contract. Note that market depth is not available for the demo account.
            var contract = new Contract
            {
                SecurityType = SecurityType.Cash,
                Symbol       = "EUR",
                Currency     = "USD",
                Exchange     = "IDEALPRO"
            };

            Title = contract.Currency + "/" + contract.Symbol;

            var depthObservable = client.Services
                                  .MarketDepthObservable(contract, rows: 5);

            var(Bids, Asks) = depthObservable.ToMarketDepthObservableCollections();
            //.ObserveOn(SynchronizationContext.Current)
            //.ObserveOnDispatcher()

            // Observe any exceptions.
            depthObservable.Subscribe(m => { }, e => Utilities.MessageBoxShow(e.Message, "InterReact", terminate: true));

            // Notify UI that all (2) properties changed.
            NotifyPropertiesChanged();

            depthObservable.Connect();
        }
Example #10
0
    internal static async Task Run(int port, ILogger logger, ILogger libLogger)
    {
        IInterReactClient client = await new InterReactClientConnector()
                                   .WithLogger(libLogger)
                                   .WithPorts(port)
                                   .ConnectAsync()
                                   .ConfigureAwait(false);

        logger.LogCritical("Connected to server.");

        logger.LogCritical("Sending some messages...");
        Enumerable.Range(0, 50).ToList().ForEach(client.Request.CancelMarketData);

        // indicate test end
        client.Request.RequestMarketData(42, new Contract());

        // wait to get the first tickSize message, indicating test start
        await client.Response.OfType <SizeTick>().FirstAsync();

        logger.LogCritical("Receiving...");

        // receive some messages to measure throughput
        Stopwatch watch = new();

        watch.Start();
        int count = await client.Response.TakeWhile(m => m is SizeTick).Count();

        watch.Stop();

        long frequency = Stopwatch.Frequency * count / watch.ElapsedTicks;

        logger.LogCritical("Received!! {Frequency:N0} messages/second.", frequency);

        logger.LogCritical("Disconnecting.");
        await client.DisposeAsync();

        logger.LogCritical("Disconnected.");
    }
        private async Task FindContract(string symbol, IInterReactClient interReactClient)
        {
            // Dispose to cancel the IB data subscription and dispose all subscriptions.
            ticksSubscription?.Dispose();

            BidPrice.Text = "";

            AskPrice.Value           = LastPrice.Value = 0;
            BidSize.Value            = AskSize.Value = LastSize.Value = Volume.Value = 0;
            LastPriceChange.Value    = Spread.Value = null;
            ContractTimeStatus.Value = "";
            LastInstant.Value        = default;
            Title.Value = "InterReact";

            if (string.IsNullOrEmpty(symbol))
            {
                return;
            }

            var xxx = SecurityType.Stock;

            var contract = new Contract {
                SecurityType = SecurityType.Stock, Symbol = symbol, Currency = "USD", Exchange = "SMART"
            };


            // Find the contract details and use it to display the full name of the contract in the window title bar.
            var contractDataList = interReactClient.Services.ContractDataObservable(contract);
            var contractData     = await contractDataList.ContractDataSingle();

            Title.Value = contractData.LongName + " (" + symbol + ")";

            // Find the current and next time status for the contract.
            var cdt = new ContractDataTime(contractData);
            ContractDataTimePeriod?status = cdt.Get();

            if (status == null)
            {
                throw new Exception("null status");
            }
            var current = status.Previous;

            if (current == null)
            {
                throw new Exception("null current status");
            }
            var next = status.Next;

            if (next == null)
            {
                throw new Exception("null next status");
            }
            ContractTimeStatus.Value = $"Status: {current.Status}, changing to {next.Status} at: {next.Time:yyyy-MM-dd HH:mm:ss}";

            // Create the observable which will emit tick updates.
            // Specify that RealTimeVolume ticks be emitted rather than LastPrice, LastSize, Volume and Time messages.
            var ticks = interReactClient.Services.TickConnectableObservable(contract, new[] { GenericTickType.RealtimeVolume }, true);

            SubscribeToTicks(ticks);

            // Make the request to IB to start receiving ticks.
            ticksSubscription = ticks.Connect();
        }