/// <summary> /// Update the instrument information in the grid. /// </summary> /// <param name="instrument">Instrument</param> private void updateInstrument(Instrument instrument) { for (int i = 1; i < dataGridViewSpreadDetails.Columns.Count; i++) { //get the instrument which is a hidden row InstrumentKey instrKey = (InstrumentKey)dataGridViewSpreadDetails.Rows[(int)FieldType.HiddenObject].Cells[i].Value; if (instrument.Key == instrKey) { string instrName = instrument.GetFormattedName(InstrumentNameFormat.Full); dataGridViewSpreadDetails.Rows[(int)FieldType.Contract].Cells[i].Value = instrName; DataGridViewComboBoxCell combo = (DataGridViewComboBoxCell)dataGridViewSpreadDetails.Rows[(int)FieldType.OrderFeedCombo].Cells[i]; combo.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton; string selectedOrderFeed = (string)combo.Value; combo.Items.Clear(); combo.Value = ""; foreach (var feed in instrument.GetValidOrderFeeds()) { combo.Items.Add(feed.ConnectionKey.GatewayKey.Name); } if (!String.IsNullOrEmpty(selectedOrderFeed) && combo.Items.Contains(selectedOrderFeed)) { combo.Value = selectedOrderFeed; } } } }
/// <summary> /// Find a given instrument based on the InstrumentKey. /// </summary> /// <param name="instrumentKey">InstrumentKey</param> private void findInstrument(InstrumentKey instrumentKey) { InstrumentLookupSubscription sub = new InstrumentLookupSubscription(m_session, m_dispatcher, instrumentKey); sub.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(instrumentLookupSubscription_Update); sub.Start(); }
}//constructor // // #endregion//Constructors #region no Properties // ***************************************************************** // **** Properties **** // ***************************************************************** // // #endregion//Properties #region Public Request / Lookup Methods // ***************************************************************** // **** Public Methods **** // ***************************************************************** // // // // // ***************************************************** // **** Request Instruments() **** // ***************************************************** /// <summary> /// Extends the MarketHub base class requests by allowing TT Users to /// request market information using only the TT InstrumentKey. /// </summary> /// <param name="key">Requests instrument details for TT InstrumentKey </param> /// <returns></returns> public bool RequestInstruments(InstrumentKey key) { MarketHubRequest request = GetRequest(MarketHubRequest.RequestType.RequestInstruments); request.Data.Add(key); return(this.HubEventEnqueue(request)); }
private void OnMessage(InstrumentKey key, string s) { if (Message != null) { Message(this, new MessageEventArgs(key, s)); } }
private void TT_OrderBookDownload(object sender, TradingTechnologies.TTAPI.OrderBookDownloadEventArgs eventArgs) { foreach (Order order in eventArgs.Orders) { InstrumentKey key = order.InstrumentKey; SendMessage("OrderBookDownload", order); } }
/// <summary> /// Subscribe to an instrument using an InstrumentDescriptor and unique Tag /// </summary> /// <param name="descriptor">InstrumentDescriptor containing the instrument information</param> /// <param name="instrumentRequestTag">unique Tag that will become part of the instrument request</param> /* public void SubscribeToInstrument(InstrumentDescriptor descriptor, string tag) * { * InstrumentLookupSubscription req = new InstrumentLookupSubscription(apiSession, Dispatcher.Current, descriptor.ProductKey, descriptor.ContractName); * req.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(instrumentLookupRequest_Update); * req.Tag = tag; // Tag our request with our unique tag string * req.Start(); * //Console.WriteLine("SUBSCRIPTION REQUEST: " + descriptor.ToString()); * } */ /// <summary> /// Subscribe to an instrument using only the InstrumentKey /// </summary> /// <param name="key">InstrumentKey of the instrument to which we want to subscribe</param> public void SubscribeToInstrument(InstrumentKey key) { EventInstruments.Instance.SubscribeToInstrument(key); /*InstrumentLookupSubscription req = new InstrumentLookupSubscription(apiSession, Dispatcher.Current, key); * req.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(instrumentLookupRequest_Update); * req.Start();*/ }
public void startInstrumentLookupSubscriptionsFromDataTable(object sender, AuthenticationStatusUpdateEventArgs e) { if (e.Status.IsSuccess) { foreach (DataRow item in TickerTable.Rows) { ttapiTicker currentTicker; if (item.Field <bool>("IsSpreadQ")) { currentTicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker: item.Field <string>("Ticker"), productType: "SPREAD"); } else { currentTicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker: item.Field <string>("Ticker"), productType: "FUTURE"); } if (currentTicker.marketKey == "CME") { mkey = MarketKey.Cme; } else if (currentTicker.marketKey == "ICE_IPE") { mkey = MarketKey.Ice; } if (currentTicker.productType == "FUTURE") { ptype = ProductType.Future; } else if (currentTicker.productType == "SPREAD") { ptype = ProductType.Spread; } InstrumentKey IKey = new InstrumentKey(new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); Console.WriteLine(currentTicker.SeriesKey); Ils = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); //Ils = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(MarketKey.Cme, ProductType.Spread, "CL"), "Nov16:-1xDec16"); for (int i = 0; i < ilsUpdateList.Count; i++) { Ils.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(ilsUpdateList[i]); } IlsDictionary.Add(IKey, Ils); Ils.Start(); } } else { Console.WriteLine("TT Login failed: {0}", e.Status.StatusMessage); Dispose(); } }
private void SendMessage(string eventName, Order order) { InstrumentKey key = order.InstrumentKey; msg.Clear(); msg.AppendFormat("{0}", eventName); msg.AppendFormat(",{0},{2}({1}),{3}", Enum.GetName(typeof(BuySell), order.BuySell), order.WorkingQuantity.ToInt(), order.LimitPrice.ToDouble(), order.FillQuantity.ToInt()); msg.AppendFormat(",{0},{1},{2}", order.Status, order.Received.ToString(Strings.FormatDateTimeZone), order.OrderKey.ToString()); OnMessage(key, msg.ToString()); }
public void FilterByInstrument(InstrumentKey instrumentKey) { TradeSubscriptionInstrumentFilter filter = new TradeSubscriptionInstrumentFilter(m_TTService.session, instrumentKey, false, instrumentKey.ToString()); this.m_TradeFilter = filter; m_TradeFilterArg = instrumentKey.ToString(); if (Log != null) { Log.NewEntry(LogLevel.Minor, "FillListener.FilterByInstrument: Filtering by instrumentKey {0}", instrumentKey); } }
/// <summary> /// Retrieve an instrument (TTInstrument) given an InstrumentKey /// </summary> /// <param name="key">Instrument key to look up</param> /// <returns>TTInstrument object associated with the specified InstrumentKey</returns> public TTInstrument GetInstrument(InstrumentKey key) { TTInstrument result = null; if (ttInstruments.ContainsKey(key)) { result = ttInstruments[key]; } return(result); }
}//SubscribeTo() /// <summary> /// Get a instrument catalog for single instrument. /// Called by external thread. /// </summary> public void SubscribeTo(InstrumentKey instrKey) { if (m_isDisposing) { return; } Job job = new Job(); job.InstrumentKey = instrKey; m_InQueue.Enqueue(job); // Net 4.5 version. No locking needed. m_Dispatcher.BeginInvoke(new Action(ProcessAJob)); m_Dispatcher.Run(); }//SubscribeTo()
/// <summary> /// This function checks the existence of a fill by exchange time. Only used by audit trail fill hub. /// </summary> /// <param name="exchangeTime"></param> /// <returns></returns> public bool TryCheckFillByExchangeTime(InstrumentKey ttKey, DateTime exchangeTime) { if (!m_FillBooks.ContainsKey(ttKey)) { return(false); } else { BookLifo book = m_FillBooks[ttKey]; bool status = book.IsFillExistByExchangeTime(exchangeTime); return(status); } }
private void btnConnect_Click(object sender, EventArgs e) { UpdateStatusBar("Connecting to Instrument..."); // Create a product key from the given values ProductKey productKey = new ProductKey(this.txtExchange.Text, (ProductType)this.cboProductType.SelectedItem, this.txtProduct.Text); InstrumentKey key = new InstrumentKey(productKey, this.txtContract.Text); //m_ttapi.FindInstrument(key); }
/// <summary> /// Retrieve a list of all orders in the system (working and not working) /// </summary> /// <param name="key">InstrumentKey of instrument in the requested orders</param> /// <returns>List of TTOrder objects representing all orders for the specified InstrumentKey</returns> public List <TTOrder> GetOrders(InstrumentKey key) { List <TTOrder> results = new List <TTOrder>(); foreach (TTOrder order in ttOrders.Values) { if (order.InstrumentKey == key) { results.Add(order); } } return(results); }
/// <summary> /// Retrieve a list of all fills in the system (current and non-current) /// </summary> /// <param name="key">InstrumentKey of instrument in the requested fills</param> /// <returns>List of TTFill objects representing all fills for the specified InstrumentKey</returns> /// <remarks>Non-current fills would include amend fill messages, etc.</remarks> public List <TTFill> GetFills(InstrumentKey key) { List <TTFill> results = new List <TTFill>(); foreach (TTFill fill in ttFills.Values) { if (fill.InstrumentKey == key) { results.Add(fill); } } return(results); }
// ************************************************* // **** SubscribeTo() **** // ************************************************* /// <summary> /// Subscribe to insturment price updates. /// This is called by an *external* thread. /// </summary> public void SubscribeTo(InstrumentKey instrKey, PriceSubscriptionSettings settings) { if (m_isDisposing) { return; } Job job = new Job(); job.InstrumentKey = instrKey; job.Settings = settings; m_InQueue.Enqueue(job); // Net 4.5 concurrent collection - no locking needed! m_Dispatcher.BeginInvoke(new Action(ProcessAJob)); m_Dispatcher.Run(); }//SubscribeTo()
}//Dispose() // // public void SubscribeToTimeAndSales(InstrumentKey instrKey) { if (m_isDisposing) { return; } Job job = new Job(); job.InstrumentKey = instrKey; job.IsTimeAndSales = true; m_InQueue.Enqueue(job); // Net 4.5 concurrent collection - no locking needed! m_Dispatcher.BeginInvoke(new Action(ProcessAJob)); m_Dispatcher.Run(); }//SubscribeTo()
public void SetAttributes(Dictionary <string, string> attributes) { InstrumentName name; InstrumentKey ttkey; foreach (string key in attributes.Keys) { if (key.Equals("Name") && InstrumentName.TryDeserialize(attributes["Name"], out name)) { this.Name = name; } else if (key.Equals("Key") && TTConvertNew.TryCreateInstrumentKey(attributes["Key"], out ttkey)) { this.Key = ttkey; } } }
/// <summary> /// Perform the instrument lookups /// </summary> public void Init() { foreach (ContractDetails cd in m_lcd) { InstrumentKey key = new InstrumentKey(new ProductKey(cd.m_marketKey, cd.m_productType, cd.m_product), cd.m_contract); Console.WriteLine("Strategy1::Subscribing to Instrument: {0}", key); InstrumentLookupSubscription req = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, key); /*InstrumentLookupSubscription req = new InstrumentLookupSubscription( * m_apiInstance.Session, Dispatcher.Current, * new ProductKey(cd.m_marketKey, cd.m_productType, cd.m_product), cd.m_contract);*/ req.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(req_Update); m_lreq.Add(req); req.Start(); } }
public void SubscribeToInstrument(InstrumentKey key) { if (_dispatcher.InvokeRequired()) { _dispatcher.BeginInvoke(() => { SubscribeToInstrument(key); }); return; } InstrumentLookupSubscription req = new InstrumentLookupSubscription(_apiSession, Dispatcher.Current, key); req.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(instrumentLookupRequest_Update); req.Start(); Console.WriteLine("SUBSCRIBETOINSTRUMENT REQUEST: " + key.ToString()); }
public void startInstrumentLookupSubscriptions(object sender, AuthenticationStatusUpdateEventArgs e) { if (e.Status.IsSuccess) { foreach (string dbTicker in dbTickerList) { ttapiTicker currentTicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker); if (currentTicker.marketKey == "CME") { mkey = MarketKey.Cme; } else if (currentTicker.marketKey == "ICE_IPE") { mkey = MarketKey.Ice; } if (currentTicker.productType == "FUTURE") { ptype = ProductType.Future; } else if (currentTicker.productType == "SPREAD") { ptype = ProductType.Spread; } InstrumentKey IKey = new InstrumentKey(new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); Ils = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); for (int i = 0; i < ilsUpdateList.Count; i++) { Ils.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(ilsUpdateList[i]); } IlsDictionary.Add(IKey, Ils); Ils.Start(); } } else { Console.WriteLine("TT Login failed: {0}", e.Status.StatusMessage); Dispose(); } }
// // //****************************************************************** // **** TimeAndSalesSubscription_Updated() **** //****************************************************************** // /// <summary> /// Time and Sales data is uncoalesced trade data. This allows us to a better job /// of diffrentiating sides volume traded on while recording data for analysis. /// This update Volume on all sides but last. The price subscription has a good last traded volume /// field, this is used only for more in depth analysis when needed /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void TimeAndSalesSubscription_Updated(object sender, TimeAndSalesEventArgs eventArgs) { if (m_isDisposing) { return; } if (eventArgs.Error == null) { UVProd.InstrumentName instrumentName; InstrumentKey key = eventArgs.Instrument.Key; if (m_KeyToInstruments.TryGetValue(key, out instrumentName)) { if (eventArgs.Data.Count != 0) { // is any data packed with this event m_NewEvents.Clear(); MarketBase newEvent = m_Market.m_MarketBaseFactory.Get(); // Get an event arg. newEvent.ClearVolume(); // make sure our event is clean. newEvent.Name = instrumentName; int[] instrumentVolumeArray = m_InstrKeyToVolume[key]; foreach (TimeAndSalesData timeAndSalesData in eventArgs.Data) { // for each trade if (!timeAndSalesData.IsOverTheCounter) { // this trade was not OTC int tradeSide = TTConvertNew.ToUVMarketSide(timeAndSalesData.Direction); //long, short or unknown if (timeAndSalesData.TradeQuantity.IsValid) { // qty is valid so aggregate all qty's by the direction of the trade instrumentVolumeArray[tradeSide] += timeAndSalesData.TradeQuantity.ToInt(); } } } for (int side = 0; side < newEvent.Volume.Length; side++) { // update all sides newEvent.Volume[side] = instrumentVolumeArray[side]; } newEvent.IsIncludesTimeAndSales = true; m_NewEvents.Add(newEvent); ProcessPriceChangeEvents(ref m_NewEvents); } } } }
// // // ***************************************************************** // **** Try Lookup Instrument() **** // ***************************************************************** public bool TryLookupInstrument(InstrumentKey ttInstrumentKey, out InstrumentName instrument) { bool isFound = false; instrument = new MistyProds.InstrumentName(); lock (m_InstrumentLock) { foreach (InstrumentName instr in m_InstrumentDetails.Keys) { if (m_InstrumentDetails[instr].Key.Equals(ttInstrumentKey)) { instrument = instr; isFound = true; break; } } } //lock return(isFound); } //
/// <summary> /// Allow drag of instrument or product from tree view. /// </summary> private void treeViewProductList_ItemDrag(object sender, ItemDragEventArgs e) { TreeNode node = e.Item as TreeNode; if (node != null) { DataObject dataObject = new DataObject(); if (node.Nodes.Count > 0) { ProductKey key = ((Product)node.Tag).Key; DoDragDrop(key.ToDataObject(), DragDropEffects.Copy); } else { InstrumentKey key = ((Instrument)node.Tag).Key; DoDragDrop(key.ToDataObject(), DragDropEffects.Copy); } } }
public override int GetHashCode() { int hash = 1; if (InstrumentKey != 0) { hash ^= InstrumentKey.GetHashCode(); } if (BucketMin != 0F) { hash ^= BucketMin.GetHashCode(); } if (BucketMax != 0F) { hash ^= BucketMax.GetHashCode(); } if (NBuckets != 0) { hash ^= NBuckets.GetHashCode(); } return(hash); }
public void StartASEEventChain() { int TagValue = 1; foreach (string dbTicker in DbTickerList) { ttapiTicker currentTicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker); if (currentTicker.marketKey == "CME") { mkey = MarketKey.Cme; } else if (currentTicker.marketKey == "ICE_IPE") { mkey = MarketKey.Ice; } if (currentTicker.productType == "FUTURE") { ptype = ProductType.Future; } else if (currentTicker.productType == "SPREAD") { ptype = ProductType.Spread; } InstrumentKey IKey = new InstrumentKey(new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); Ils = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); Ils.Tag = TagValue; SpreadLegKeys.Add(TagValue, null); TagValue++; Ils.Update += new EventHandler <InstrumentLookupSubscriptionEventArgs>(CreateAutoSpreader); IlsDictionary.Add(IKey, Ils); Ils.Start(); } }
public InstrumentMapEntry(InstrumentName name, InstrumentKey key) { this.Name = name; this.Key = key; }
public void startInstrumentLookupSubscriptionsFromTTAPITickers(object sender, AuthenticationStatusUpdateEventArgs e) { if (e.Status.IsSuccess) { foreach (ttapiTicker ticker in TTAPITickerList) { if (ticker.marketKey == "CME") mkey = MarketKey.Cme; else if (ticker.marketKey == "ICE_IPE") mkey = MarketKey.Ice; if (ticker.productType == "FUTURE") ptype = ProductType.Future; else if (ticker.productType == "SPREAD") ptype = ProductType.Spread; InstrumentKey IKey = new InstrumentKey(new ProductKey(mkey, ptype, ticker.productName), ticker.SeriesKey); Ils = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(mkey, ptype, ticker.productName), ticker.instrumentName); for (int i = 0; i < ilsUpdateList.Count; i++) { Ils.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(ilsUpdateList[i]); } IlsDictionary.Add(IKey, Ils); Ils.Start(); } } else { Console.WriteLine("TT Login failed: {0}", e.Status.StatusMessage); Dispose(); } }
/// <summary> /// Add a new leg to the spread given a InstrumentKey. /// </summary> /// <param name="instrKey">InstrumentKey</param> private void addDefaultLeg(InstrumentKey instrKey) { DataGridViewColumn col = new DataGridViewColumn(); col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None; col.Width = 150; col.HeaderText = "Leg " + Convert.ToString(dataGridViewSpreadDetails.Columns.Count); col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; DataGridViewTextBoxCell textCell = new DataGridViewTextBoxCell(); textCell.Style.BackColor = Color.White; col.CellTemplate = textCell; int retunValue = dataGridViewSpreadDetails.Columns.Add(col); int columnNum = dataGridViewSpreadDetails.Columns.Count; DataGridViewButtonCell cell = new DataGridViewButtonCell(); cell.ToolTipText = "Delete this leg"; cell.Style.BackColor = Color.Red; cell.Value = "Delete this leg"; dataGridViewSpreadDetails.Rows[(int)FieldType.DeleteButton].Cells[columnNum - 1] = cell; textCell = new DataGridViewTextBoxCell(); textCell.Value = "Waiting for subscription"; dataGridViewSpreadDetails.Rows[(int)FieldType.Contract].Cells[columnNum - 1] = textCell; DataGridViewComboBoxCell comboCell = new DataGridViewComboBoxCell(); comboCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton; comboCell.Items.Clear(); dataGridViewSpreadDetails.Rows[(int)FieldType.OrderFeedCombo].Cells[columnNum - 1] = comboCell; comboCell = new DataGridViewComboBoxCell(); comboCell.Items.Add("<Default>"); comboCell.Value = comboCell.Items[0]; dataGridViewSpreadDetails.Rows[(int)FieldType.CustomerAccount].Cells[columnNum - 1] = comboCell; DataGridViewCheckBoxCell checkCell = new DataGridViewCheckBoxCell(); checkCell.Value = true; dataGridViewSpreadDetails.Rows[(int)FieldType.ActiveQuoting].Cells[columnNum - 1] = checkCell; checkCell = new DataGridViewCheckBoxCell(); checkCell.Value = false; dataGridViewSpreadDetails.Rows[(int)FieldType.ConsiderOwnOrders].Cells[columnNum - 1] = checkCell; comboCell = new DataGridViewComboBoxCell(); comboCell.Items.Add("LimitOrder"); comboCell.Items.Add("MarketOrder"); comboCell.Items.Add("MLMOrder"); comboCell.Value = comboCell.Items[0]; dataGridViewSpreadDetails.Rows[(int)FieldType.OffsetHedge].Cells[columnNum - 1] = comboCell; //Payup ticks textCell = new DataGridViewTextBoxCell(); textCell.Value = "0"; dataGridViewSpreadDetails.Rows[(int)FieldType.PayupTicks].Cells[columnNum - 1] = textCell; //spread ratio textCell = new DataGridViewTextBoxCell(); textCell.Value = (columnNum % 2) == 0 ? "1" : "-1"; dataGridViewSpreadDetails.Rows[(int)FieldType.SpreadRatio].Cells[columnNum - 1] = textCell; //spread Multiplier textCell = new DataGridViewTextBoxCell(); textCell.Value = (columnNum % 2) == 0 ? "1" : "-1"; dataGridViewSpreadDetails.Rows[(int)FieldType.SpreadMultiplier].Cells[columnNum - 1] = textCell; //offset volume multiplier textCell = new DataGridViewTextBoxCell(); textCell.Value = "1"; dataGridViewSpreadDetails.Rows[(int)FieldType.QuantityMultiplier].Cells[columnNum - 1] = textCell; //base volume mulitplier textCell = new DataGridViewTextBoxCell(); textCell.Value = "0"; dataGridViewSpreadDetails.Rows[(int)FieldType.BasicVolumeLean].Cells[columnNum - 1] = textCell; //use cancel replace checkCell = new DataGridViewCheckBoxCell(); checkCell.Value = false; dataGridViewSpreadDetails.Rows[(int)FieldType.UserCancelReplace].Cells[columnNum - 1] = checkCell; //Queue Holder orders textCell = new DataGridViewTextBoxCell(); textCell.Value = "0"; dataGridViewSpreadDetails.Rows[(int)FieldType.QueueHolderOrders].Cells[columnNum - 1] = textCell; //inside smart quote textCell = new DataGridViewTextBoxCell(); textCell.Value = "99"; dataGridViewSpreadDetails.Rows[(int)FieldType.InsideSmartQuote].Cells[columnNum - 1] = textCell; //Smart Quote Limit textCell = new DataGridViewTextBoxCell(); textCell.Value = "99"; dataGridViewSpreadDetails.Rows[(int)FieldType.SmartQuoteLimit].Cells[columnNum - 1] = textCell; //Consider implied checkCell = new DataGridViewCheckBoxCell(); checkCell.Value = true; dataGridViewSpreadDetails.Rows[(int)FieldType.ConsiderImplied].Cells[columnNum - 1] = checkCell; //Hedge round checkCell = new DataGridViewCheckBoxCell(); checkCell.Value = false; dataGridViewSpreadDetails.Rows[(int)FieldType.HedgeRound].Cells[columnNum - 1] = checkCell; //Max Price Move textCell = new DataGridViewTextBoxCell(); textCell.Value = "9999"; dataGridViewSpreadDetails.Rows[(int)FieldType.MaxPriceMove].Cells[columnNum - 1] = textCell; //Max Order Move textCell = new DataGridViewTextBoxCell(); textCell.Value = "9999"; dataGridViewSpreadDetails.Rows[(int)FieldType.MaxOrderMove].Cells[columnNum - 1] = textCell; //Cancel replace for Quantity checkCell = new DataGridViewCheckBoxCell(); checkCell.Value = false; dataGridViewSpreadDetails.Rows[(int)FieldType.CancelReplaceForQuantity].Cells[columnNum - 1] = checkCell; //1/Price checkCell = new DataGridViewCheckBoxCell(); checkCell.Value = false; dataGridViewSpreadDetails.Rows[(int)FieldType.OneOverPrice].Cells[columnNum - 1] = checkCell; //Hidden row has the actual object ot instrument textCell = new DataGridViewTextBoxCell(); textCell.Value = instrKey; dataGridViewSpreadDetails.Rows[(int)FieldType.HiddenObject].Visible = false; dataGridViewSpreadDetails.Rows[(int)FieldType.HiddenObject].Cells[columnNum - 1] = textCell; }
/// <summary> /// Find a given instrument based on the InstrumentKey. /// </summary> /// <param name="instrumentKey">InstrumentKey</param> private void findInstrument(InstrumentKey instrumentKey) { InstrumentLookupSubscription sub = new InstrumentLookupSubscription(m_session, m_dispatcher, instrumentKey); sub.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(instrumentLookupSubscription_Update); sub.Start(); }
// ***************************************************************** // **** Properties **** // ***************************************************************** // // #endregion//Properties #region Public Methods // ***************************************************************** // **** Public Methods **** // ***************************************************************** // // // // // // /// <summary> /// This function reads all lines in the audit trail file, generating fill event args and store them. /// In addition to that, it also collect the last most recent fill information and update the position for the next step. /// </summary> /// <param name="startDateTime"></param> /// <param name="endDateTime"></param> /// <returns></returns> public bool TryReadAuditTrailFills(DateTime startDateTime, DateTime endDateTime, AuditTrailFillHub auditTrailFillHub) { // This method will load the audit trail fills from TT given start and end date time automatically. // The results will be added to the audit trail fills dictionary. // It will also construct the fill hub name by user dictionary. // Get the target audit trail files to read. The file name format is AuditLog_yyyy-mm-dd_N. DateTime startDate; DateTime endDate; startDate = startDateTime.Subtract(startDateTime.TimeOfDay); while (startDate.DayOfWeek == DayOfWeek.Saturday || startDate.DayOfWeek == DayOfWeek.Sunday) { startDate = startDate.AddDays(-1); } endDate = endDateTime.Subtract(endDateTime.TimeOfDay).AddDays(1); while (endDate.DayOfWeek == DayOfWeek.Saturday || endDate.DayOfWeek == DayOfWeek.Sunday) { endDate = endDate.AddDays(1); } if (!System.IO.Directory.Exists(m_AuditTrailPath)) { System.IO.Directory.CreateDirectory(m_AuditTrailPath); } string pattern = "AuditLog*.mdb"; List <string> fileList = new List <string>(); List <string> targetFileList = new List <string>(); List <string> targetTableList = new List <string>(); List <DateTime> targetDateList = new List <DateTime>(); fileList.AddRange(System.IO.Directory.GetFiles(m_AuditTrailPath, pattern)); int dateDelimiterStart; int dateDelimiterEnd; DateTime fileDate = DateTime.MinValue; string fileDateString; // Loop through the file collection and choose the desired files. foreach (string fileName in fileList) { dateDelimiterEnd = fileName.LastIndexOf("_"); dateDelimiterStart = fileName.LastIndexOf("_", dateDelimiterEnd - 1); if (dateDelimiterStart < fileName.Length && dateDelimiterEnd < fileName.Length) { fileDateString = fileName.Substring(dateDelimiterStart + 1, dateDelimiterEnd - dateDelimiterStart - 1); if (DateTime.TryParseExact(fileDateString, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out fileDate)) { if (startDate <= fileDate && fileDate <= endDate) { Log.NewEntry(LogLevel.Minor, "Include the file name:{0}.", fileName); targetFileList.Add(fileName); targetTableList.Add(fileDate.ToString("MMMdd")); targetDateList.Add(fileDate); } else { Log.NewEntry(LogLevel.Major, "Exclude the file name:{0}.", fileName); continue; } } else { Log.NewEntry(LogLevel.Major, "There is problem in parsing file date string:{0}.", fileDateString); continue; } } else { Log.NewEntry(LogLevel.Major, "There is problem in parsing file name:{0}.", fileName); continue; } } // Build the connections and load data from the file collection. m_FillEventArgsList.Clear(); bool isBadRow; List <InstrumentKey> instrumentKeyList = new List <InstrumentKey>(); bool readAllFillAccounts = false; if (auditTrailFillHub.HubName == string.Empty) { readAllFillAccounts = true; } for (int fileIndex = 0; fileIndex < targetFileList.Count; ++fileIndex) { // Read from the audit file. List <List <object> > dataCollections = new List <List <object> >(); if (AccessReader.TryReadAccessFile(targetFileList[fileIndex], targetTableList[fileIndex], out dataCollections)) { // Get the information from the output. All the values are in object type. int rowNumber = dataCollections.Count; for (int rowIndex = 0; rowIndex < rowNumber; ++rowIndex) { isBadRow = false; // The valid data types are explored in detail by test program. string localTimeStamp = (string)dataCollections[rowIndex][ObjectListSchema.LocalTimeStamp]; string exchangeName = (string)dataCollections[rowIndex][ObjectListSchema.ExchangeName]; string orderStatus = (string)dataCollections[rowIndex][ObjectListSchema.OrderStatus]; string orderAction = (string)dataCollections[rowIndex][ObjectListSchema.OrderAction]; string orderSide = (string)dataCollections[rowIndex][ObjectListSchema.OrderSide]; int orderQty = (int)dataCollections[rowIndex][ObjectListSchema.OrderQty]; string product = (string)dataCollections[rowIndex][ObjectListSchema.Product]; string contract = (string)dataCollections[rowIndex][ObjectListSchema.Contract]; string orderPrice = (string)dataCollections[rowIndex][ObjectListSchema.OrderPrice]; string accountName = (string)dataCollections[rowIndex][ObjectListSchema.AccountName]; string userName = (string)dataCollections[rowIndex][ObjectListSchema.UserName]; string exchangeTime = (string)dataCollections[rowIndex][ObjectListSchema.ExchangeTime]; string exchangeDate = (string)dataCollections[rowIndex][ObjectListSchema.ExchangeDate]; string tradeSource = (string)dataCollections[rowIndex][ObjectListSchema.TradeSource]; string ttOrderKey = (string)dataCollections[rowIndex][ObjectListSchema.TTOrderKey]; string ttSeriesKey = (string)dataCollections[rowIndex][ObjectListSchema.TTSeriesKey]; // Check whether the account is desired. if (!readAllFillAccounts && !accountName.Equals(m_FillHubName)) { continue; } // Check whether the exchange name includes AlgoSE sub string. if (exchangeName.Contains(m_ExchangeName_AlgoSE)) { continue; } // Check whether it is a fill event. if (!orderAction.Equals(m_Action_Fill) && !orderAction.Equals(m_Action_PartialFill)) { continue; } // Check whether it is a OK status. if (!orderStatus.Equals(m_OrderStatus_OK)) { continue; } // Check whether the product type is future. if (product.Equals(m_Product_AutoSpreader)) { continue; } // Check whether the contract string contains Calendar string to avoid duplicate fills. foreach (string specialString in m_Contract_Special) { if (contract.Contains(specialString)) { isBadRow = true; if (exchangeName.Contains("TOCOM") && specialString.Equals("/") && isBadRow) { isBadRow = false; } break; } } if (isBadRow) { continue; } // Try parse some necessary variables. DateTime localDateTimeValid = DateTime.MinValue; DateTime exchangeTimeValid = DateTime.MinValue; DateTime exchangeDateValid = DateTime.MinValue; double fillPrice = double.NaN; if (!DateTime.TryParseExact(localTimeStamp, "HH:mm:ss.fff", null, System.Globalization.DateTimeStyles.None, out localDateTimeValid)) { Log.NewEntry(LogLevel.Major, "Failed to parse the utc time of {0}.", localTimeStamp); continue; } if (!DateTime.TryParseExact(exchangeTime, "HH:mm:ss.fff", null, System.Globalization.DateTimeStyles.None, out exchangeTimeValid)) { Log.NewEntry(LogLevel.Major, "Failed to parse the exchange time of {0}.", exchangeTime); continue; } if (!DateTime.TryParseExact(exchangeDate, "ddMMMyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out exchangeDateValid)) { Log.NewEntry(LogLevel.Major, "Failed to parse the exchange time of {0}.", exchangeDate); continue; } if (!double.TryParse(orderPrice, out fillPrice)) { Log.NewEntry(LogLevel.Major, "Failed to parse the order price of {0}.", orderPrice); continue; } localDateTimeValid = targetDateList[fileIndex].Add(localDateTimeValid.TimeOfDay); exchangeTimeValid = exchangeDateValid.Add(exchangeTimeValid.TimeOfDay); // Edit the market. int validEndIndex = exchangeName.LastIndexOf("-"); if (validEndIndex >= 0) { exchangeName = exchangeName.Substring(0, validEndIndex); } // Create fill. Fill fill = new Fill(); fill.ExchangeTime = exchangeTimeValid; //TimeZoneInfo localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(m_LocalTimeZoneString); //DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(localDateTimeValid, localTimeZone); fill.LocalTime = localDateTimeValid; fill.Price = fillPrice; fill.Qty = orderSide.Equals(m_OrderSide_Buy) ? orderQty : (orderSide.Equals(m_OrderSide_Sell) ? -orderQty : 0); // Create fill event args. InstrumentKey instrumentKey = new InstrumentKey(exchangeName, TradingTechnologies.TTAPI.ProductType.Future, product, ttSeriesKey); FillEventArgs fillEventArgs = new FillEventArgs(); fillEventArgs.Fill = fill; fillEventArgs.AccountID = accountName; //fillEventArgs.FillKey = ttOrderKey; fillEventArgs.Type = FillType.Historic; fillEventArgs.TTInstrumentKey = instrumentKey; // Add the instrument key to the list. if (startDateTime.AddSeconds(-3) <= localDateTimeValid && localDateTimeValid <= endDateTime.AddSeconds(3)) { if (!TTConvert.CheckExistenceOfInstrumentKey(instrumentKeyList, instrumentKey)) { instrumentKeyList.Add(instrumentKey); } // Add the fill event args to the list. string rowInfo = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}.", localTimeStamp, exchangeName, orderStatus, orderAction, orderSide, orderQty, product, contract, orderPrice, accountName, userName, exchangeTime, exchangeDate, tradeSource, ttOrderKey, ttSeriesKey); Log.NewEntry(LogLevel.Minor, "Record:{0}", rowInfo); m_FillEventArgsList.Add(fillEventArgs); } } } else { Log.NewEntry(LogLevel.Major, "Failed to read access file with name:{0}.", targetFileList[fileIndex]); continue; } Log.NewEntry(LogLevel.Minor, "Complete reading access file with name:{0}.", targetFileList[fileIndex]); } // Get the last local time of fill for each instrument in initial fill hub. m_NeededBookInstrumentList.Clear(); //foreach (InstrumentKey ttKeyInWaitList in auditTrailFillHub.InitialWaitDictionary.Keys) //{ // // These fills that do not have books will be requested to create new books if possible. To ensure they have books, create them if necessary here. // if (!auditTrailFillHub.TryCheckExistenceOfInstrumentKey(ttKeyInWaitList) && !TTConvert.CheckExistenceOfInstrumentKey(neededBookInstrumentList, ttKeyInWaitList)) // { // neededBookInstrumentList.Add(ttKeyInWaitList); // } //} // For the fills from the audit trail files, also get instruments that need books. foreach (InstrumentKey instrumentKeyInAuditTrail in instrumentKeyList) { if (!auditTrailFillHub.TryCheckExistenceOfInstrumentKey(instrumentKeyInAuditTrail) && !TTConvert.CheckExistenceOfInstrumentKey(m_NeededBookInstrumentList, instrumentKeyInAuditTrail)) { m_NeededBookInstrumentList.Add(instrumentKeyInAuditTrail); } } // Clear all trades in the waiting list because they are all included in the audit trail files. auditTrailFillHub.InitialWaitDictionary.Clear(); // Create books if necessary. // The instrument that need book creation is those got from FillEventArgs from drop file and the new fills listened in the audit trail file. // It is crucial to get all the books ready before updating positions. foreach (InstrumentKey key in m_NeededBookInstrumentList) { OrderHubRequest creatFillBookRequest = new OrderHubRequest(OrderHubRequest.RequestType.RequestCreateFillBook); creatFillBookRequest.Data = new object[1]; creatFillBookRequest.Data[0] = key; auditTrailFillHub.HubEventEnqueue(creatFillBookRequest); } Log.NewEntry(LogLevel.Minor, "Complete loading audit trail fills."); return(true); }
/// <summary> /// Event notification for status of authentication /// </summary> public void apiInstance_AuthenticationStatusUpdate(object sender, AuthenticationStatusUpdateEventArgs e) { if (e.Status.IsSuccess) { // lookup an instrument InstrumentKey IKey = new InstrumentKey(new ProductKey(MarketKey.Cme, ProductType.Spread, "CL"), "Nov16:-1xDec16"); //m_req = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, // IKey); m_req = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(MarketKey.Cme, ProductType.Spread, "CL"), "Calendar: 1xCL Jun17:-1xJul17"); m_req.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(m_req_Update); m_req.Start(); } else { Console.WriteLine("TT Login failed: {0}", e.Status.StatusMessage); Dispose(); } }
/// <summary> /// Construct a TTInstrument object by passing an instrument key /// </summary> /// <param name="key">Same InstrumentKey used by the underlying TTAPI</param> public TTInstrument(InstrumentKey key) { Key = key; InstrumentDescriptor = null; }
public void startInstrumentLookupSubscriptionsFromDataTable(object sender, AuthenticationStatusUpdateEventArgs e) { if (e.Status.IsSuccess) { foreach (DataRow item in TickerTable.Rows) { ttapiTicker currentTicker; if (item.Field<bool>("IsSpreadQ")) { currentTicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker: item.Field<string>("Ticker"), productType: "SPREAD"); } else { currentTicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker: item.Field<string>("Ticker"), productType: "FUTURE"); } if (currentTicker.marketKey == "CME") mkey = MarketKey.Cme; else if (currentTicker.marketKey == "ICE_IPE") mkey = MarketKey.Ice; if (currentTicker.productType == "FUTURE") ptype = ProductType.Future; else if (currentTicker.productType == "SPREAD") ptype = ProductType.Spread; InstrumentKey IKey = new InstrumentKey(new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); Console.WriteLine(currentTicker.SeriesKey); Ils = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); //Ils = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(MarketKey.Cme, ProductType.Spread, "CL"), "Nov16:-1xDec16"); for (int i = 0; i < ilsUpdateList.Count; i++) { Ils.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(ilsUpdateList[i]); } IlsDictionary.Add(IKey, Ils); Ils.Start(); } } else { Console.WriteLine("TT Login failed: {0}", e.Status.StatusMessage); Dispose(); } }
void GetBidAsk(object sender, FieldsUpdatedEventArgs e) { if (e.Error == null) { if ((string.IsNullOrEmpty(e.Fields.GetDirectBidPriceField().FormattedValue)) || (string.IsNullOrEmpty(e.Fields.GetDirectAskPriceField().FormattedValue))) { return; } string InstrumentName = e.Fields.Instrument.Name.ToString(); TickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString()); string TickerHead = TA.TickerheadConverters.ConvertFromTT2DB(e.Fields.Instrument.Product.ToString()); UpdatePriceData(ticker: TickerDB, tickerHead: TickerHead, e: e); TA.ttapiTicker TTAPITicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker: TickerDB, productType: e.Fields.Instrument.Product.Type.ToString()); InstrumentKey IKey = new InstrumentKey(new ProductKey(e.Fields.Instrument.Product.Market.Key, e.Fields.Instrument.Product.Type, e.Fields.Instrument.Product.Name), TTAPITicker.SeriesKey); Ts = TTAPISubs.TsDictionary[e.Fields.Instrument.Key]; if (IlsDictionary.ContainsKey(IKey)) { for (int i = 0; i < ilsUpdateList.Count; i++) { IlsDictionary[IKey].Update -= ilsUpdateList[i]; } IlsDictionary[IKey].Dispose(); IlsDictionary[IKey] = null; IlsDictionary.Remove(IKey); TTAPISubs.IlsDictionary = IlsDictionary; } if ((IlsDictionary.Count == 0) & (!PricesReceivedQ)) { PricesReceivedQ = true; HedgeStrategies.HedgeStrategiesAgainstDelta(conn: conn, priceTable: PriceData); DataTable StdMoves = CalculateStdMoves(priceData: PriceData); DataTable HedgeTable = GenerateHedgeTable(conn: conn); NetHedgeTable = CalculateUrgency(hedgeTable: HedgeTable); //NetHedgeTable = NetHedgeTable.Select("IsSpreadQ=true").CopyToDataTable(); List <string> TickerHeads2Report = DataAnalysis.DataTableFunctions.GetColumnAsList <string>(dataTableInput: StdMoves, columnName: "TickerHead", uniqueQ: true); foreach (string TickerHead2Report in TickerHeads2Report) { DeltaLogger.Log(new String('-', 20)); DataRow[] SelectedRows = StdMoves.Select("TickerHead='" + TickerHead2Report + "'"); foreach (DataRow Row in SelectedRows) { DeltaLogger.Log(Row.Field <string>("Ticker") + " std change: " + Row.Field <double>("StdChange")); } DataRow[] SelectedHedgeRows = NetHedgeTable.Select("TickerHead='" + TickerHead2Report + "'"); foreach (DataRow Row in SelectedHedgeRows) { DeltaLogger.Log(Row.Field <int>("Hedge") + " " + Row.Field <string>("Ticker") + " with urgency " + Row.Field <decimal>("Urgency")); } } Console.Write("Do you agree? (Y/N): "); Decision = Console.ReadLine(); Decision = Decision.ToUpper(); DataColumn WorkingOrdersColumn = new DataColumn("WorkingOrders", typeof(int)); WorkingOrdersColumn.DefaultValue = 0; NetHedgeTable.Columns.Add(WorkingOrdersColumn); NetHedgeTickerList = DataAnalysis.DataTableFunctions.GetColumnAsList <string>(dataTableInput: NetHedgeTable, columnName: "Ticker"); } if ((PricesReceivedQ) && (Decision == "Y")) { int RowIndex = NetHedgeTickerList.IndexOf(TickerDB); if ((RowIndex < 0) || (NetHedgeTable.Rows[RowIndex].Field <int>("WorkingOrders") != 0)) { return; } Price BidPrice = e.Fields.GetDirectBidPriceField().Value; Price AskPrice = e.Fields.GetDirectAskPriceField().Value; Price MidPrice = (AskPrice + BidPrice) / 2; Price TradePrice; NetHedgeTable.Rows[RowIndex]["WorkingOrders"] = NetHedgeTable.Rows[RowIndex].Field <int>("Hedge"); if (NetHedgeTable.Rows[RowIndex].Field <int>("Hedge") > 0) { if (NetHedgeTable.Rows[RowIndex].Field <decimal>("Urgency") > 5) { TradePrice = MidPrice.Round(Rounding.Up); } else { TradePrice = BidPrice; } } else if (NetHedgeTable.Rows[RowIndex].Field <int>("Hedge") < 0) { if (NetHedgeTable.Rows[RowIndex].Field <decimal>("Urgency") > 5) { TradePrice = MidPrice.Round(Rounding.Down); } else { TradePrice = AskPrice; } } else { return; } DeltaLogger.Log(NetHedgeTable.Rows[RowIndex].Field <int>("Hedge") + " " + TickerDB + " for " + TradePrice + ", Bid: " + e.Fields.GetDirectBidPriceField().FormattedValue + ", Ask: " + e.Fields.GetDirectAskPriceField().FormattedValue); ttapiUtils.Trade.SendLimitOrder(instrument: e.Fields.Instrument, price: TradePrice, qty: NetHedgeTable.Rows[RowIndex].Field <int>("Hedge"), ttapisubs: TTAPISubs, orderTag: "DeltaHedge"); } } else { if (e.Error.IsRecoverableError == false) { Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message); //Dispose(); } } }
public void StartASEEventChain() { int TagValue = 1; foreach (string dbTicker in DbTickerList) { ttapiTicker currentTicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker); if (currentTicker.marketKey == "CME") mkey = MarketKey.Cme; else if (currentTicker.marketKey == "ICE_IPE") mkey = MarketKey.Ice; if (currentTicker.productType == "FUTURE") ptype = ProductType.Future; else if (currentTicker.productType == "SPREAD") ptype = ProductType.Spread; InstrumentKey IKey = new InstrumentKey(new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); Ils = new InstrumentLookupSubscription(m_apiInstance.Session, Dispatcher.Current, new ProductKey(mkey, ptype, currentTicker.productName), currentTicker.SeriesKey); Ils.Tag = TagValue; SpreadLegKeys.Add(TagValue, null); TagValue++; Ils.Update += new EventHandler<InstrumentLookupSubscriptionEventArgs>(CreateAutoSpreader); IlsDictionary.Add(IKey, Ils); Ils.Start(); } }