private void axTws1_historicalData(object sender, AxTWSLib._DTwsEvents_historicalDataEvent e) { // Handle the incoming historical data records. // Object e contains: // e.date Date (and time) of the historical data bar // e.open The opening price of the bar/interval // e.high The high price for the bar/interval // e.low The low price for the bar/interval // e.close The closing price of the bar/interval // e.volume The volume (number of shares/contract) for the bar/interval // e.wAP The average price during the bar/interval string OutputString; // Concatenate all of the required fields into the OutputString OutputString = e.date + " " + e.open.ToString("N2") + " " + e.close.ToString("N2") + " " + e.volume; // Add the output string to the ListBox lbData.Items.Add(OutputString); // Declare a stream writer to append data to a file StreamWriter sw = File.AppendText("mydata.txt"); // write the data to the file sw.Write(OutputString); // Flush the output to disk sw.Flush(); // Close the streamwriter sw.Close(); // Add data points to the chart if (e.close > 0.0) { chtStocks.Series["Series1"].Points.AddXY(e.date, e.close); } }
private void axTws1_orderStatus(object sender, AxTWSLib._DTwsEvents_orderStatusEvent e) { // Update the order status fields // e.id // e.parentId // e.remaining string strOrderStatus; strOrderStatus = e.id + " " + e.parentId + " " + e.status + " " + e.filled + " " + e.lastFillPrice; // Add to list box lbOrderStatus.Items.Add(strOrderStatus); }
private void axTws1_contractDetails(object sender, AxTWSLib._DTwsEvents_contractDetailsEvent e) { // Report all of the contract details in response to // reqContractDetailsEX // This method will be called one time per contract // e.conId - ContractID // GridViewRowInfo rowInfo = dgOptionsSeries.Rows.AddNew(); // Only add if we already did not put this one in if ( ! (alOptionsSeries.Contains(e.conId) ) ) { dgOptionsSeries.Rows.Add(e.conId, e.symbol, e.expiry, e.strike, e.right); alOptionsSeries.Add(e.conId); } }
private void axTws1_orderStatus(object sender, AxTWSLib._DTwsEvents_orderStatusEvent e) { // Get the status of an order. // Responds to every change in order status. // Status in in event object e: // e.id The OrderID (long) // e.status The status of the order (string) // e.filled The number of shares/contracts filled in the so far // e.remaining The number of shares/contracts remaining in the order // e.avgFillPrice The average fill price (double) // e.permId The permanent order Id (long) // e.lastFilledPrice The price of the last partial fill (double) // e.clientId The Id of the client who placed the order (long) // Use the Convert.ToString() to convert int and double values to strings tbStatus.Text = e.status; // Quantity of shares filled on this order tbFilled.Text = Convert.ToString(e.filled); // Number of shares remaining to be filled on this order tbRemaining.Text = Convert.ToString(e.remaining); // The average price for all executions against this order tbAveragePrice.Text = Convert.ToString(e.avgFillPrice); }
/// <summary> /// apply an order status change /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void TWS_orderStatus(object sender, AxTWSLib._DTwsEvents_orderStatusEvent e) { try { if (m_DriverLog.IsDebugEnabled) { m_DriverLog.Debug("TWS_openOrderEx:" + e.clientId.ToString() + ": " + e.ToString() + ": " + e.status.ToString()); } QuickFix.OrdStatus myOrdStatus; QuickFix.ExecType myExecType = new QuickFix.ExecType(QuickFix.ExecType.ORDER_STATUS); double myLastFill = 0.0; // get the order contect using the IB ID DriverBase.OrderContext myCntx = null; if (this.m_ApiIDOrderMap.ContainsKey(e.id.ToString())) { myCntx = m_ApiIDOrderMap[e.id.ToString()]; } if (myCntx == null) { string myErr = "IB TWS: no context found for IB ID:" + e.id.ToString(); Exception myE = new Exception(myErr); throw myE; } myLastFill = myCntx.LeavesQty - e.remaining; myCntx.CumQty = e.filled; // get the original order from the context QuickFix.Message myOrder = myCntx.QFOrder; switch (e.status) { case "PendingSubmit": myOrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.PENDING_NEW); sendExecReport(myOrder, new QuickFix.OrderID(e.id.ToString()), myOrdStatus, myExecType, myLastFill, e.remaining, e.filled, e.lastFillPrice, e.avgFillPrice); break; case "PendingCancel": myOrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.PENDING_CANCEL); sendExecReport(myOrder, new QuickFix.OrderID(e.id.ToString()), myOrdStatus, myExecType, myLastFill, e.remaining, e.filled, e.lastFillPrice, e.avgFillPrice); break; case "PreSubmitted": break; case "Inactive": break; case "Submitted": if (e.filled > 0) { myOrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.PARTIALLY_FILLED); myExecType = new QuickFix.ExecType(QuickFix.ExecType.PARTIAL_FILL); } else { myOrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.NEW); } // mark the context as done for the sub SetContextCommand(myCntx, DriverBase.ORCommand.Submit, DriverBase.ORCommand.Undefined); sendExecReport(myOrder, new QuickFix.OrderID(e.id.ToString()), myOrdStatus, myExecType, myLastFill, e.remaining, e.filled, e.lastFillPrice, e.avgFillPrice); break; case "Cancelled": myOrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.CANCELED); sendExecReport(myOrder, new QuickFix.OrderID(e.id.ToString()), myOrdStatus, myExecType, myLastFill, e.remaining, e.filled, e.lastFillPrice, e.avgFillPrice); // mark the context as done for the sub SetContextCommand(myCntx, DriverBase.ORCommand.Pull, DriverBase.ORCommand.Undefined); break; case "Filled": myOrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.FILLED); myExecType = new QuickFix.ExecType(QuickFix.ExecType.FILL); sendExecReport(myOrder, new QuickFix.OrderID(e.id.ToString()), myOrdStatus, myExecType, myLastFill, e.remaining, e.filled, e.lastFillPrice, e.avgFillPrice); // mark the context as done for the sub SetContextCommand(myCntx, DriverBase.ORCommand.Undefined, DriverBase.ORCommand.Undefined); break; default: _log.Error("TWS_orderStatus:unknown status" + e.status); break; } } catch (Exception myE) { _log.Error("TWS_orderStatus", myE); } }
/// <summary> /// Handles the openOrderEx event of the AxTWSLib.AxTws object in the TwsHostForm. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> void TWS_openOrderEx(object sender, AxTWSLib._DTwsEvents_openOrderExEvent e) { try { if (_log.IsDebugEnabled) { _log.Debug("TWS_openOrderEx:" + e.orderId.ToString() + ": " + e.contract.ToString() + ": " + e.orderState.ToString()); } switch (e.orderState.status) { case "PendingSubmit": break; case "PendingCancel": break; case "PreSubmitted": break; case "Cancelled": break; case "Inactive": break; case "Submitted": break; case "Filled": break; default: _log.Error("TWS_openOrderEx:unknown order state" + e.orderState.status); break; } } catch (Exception myE) { _log.Error("TWS_openOrderEx", myE); } }
/// <summary> /// Handles the nextValidId event of the AxTWSLib.AxTws object in the TwsHostForm. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The _DTwsEvents_nextValidIdEvent.</param> void TWS_nextValidId(object sender, AxTWSLib._DTwsEvents_nextValidIdEvent e) { m_NextID = e.id; }
private void axTws1_nextValidId(object sender, AxTWSLib._DTwsEvents_nextValidIdEvent e) { // The next unique OrderId will be held in e.id // Assign the unique id to the text box tbOrderId.Text = Convert.ToString(e.id); }
private void DumpRecord(KaiTrade.Interfaces.ITSItem tsItem, KaiTrade.Interfaces.ITSSet tsSet, AxTWSLib._DTwsEvents_realtimeBarEvent e) { try { // get a new TS item tsItem.Index = e.count; tsItem.Tag = e.time; //tsItem.TimeStamp = e.date //tsItem.TimeStamp = e.date; tsItem.Open = e.open; tsItem.High = e.high; tsItem.Low = e.low; tsItem.Close = e.close; tsItem.Volume = e.volume; DateTime result=new DateTime(1970,1,1); TimeSpan span = new TimeSpan(0, 0, e.time); result.Add(span); tsItem.TimeStamp = result; } catch (Exception myE) { _log.Error("DumpRecord", myE); } }
/// <summary> /// Updates the publisher price /// </summary> /// <param name="myPub"></param> /// <param name="e"></param> private void UpdatePrice(KaiTrade.Interfaces.TradableProduct product, AxTWSLib._DTwsEvents_tickPriceEvent e) { try { KaiTrade.TradeObjects.PXUpdateBase pxupdate = new KaiTrade.TradeObjects.PXUpdateBase(m_ID); pxupdate.Mnemonic = product.Mnemonic; pxupdate.DepthOperation = KaiTrade.Interfaces.PXDepthOperation.none; switch (e.tickType) { case 1: pxupdate.BidPrice = (decimal)e.price; break; case 2: pxupdate.OfferPrice = (decimal)e.price; break; case 4: pxupdate.TradePrice = (decimal)e.price; break; case 6: pxupdate.DayHigh = (decimal)e.price; break; case 7: pxupdate.DayLow = (decimal)e.price; break; } //myPub.APIUpdateTime = DateTime.Now; ApplyPriceUpdate(pxupdate); } catch (Exception myE) { _log.Error("UpdateMDSubjectPrice", myE); } }
/// <summary> /// apply a size update /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void TWS_tickSize(object sender, AxTWSLib._DTwsEvents_tickSizeEvent e) { try { if (m_IBReqIDProductMap.ContainsKey(e.id)) { this.UpdateSize(m_IBReqIDProductMap[e.id], e); } } catch (Exception myE) { _log.Error("TWS_tickSize", myE); } }
private void axTws1_nextValidId(object sender, AxTWSLib._DTwsEvents_nextValidIdEvent e) { // Set to the next available order id tbOrderId.Text = e.id.ToString(); }
private void axTws1_errMsg(object sender, AxTWSLib._DTwsEvents_errMsgEvent e) { lbErrors.Items.Add(e.errorCode + " " + e.errorMsg); }
private void axTws1_errMsg(object sender, AxTWSLib._DTwsEvents_errMsgEvent e) { // Report any errors if occuring lbErrors.Items.Add(e.errorMsg); }
void TWS_realtimeBar(object sender, AxTWSLib._DTwsEvents_realtimeBarEvent e) { try { if (m_IBReqIDTSSet.ContainsKey(e.tickerId)) { KaiTrade.Interfaces.ITSSet tsSet = m_IBReqIDTSSet[e.tickerId]; // get a new TS item KaiTrade.Interfaces.ITSItem tsItem = tsSet.GetNewItem(); DumpRecord(tsItem, tsSet, e); tsSet.AddItem(tsItem); tsSet.Added = true; } else { _log.Error("TWS_realtimeBar:unknown request id"); } } catch (Exception myE) { _log.Error("TWS_realtimeBar", myE); } }
void TWS_contractDetailsEx(object sender, AxTWSLib._DTwsEvents_contractDetailsExEvent e) { try { KaiTrade.Interfaces.TradableProduct myProduct = m_ContractDetailsRequest[e.reqId]; if (myProduct.TradeVenueSequence == 0) { myProduct.TradeVenueSequence += 1; } else { // this is not the first definition long venueSeq = myProduct.TradeVenueSequence; myProduct.TradeVenueSequence += 1; myProduct = Facade.Factory.GetProductManager().CloneProduct(myProduct.Identity); myProduct.Mnemonic = myProduct.Mnemonic + "." + venueSeq.ToString(); Facade.Factory.GetProductManager().RegisterProduct(myProduct); } //string zztemp = e.contractDetails.summary.ToString(); myProduct.TickSize = (decimal)e.contractDetails.minTick; myProduct.LongName = e.contractDetails.longName; string[] temp = myProduct.TickSize.ToString().Split('.'); if (temp.Length > 1) { myProduct.NumberDecimalPlaces = temp[1].Length; } else { myProduct.NumberDecimalPlaces = 0; } if ( (e.contractDetails.contractMonth.Length > 0)) { myProduct.MMY = e.contractDetails.contractMonth; } if (myProduct.CFICode != null) { if (myProduct.CFICode.ToString()[0] == 'E') { myProduct.PriceFeedQuantityMultiplier = 100; } else { myProduct.PriceFeedQuantityMultiplier = 1; } } } catch (Exception myE) { _log.Error("TWS_contractDetailsEx", myE); } }
/// <summary> /// Apply a price update /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void TWS_tickPrice(object sender, AxTWSLib._DTwsEvents_tickPriceEvent e) { try { if (m_IBReqIDProductMap.ContainsKey(e.id)) { this.UpdatePrice(m_IBReqIDProductMap[e.id], e); /* (m_IBReqIDPubMap[e.id] as KaiTrade.Interfaces.Publisher).OnUpdate(null); if ((m_IBReqIDPubMap[e.id] as KaiTrade.Interfaces.Publisher).Status != KaiTrade.Interfaces.Status.open) { (m_IBReqIDPubMap[e.id] as KaiTrade.Interfaces.Publisher).Status = KaiTrade.Interfaces.Status.open; } */ } } catch (Exception myE) { _log.Error("TWS_tickPrice", myE); } }
void TWS_currentTime(object sender, AxTWSLib._DTwsEvents_currentTimeEvent e) { try { // We use this to determine if the connection is open if (this.Status != KaiTrade.Interfaces.Status.open) { this.setStatus(KaiTrade.Interfaces.Status.open); } } catch (Exception myE) { _log.Error("TWS_currentTime", myE); } }
void TWS_updateMktDepthL2(object sender, AxTWSLib._DTwsEvents_updateMktDepthL2Event e) { try { updateMktDepth(e.id, e.position, e.marketMaker, e.operation, e.side, e.price, e.size); } catch (Exception myE) { _log.Error("TWS_updateMktDepthL2", myE); } }
/// <summary> /// Handles the errMsg event of the AxTWSLib.AxTws object in the TwsHostForm. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> void TWS_errMsg(object sender, AxTWSLib._DTwsEvents_errMsgEvent e) { try { string myError = "TWS_errMsg: " + e.errorMsg + " " + e.errorCode + " " + e.id; _log.Error(myError); this.SendAdvisoryMessage(myError); if (e.errorCode == 504) { setStatus(KaiTrade.Interfaces.Status.closed); } //will reject the order - if any if (e.id >= 0) { rejectOrder(e.id.ToString(), e.errorMsg); } } catch (Exception myE) { _log.Error("TWS_errMsg", myE); } }
/// <summary> /// Update the publisher size /// </summary> /// <param name="mySubject"></param> /// <param name="e"></param> private void UpdateSize(KaiTrade.Interfaces.TradableProduct product, AxTWSLib._DTwsEvents_tickSizeEvent e) { KaiTrade.TradeObjects.PXUpdateBase pxupdate = new KaiTrade.TradeObjects.PXUpdateBase(m_ID); pxupdate.Mnemonic = product.Mnemonic; switch (e.tickType) { case 0: pxupdate.BidSize = e.size * product.PriceFeedQuantityMultiplier; break; case 3: pxupdate.OfferSize = e.size * product.PriceFeedQuantityMultiplier; break; case 5: pxupdate.TradeVolume = e.size * product.PriceFeedQuantityMultiplier; break; } ApplyPriceUpdate(pxupdate); }
/// <summary> /// Process historical data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void TWS_historicalData(object sender, AxTWSLib._DTwsEvents_historicalDataEvent e) { try { if (m_IBReqIDTSSet.ContainsKey(e.reqId)) { KaiTrade.Interfaces.ITSSet tsSet = m_IBReqIDTSSet[e.reqId]; // get a new TS item KaiTrade.Interfaces.ITSItem tsItem = tsSet.GetNewItem(); if (tsSet.Items.Count > 200) { tsSet.Added = true; tsSet.Items.Clear(); } DumpRecord(tsItem, tsSet,e); tsSet.AddItem(tsItem); if (tsItem.Tag.ToString().IndexOf("fin",0) >= 0) { tsSet.Added = true; } if (tsSet.Items.Count > 200) { } _log.Info("BAR: " + tsItem.ToString()); } else { _log.Error("TWS_historicalData:unknown request id"); } } catch (Exception myE) { _log.Error("TWS_historicalData", myE); } }
private void DumpRecord(KaiTrade.Interfaces.ITSItem tsItem, KaiTrade.Interfaces.ITSSet tsSet, AxTWSLib._DTwsEvents_historicalDataEvent e) { try { // get a new TS item tsItem.Index = e.barCount; tsItem.Tag = e.date; //tsItem.TimeStamp = e.date //tsItem.TimeStamp = e.date; tsItem.Open = e.open; tsItem.High = e.high; tsItem.Low = e.low; tsItem.Close =e.close; tsItem.Volume = e.volume; DateTime result; if (e.date.Length > 10) { DriverBase.DriverUtils.FromLocalMktDate(out result, e.date.Substring(0, 8), e.date.Substring(10, 8)); } else { DriverBase.DriverUtils.FromLocalMktDate(out result, e.date); } tsItem.TimeStamp = result; //tsItem.AskVolume = e.; //tsItem.BidVolume = myBar.BidVolume; // e.volume //tsItem.Mid = e.m; //tsItem.HLC3 = myBar.HLC3; //tsItem.Avg = myBar.Avg; //tsItem.TrueHigh = myBar.TrueHigh; //tsItem.TrueLow = myBar.TrueLow; //tsItem.Range = myBar.Range; //tsItem.TrueRange = myBar.TrueRange; //tsItem.Index = int.Parse(e.date); } catch (Exception myE) { _log.Error("DumpRecord", myE); } }
private void axTws1_tickPrice(object sender, AxTWSLib._DTwsEvents_tickPriceEvent e) { // Callback method to handle new market data Price change events // When this callback method/routine is activated, price changes will appear // in the Events objects named "e" // Properties of "e" include: // e.id The identifier that was set during the call to reqMktData // e.price The latest Price // e.tickType The tick type 1=bid,2=ask, 4=last, 6=high, 7=low, 9=close // e.canAutoExecute A flag 1= the order can be automatically executed // If this is a bid price change, then display it if ((e.tickType) == 1) { // Add the bid price to the text box lbPrice.Items.Add("Bid = " + e.price); } // If this is a ask price change, then display it if ((e.tickType) == 2) { // Add the ask price to the text box lbPrice.Items.Add("Ask = " + e.price); } // If this is a last price change, then display it if ((e.tickType) == 4) { // Add the last price to the list box // Note: In C# the plus sign can be used for string concatenation lbPrice.Items.Add("Last =" + e.price); // Add the trade's latest price to the chart box chtPrices.Series["Prices"].Points.AddY(e.price); // Add latest price to lstPriceHistory's list lstPriceHistory.Add(e.price); //Calculate when lstPriceHistory's count is above 20 if (lstPriceHistory.Count > 20) { // Remove the first price entry from lstPriceHistory's list lstPriceHistory.RemoveAt(0); // Calculating the Average Prices and then plotting it double dblTotalPrice = lstPriceHistory.Sum(); double dblMovingAverage = (dblTotalPrice) / 20.0; chtPrices.Series["AveragePrices"].Points.AddY(dblMovingAverage); } // Calculate when lstPriceHistory's count is below 20 else { // Add the point to the graph (0.0) chtPrices.Series["AveragePrices"].Points.AddY(0.0); // Now making that point "Empty" chtPrices.Series["AveragePrices"].Points.ElementAt( (lstPriceHistory.Count() - 1) ).IsEmpty = true; // Adding an Empty Point chtPrices.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, "AveragePrices"); } } }