Trading Evolution

Markets are never wrong - opinions often are

Getting real-time data from TWS API in C#

Small code snippet to get real-time data using C# TWS API.

Here how it looks like:

Real-time data

  • Lines 13-15: Define contract (stock, futures, forex). In this case it is SPY ETF for S&P 500
  • Line 23: Connect when "Connect" button is clicked
  • Line 28: Request market data after application is connected
  • Lines 33-43: Handle real-time tick data
// Interactive Brokers fields
IBWrapper _ibWrapper;
Contract _ibContract;
int _nextTickerId = 0;

public Main()
{
	InitializeComponent();

	_ibWrapper = new IBWrapper(this);
	_ibContract = new Contract();

	_ibContract.Symbol			= "SPY";
	_ibContract.SecType			= "STK";
	_ibContract.Exchange		= "SMART";
}

private void Connect_Click(object sender, EventArgs e)
{
	_ibWrapper.ClientConnected      += IbWrapper_ClientConnected;
	_ibWrapper.TickPrice            += IbWrapper_TickPrice;

	_ibWrapper.Connect("127.0.0.1", 7496, 0);
}

private void IbWrapper_ClientConnected(object sender, EventArgs e)
{
	_ibWrapper.IBClient.reqMktData(_nextTickerId++, _ibContract, null, false, null);
}

private void IbWrapper_TickPrice(object sender, TickPriceEventArgs e)
{
	switch (e.Field)
	{
		case TickTypeEnum.Bid:
			_bidTextBox.Text = e.Price.ToString("C");
			break;
		case TickTypeEnum.Ask:
			_askTextBox.Text = e.Price.ToString("C");
			break;
		case TickTypeEnum.Last:
			_lastTextBox.Text = e.Price.ToString("C");
			break;
	}
}

 

Loading