Monday, 1 June 2020

Trading Platform in C# Part 1 - Connect to TWS API

Create a trading platform in C#

Write a Windows form program in C# using Visual Studio and connect to Interactive Brokers Application Program Interface. I prefer writing GUI apps and not console apps. Other things you will need to do is sign up for a trial version of the Interactive Brokers trading software, if you already have an account with Interactive Brokers then great 

 

 

You will need to install 3 different software applications

 

Links to the programs that you need to install
Visual Studio 
https://visualstudio.microsoft.com/downloads/

Interactive Brokers Traders Workstation trading platform 
https://www.interactivebrokers.com/en/index.php?f=15876


Interactive Brokers API 
https://www.interactivebrokers.com/en/index.php?f=5041

Once you have downloaded and installed the above software you are ready to get started



# Control Name Text or Value
1 Button
btnConnect Connect
2 Combobox cbSymbol
MSFT
3 Listbox
lbData


Place this on line 19 in the EWrapperImpl.cs file


public Form1 myform;

Place the highlighted text in the tickPrice method within the EWrapperImpl.cs file


public virtual void tickPrice(int tickerId, int field, double price, TickAttrib attribs) 
        {
            Console.WriteLine("Tick Price. Ticker Id:" +tickerId+ ", Field: "+field+", Price: "+price+", CanAutoExecute: "+attribs.CanAutoExecute + 
                ", PastLimit: " + attribs.PastLimit + ", PreOpen: " + attribs.PreOpen);

            string strData = "Tick Price. Ticker Id:" + tickerId + ", Field: " + field +
                      ", Price: " + price + ", CanAutoExecute: " + attribs.CanAutoExecute;

            
            // Add this tick price to the form by calling the AddListBoxItem delegate
            myform.AddListBoxItem(strData);



        }

This is how the Form1.cs file should look.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using IBApi;

namespace IB_TradingPlatform
{
    public partial class Form1 : Form
    {
        // This delegate enables asynchronous calls for setting
        // the text property on a ListBox control.
        delegate void SetTextCallback(string text);

        public void AddListBoxItem(string text)
        {
            // See if a new invocation is required form a different thread            
            if (this.lbData.InvokeRequired)            
            {
                SetTextCallback d = new SetTextCallback(AddListBoxItem);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                // Add the text string to the list box
                this.lbData.Items.Add(text);
            }
        }

        // Create the ibClient object to represent the connection
        IB_TradingPlatform.EWrapperImpl ibClient;

        public Form1()
        {
            InitializeComponent();

            // instantiate the ibClient
            ibClient = new IB_TradingPlatform.EWrapperImpl();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            // Parameters to connect to TWS are:
            // host       - IP address or host name of the host running TWS
            // port       - listening port 7496 or 7497
            // clientId   - client application identifier can be any number
            ibClient.ClientSocket.eConnect("", 7497, 0);

            var reader = new EReader(ibClient.ClientSocket, ibClient.Signal);
            reader.Start();
            new Thread(() => {
                while (ibClient.ClientSocket.IsConnected())
                {
                    ibClient.Signal.waitForSignal();
                    reader.processMsgs();
                }
            })
            { IsBackground = true }.Start();
            // Wait until the connection is completed
            while (ibClient.NextOrderId <= 0) { }

            // Set up the form object in the EWrapper
            ibClient.myform = (Form1)Application.OpenForms[0];

            getData();
        }

        private void getData()
        {
            ibClient.ClientSocket.cancelMktData(1); // cancel market data

            // Create a new contract to specify the security we are searching for
            IBApi.Contract contract = new IBApi.Contract();
            // Create a new TagValueList object (for API version 9.71 and later) 
            List<IBApi.TagValue> mktDataOptions = new List<IBApi.TagValue>();

            // Set the underlying stock symbol fromthe cbSymbol combobox            
            contract.Symbol = cbSymbol.Text;
            // Set the Security type to STK for a Stock
            contract.SecType = "STK";
            // Use "SMART" as the general exchange
            contract.Exchange = "SMART";
            // Set the primary exchange (sometimes called Listing exchange)
            // Use either NYSE or ISLAND
            contract.PrimaryExch = "ISLAND";
            // Set the currency to USD
            contract.Currency = "USD";

            // If using delayed market data subscription un-comment 
            // the line below to request delayed data
            ibClient.ClientSocket.reqMarketDataType(3);  // delayed data = 3 live = 1

            // Kick off the subscription for real-time data (add the mktDataOptions list for API v9.71)
            
            // For API v9.72 and higher, add one more parameter for regulatory snapshot
            ibClient.ClientSocket.reqMktData(1, contract, "", false, false, mktDataOptions);
        }  
    }
}

No comments:

Post a Comment