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;
	}
}

 

How to enable API access in TWS

 

  1. File ⇒ Global Configuration or Edit ⇒ Global Configuration (Classic TWS)
  2. API ⇒ Settings
  3. Check "Enable ActiveX and Socket Clients"
  4. Uncheck "Read-Only API"
  5. Verify socket port. The default it 7496
  6. Check "Allow connections from localhost only"

 

More details on InteractiveBrokers.com Trader Workstation API Settings

Trader Workstation talks

Every trader gets bored during trading day so I decided to spice up my life and created a little app that plays random audio clips from famous movies based on your trading. The app connects to Interactive Brokers TWS and if you open position might say "And don't screw it up, sport" (Wall Street / 1987) or it might say "Now I wanna dance, I wanna win. I want that trophy" (Pulp Fiction). If position is closed with loss it might say "I told you not to go there! I told you not to go there!" (Anger Management / 2003). For profit "Ah, Buddy, Buddy, I hate to tell you this, but you are a genius!" (Wall Street / 1987). Which movie quotes would you play and when?

Download: IbTalk.zip

 
If you want to add your quotes and know a little bit of XML then open IbTalks.exe.config with any XML or text editor and add your own mp3 links. 
Here is an example:
  <!-- Close Position With Profit -->
  <ClosePositionWithProfitSounds>
    <Sound FileName="Sounds/Pulp Fiction/What-happened-here-was-a-miracle-and-I-want-you-to-fucking-acknowledge-it-!.mp3" />
    <Sound FileName="Sounds/Wall Street/Ah-Buddy-Buddy-I-hate-to-tell-you-this-but-you-are-a-genius!.mp3" />
    <Sound FileName="Sounds/Zombieland/All-I-could-think-of-was-What-are-the-odds.mp3" />
  </ClosePositionWithProfitSounds>
  
  <!-- Close Position With Loss -->
  <ClosePositionWithLossSounds>
    <Sound FileName="Sounds/Anger Management/I-told-you-not-to-go-there!-I-told-you-not-to-go-there!.mp3" />
    <Sound FileName="Sounds/Pulp Fiction/Everybody-be-cool-!-This-is-a-robbery.mp3" />
    <Sound FileName="Sounds/Pulp Fiction/lm-through-never-again-too-dangerous.mp3" />
    <Sound FileName="Sounds/Pulp Fiction/Oh-fuck-me-Fuck-me-!.mp3" />
    <Sound FileName="Sounds/Trading Places/Business-is-business-Ill-go-for-a-walk.mp3" />
    <Sound FileName="Sounds/Wall Street/Almost.mp3" />
  </ClosePositionWithLossSounds>
 

How to send an order to IB TWS in just 68 lines

Below is C# code snippet to send buy 100 shares of SPY at market order. Code is pretty much self-explanatory. Connect, PlaceOrder, Disconnect and we are done.

class Program
{
	static IBWrapper _ibWrapper;
	static IBApi.Contract _ibContract;
	static IBApi.Order _ibOrder;

	static ManualResetEvent _connectedEvent = new ManualResetEvent(false);
	static ManualResetEvent _orderSubmittedEvent = new ManualResetEvent(false);

	static void Main(string[] args)
	{
		try
		{
			_ibWrapper = new IBWrapper();

			// Subscribe to events
			_ibWrapper.ClientConnected      += IbWrapper_ClientConnected;
			_ibWrapper.OrderStatusEvent     += IbWrapper_OrderStatusEvent;
			_ibWrapper.Error                += IbWrapper_Error;

			// Connect to TWS
			_ibWrapper.Connect("127.0.0.1", 7496, 0);
			if (!_ibWrapper.IBClient.IsConnected())
			{
				Console.WriteLine("Failed to connect to TWS");
				return;
			}

			_connectedEvent.WaitOne();

			_ibContract = new IBApi.Contract() { Symbol = "SPY", SecType="STK", Exchange = "SMART", PrimaryExch = "Nasdaq" };
			_ibOrder = new IBApi.Order() { Action = "BUY", OrderType = "MKT", Tif = "DAY", TotalQuantity = 100, Transmit = true, OrderId = _ibWrapper.NextOrderId++ };

			_ibWrapper.IBClient.placeOrder(_ibOrder.OrderId, _ibContract, _ibOrder);
			_orderSubmittedEvent.WaitOne();
			Console.WriteLine("Disconnect");

			_ibWrapper.Disconnect();
		}
		catch (Exception e)
		{
			Console.WriteLine(e.Message);
		}
	}

	private static void IbWrapper_ClientConnected(object sender, EventArgs e)
	{
		Console.WriteLine("Connected");
		_connectedEvent.Set();
	}

	private static void IbWrapper_OrderStatusEvent(object sender, OrderStatusEventArgs e)
	{
		if (_ibOrder != null && _ibOrder.OrderId == e.OrderId)
		{
			Console.WriteLine("Order status: " + e.Status);
			_orderSubmittedEvent.Set();
		}
	}

	private static void IbWrapper_Error(object sender, ErrorEventArgs e)
	{
		Console.WriteLine(string.Format("Error: {0}.", e.Error));

		_connectedEvent.Set();
		_orderSubmittedEvent.Set();
	}
}

Command line tool for Interactive Brokers

Many times in the past I came across people who needed quick and simple way to send orders to Interactive Brokers. I decided to share command line tool that I use to send orders to TWS and IB Gateway from command line. It can be used in automated trading systems or scripts.

Download:  IbCmdDemo.zip

Few simple examples: 

Buy 100 shares of Facebook at Market

IbCmd.exe /s:FB /pe:Nasdaq

Buy 250 shares of Google at $752.5

IbCmd.exe /s:GOOG /pe:Nasdaq /q:250 /p:752.5

Sell 1 ES (E-Mini S&P 500) at Market

IbCmd.exe /s:ES /e:Globex /t:Future /a:Sell

Full list of parameters for IbCmd 

/ServerIp:<string> IP address of copumter that hosts TWS or TWS Gateway. Default value:'127.0.0.1' (short form /srv)

/ServerPort:<int> Port number. Default value:'7496' (short form /port)

/ClientId:<int> API client id. Default value:'10' (short form /cid)

/Action:{Buy|Sell} Buy or sell. Default value:'Buy' (short form /a)

/Symbol:<string> Symbol of the underlying asset. (short form /s)

/SecurityType:{Stock|Future} Security type. (short form /t)

/Exchange:<string> The order destination, such as SMART. Default value:'SMART' (short form /e)

/PrimaryExchange:<string> To clarify any ambiguity for Smart-routed contracts, include the primary exchange, along with the Smart designation. (short form /pe)

/Quantity:<int> The order quantity. Default is 100 for stocks and 1 for futures. Default value:'0' (short form /q)

/OrderType:{Market|Limit} The order type. Default value:'Market' (short form /ot)

/Price:<decimal>  The price for limit orders. (short form /p)