Trading Evolution

Markets are never wrong - opinions often are

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)