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();
	}
}
Loading