/* IMPORTANT: always use your paper trading account. The code below will submit orders as part of the demonstration. */ /* IB will not be responsible for accidental executions on your live account. */ /* Any stock or option symbols displayed are for illustrative purposes only and are not intended to portray a recommendation. */ /* Before contacting our API support team please refer to the available documentation. */ public static int Main(string[] args) { EWrapperImpl testImpl = new EWrapperImpl(); EClientSocket clientSocket = testImpl.ClientSocket; EReaderSignal readerSignal = testImpl.Signal; //! [connect] clientSocket.eConnect("127.0.0.1", 7497, 0); //! [connect] //! [ereader] //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(clientSocket, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); int tickerId = 100; clientSocket.reqMarketDataType(2); getStockPrice(clientSocket, "AAPL", tickerId); Thread.Sleep(300000); Console.WriteLine("Disconnecting..."); clientSocket.eDisconnect(); return(0); }
/// <summary> /// Connects to the IB machine /// </summary> private void Connect() { EReaderSignal readerSignal = ibClient.Signal; EClientSocket clientSocket = ibClient.ClientSocket; clientSocket.eConnect("127.0.0.1", 7496, 3); //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(clientSocket, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); /*************************************************************************************************************************************************/ /* One (although primitive) way of knowing if we can proceed is by monitoring the order's nextValidId reception which comes down automatically after connecting. */ /*************************************************************************************************************************************************/ while (ibClient.NextOrderId <= 0) { } Log.Info(2, string.Format("Exiting Connect")); }
internal void Connect() { if (!IsConnected) { try { HandleErrorMessage(new ErrorMessage(-1, -1, "Connecting...")); responder = new Responder(); clientSocket = responder.ClientSocket; EReaderSignal readerSignal = responder.Signal; clientSocket.eConnect(gatewayCredentials.Host, gatewayCredentials.Port, gatewayCredentials.ClientId); EReader reader = new EReader(clientSocket, readerSignal); reader.Start(); new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); int counter = 0; while (responder.NextOrderId <= 0) { counter++; Thread.Sleep(1000); if (counter > 10) { HandleErrorMessage(new ErrorMessage(-1, -1, "Failure to Connect.")); IsConnected = false; return; } } NextOrderNo = responder.NextOrderId; IsConnected = true; HandleErrorMessage(new ErrorMessage(-1, -1, "Connected.")); } catch (Exception) { HandleErrorMessage(new ErrorMessage(-1, -1, "Please check your connection attributes.")); } } else { IsConnected = false; HandleErrorMessage(new ErrorMessage(-1, -1, "Disconnected.")); } }
private void connectToTWS() { logMessage("Connecting to TWS"); setConnectionState(ConnectionState.Connecting); // this ensures the state changes are visible: otherwise the synchronous connection mechanism // blocks them until it's finished ConnectionPanel.Refresh(); mApi.eConnect(ServerTextBox.Text, int.Parse(PortTextBox.Text), int.Parse(ClientIdTextBox.Text), false); // the following causes the IB API to start processing messages // received From TWS Task task = new Task((Action)(() => { EReader ereader = new EReader(mApi, mSignal); ereader.Start(); while (mApi.IsConnected()) { mSignal.waitForSignal(); ereader.processMsgs(); } }), TaskCreationOptions.LongRunning); if (mApi.ServerVersion > 0) { task.Start(); } }
public void Connect(string clientUrl, int clientPort) { clientSocket.eConnect(clientUrl, clientPort, ClientId); // Create a reader to consume incoming messages // and store them in a queue. var reader = new EReader(clientSocket, readerSignal); reader.Start(); // Once the messages are in the queue, an additional thread is needed to process them. // This is best accomplished by a dedicated long-running background thread. Task.Factory.StartNew(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); // It's worth noting that message processing is what raises all EWrapper events, // e.g. NextValidId, TickPrice, Position, PositionEnd, Error, ConnectionClosed, etc. // Events are handled by the thread that raises them, i.e. this thread! reader.processMsgs(); } }, TaskCreationOptions.LongRunning); }
/* IMPORTANT: always use your paper trading account. The code below will submit orders as part of the demonstration. */ /* IB will not be responsible for accidental executions on your live account. */ /* Any stock or option symbols displayed are for illustrative purposes only and are not intended to portray a recommendation. */ /* Before contacting our API support team please refer to the available documentation. */ public static int Main(string[] args) { EWrapperImpl testImpl = new EWrapperImpl(); EClientSocket clientSocket = testImpl.ClientSocket; EReaderSignal readerSignal = testImpl.Signal; //! [connect] clientSocket.eConnect("127.0.0.1", 7496, 0); //! [connect] //! [ereader] //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(clientSocket, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); //! [ereader] /*************************************************************************************************************************************************/ /* One (although primitive) way of knowing if we can proceed is by monitoring the order's nextValidId reception which comes down automatically after connecting. */ /*************************************************************************************************************************************************/ while (testImpl.NextOrderId <= 0) { } testIBMethods(clientSocket, testImpl.NextOrderId); Console.WriteLine("Disconnecting..."); clientSocket.eDisconnect(); return(0); }
/// <summary> /// 连接到TWS /// </summary> /// <param name="IP_Address">TWS 客户端所在的IP地址</param> /// <param name="Port">端口号,默认为7496,模拟账号默认为7497</param> /// <returns>如果成功连接返回true,否则返回false</returns> public bool ConnectToTWS(string IP_Address, int Port) { if (IP_Address == Host && Port == this.Port && IsConnected()) { return(true); } else if (IsConnected()) { Disconnect(); } try { wrapper.ClientSocket.eConnect(IP_Address, Port, 0, false); EClientSocket clientSocket = wrapper.ClientSocket; EReaderSignal readerSignal = wrapper.Signal; //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(clientSocket, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); while (wrapper.NextOrderId <= 0) { } new Thread(() => { while (clientSocket.IsConnected()) { clientSocket.reqPositions(); Thread.Sleep(500); } }) { IsBackground = true }.Start(); //wrapper.NextOrderId = 2000; OrderID = wrapper.NextOrderId; //IsConnected = true; this.Port = Port; this.Host = IP_Address; return(true); } catch (Exception exp) { Console.WriteLine(exp.Message.ToString()); return(false); } finally { } }
public void StartMessageProcessing() { reader = new EReader(clientSocket, signal); reader.Start(); messageProcessingTask = new Task(() => { while (clientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }); messageProcessingTask.Start(); }
public void Connect(string username, string password, int port = 7497, string ip = "127.0.0.1") { Output.WriteLine("Connecting to TWS..."); int numTries = 0; do { numTries++; if (numTries > 1) { Output.WriteLine("Launching TWS..."); LaunchTWS(username, password, port); } ClientSocket.eConnect(ip, port, 0); if (ClientSocket.IsConnected()) { Output.WriteLine("Socket connected."); break; } } while (numTries <= 3); EReaderSignal readerSignal = Signal; var reader = new EReader(ClientSocket, readerSignal); reader.Start(); new Thread(() => { while (ClientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); while (NextOrderId <= 0) { // once we are connected, we will have an order id > 0 } Output.WriteLine("TWS API connected."); }
public void connectAck() { try { if (Connected == clientSocket.IsConnected()) { return; } Connected = clientSocket.IsConnected(); if (!Connected) { return; } //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue EReader reader = new EReader(clientSocket, signal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { try { while (clientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } } catch (Exception ex) { Console.WriteLine($"Exception in reader thread: {ex.Message}"); throw ex; } }) { IsBackground = true }.Start(); } catch (Exception ex) { Log(new LogMessage(ToString(), ex.Message, LogMessageType.SystemError)); Console.WriteLine($"EXCEPTION:{GetCurrentMethod()} {ex.Message}"); return; } }
public EWrapperImpl() { signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); clientSocket.eConnect("127.0.0.1", 7496, 0); //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue reader = new EReader(clientSocket, signal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (clientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); }
public void Login(int port, int id) { if (!_Client.IsConnected()) { EReaderSignal readerSignal = _Core.Signal; //! [connect] _Client.eConnect("127.0.0.1", port, id); var reader = new EReader(_Client, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (_Client.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } }
private static void ConnectToIb() { RequestsClient client = new RequestsClient( MyAppSettings.PushSocketPort, MyAppSettings.RequestSocketPort); client.Connect(); wrapper = new IbClient(client, MyAppSettings); EClientSocket clientSocket = wrapper.ClientSocket; EReaderSignal readerSignal = wrapper.Signal; clientSocket.eConnect(MyAppSettings.InteractiveBrokersIP, MyAppSettings.InteractiveBrokersPort, 0); //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(clientSocket, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); while (wrapper.NextOrderId <= 0) { } }
public static int Main(string[] args) { // specify account and strategy string IBaccount = TradeBooks.accountInit(); string tradingModel = "es_growth"; string tradingInstrument = "ES"; int multipler = 50; int tryCNT = 1; int tryGap = (int)openBook.gap * 20; int bestCNT = 0; double[] Returns = new double[2]; double[] Premium = new double[tryCNT]; int[] LegB_ID = new int[tryCNT]; int[] LegB = new int[tryCNT]; int legS; int legS_ID; openBook.positionCNT = 1; for (int n = 0; n < openBook.positionCNT; n++) { openBook.symbol[n] = tradingInstrument; openBook.multipler[n] = multipler; } //! start the connection int[] channel = new int[2]; channel = TradeBooks.channelSetup(IBaccount, tradingModel); EClientSocket clientSocket = Allture.ClientSocket; EReaderSignal readerSignal = Allture.Signal; //! [connect] clientSocket.eConnect("127.0.0.1", channel[0], channel[1]); //! [connect] //! [ereader] //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(clientSocket, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); //! [ereader] //**** current time ***** string date_time, last_time; date_time = DateTime.Now.ToString("hh:mm:ss tt"); //************************** //*** Account Info *** //************************** clientSocket.reqAccountSummary(9001, "All", AccountSummaryTags.GetAllTags()); Thread.Sleep(1000); Console.WriteLine("account ID: " + Allture.account_ID); Console.WriteLine("account Value: " + Allture.account_value); Console.WriteLine("account_BuyingPower: " + Allture.account_BuyingPower); Console.WriteLine("account_InitMarginReq: " + Allture.account_InitMarginReq); Console.WriteLine("account_MaintMarginReq: " + Allture.account_MaintMarginReq); Console.WriteLine("account_ExcessLiquidity: " + Allture.account_ExcessLiquidity); Console.WriteLine("account_AvailableFunds: " + Allture.account_AvailableFunds); Console.WriteLine("\n"); Allture.remainingOrderSize = 100000; // set to maxium order size clientSocket.reqMarketDataType(1); // clientSocket.reqGlobalCancel(); Thread.Sleep(sleep1); while ((DateTime.Now > Convert.ToDateTime("09:30:00 AM")) && (DateTime.Now < Convert.ToDateTime("16:00:00 PM"))) { last_time = date_time; for (int n = 0; n < openBook.positionCNT; n++) { if (openBook.status[n] == "complete") { continue; } if (openBook.status[n] == "submit") { Allture.currOrderId = openBook.currOrderID[n]; Allture.remainingOrderSize = 0; Allture.checkOrderEnd = false; clientSocket.reqOpenOrders(); while (!Allture.checkOrderEnd) { Thread.Sleep(200); } if (Allture.remainingOrderSize == 0) { openBook.status[n] = "complete"; openBook.capital[n] = 0; openBook.size[n] = 0; continue; // if remaining size = 0, means this order has completely filled. then go to the next position } } legS = 2700; legS_ID = getContractID(clientSocket, Allture, openBook, n, legS, "FOP", "GLOBEX"); LegB[0] = legS - 100; LegB_ID[0] = getContractID(clientSocket, Allture, openBook, n, LegB[0], "FOP", "GLOBEX"); //******* check the order status again. if still exiting, cancel the order order, update the order size and capital if (openBook.status[n] == "submit") { Allture.currOrderId = openBook.currOrderID[n]; Allture.remainingOrderSize = 0; Allture.checkOrderEnd = false; clientSocket.reqOpenOrders(); while (!Allture.checkOrderEnd) { Thread.Sleep(200); } if (Allture.remainingOrderSize == 0) { openBook.status[n] = "complete"; openBook.capital[n] = 0; openBook.size[n] = 0; continue; } else { clientSocket.cancelOrder(openBook.currOrderID[n]); //cancel existing order Thread.Sleep(sleep1); openBook.status[n] = "cancel"; if (Allture.remainingOrderSize > openBook.size[n]) { Allture.remainingOrderSize = openBook.size[n]; } openBook.capital[n] = openBook.capital[n] - (openBook.size[n] - Allture.remainingOrderSize) * openBook.margin[n]; openBook.size[n] = (int)(openBook.usingCapital * openBook.capital[n] / 10000); } } else { openBook.size[n] = (int)(100); } //********* Place order ************************ clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], LegB_ID[0], legS_ID, openBook.multipler[n].ToString(), "GLOBEX"), OrderSamples.ComboLimitOrder("BUY", openBook.size[n], -1.0, false)); Thread.Sleep(sleep1); //********* update remaining of the trading book ************** openBook.status[n] = "submit"; openBook.currOrderID[n] = Allture.NextOrderId; openBook.legS[n] = legS; openBook.legB[n] = LegB[0]; openBook.premium[n] = 1.0; } } clientSocket.reqGlobalCancel(); Thread.Sleep(sleep1); Console.WriteLine("today's trading is done...time: " + DateTime.Now); clientSocket.eDisconnect(); return(0); }
private IDictionary <string, int> m_mktDataRequestsStrToIdMapping = new Dictionary <string, int>(); // map: mktDataRequestStr(e.g. "IBM_STK_...") => twsReqId // constructor public TwsRtdServerConnection(TwsRtdServer twsRtdServer, string connectionStr) { try { SetError(TwsRtdServerErrors.NO_ERROR); m_twsReqIdNext = 0; // parse connection string to host/port ExtractConnectionParams(connectionStr); // check for error if (GetErrorCode() != TwsRtdServerErrors.NO_ERROR) { return; } m_twsRtdServerWrapper = new TwsRtdServerWrapper(twsRtdServer, this); this.m_eClientSocket = new EClientSocket(m_twsRtdServerWrapper, m_eReaderSignal); // allow PACEAPI feature this.m_eClientSocket.SetConnectOptions("+PACEAPI"); // connect to TWS this.m_eClientSocket.eConnect(m_host, m_port, m_clientId, false); if (m_eClientSocket.ServerVersion == 0) { SetError(TwsRtdServerErrors.CANNOT_CONNECT_TO_TWS); // TwsRtdServer: error connecting to TWS return; } var reader = new EReader(m_eClientSocket, m_eReaderSignal); reader.Start(); new Thread(() => { while (m_eClientSocket.IsConnected()) { m_eReaderSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); // wait 5 seconds till fully connected int i = 0; while (m_twsRtdServerWrapper.NextOrderId <= 0 && i < 50) { Thread.Sleep(100); i++; } if (i >= 50) { SetError(TwsRtdServerErrors.CANNOT_CONNECT_TO_TWS); // TwsRtdServer: error connecting to TWS } // send request market data type this.m_eClientSocket.reqMarketDataType(2); this.m_eClientSocket.reqMarketDataType(4); } catch { SetError(TwsRtdServerErrors.CANNOT_CONNECT_TO_TWS); // TwsRtdServer: error connecting to TWS } }
public void Connect() { // Connect _____________________________________________________________________________Logger.Info("Connecting to IB..."); Locks[(nameof(connectAck))] = new ManualResetEvent(false); Socket.eConnect("127.0.0.1", Port, ClientId); Locks[nameof(connectAck)].WaitOne(); _____________________________________________________________________________Logger.Info("Connecting to IB was successful"); // Start api _____________________________________________________________________________Logger.Info("Starting IB API..."); Socket.startApi(); _____________________________________________________________________________Logger.Info("IB API has started"); // Start reader loop _____________________________________________________________________________Logger.Info("Starting listenning to IB messages..."); Locks[nameof(managedAccounts)] = new ManualResetEvent(false); Locks[nameof(nextValidId)] = new ManualResetEvent(false); EReader reader = new EReader(Socket, Signal); reader.Start(); new Thread((mainThread) => { // Because of parsing we have to set this culture Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); try { while (Socket.IsConnected()) { Signal.waitForSignal(); lock (MessageLock) { reader.processMsgs(); } } } catch (Exception ex) { ThreadMessage.ThrownException = ex; (mainThread as Thread).Interrupt(); } }) { IsBackground = true }.Start(Thread.CurrentThread); _____________________________________________________________________________Logger.Info("We are listenning to IB messages now"); // Wait for starting info _____________________________________________________________________________Logger.Info("Waiting for starting info"); Locks[nameof(managedAccounts)].WaitOne(); Locks[nameof(nextValidId)].WaitOne(); _____________________________________________________________________________Logger.Info("Starting info was received"); // Check if account exists if (!AccountNames.Contains(AccountName)) { throw new IBException(String.Format("Given account {0} not found among these accounts found: {1}", AccountName, String.Join(", ", AccountNames))); } }
public static int Main(string[] args) { contractId = new Dictionary <int, SpecContract>(); ListToMonitor = new List <SpecContract>(); //{ // new SpecContract() // { // Symbol = "AAPL", // Strike = 320, // LastTradeDateOrContractMonth = "200131" // }, // new SpecContract() // { // Symbol = "NFLX", // Strike = 340, // LastTradeDateOrContractMonth = "200124" // } //}; var symbols = Properties.Settings.Default.Stock.Split(','); for (int i = 0; i < symbols.Length; i++) { ListToMonitor.Add(new SpecContract() { Symbol = symbols[i], Strike = double.Parse(Properties.Settings.Default.Strike.Split(',')[i]), LastTradeDateOrContractMonth = Properties.Settings.Default.ExpDate.Split(',')[i] } ); } EWrapperImpl testImpl = new EWrapperImpl(); EClientSocket clientSocket = testImpl.ClientSocket; EReaderSignal readerSignal = testImpl.Signal; //! [connect] //clientSocket.eConnect("127.0.0.1", 7496, 0); clientSocket.eConnect("", 7496, 1); //! [connect] //! [ereader] //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(clientSocket, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); int tickerId = 100; int tickerId_Option = 200; foreach (var stock in ListToMonitor) { Console.WriteLine($"Symbol {stock.Symbol} - {stock.LastTradeDateOrContractMonth}"); stock.TickerId = tickerId++; stock.TickerOptionId = tickerId_Option++; clientSocket.reqMarketDataType(2); getStockPrice(clientSocket, stock.Symbol, stock.TickerId, stock.LastTradeDateOrContractMonth); string expDate = stock.LastTradeDateOrContractMonth; getContractDetails(clientSocket, stock.Symbol, stock.TickerOptionId, expDate, stock.Strike); while (contractId.Count == 0) { } Thread.Sleep(500); Console.WriteLine("====================================="); Console.WriteLine("Contract Id set to: " + contractId); foreach (var contId in contractId) { Console.WriteLine($"ContractId {contId.Value.ConId} , tickerId {contId.Key}"); getOptionPrice(clientSocket, stock.Symbol, contId.Key, contId.Value.ConId, stock.Strike); } } Console.ReadKey(); foreach (var stock in ListToMonitor) { clientSocket.cancelMktData(stock.TickerId); clientSocket.cancelMktData(stock.TickerOptionId); } Console.WriteLine("Disconnecting..."); clientSocket.eDisconnect(); return(0); }
public void REQ_OpenSocket(string connIp, int connPort, int connClientID) { if (ClientSocket.IsConnected()) { return; } Semaphore semaphore = new Semaphore(0, 1); EReaderSignal readerSignal = Signal; EReader reader = null; new Thread(() => { try { ClientSocket.eConnect(connIp, connPort, connClientID); //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue reader = new EReader(ClientSocket, readerSignal); reader.Start(); } catch (Exception ex) { error(ex.Message); } finally { semaphore.Release(); } SocketConnected_Event?.Invoke(this, new SocketConnected_EventArgs(ClientSocket.IsConnected())); }) { IsBackground = true }.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { semaphore.WaitOne(); try { while (ClientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); // Just for testing catch inside this loop: //EReader reader2 = null; //reader2.processMsgs(); } } catch (Exception ex) { error(ex.Message); error("A critical error occured. You need to restart the application!"); } finally { ClientSocket.Close(); } }) { IsBackground = true }.Start(); }
public static int Main(string[] args) { // specify account and strategy string IBaccount = TradeBooks.accountInit(); string tradingModel = "monitor"; double indexPrice = 0, lastPrice = 0, vixPrice = 0, vix1Price = 0, vix2Price = 0; int legB_ID, legS_ID; double spread_premium; //*** set the monitoring parameters ********** bool autoExit = false; double SPXexitPoint = 30; double ESexitPoint = 30; double CLexitPoint = 3; double GCexitPoint = 20; double exitPoint = 100; int Alert1 = 0; int Alert2 = 0; bool[] alert1 = new bool[Constants.max_position]; bool[] alert2 = new bool[Constants.max_position]; bool[] alert3 = new bool[Constants.max_position]; bool alert_vix = false; // vix/vix1 backwardation bool alert_vix1 = false; // vix1/vix2 backwardation List <double> putSPXlegS = new List <double>(); List <double> callSPXlegS = new List <double>(); List <double> putESlegS = new List <double>(); List <double> callESlegS = new List <double>(); List <double> putCLlegS = new List <double>(); List <double> callCLlegS = new List <double>(); List <double> putGClegS = new List <double>(); List <double> callGClegS = new List <double>(); //**** current date and time ***** string date_time, today; date_time = DateTime.Now.ToString("h:mm:ss tt"); today = DateTime.Now.ToString("MMdd"); // today = "0928"; // if today is not the trading close day //***** set up excel ************** _Excel.Application excel = new _Excel.Application(); excel.DisplayAlerts = false; _Excel.Workbook monitor_wb = excel.Workbooks.Open("C:\\Users\\Jack\\Documents\\Companies\\allture\\Trading\\option_spread\\Accounts\\All_Account_Oct_2018.xlsm"); _Excel.Worksheet csheet = monitor_wb.Worksheets[today]; // string path = TradeBooks.xlsPathSetup(IBaccount); // _Excel.Workbook monitor_wb = excel.Workbooks.Open(path + IBaccount + "\\account_" + IBaccount + ".xlsm"); // _Excel.Worksheet csheet = monitor_wb.Worksheets["Positions"]; Console.WriteLine("\n start calculating, time: " + DateTime.Now + " \n"); //******* read position data to openBook position_xls_readin(csheet, openBook); monitor_wb.Close(0); excel.Quit(); for (int n = 0; n < openBook.positionCNT; n++) { if (openBook.symbol[n] == "SPX") { if (openBook.CallPut[n] == "Put") { putSPXlegS.Add(openBook.legS[n]); } else { callSPXlegS.Add(openBook.legS[n]); } } if (openBook.symbol[n] == "ES") { if (openBook.CallPut[n] == "Put") { putESlegS.Add(openBook.legS[n]); } else { callESlegS.Add(openBook.legS[n]); } } if (openBook.symbol[n] == "CL") { if (openBook.CallPut[n] == "Put") { putCLlegS.Add(openBook.legS[n]); } else { callCLlegS.Add(openBook.legS[n]); } } if (openBook.symbol[n] == "GC") { if (openBook.CallPut[n] == "Put") { putGClegS.Add(openBook.legS[n]); } else { callGClegS.Add(openBook.legS[n]); } } } callSPXlegS.Sort((s1, s2) => s1.CompareTo(s2)); callESlegS.Sort((s1, s2) => s1.CompareTo(s2)); callCLlegS.Sort((s1, s2) => s1.CompareTo(s2)); callGClegS.Sort((s1, s2) => s1.CompareTo(s2)); putSPXlegS.Sort((s1, s2) => s2.CompareTo(s1)); putESlegS.Sort((s1, s2) => s2.CompareTo(s1)); putCLlegS.Sort((s1, s2) => s2.CompareTo(s1)); putGClegS.Sort((s1, s2) => s2.CompareTo(s1)); //! start the connection ********************************// int[] channel = new int[2]; channel = TradeBooks.channelSetup(IBaccount, tradingModel); EClientSocket clientSocket = Allture.ClientSocket; EReaderSignal readerSignal = Allture.Signal; //! [connect] clientSocket.eConnect("127.0.0.1", channel[0], channel[1]); //! [connect] //! [ereader] //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(clientSocket, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); //! [ereader] //************************** //*** Account Info *** //************************** clientSocket.reqAccountSummary(9001, "All", AccountSummaryTags.GetAllTags()); Thread.Sleep(1000); Console.WriteLine("account ID: " + Allture.account_ID); Console.WriteLine("account Value: " + Allture.account_value); Console.WriteLine("account_BuyingPower: " + Allture.account_BuyingPower); Console.WriteLine("account_ExcessLiquidity: " + Allture.account_ExcessLiquidity); Console.WriteLine("account_AvailableFunds: " + Allture.account_AvailableFunds); Console.WriteLine("\n"); //******* calculate the adj std, return with spx, vix, vxx at order execuation in xls // runSPXstrategyCurr(trading_new, csheet, clientSocket); for (int n = 0; n < openBook.positionCNT; n++) { alert1[n] = false; alert2[n] = false; alert3[n] = false; } clientSocket.reqMarketDataType(1); Thread.Sleep(sleep1); while ((DateTime.Now > Convert.ToDateTime("09:30:00 AM")) && (DateTime.Now < Convert.ToDateTime("16:01:00 PM"))) { do { indexPrice = getMktData(clientSocket, Allture, "SPX", "IND", "", "CBOE"); }while (indexPrice == lastPrice); lastPrice = indexPrice; // to ensure vix, vix1, vix2 not consecutive, since their prices aren't chaning very much each time, can't be consecutive for lastPrice. do { vixPrice = getMktData(clientSocket, Allture, "VIX", "IND", "", "CBOE"); }while (vixPrice == lastPrice); lastPrice = vixPrice; do { indexPrice = getMktData(clientSocket, Allture, "SPX", "IND", "", "CBOE"); }while (indexPrice == lastPrice); lastPrice = indexPrice; // to ensure vix, vix1, vix2 not consecutive, since their prices aren't chaning very much each time, can't be consecutive for lastPrice. do { vix1Price = getMktData(clientSocket, Allture, "VIX", "FUT", openBook.vx1Exp, "CFE"); }while (vix1Price == lastPrice); lastPrice = vix1Price; do { indexPrice = getMktData(clientSocket, Allture, "SPX", "IND", "", "CBOE"); }while (indexPrice == lastPrice); lastPrice = indexPrice; // to ensure vix, vix1, vix2 not consecutive, since their prices aren't chaning very much each time, can't be consecutive for lastPrice. do { vix2Price = getMktData(clientSocket, Allture, "VIX", "FUT", openBook.vx2Exp, "CFE"); }while (vix2Price == lastPrice); lastPrice = vix2Price; Console.WriteLine("\n UX2 price: " + vix2Price + "\n"); if (!alert_vix && (vix1Price < vixPrice)) { SendMail("*****@*****.**", "Alert vix backwardation ! ", "VIX:" + vixPrice + " UX1:" + vix1Price); // SendMail("*****@*****.**", "Alert vix backwardation ! ", "VIX:" + vixPrice + " UX1:" + vix1Price); alert_vix = true; } if (!alert_vix1 && (vix2Price < vix1Price)) { SendMail("*****@*****.**", "Alert UX1 backwardation ! ", "UX1:" + vix1Price + " UX2:" + vix2Price); // SendMail("*****@*****.**", "Alert UX1 backwardation ! ", "UX1:" + vix1Price + " UX2:" + vix2Price); alert_vix1 = true; } for (int n = 0; n < openBook.positionCNT; n++) { if (openBook.size[n] == 0) { continue; } //********************************************************** //*** Real time market price - Real Time Index bid/ask/mid** //********************************************************** if (openBook.symbol[n] == "SPX") { if (openBook.CallPut[n] == "Put") { if (openBook.legS[n] < putSPXlegS[0]) { continue; } } do { indexPrice = getMktData(clientSocket, Allture, "SPX", "IND", "", "CBOE"); }while (indexPrice == lastPrice); lastPrice = indexPrice; Console.WriteLine("\n spx price: " + indexPrice + "\n"); exitPoint = SPXexitPoint; } else if (openBook.symbol[n] == "ES") { if (openBook.CallPut[n] == "Put") { if (openBook.legS[n] < putESlegS[0]) { continue; } } do { indexPrice = getMktData(clientSocket, Allture, "ES", "FUT", openBook.underlyingExp[n], "GLOBEX"); }while (indexPrice == lastPrice); lastPrice = indexPrice; Console.WriteLine("\n es price: " + indexPrice + "\n"); exitPoint = ESexitPoint; } else if (openBook.symbol[n] == "CL") { if (openBook.CallPut[n] == "Put") { if (openBook.legS[n] < putCLlegS[0]) { continue; } } do { indexPrice = getMktData(clientSocket, Allture, "CL", "FUT", openBook.underlyingExp[n], "NYMEX"); }while (indexPrice == lastPrice); lastPrice = indexPrice; Console.WriteLine("\n cl price: " + indexPrice + "\n"); exitPoint = CLexitPoint; } else if (openBook.symbol[n] == "GC") { if (openBook.CallPut[n] == "Put") { if (openBook.legS[n] < putGClegS[0]) { continue; } } do { indexPrice = getMktData(clientSocket, Allture, "GC", "FUT", openBook.underlyingExp[n], "NYMEX"); }while (indexPrice == lastPrice); lastPrice = indexPrice; Console.WriteLine("\n GC price: " + indexPrice + "\n"); exitPoint = GCexitPoint; } else { continue; } if (openBook.CallPut[n] == "Put") { if (!alert1[n] && (indexPrice <= (openBook.legS[n] + exitPoint + Alert1))) { // if alert1, sending email; SendMail("*****@*****.**", "Alert1 !! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]); // SendMail("*****@*****.**", "Alert1 ! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]); alert1[n] = true; } /* if (!alert2[n] && (indexPrice <= (openBook.legS[n] + exitPoint + Alert2))) * // { * // if alert2, sending email; * // SendMail("*****@*****.**", "Alert2 !! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.legS[n] + ", " + openBook.size[n] + ", " + openBook.accountID[n]); * // SendMail("*****@*****.**", "Alert2 ! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]); * // alert2[n] = true; * // } * if (!alert3[n] && (indexPrice <= (openBook.legS[n] + exitPoint))) * { * // if alert3, sending email; * SendMail("*****@*****.**", "Alert3 !! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]); * // SendMail("*****@*****.**", "Alert3 ! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + ", " + openBook.legS[n] + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]); * alert3[n] = true; * } */ // very complicated for auto exit and high risk, need more time to think through !!! // seems if we don't directly get position info from IB, then should not do any auto exits if (autoExit) { if (alert3[n]) { //*** estimate the current spread's price and contract ID for combo orders if (openBook.symbol[n] == "SPX") { spread_premium = 0; // spread_premium = 0.05 + getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "OPT", "SMART"); legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "OPT", "SMART"); legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "OPT", "SMART"); //********* Place order *************************** clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "100", "SMART"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false)); Thread.Sleep(sleep2); openBook.size[n] = 0; if (openBook.legS[n] == putSPXlegS[0]) { putSPXlegS.RemoveAt(0); } // else if (openBook.legS[n] == putSPXlegS[1]) putSPXlegS.RemoveAt(1); // else if (openBook.legS[n] == putSPXlegS[2]) putSPXlegS.RemoveAt(2); } else if (openBook.symbol[n] == "ES") { spread_premium = 0; // spread_premium = 0.05 + getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "GLOBEX"); legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "GLOBEX"); legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "GLOBEX"); //********* Place order ************************ clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "50", "GLOBEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false)); Thread.Sleep(sleep2); openBook.size[n] = 0; if (openBook.legS[n] == putESlegS[0]) { putESlegS.RemoveAt(0); } // else if (openBook.legS[n] == putESlegS[1]) putESlegS.RemoveAt(1); // else if (openBook.legS[n] == putESlegS[2]) putESlegS.RemoveAt(2); } else if (openBook.symbol[n] == "CL") { spread_premium = 0; // spread_premium = getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "NYMEX"); legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "NYMEX"); legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "NYMEX"); //********* Place order ************************ clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "1000", "NYMEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false)); Thread.Sleep(sleep2); openBook.size[n] = 0; if (openBook.legS[n] == putESlegS[0]) { putCLlegS.RemoveAt(0); } // else if (openBook.legS[n] == putESlegS[1]) putESlegS.RemoveAt(1); // else if (openBook.legS[n] == putESlegS[2]) putESlegS.RemoveAt(2); } else if (openBook.symbol[n] == "GC") { spread_premium = 0; // spread_premium = getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "NYMEX"); legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "NYMEX"); legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "NYMEX"); //********* Place order ************************ clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "100", "NYMEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false)); Thread.Sleep(sleep2); openBook.size[n] = 0; if (openBook.legS[n] == putESlegS[0]) { putGClegS.RemoveAt(0); } // else if (openBook.legS[n] == putESlegS[1]) putESlegS.RemoveAt(1); // else if (openBook.legS[n] == putESlegS[2]) putESlegS.RemoveAt(2); } else { continue; } // very complicated, need more time to think through !!! one thought - just simply place order, don't cancel it, until it filled // seems if we don't directly get position info from IB, then should not do any auto exits } } } else if (openBook.CallPut[n] == "Call") { if (!alert3[n] && (indexPrice >= (openBook.legS[n] - exitPoint))) { // if alert3, sending email; SendMail("*****@*****.**", "call Alert3 !! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + openBook.legS[n] + ", " + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]); SendMail("*****@*****.**", "call Alert3 ! " + openBook.model[n], openBook.symbol[n] + " " + indexPrice + ", " + ", " + openBook.legS[n] + openBook.expiration[n].Substring(4) + ", " + openBook.size[n] + ", " + openBook.accountID[n]); alert3[n] = true; } // very complicated for auto exit and high risk, need more time to think through !!! // seems if we don't directly get position info from IB, then should not do any auto exits // must have the auto exit. otherwise, you can't handle that many position mannually. and sychological/emotion is another issue. if (autoExit) { if (alert3[n]) { //*** estimate the current spread's price and contract ID for combo orders if (openBook.symbol[n] == "SPX") { // spread_premium = 0; spread_premium = 0.05 + getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "OPT", "SMART"); legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "OPT", "SMART"); legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "OPT", "SMART"); //********* Place order *************************** clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "100", "SMART"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false)); Thread.Sleep(sleep2); openBook.size[n] = 0; if (openBook.legS[n] == callSPXlegS[0]) { callSPXlegS.RemoveAt(0); } // else if (openBook.legS[n] == callSPXlegS[1]) callSPXlegS.RemoveAt(1); // else if (openBook.legS[n] == callSPXlegS[2]) callSPXlegS.RemoveAt(2); } else if (openBook.symbol[n] == "ES") { // spread_premium = 0; spread_premium = 0.05 + getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "GLOBEX"); legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "GLOBEX"); legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "GLOBEX"); //********* Place order ************************ clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "50", "GLOBEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false)); Thread.Sleep(sleep2); openBook.size[n] = 0; if (openBook.legS[n] == callESlegS[0]) { callESlegS.RemoveAt(0); } // else if (openBook.legS[n] == callESlegS[1]) callESlegS.RemoveAt(1); // else if (openBook.legS[n] == callESlegS[2]) callESlegS.RemoveAt(2); else if (openBook.symbol[n] == "CL") { spread_premium = 0; // spread_premium = getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "NYMEX"); legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "NYMEX"); legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "NYMEX"); //********* Place order ************************ clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "1000", "NYMEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false)); Thread.Sleep(sleep2); openBook.size[n] = 0; if (openBook.legS[n] == callCLlegS[0]) { callCLlegS.RemoveAt(0); } // else if (openBook.legS[n] == callCLlegS[1]) callCLlegS.RemoveAt(1); // else if (openBook.legS[n] == callCLlegS[2]) callCLlegS.RemoveAt(2); } else if (openBook.symbol[n] == "GC") { spread_premium = 0; // spread_premium = getSpreadPremium(clientSocket, Allture, openBook, n, openBook.legS[n], openBook.legB[n], "FOP", "NYMEX"); legS_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legS[n], "FOP", "NYMEX"); legB_ID = getContractID(clientSocket, Allture, openBook, n, openBook.legB[n], "FOP", "NYMEX"); //********* Place order ************************ clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], legB_ID, legS_ID, "100", "NYMEX"), OrderSamples.ComboLimitOrder("SELL", openBook.size[n], -spread_premium, false)); Thread.Sleep(sleep2); openBook.size[n] = 0; if (openBook.legS[n] == callCLlegS[0]) { callGClegS.RemoveAt(0); } // else if (openBook.legS[n] == callCLlegS[1]) callCLlegS.RemoveAt(1); // else if (openBook.legS[n] == callCLlegS[2]) callCLlegS.RemoveAt(2); } // very complicated, need more time to think through !!! one thought - just simply place order, don't cancel it, until it filled // seems if we don't directly get position info from IB, then should not do any auto exits } } } } } } Console.WriteLine("\n start finish, time: " + DateTime.Now + " \n"); return(0); }