using TIWebApi.Clients.MarketData; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; //using System.Windows.Controls; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using System.Xml; using TradeIdeas.Logging; using TradeIdeas.MiscSupport; using TradeIdeas.TIProData; using TradeIdeas.TIProData.Configuration; using TradeIdeas.TIProData.Interfaces; using TradeIdeas.XML; using WeifenLuo.WinFormsUI.Docking; using static TradeIdeas.TIProData.InsiderTrade; namespace TradeIdeas.TIProGUI.EnhancedSingleStockWindow { public partial class EnhancedSingleStockDockWindow : Form, IDemoMode, ISnapToGrid, IAcceptSymbolLinking, ISupportLimitedMode, ISaveLayout, IContextMenuStrip, IFont, IRowSelect, TopListRequest.Listener, IHaveGrids, ISymbolLinkingChannel { struct ColumnSetting { public int dIndex; public int width; // DataGridLength width; } private string _id = ""; private string _demoDisclaimer = ""; List _phrases; private bool _pinned = false; private bool _limitedMode = false; private bool _symbolLinkingEnabled = true; ISendManager _sendManager; private LayoutManager _layoutManager = LayoutManager.Instance(); private string _fileNameSaved; private const string NEW_FORM_TYPE = "SINGLE_STOCK_DOCK_WINDOW"; private const string FORM_TYPE = "SINGLE_STOCK_WINDOW"; // This is for backward compatibility - RVH20210730 private const string _defaultFileName = "DEFAULT_SINGLE_STOCK.WTI"; static XmlNode _defaultSingleStockSettings = null; // THESE CONTROLS NEED REMOVED - RVH //private System.Windows.Controls.DataGrid _insidersGrid; //private DetailsTab _detailsTab; //private InsidersTab _insidersTab; //private SimilarTab _similarTab; private List _selectedFilters = new List(); TransactionsWindow _tWindow; private bool _filterPopupInUse = false; private bool _viewModePopupInUse = false; /// /// True = a window is open that should cause surfing to continue to be paused. For example, the Congiguration /// form has been chosen from the context menu. The config code in this file is responsible for turning /// this variable to false and calling UnPauseSurfing. /// private bool _remainPaused = false; public delegate void ReceiveInsiderSelectedTransactions(List selectedItems); public event ReceiveInsiderSelectedTransactions onTransactionSelectedUpdate; public static HashSet _listsForSingleStock = new HashSet(); private ConfigurationWindowManager _configurationWindowManager; // new variable to set that dock panel is being used - RVH20210329 private bool _dockPanelMode = true; // new variables to support the dock panel - RVH20210618 private List _childControls; private VS2015BlueTheme _theme = new VS2015BlueTheme(); private DeserializeDockContent _deserializeDockContent; // this panel control will eventually need to be hosted in another control with all controls for the Similar tab - RVH20210618 //private TopListPanel _tPanel = new TopListPanel(); // this will need taken out. Just added to temporarily remove errors - RVH20210618 //private WPF_SingleStock wpF_SingleStock1 = new WPF_SingleStock(); // NEW controls - RVH20210621 private DetailsControl _detailsControl; private bool _useBrowserInterface = true; private ChromiumDetailsControl _chromiumDetailsControl; private NewsControl _newsControl; private ProfileControl _profileControl; // BLOCK OUT THE INSIDERS CONTROL FOR NOW - IT HAS OLD DATA AND CAUSES AN EXCEPTION - RVH20210729 //private InsidersControl _insidersControl; private SimilarControl _similarControl; // NEW delegates and events - RVH20210621 private TopListRequest.Token _topList; private CompanyProfileManager _companyProfileManager; private InsidersManager _insidersManager; private int _startSymbolTally = 0; // tells us when we should ultimately give a server call within the Similar Tab go get data when we're in the Competitor mode //many, if not all tabs will probably need to use these handler. public delegate void ReceiveTopListData(TopListInfo metaData, RowData rowData, DateTime? start, DateTime? end, bool validDataReceived); public event ReceiveTopListData receiveTopListDataEvent; public delegate void ReceiveWindowNameData(string windowName); public event ReceiveWindowNameData onWindowNameUpdate; public delegate void OnSubindustryReceived(string subIndustry, string industry, string industryGroup, string subSector, string sector); public event OnSubindustryReceived subIndustryReceivedEvent; //this keeps track of the current symbol for the SimilarControl.cs. When we're in the prica-action mode //we would need to know when the symbol actually gets changes so we know when to create a new config string. public delegate void onCurrentSymbolUpdate(string symbol); public event onCurrentSymbolUpdate onSymbolUpdate; //profile tab will use this delegate to listen for information concerning the business profile public delegate void ReceivedCompanyProfileInfo(CompanyProfileInfo profile); public event ReceivedCompanyProfileInfo onCompanyProfileInfo; //Insiders tab will use this delegate to listen for information coming from the InsidersManager public delegate void ReceivedInsidersInfo(List insiderData, string id); public event ReceivedInsidersInfo onInsiderDataReceived; //The price action items will use these events/delegates. Currently we're collecting Yearly position in range, relative volume, and change from the close public delegate void ReceivedPriceActionData(Double ry, Double rv, Double fcp, Double r10D, Double r3mo, Double r6mo); public event ReceivedPriceActionData onPriceActionDataReceived; private IConnectionMaster _connectionMaster; private string _currentSymbol = ""; private string _config; private bool _outsideMarketHours; private string _windowNameString = ""; private List _dataGrids = new List(); public IntPtr focusWindowHandle; public IntPtr thisWindowHandle; public bool checkFocus = false; private FontSize _selectedFontSize = FontSize.NORMAL; public EnhancedSingleStockDockWindow() { _instance = this; InitializeComponent(); InitializeMarketDataClient(); viewModeToolStripMenuItem.Visible = false; if (_listsForSingleStock.Count == 0) { if (_configurationWindowManager != null) { _configurationWindowManager.Abandon(); } _configurationWindowManager = new ConfigurationWindowManager(); _configurationWindowManager.LoadFromServer(GuiEnvironment.FindConnectionMaster(""), ConfigurationType.TopList, OnLoaded, "", skipStrategies: false); } competitorsToolStripMenuItem.Checked = true; priceActionToolStripMenuItem.Checked = false; Guid obj = Guid.NewGuid(); _id = obj.ToString(); _limitedMode = GuiEnvironment.LimitedMode; SetSnapToGrid(GuiEnvironment.SnapToGrid); _demoDisclaimer = GuiEnvironment.XmlConfig.Node("COMMON_PHRASES").Node("DEMO_DISCLAIMER").PropertyForCulture("TEXT", "***"); _phrases = GuiEnvironment.XmlConfig.Node("SINGLE_SYMBOL_WINDOW").Node("PHRASES"); //wpF_SingleStock1.onWindowNameUpdate += wpf_onWindowNameUpdate; //wpF_SingleStock1.receiveSymbolFromComboEvent += WpF_SingleStock1_receiveSymbolFromComboEvent; //wpF_SingleStock1.MouseEnter += Wpf_SingleStock1_MouseEnter; //wpF_SingleStock1.MouseLeave += Wpf_SingleStock1_MouseLeave; //wpF_SingleStock1.onSymbolUpdate += WpF_SingleStock1_onSymbolUpdate; onSymbolUpdate += SimilarControl_onSymbolUpdate; VisibleChanged += EnhancedSingleStockDockWindow_VisibleChanged; saveToCloudToolStripMenuItem.Image = SaveToCloud.WindowIconCache.MenuImage; //_detailsTab = wpF_SingleStock1.detailsTab; //_insidersTab = wpF_SingleStock1.insidersTab; //_insidersTab.setId(_id); //_similarTab = wpF_SingleStock1.similarTab; WindowIconCache.SetIcon(this); //wpF_SingleStock1.setId(_id); //wpF_SingleStock1.Tag = this;//this is how we'll communicate with the InsidersTab. We transport an instance of this winform object so we can set up the delegate for selections of transaction (ReceiveInsiderSelectedTransactions); //_insidersGrid = wpF_SingleStock1.insidersDataGrid; _sendManager = GuiEnvironment.FindConnectionMaster("").SendManager; populateStrings(); UpdateSymbolLinkingCheckboxStatus(); Text = ""; // set up connection master - RVH20210621 _connectionMaster = GuiEnvironment.FindConnectionMaster(""); _companyProfileManager = _connectionMaster.CompanyProfileManager; _companyProfileManager.ProfileReceived += new CompanyProfileReceived(CompanyProfileManager_ProfileReceived); _insidersManager = _connectionMaster.InsidersManager; _insidersManager.InsidersReceived += new InsidersReceived(InsidersManager_InsidersReceived); // set up dock panel - RVH20210618 dockPanel.Theme = _theme; //dockPanel.Theme.Extender.FloatWindowFactory = new CustomFloatWindowFactory(); _deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString); // create new list of child controls - RVH20210618 _childControls = new List(); // set up event handlers - RVH20210622 onWindowNameUpdate += WindowNameUpdate; } public string MainCurrentSymbol { get { return _currentSymbol; } set { UnsubscribeMarketDataClient(); _currentSymbol = value; _companyProfileManager.RequestNow(_currentSymbol); _insidersManager.RequestNow(_currentSymbol); //setNewSymbol(_currentSymbol, _config); //_similarControl.clearData(); _startSymbolTally = 0; if (_similarControl != null) { _similarControl.SetCurrentSymbol(_currentSymbol); } SubscribeMarketDataClient(); } } /// /// Show the forms context menu. /// public void ShowContextMenu() { this.InvokeIfRequired(delegate () { contextMenuStrip1.Show(Cursor.Position); }); } /// /// Hide the forms context menu. /// public void HideContextMenu() { this.InvokeIfRequired(delegate () { contextMenuStrip1.Hide(); }); } /// /// Set the symbol link channel from symbol linking /// /// The link channel void ISymbolLinkingChannel.SetLinkChannel(string linkChannel) { SetLinkChannel(linkChannel); } /// /// Set the symbol link channel /// /// The link channel private void SetLinkChannel(string linkChannel) { _linkChannel = linkChannel; // Start using the link channel from the parent SSW form - RVH20220310 //if (_similarControl != null) // _similarControl.SetLinkChannel(linkChannel); // change window icon SymbolLinkingChannelsHelper.SetFormIcon(this, "S", linkChannel); } /// /// Get the symbol link channel /// /// string ISymbolLinkingChannel.GetLinkChannel() { return _linkChannel; } public string MainConfig { get { return _config; } set { _config = value; } } public bool OutSideMarketHours { get { return _outsideMarketHours; } set { _outsideMarketHours = value; } } /// /// Exposes the data grids. /// public List DataGrids { get { return _dataGrids; } } /* private void WpF_SingleStock1_onSymbolUpdate(string symbol) { _similarTab.setCurrentSymbol(symbol); } */ private void SimilarControl_onSymbolUpdate(string symbol) { if (_similarControl != null) { _similarControl.SetCurrentSymbol(symbol); } } private void EnhancedSingleStockDockWindow_VisibleChanged(object sender, EventArgs e) { if (this.Visible) { this.Invalidate(); //wpF_SingleStock1.refreshDetailsTab(); } } private void OnLoaded(ConfigurationWindowManager configurationWindowManager) { //must load here or else may receive null exceptions foreach (SymbolList s in _configurationWindowManager.SymbolListsInOrder) if (!s.InternalCode.Contains("SL_0_") && !s.InternalCode.Contains("SL_1_")) _listsForSingleStock.Add(s); } public void setFilterPopupInUse(bool value) { _filterPopupInUse = value; } public bool getFilterPopupInUse() { return _filterPopupInUse; } public void setViewModePopupInUse(bool value) { _viewModePopupInUse = value; } public bool getViewModePopupInUse() { return _viewModePopupInUse; } public string getId() { return _id; } /* private void WpF_SingleStock1_receiveSymbolFromComboEvent(string symbol) { if (SymbolLinkingEnabled) SendToExternalLinking(); } private void Wpf_SingleStock1_MouseLeave(object sender, EventArgs e) { if (SymbolLinkingEnabled) UnPauseSurfing(); } private void Wpf_SingleStock1_MouseEnter(object sender, EventArgs e) { if (SymbolLinkingEnabled) PauseSurfing(); } */ public void PauseSurfing() { // temporarily pause surfing if the context menu is opened Surfer.SurfManager surfManager = Surfer.SurfManager.Instance(); if (null != surfManager) { if (surfManager.IsRunning) surfManager.Stop(true); } } public void UnPauseSurfing() { Surfer.SurfManager surfManager = Surfer.SurfManager.Instance(); if (null != surfManager) { //if (surfManager.Paused && !_remainPaused) //if ((surfManager.Paused || !surfManager.IsRunning) && !_remainPaused && (_detailsControl != null && !_detailsControl.AutoCompleteShown)) if (surfManager.Paused && !_remainPaused && (_detailsControl != null && !_detailsControl.AutoCompleteShown)) surfManager.Start(false); else if (surfManager.Paused && !_remainPaused) surfManager.Start(false); } } // change parameters to accommodate dock panel changes - RVH20210402 //static public void OpenNewSingleStockWindow(string initialSymbol, Form parentForm) static public void OpenNewSingleStockWindow(string initialSymbol, Form parentForm, bool dockPanelMode = false, string mainDockPanelName = "", string mainDockPanelTitle = "", string dockPanelID = "") { List _phs; _phs = GuiEnvironment.XmlConfig.Node("SINGLE_SYMBOL_WINDOW").Node("PHRASES"); string singleStockFileName = "DEFAULT_SINGLE_STOCK.WTI"; LayoutManager layoutManager = LayoutManager.Instance(); string programDirFileName = layoutManager.Directory + "\\" + singleStockFileName; string readOnlyDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); string sharedDirFileName = readOnlyDir + "\\" + GuiEnvironment.AppNameInternal + "\\" + singleStockFileName; string singleStockConfig = _phs.Node("NEW_SINGLE_STOCK_WINDOW_DEFAULT").Property("TEXT"); XmlNode singleStockDefinition = null; if (System.IO.File.Exists(programDirFileName)) //check if it's there in user's home dir singleStockDefinition = layoutManager.GetXmlFromFile(programDirFileName); else if (System.IO.File.Exists(sharedDirFileName)) //check for default in shared folder... singleStockDefinition = layoutManager.GetXmlFromFile(sharedDirFileName); EnhancedSingleStockDockWindow singleStockWindow; if (null != singleStockDefinition) { EnhancedSingleStockDockWindow.SetDefaultSingleStockSettings(singleStockDefinition); singleStockConfig = singleStockDefinition.Node("WINDOW").Property("CONFIG", ""); if (initialSymbol == null) { initialSymbol = singleStockDefinition.Node("WINDOW").Property("SYMBOL", null); } singleStockWindow = new EnhancedSingleStockDockWindow(); // change parameters to accommodate dock panel changes - RVH20210402 //singleStockWindow.Restore(_defaultSingleStockSettings, false, false); singleStockWindow.Restore(_defaultSingleStockSettings, false, false, dockPanelMode, mainDockPanelName, mainDockPanelTitle, dockPanelID); singleStockWindow.setNewSymbol(initialSymbol, singleStockConfig); } else { singleStockWindow = new EnhancedSingleStockDockWindow(); singleStockWindow.Restore(_defaultSingleStockSettings, false, false, dockPanelMode, mainDockPanelName, mainDockPanelTitle, dockPanelID); if (initialSymbol != null) { singleStockWindow.setNewSymbol(initialSymbol, singleStockConfig); } else { singleStockWindow.setNewSymbol("SPY", singleStockConfig); } singleStockWindow.Show(); } GuiEnvironment.SetWindowOpeningPosition(singleStockWindow, parentForm); } static public void SetDefaultSingleStockSettings(XmlNode description) { _defaultSingleStockSettings = XmlHelper.Node(description, "WINDOW"); } public static readonly WindowIconCache WindowIconCache = new WindowIconCache("SINGLE_SYMBOL_WINDOW"); /// /// Is this window docked. /// /// public bool IsWindowDocked() { bool windowDocked = false; if (this.ParentForm != null) { WindowDocumentDock windowDocumentDock = this.ParentForm as WindowDocumentDock; if (windowDocumentDock != null) windowDocked = true; } return windowDocked; } public void SendToExternalLinking() { //string currentSymbol = wpF_SingleStock1.getCurrentSymbol(); // Link only if enabled if (SymbolLinkingEnabled && (!string.IsNullOrEmpty(_currentSymbol))) { RecordExternalLinkUseCase(_currentSymbol); SymbolDetailsCacheManager.Info info = GuiEnvironment.FindConnectionMaster("").SymbolDetailsCacheManager.Request(_currentSymbol); string exchange = (null == info) ? "" : info.Exchange; // add symbol linking channels here GuiEnvironment.sendSymbolToExternalConnector(_currentSymbol, exchange, "", this, linkChannel: _linkChannel, dockWindowID: GuiEnvironment.GetDockWindowID(this)); //GuiEnvironment.sendSymbolToExternalConnector(_currentSymbol, exchange, "", this); } else if (string.IsNullOrEmpty(_currentSymbol)) { // Clear stale data in tabs when user enters an empty string as a symbol. ClearAllTabData(); } } private void RecordExternalLinkUseCase(string symbol) { GuiEnvironment.RecordExternalLinkingUseCase(symbol, "SS", GuiEnvironment.FindConnectionMaster("").SendManager); } public Rectangle? ActualSize { get; set; } /// /// This gets called before any other code in the SaveLayout function. Currently this is aimed at the Scottrade addin but anything can set this code(no more Scottrade, but will leave this in nevertheless. /// public Action
PreSaveLayoutCode { get; set; } /// /// This is the xml that was used to restore this form. If this form wasn't layout-restored then this will be null. /// public XmlNode RestoredLayout { get; set; } WindowIconCache ISaveLayout.WindowIconCache { get { return WindowIconCache; } } /// /// This gets called after SaveBase and it passes the XmlNode that the form is being saved to. This allows extensions to add properties to the layout. Access the layout XmlNode /// from a form using RestoredLayout. /// public Action SaveLayoutCode { get; set; } private void populateStrings() { configureToolStripMenuItem.Text = _phrases.Node("CONFIGURE").PropertyForCulture("TEXT", "***"); duplicateToolStripMenuItem.Text = _phrases.Node("DUPLICATE").PropertyForCulture("TEXT", "***"); smallBordersToolStripMenuItem.Text = _phrases.Node("SMALL_BORDERS").PropertyForCulture("TEXT", "***"); saveAsDefaultToolStripMenuItem.Text = _phrases.Node("SAVE_AS_DEFAULT").PropertyForCulture("TEXT", "***"); saveAsToolStripMenuItem.Text = _phrases.Node("SAVE_AS").PropertyForCulture("TEXT", "***"); outsideMarketHoursToolStripMenuItem.Text = _phrases.Node("OUTSIDE_HOURS").PropertyForCulture("TEXT", "***"); doSymbolLinkingToolStripMenuItem.Text = _phrases.Node("SYMBOL_LINKING").PropertyForCulture("TEXT", "***"); } public void SetSnapToGrid(bool enabled) { formSnapper1.Enabled = enabled; if (GuiEnvironment.RunningWin10 && enabled) { formSnapper1.Win10HeightAdjustment = GuiEnvironment.HEIGHT_INCREASE; formSnapper1.Win10WidthAdjustment = GuiEnvironment.WIDTH_INCREASE; } } public void setNewSymbol(string initialSymbol, string singleStockConfig, bool? omh = false) { // RVH - replaced with new code //wpF_SingleStock1.setSingleStockWindowParameters(GuiEnvironment.FindConnectionMaster(""), singleStockConfig, true, initialSymbol,omh);//remnant from the original Winform SingleStockWindow //wpF_SingleStock1.setNewSymbol(initialSymbol); // set up configuration for this window - RVH20210622 UnsubscribeMarketDataClient(); _currentSymbol = initialSymbol; _companyProfileManager.RequestNow(_currentSymbol); _insidersManager.RequestNow(_currentSymbol); _startSymbolTally = 0; SetConfiguration(singleStockConfig); SubscribeMarketDataClient(); } /* private void wpf_onWindowNameUpdate(string nameUpdate) { if (nameUpdate.Contains("&")) nameUpdate = nameUpdate.Replace("&", "&&"); Text = nameUpdate; if (GuiEnvironment.FindConnectionMaster("").LoginManager.IsDemo) Text = nameUpdate + _demoDisclaimer; else Text = nameUpdate; // change Text of parent form if running in dock panel mode - RVH20210329 if (_dockPanelMode) { Form parent = (Form)this.Parent; if (parent != null) parent.Text = this.Text; } } */ private void WindowNameUpdate(string nameUpdate) { //nameUpdate = GuiEnvironment.FixFormLabelText(nameUpdate); Text = nameUpdate; if (GuiEnvironment.FindConnectionMaster("").LoginManager.IsDemo) Text = nameUpdate + _demoDisclaimer; else Text = nameUpdate; // change Text of parent form if running in dock panel mode - RVH20210329 if (_dockPanelMode) { Form parent = (Form)this.Parent; if (parent != null) parent.Text = this.Text; } } public void OnDemoModeChanged() { if (GuiEnvironment.FindConnectionMaster("").LoginManager.IsDemo) Text = _windowNameString + _demoDisclaimer; //Text = wpF_SingleStock1.getWindowName() + _demoDisclaimer; } private void ConfigureToolStripMenuItem_Click(object sender, EventArgs e) { _remainPaused = true; doConfiguration(); _remainPaused = false; UnPauseSurfing(); } private void doConfiguration() { ConfigWindowWrapper configWindowWrapper = ConfigWindowWrapper.DefaultFactory(ConfigurationType.TopList, GuiEnvironment.FindConnectionMaster("")); configWindowWrapper.InitialConfig = _config; // wpF_SingleStock1.getCurrentConfigString(); configWindowWrapper.AllowOkayImmediately = true; configWindowWrapper.IsSingleStock = true; if (_useBrowserInterface) { configWindowWrapper.ColumnCount = _chromiumDetailsControl.GetColumnCount(); } else configWindowWrapper.ColumnCount = _detailsControl.GetColumnsCount(); //int leftSideCount = wpF_SingleStock1.getLeftSideColInfoCount(); //int rightSideCount = wpF_SingleStock1.getRightSideColInfoCount(); //int sideRightLeft = wpF_SingleStock1.getSideRightLeftIndicator(); //if (leftSideCount == rightSideCount) //{ // if (sideRightLeft == 1) // { // //sideRightLeft = 0; // wpF_SingleStock1.setSideRightLeftIndicator(0); // } //} //configWindowWrapper.SingleStockWindowValue = wpF_SingleStock1.getDisplayBeginPopulate(); configWindowWrapper.ShowIt(); if (!configWindowWrapper.Canceled) { //wpF_SingleStock1.setSideRightLeftIndicator(configWindowWrapper.SingleStockWindowValue); //wpF_SingleStock1.setDisplayBeginPopulate(configWindowWrapper.SingleStockWindowValue); TopListStrategy strategy = (TopListStrategy)configWindowWrapper.Strategy; // Make sure we store _currentSymbol and _outsideMarketHours back into the collaborate // string. The new client ignores those. We will also store them directly into the // XML file. The new client reads these directly from the XML file. But the older // client will ignore the symbol that we store directly into the XML file. It will only // look at the symbol that we store here. There are similar issues with the // OutsideMarketHours flag. In that case the older client actually looks at both // places and if they don't match things might not work well. // // If you only have the new client, you don't have to worry about any of this. The // next three lines are useless but they don't hurt anything. // // If you have a new client but you want to be compatible with old and new clients, // the following three lines will help. (E.g. if Brad is making a new cloud layout // to share with a lof of people, this applies to him.) If you want to make a layout // that everyone can use, start by setting the symbol and OMH the way you want them. // Then start the config window. Then hit OK (not Cancel) in the config window. Then // save your layout. strategy.SingleSymbol = _currentSymbol; // wpF_SingleStock1.getCurrentSymbol(); strategy.SymbolListDisposition = SymbolListDisposition.SingleSymbol; strategy.OutsideMarketHours = _outsideMarketHours; //wpF_SingleStock1.getOutSideMarkeHours(); // The detailsControl may still be null under custom display scaling. if (_useBrowserInterface) { if (null != _chromiumDetailsControl) _chromiumDetailsControl.ClearLabelData(true); } else { if (null != _detailsControl) _detailsControl.ClearLabelData(); //wpF_SingleStock1.clearChildrenFromDetailsPanel(); } SetConfiguration(strategy.MakeConfigString()); //wpF_SingleStock1.SetConfiguration(strategy.MakeConfigString()); } } private void OutsideMarketHoursToolStripMenuItem_Click(object sender, EventArgs e) { setMarketHours(); } private void DoSymbolLinkingToolStripMenuItem_Click(object sender, EventArgs e) { SymbolLinkingEnabled = !SymbolLinkingEnabled; UpdateSymbolLinkingCheckboxStatus(); } private void UpdateSymbolLinkingCheckboxStatus() { doSymbolLinkingToolStripMenuItem.Checked = SymbolLinkingEnabled; } private void DuplicateToolStripMenuItem_Click(object sender, EventArgs e) { _layoutManager.Duplicate(this); } private void CopyToClipboardToolStripMenuItem_Click(object sender, EventArgs e) { CopyProfileDataToClipboard(); ; } private void CopyProfileDataToClipboard() { System.Windows.Clipboard.Clear(); System.Windows.Clipboard.SetText(_profileControl.profileData()); //wpF_SingleStock1.getProfileData()); } private void SmallBordersToolStripMenuItem_Click(object sender, EventArgs e) { setBorders(); } private void SetFontSize(FontSize fontSize) { _selectedFontSize = fontSize; UncheckAllSizes(); switch (_selectedFontSize) { case FontSize.SMALL: this.fontSmallToolStripMenuItem.Checked = true; break; case FontSize.NORMAL: this.fontNormalToolStripMenuItem.Checked = true; break; case FontSize.LARGE: this.fontLargeToolStripMenuItem.Checked = true; break; default: break; } if (_useBrowserInterface) { if (null != this._chromiumDetailsControl) this._chromiumDetailsControl.SetFontSize(_selectedFontSize, true); } else { this._detailsControl.SetFontSize(_selectedFontSize); } this._newsControl.SetFontSize(_selectedFontSize); this._profileControl.SetFontSize(_selectedFontSize); } private void SmallToolStripMenuItem_Click(object sender, EventArgs e) { GuiEnvironment.RecordUseCase("SingleStockWindow.RightClick.FontSize.Small", _sendManager); this.SetFontSize(FontSize.SMALL); } private void NormalToolStripMenuItem_Click(object sender, EventArgs e) { GuiEnvironment.RecordUseCase("SingleStockWindow.RightClick.FontSize.Normal", _sendManager); this.SetFontSize(FontSize.NORMAL); } private void LargeToolStripMenuItem_Click(object sender, EventArgs e) { GuiEnvironment.RecordUseCase("SingleStockWindow.RightClick.FontSize.Large", _sendManager); this.SetFontSize(FontSize.LARGE); } /// /// This implementation uncheck all submenus from the FontSizeToolStrip submenu. /// private void UncheckAllSizes() { foreach (var item in this.fontSizeToolStripMenuItem.DropDownItems) { var toolStripM = item as ToolStripMenuItem; if (toolStripM != null) toolStripM.Checked = false; } } private void PinnedToolStripMenuItem_Click(object sender, EventArgs e) { _pinned = pinnedToolStripMenuItem.Checked; } private void SaveToCloudToolStripMenuItem_Click(object sender, EventArgs e) { _remainPaused = true; SaveToCloud.DoIt(_sendManager, this); _remainPaused = false; UnPauseSurfing(); } private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e) { _remainPaused = true; GuiEnvironment.RecordUseCase("SingleStockWindow.RightClick.SaveAs", _sendManager); LayoutManager layoutManager = LayoutManager.Instance(); SaveFileDialog dialog = new SaveFileDialog(); if (null != layoutManager.Directory) dialog.InitialDirectory = layoutManager.Directory; dialog.Filter = _phrases.Node("WINDOW_FILTER").PropertyForCulture("TEXT", "***"); dialog.DefaultExt = "WTI"; string fileName = ""; // The detailsControl may still be null under custom display scaling. if (_fileNameSaved == null) // && null != _detailsControl) { if (_useBrowserInterface) { if (null != _chromiumDetailsControl) fileName = _phrases.Node("FILE_PREFIX").PropertyForCulture("TEXT", "***") + _chromiumDetailsControl.GetShortWindowName(); } else { if (null != _detailsControl) fileName = _phrases.Node("FILE_PREFIX").PropertyForCulture("TEXT", "***") + _detailsControl.GetShortWindowName(); } } else { fileName = _fileNameSaved; } dialog.FileName = FileNameMethod.QuoteFileName(fileName); if (dialog.ShowDialog() == DialogResult.OK) { layoutManager.SaveOne(this, dialog.FileName); _fileNameSaved = Path.GetFileName(dialog.FileName); } dialog.Dispose(); _remainPaused = false; UnPauseSurfing(); } private void SaveAsDefaultToolStripMenuItem_Click(object sender, EventArgs e) { GuiEnvironment.RecordUseCase("SingleStockWindow.RightClick.SaveAsDefault", _sendManager); string programDirFileName = _layoutManager.Directory + "\\" + _defaultFileName; _layoutManager.SaveOne(this, programDirFileName); } private void setBorders() { if (smallBordersToolStripMenuItem.Checked) { FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; } else { FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; } } private void setMarketHours() { // MODIFY FOR NEW CONTROLS //wpF_SingleStock1.setOutSideMarkeHours(outsideMarketHoursToolStripMenuItem.Checked); //String cfg = wpF_SingleStock1.getCurrentConfigString(); //cfg = putOutSideMarketHours(cfg, outsideMarketHoursToolStripMenuItem.Checked); //wpF_SingleStock1.SetConfiguration(cfg); // call SetConfiguration in this form and new controls - RVH20210629 _outsideMarketHours = outsideMarketHoursToolStripMenuItem.Checked; _similarControl.SetOutsideMarkeHours(_outsideMarketHours); string cfg = _config; cfg = PutOutSideMarketHours(cfg, outsideMarketHoursToolStripMenuItem.Checked); SetConfiguration(cfg); } public void ChangeSymbol(string symbol, RowData rowData, string sourceWindow) { try { if (SymbolLinkingEnabled) { UnsubscribeMarketDataClient(); // get the handle of this window and the window that has focus focusWindowHandle = GuiEnvironment.GetForegroundWindow(); thisWindowHandle = this.Handle; checkFocus = true; //_detailsControl.clearLabelData(); //MainCurrentSymbol = symbol; if (_useBrowserInterface) { if (null != _chromiumDetailsControl) _chromiumDetailsControl.SetNewSymbol(symbol); } else { if (null != _detailsControl) _detailsControl.SetNewSymbol(symbol); } //setNewSymbol(symbol, _config); //wpF_SingleStock1.clearChildrenFromDetailsPanel(); //wpF_SingleStock1.setNewSymbol(symbol); SubscribeMarketDataClient(); } } catch (Exception ex) { TILogger.Error($"Exception when calling ChangeSymbol in the Single Stock window: {ex.Message}", ex); } } public string CurrentSymbol() { return _currentSymbol; // wpF_SingleStock1.getCurrentSymbol(); } public bool Pinned { get { return _pinned; } set { _pinned = value; } } public bool SymbolLinkingEnabled { get { return _symbolLinkingEnabled; } set { _symbolLinkingEnabled = value; //_similarTab.setSymbolLinking(value); _similarControl.SetSymbolLinking(value); // The detailsControl may still be null under custom display scaling. if (_useBrowserInterface) { if (null != _chromiumDetailsControl) _chromiumDetailsControl.SymbolLinking = value; } else { if (null != _detailsControl) _detailsControl.SymbolLookupLinking = value; } UpdateSymbolLinkingCheckboxStatus(); // update icon if (_symbolLinkingEnabled) SymbolLinkingChannelsHelper.SetFormIcon(this, "S", _linkChannel); else SymbolLinkingChannelsHelper.SetFormIcon(this, "S", "GREY"); } } private string _linkChannel = SymbolLinkChannels.DefaultLinkChannel; public string LinkChannel { get { return _linkChannel; } set { _linkChannel = value; } } public bool LinkEnabled { get { return SymbolLinkingEnabled; } set { SymbolLinkingEnabled = value; } } public bool LimitedMode { get { return _limitedMode; } set { _limitedMode = value; } } public ContextMenuStrip MyContextMenuStrip { get { return contextMenuStrip1; } } private void ContextMenuStrip1_Opening(object sender, CancelEventArgs e) { //string symbl = wpF_SingleStock1.getCurrentSymbol(); copyToClipboardToolStripMenuItem.Visible = false; string activeID = GetDocumentFocusID(); if (activeID == "0") //wpF_SingleStock1.getSelectedTabIndex() == 0) { configureToolStripMenuItem.Visible = true; outsideMarketHoursToolStripMenuItem.Visible = true; } else { configureToolStripMenuItem.Visible = false; } if (activeID == "1") //wpF_SingleStock1.getSelectedTabIndex() == 1) { outsideMarketHoursToolStripMenuItem.Visible = false; singleColumnToolStripMenuItem.Visible = true; } else { singleColumnToolStripMenuItem.Visible = false; } if (activeID == "2") //wpF_SingleStock1.getSelectedTabIndex() == 2) { outsideMarketHoursToolStripMenuItem.Visible = false; if (GuiEnvironment.DevelopmentMode) copyToClipboardToolStripMenuItem.Visible = true; } if (activeID == "3") //wpF_SingleStock1.getSelectedTabIndex() == 3) { tradeFiltersStripMenuItem.Visible = true; tradeFiltersStripMenuItem.Checked = (_selectedFilters.Count > 0); outsideMarketHoursToolStripMenuItem.Visible = false; } else { tradeFiltersStripMenuItem.Visible = false; } if (activeID == "4") //wpF_SingleStock1.getSelectedTabIndex() == 4) { // viewModeToolStripMenuItem.Visible = true; popOutToolStripMenuItem.Visible = true; outsideMarketHoursToolStripMenuItem.Visible = true; priceActionToolStripMenuItem1.Visible = true; competitorsToolStripMenuItem1.Visible = true; } else { // viewModeToolStripMenuItem.Visible = false; popOutToolStripMenuItem.Visible = false; priceActionToolStripMenuItem1.Visible = false; competitorsToolStripMenuItem1.Visible = false; } if (null != GuiEnvironment.RobotStrategyMenuCode) GuiEnvironment.RobotStrategyMenuCode(contextMenuStrip1, _currentSymbol, "SS", null); GuiEnvironment.HideMenuItems(contextMenuStrip1.Items); GuiEnvironment.EnforceLimitedMode(contextMenuStrip1); // add symbol linking channels here doSymbolLinkingToolStripMenuItem.DropDown.Items.Clear(); //Detect if the current window is in floating mode var floatingMode = string.IsNullOrEmpty(GuiEnvironment.GetDockWindowID(this)); foreach (KeyValuePair channel in SymbolLinkChannels.Channels) { if (channel.Key == SymbolLinkChannels.DockWindowChannel && floatingMode) continue; ToolStripMenuItem menuItem = new ToolStripMenuItem(channel.Key, null, delegate { SetLinkChannel(channel.Key); }); menuItem.BackColor = channel.Value; Color foreColor = GradientInfo.AltColor(channel.Value); menuItem.ForeColor = foreColor; menuItem.Checked = _linkChannel == channel.Key; doSymbolLinkingToolStripMenuItem.DropDown.Items.Add(menuItem); } } private void ContextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e) { _remainPaused = false; } static public void RegisterLayout() { // change parameters to accommodate dock panel changes - RVH20210402 //LayoutManager.Instance().AddRestoreRule(FORM_TYPE, (RestoreLayout)delegate(XmlNode description, bool ignorePosition, bool cascadePosition) LayoutManager.Instance().AddRestoreRule(FORM_TYPE, (RestoreLayout)delegate (XmlNode description, bool ignorePosition, bool cascadePosition, bool dockPanelMode, string mainDockPanelName, string mainDockPanelTitle, string dockPanelID) { IConnectionMaster connectionMaster = GuiEnvironment.FindConnectionMaster(description.Property("CONNECTION")); if (null == connectionMaster) { // We could report an error here, but it's simpler just to do nothing. Any error message we tried to // report would probably be confusing at best to the user. } else { EnhancedSingleStockDockWindow singleStockWindow = new EnhancedSingleStockDockWindow(); // change parameters to accommodate dock panel changes - RVH20210402 //singleStockWindow.Restore(description, ignorePosition, cascadePosition); singleStockWindow.Restore(description, ignorePosition, cascadePosition, dockPanelMode, mainDockPanelName, mainDockPanelTitle, dockPanelID); singleStockWindow.RestoredLayout = description; } }); // This is for backward compatibility - RVH20210730 // Register with the old form type above and the new one here LayoutManager.Instance().AddRestoreRule(NEW_FORM_TYPE, (RestoreLayout)delegate (XmlNode description, bool ignorePosition, bool cascadePosition, bool dockPanelMode, string mainDockPanelName, string mainDockPanelTitle, string dockPanelID) { IConnectionMaster connectionMaster = GuiEnvironment.FindConnectionMaster(description.Property("CONNECTION")); if (null == connectionMaster) { // We could report an error here, but it's simpler just to do nothing. Any error message we tried to // report would probably be confusing at best to the user. } else { EnhancedSingleStockDockWindow singleStockWindow = new EnhancedSingleStockDockWindow(); // change parameters to accommodate dock panel changes - RVH20210402 //singleStockWindow.Restore(description, ignorePosition, cascadePosition); singleStockWindow.Restore(description, ignorePosition, cascadePosition, dockPanelMode, mainDockPanelName, mainDockPanelTitle, dockPanelID); singleStockWindow.RestoredLayout = description; } }); } public void SaveLayout(XmlNode parent) { //string currentSymbol = wpF_SingleStock1.getCurrentSymbol(); //string config = wpF_SingleStock1.getCurrentConfigString(); if (null != PreSaveLayoutCode) { PreSaveLayoutCode(this); } string layoutString = SaveDockPanelLayout(); XmlNode description = LayoutManager.SaveBase(parent, this, FORM_TYPE, ActualSize, layoutString); if (null != SaveLayoutCode) { SaveLayoutCode(this, description); } if (!string.IsNullOrWhiteSpace(_config)) { description.SetProperty("CONFIG", _config); } //for Similar Tab description = _similarControl.SaveGridColumnForDuplication(description); description.SetProperty("SUB_INDUSTRY", _similarControl.GetSubindustryString()); description.SetProperty("SYMBOL", _currentSymbol); // wpF_SingleStock1.getCurrentSymbol()); description.SetProperty("SIMILAR_TAB_CONFIG", _similarControl.GetConfigString()); description.SetProperty("SMALL_BORDERS", smallBordersToolStripMenuItem.Checked.ToString()); description.SetProperty("OUTSIDE_MARKET_HOURS", outsideMarketHoursToolStripMenuItem.Checked); description.SetProperty("LOCALSORTENABLED", _similarControl.GetLocalSortEnabled()); description.SetProperty("LOCALSORTCODE", _similarControl.GetLocalSortCode()); description.SetProperty("LOCALSORTTYPE", _similarControl.GetLocalSortType()); //description = _similarTab.saveGridColumnForDuplication(description); //description.SetProperty("SUB_INDUSTRY", _similarTab.getSubindustryString()); //description.SetProperty("SYMBOL", _currentSymbol); // wpF_SingleStock1.getCurrentSymbol()); //description.SetProperty("SIMILAR_TAB_CONFIG", _similarTab.getConfigString()); //description.SetProperty("SMALL_BORDERS", smallBordersToolStripMenuItem.Checked.ToString()); //description.SetProperty("OUTSIDE_MARKET_HOURS", outsideMarketHoursToolStripMenuItem.Checked); //description.SetProperty("LOCALSORTENABLED", _similarTab.getLocalSortEnabled()); //description.SetProperty("LOCALSORTCODE", _similarTab.getLocalSortCode()); //description.SetProperty("LOCALSORTTYPE", _similarTab.getLocalSortType()); //description.SetProperty("CONTRACTED_WINDOW", _contractedWindow); // These 2 settings are no longer needed - RVH20210714 //description.SetProperty("SIDE_RIGHT_LEFT", wpF_SingleStock1.getSideRightLeftIndicator()); //description.SetProperty("DISPLAY_BEGIN_POPULATE", wpF_SingleStock1.getDisplayBeginPopulate()); description.SetProperty("SYMBOL_LINKING_ENABLED", SymbolLinkingEnabled); description.SetProperty("SAVED_WINDOW", true); description.SetProperty("PINNED", _pinned); description.SetProperty("IN_BLANK_MODE", false); //remnant from scottrade(no longer exist) //int selectedTabIndex = wpF_SingleStock1.getSelectedTabIndex string activeID = GetDocumentFocusID(); description.SetProperty("ACTIVE_TAB", activeID); // selectedTabIndex); description.SetProperty("VIEW_MODE", _similarControl.GetViewMode().ToString()); // _similarTab.getViewMode().ToString()); description.SetProperty("NEWS_SINGLE_COLUMN", _newsControl.SingleColumn); // new setting for news single column - RVH20210715 description.SetProperty("PROFILE_COLLAPSED", _profileControl.Collapsed); // new setting for profile collapsed - RVH20210813 description.SetProperty("FONT_SIZE", (int)_selectedFontSize); XmlNode columnsChild = description.NewNode("COLUMNS"); // pull columns from new InsidersControl datagridview - RVH20210714 // BLOCK OUT THE INSIDERS CONTROL FOR NOW - IT HAS OLD DATA AND CAUSES AN EXCEPTION - RVH20210729 //foreach (DataGridViewColumn col in _insidersControl.dataGrid.Columns) //{ // XmlNode column = columnsChild.NewNode("COLUMN"); // column.SetProperty("HEADER", col.HeaderText); // column.SetProperty("DISPLAY_INDEX", col.DisplayIndex); // column.SetProperty("WIDTH", col.Width); //} //ObservableCollection colList = _insidersGrid.Columns; //foreach (DataGridColumn col in colList) //{ // XmlNode column = columnsChild.NewNode("COLUMN"); // column.SetProperty("HEADER", col.Header); // column.SetProperty("DISPLAY_INDEX", col.DisplayIndex); // column.SetProperty("WIDTH",col.Width.Value); //} //filters XmlNode transactionFiltersNode = description.NewNode("FILTERS"); foreach (InsiderTransactionType t in _selectedFilters) { XmlNode transactionFilterNode = transactionFiltersNode.NewNode("FILTER"); transactionFilterNode.SetProperty("TRANSACTION", t.ToString()); } } // change parameters to accommodate dock panel changes - RVH20210402 //public void Restore(XmlNode description, bool ignorePosition, bool cascadePosition) public void Restore(XmlNode description, bool ignorePosition, bool cascadePosition, bool dockPanelMode = false, string mainDockPanelName = "", string mainDockPanelTitle = "", string dockPanelID = "") { var defaultConfig = GuiEnvironment.XmlConfig.Node("SINGLE_SYMBOL_WINDOW").Node("NEW_SINGLE_STOCK_WINDOW_DEFAULT").Property("TEXT"); // Use the config defined in Global settings if defined. var globalConfig = GuiEnvironment.GlobalSettings.Node("SINGLE_SYMBOL_WINDOW").Node("NEW_SINGLE_STOCK_WINDOW_DEFAULT").Property("TEXT"); if (!string.IsNullOrWhiteSpace(globalConfig)) defaultConfig = globalConfig; var config = description.Property("CONFIG", defaultConfig); // Add check due to old builds allowed blank config strings. if (string.IsNullOrWhiteSpace(config)) config = defaultConfig; var symbol = description.Property("SYMBOL", null); if (string.IsNullOrWhiteSpace(symbol)) symbol = SingleString(config); int fontSize = description.Property("FONT_SIZE", 1); bool? outsideMarketHours = description.PropertyBool("OUTSIDE_MARKET_HOURS") ?? false; // new settings for tabs - RVH20210723 int standardArticleWidth = GuiEnvironment.XmlConfig.Node("SINGLE_SYMBOL_WINDOW").Node("NEWS_TAB").Property("STANDARD_ARTICLE_WIDTH", 450); int minimumArticleWidth = GuiEnvironment.XmlConfig.Node("SINGLE_SYMBOL_WINDOW").Node("NEWS_TAB").Property("MINIMUM_ARTICLE_WIDTH", 50); int detailsColumnWidth = GuiEnvironment.XmlConfig.Node("SINGLE_SYMBOL_WINDOW").Node("DETAILS_TAB").Property("COLUMN_WIDTH", 200); int detailsColumnWidth_small = GuiEnvironment.XmlConfig.Node("SINGLE_SYMBOL_WINDOW").Node("DETAILS_TAB").Property("COLUMN_WIDTH_SMALL", 150); int detailsColumnWidth_large = GuiEnvironment.XmlConfig.Node("SINGLE_SYMBOL_WINDOW").Node("DETAILS_TAB").Property("COLUMN_WIDTH_LARGE", 250); // change parameters to accommodate dock panel changes - RVH20210402 // LayoutManager.RestoreBase(description, this, ignorePosition, cascadePosition); LayoutManager.RestoreBase(description, this, ignorePosition, cascadePosition, null, false, dockPanelMode, mainDockPanelName, mainDockPanelTitle, dockPanelID); _dockPanelMode = dockPanelMode; // restore dock panel layout - RVH20210520 XmlNode baseNode = description.Node("BASE"); string layoutString = baseNode.Property("DockPanelLayout", ""); if (!string.IsNullOrEmpty(layoutString)) LoadDockPanelLayoutFromString(layoutString); smallBordersToolStripMenuItem.Checked = description.Property("SMALL_BORDERS", false); outsideMarketHoursToolStripMenuItem.Checked = outsideMarketHours.Value; // only call this if not in dock panel mode - RVH20210329 if (!_dockPanelMode) setBorders(); // Add NEW controls to dock panels - RVH20210618 if (_useBrowserInterface) { // Add ChromiumDetailsControl. _chromiumDetailsControl = new ChromiumDetailsControl(this); AddChildControl(_chromiumDetailsControl, "Details", "0"); } else { _detailsControl = new DetailsControl(this, detailsColumnWidth, detailsColumnWidth_small, detailsColumnWidth_large); // The detailsControl may still be null under custom display scaling. if (null != _detailsControl) AddChildControl(_detailsControl, "Details", "0"); } _newsControl = new NewsControl(this, standardArticleWidth, minimumArticleWidth); AddChildControl(_newsControl, "News", "1"); _profileControl = new ProfileControl(this); AddChildControl(_profileControl, "Profile", "2"); // BLOCK OUT THE INSIDERS CONTROL FOR NOW - IT HAS OLD DATA AND CAUSES AN EXCEPTION - RVH20210729 //_insidersControl = new InsidersControl(this); // hide the Insiders tab for now because of an issue with the data - RVH20210716 //AddChildControl(_insidersControl, "Insiders", "3"); _similarControl = new SimilarControl(this); AddChildControl(_similarControl, "Similar", "4"); _similarControl.BeginToplist(); _dataGrids.Add(_similarControl.GetDataGridView()); //AddChildControl(_tPanel, "Similar-TEST", ""); //_tPanel.beginToplist(); selectTheFont(); // TAKE OUT FOR NOW - RVH20210729 //FindSymbolLookupControl(Controls); WindowDocumentDock windowDocumentDock = FindDocumentByID("0"); windowDocumentDock.Activate(); // User maybe loading a contracted window saved under a different font size // so we need to set _contractedWindow correctly // int contractedWindow = description.Property("CONTRACTED_WINDOW", _contractedWindowDefault); // if (contractedWindow > _contractedWindow) // _contractedWindow = contractedWindow; Dictionary dictionary = new Dictionary(); foreach (XmlNode node in description.Node("COLUMNS").Enum()) { String header = node.Property("HEADER", ""); int? displayIndex = XmlHelper.PropertyInt32(node, "DISPLAY_INDEX"); int? width = XmlHelper.PropertyInt32(node, "WIDTH"); //double? width = XmlHelper.PropertyDouble(node, "WIDTH"); if (header != "" && displayIndex != null && displayIndex != -1 && width != null) { //DataGridLength dGL = new DataGridLength(width.Value, DataGridLengthUnitType.Star); ColumnSetting s; s.dIndex = displayIndex.Value; s.width = width.Value; // dGL; dictionary.Add(header, s); } } _selectedFilters.Clear(); if (null != description.Node("FILTERS") && description.Node("FILTERS").HasChildNodes) { XmlNodeList filtersNodeList = description.Node("FILTERS").ChildNodes; foreach (XmlNode filterNode in filtersNodeList) { InsiderTransactionType transType = filterNode.PropertyEnum("TRANSACTION", InsiderTransactionType.Buy); if (!_selectedFilters.Contains(transType)) { _selectedFilters.Add(transType); } } } _filterPopupInUse = false; _viewModePopupInUse = false; //If there were changes to the insider grid (e.g. width, order), and the grid has actually been accessed (index won't be -1 in this case) // then the dictionary d, should have 7 members (number of columns of the grid within the Insider tab. if (dictionary.Count == 7) { // update columns in new InsidersControl datagridview - RVH20210714 //DataGridViewColumnCollection dataGridViewColumnCollection = new DataGridViewColumnCollection(_insidersControl.dataGrid); //_insidersControl.dataGrid.Columns.Clear(); // BLOCK OUT THE INSIDERS CONTROL FOR NOW - IT HAS OLD DATA AND CAUSES AN EXCEPTION - RVH20210729 //foreach (DataGridViewColumn col in _insidersControl.dataGrid.Columns) //{ // String header = col.HeaderText; // ColumnSetting setting; // dictionary.TryGetValue(header, out setting); // col.DisplayIndex = setting.dIndex; // col.Width = setting.width; // //_insidersControl.dataGrid.Columns.Add(col); //} //ObservableCollection temp = new ObservableCollection(_insidersGrid.Columns); //_insidersGrid.Columns.Clear(); //foreach (DataGridColumn col in temp) //{ // String header = col.Header.ToString(); // ColumnSetting setting; // dictionary.TryGetValue(header, out setting); // col.DisplayIndex = setting.dIndex; // col.Width = setting.width; // _insidersGrid.Columns.Add(col); //} } setNewSymbol(symbol, config, outsideMarketHours); // These 2 settings are no longer needed - RVH20210714 //wpF_SingleStock1.setSideRightLeftIndicator(description.Property("SIDE_RIGHT_LEFT", 0)); //wpF_SingleStock1.setDisplayBeginPopulate(description.Property("DISPLAY_BEGIN_POPULATE", 0)); SymbolLinkingEnabled = description.Property("SYMBOL_LINKING_ENABLED", false); _pinned = description.Property("PINNED", false); pinnedToolStripMenuItem.Checked = _pinned; //_savedWindow = description.Property("SAVED_WINDOW", false); //SIMILAR TAB: String viewModeString = description.Property("VIEW_MODE", "Competitor"); String similarTabConfigString = description.Property("SIMILAR_TAB_CONFIG", ""); String sInd = description.Property("SUB_INDUSTRY", null); //_similarTab.setSubindustryOnRestore(sInd); _similarControl.SetSubindustryOnRestore(sInd); //TopListPanel.ViewMode vM; SimilarControl.ViewMode vM2; if (viewModeString == "Competitor") { competitorsToolStripMenuItem.Checked = true; priceActionToolStripMenuItem.Checked = false; priceActionToolStripMenuItem1.Checked = false; competitorsToolStripMenuItem1.Checked = true; //vM = TopListPanel.ViewMode.Competitor; vM2 = SimilarControl.ViewMode.Competitor; if (description.Node("SIMILAR_COLUMNS") != null) { //_similarTab.setCompetitorNode(description.Node("SIMILAR_COLUMNS")); _similarControl.SetCompetitorNode(description.Node("SIMILAR_COLUMNS")); } } else { competitorsToolStripMenuItem.Checked = false; priceActionToolStripMenuItem.Checked = true; priceActionToolStripMenuItem1.Checked = true; competitorsToolStripMenuItem1.Checked = false; //vM = TopListPanel.ViewMode.PriceAction; vM2 = SimilarControl.ViewMode.PriceAction; if (description.Node("SIMILAR_COLUMNS") != null) { //_similarTab.setPriceActionNode(description.Node("SIMILAR_COLUMNS")); _similarControl.SetPriceActionNode(description.Node("SIMILAR_COLUMNS")); } } if (null != description.Property("LOCALSORTENABLED")) { //_similarTab.setLocalSortEnabled(bool.Parse(description.Property("LOCALSORTENABLED", "False"))); _similarControl.SetLocalSortEnabled(bool.Parse(description.Property("LOCALSORTENABLED", "False"))); } if (null != description.Property("LOCALSORTTYPE")) { TopListSortType localSortType = (TopListSortType)Enum.Parse(typeof(TopListSortType), description.Property("LOCALSORTTYPE", "ServerSort")); //_similarTab.setLocalSortType(localSortType); _similarControl.SetLocalSortType(localSortType); } if ("" != description.Property("LOCALSORTCODE")) { //_similarTab.setLocalSortCode(description.Property("LOCALSORTCODE")); _similarControl.SetLocalSortCode(description.Property("LOCALSORTCODE")); } //_similarTab.setViewModeOnRestore(vM); _similarControl.SetViewModeOnRestore(vM2); //wpF_SingleStock1.updateToggleText(vM); // News Control - RVH20210715 bool newsSingleColumn = description.Property("NEWS_SINGLE_COLUMN", false); singleColumnToolStripMenuItem.Checked = newsSingleColumn; _newsControl.SingleColumn = newsSingleColumn; // Profile Control - RVH20210813 bool profileCollapsed = description.Property("PROFILE_COLLAPSED", false); _profileControl.Collapsed = profileCollapsed; string activeID = description.Property("ACTIVE_TAB", "0"); SetDocumentFocus(activeID); //int activeTab = description.Property("ACTIVE_TAB", 0); //wpF_SingleStock1.setTabControlSelectedIndex(activeTab); setMarketHours(); SetFontSize((FontSize)fontSize); } /// /// Returns the SingleSymbol string from a config string. If it is not found, null is returned. /// /// /// Value of SingleString from a config string private string SingleString(string config) { var dict = config.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(part => part.Split('=')) .ToDictionary(split => split[0], split => split[1]); dict.TryGetValue("SingleSymbol", out var value); return value; } private void EnhancedSingleStockDockWindow_Activated(object sender, EventArgs e) { //wpF_SingleStock1.mainWindowActivated(); } public List getSelectedFIlterList() { return _selectedFilters; } //for receiving updates using the dialog checked listbox for selecting transactions public void receiveCheckedFilters(List chosenFilters) { _selectedFilters = new List(chosenFilters); fetchSelectedFilters(); } public void fetchSelectedFilters() { List temp = new List(_selectedFilters); if (onTransactionSelectedUpdate != null) onTransactionSelectedUpdate(temp); } private void TradeFiltersStripMenuItem_Click(object sender, EventArgs e) { if (_filterPopupInUse == false) { _filterPopupInUse = true; _tWindow = new TransactionsWindow(this); _tWindow.ShowDialog(); } } private void EnhancedSingleStockDockWindow_FormClosing(object sender, FormClosingEventArgs e) { try { if (_tWindow != null) { _tWindow.Close(); } //wpF_SingleStock1.onWindowNameUpdate -= wpf_onWindowNameUpdate; // delete event handlers - RVH20210622 onWindowNameUpdate -= WindowNameUpdate; VisibleChanged -= EnhancedSingleStockDockWindow_VisibleChanged; contextMenuStrip1.Opening -= LayoutManager.Instance().contextMenuStrip_Opening; UnsubscribeMarketDataClientOnFormClose(); //wpF_SingleStock1.receiveSymbolFromComboEvent -= WpF_SingleStock1_receiveSymbolFromComboEvent; //wpF_SingleStock1.MouseEnter -= Wpf_SingleStock1_MouseEnter; //wpF_SingleStock1.MouseLeave -= Wpf_SingleStock1_MouseLeave; //wpF_SingleStock1.onSymbolUpdate -= WpF_SingleStock1_onSymbolUpdate; onSymbolUpdate -= SimilarControl_onSymbolUpdate; // delete control event handlers - RVH20210630 _companyProfileManager.ProfileReceived -= CompanyProfileManager_ProfileReceived; _insidersManager.InsidersReceived -= InsidersManager_InsidersReceived; //we'll stop events from firing and unhook event handlers from other tabs when window is closing if (_useBrowserInterface) { if (null != _chromiumDetailsControl) { _chromiumDetailsControl.UnLoadEventHandlers(); _chromiumDetailsControl.Cleanup(); } } else { if (null != _detailsControl) _detailsControl.UnLoadEventHandlers(); } if (null != _profileControl) _profileControl.UnLoadEventHandlers(); if (null != _newsControl) _newsControl.UnLoadEventHandlers(); // BLOCK OUT THE INSIDERS CONTROL FOR NOW - IT HAS OLD DATA AND CAUSES AN EXCEPTION - RVH20210729 //_insidersControl.unLoadEventHandlers(); if (null != _similarControl) _similarControl.UnLoadEventHandlers(); //_similarTab.unLoadEventHandlers(); SetConfiguration(null); // close dock panel documents - RVH20210618 if (null != _childControls) _childControls.Clear(); CloseAllDocuments(); } catch (Exception ex) { TILogger.Error($"Exception when closing Single Stock window: {ex.Message}", ex); } } private void contextMenuStrip1_Opened(object sender, EventArgs e) { if (SymbolLinkingEnabled) { _remainPaused = true; PauseSurfing(); } } /* public WPF_SingleStock getWPF_SingleStock() { return wpF_SingleStock1; } */ private void popOutToolStripMenuItem_Click(object sender, EventArgs e) { // change to new control - RVH20210715 _similarControl.Duplicate(); //_similarTab.duplicate(); } public static string PutOutSideMarketHours(String cfg, bool inOutsideMarketHours) { string retVal = ""; if (cfg.Contains("omh=1")) { if (inOutsideMarketHours) retVal = cfg; else retVal = cfg.Replace("omh=1", "omh=0"); } else if (cfg.Contains("omh=0")) { if (inOutsideMarketHours) retVal = cfg.Replace("omh=0", "omh=1"); else retVal = cfg; } else if (!cfg.Contains("omh")) { if (inOutsideMarketHours) retVal = cfg.Replace("col_ver=1", "omh=1&col_ver=1"); else retVal = cfg.Replace("col_ver=1", "omh=1&col_ver=0"); } return retVal; } private void competitorsToolStripMenuItem_Click(object sender, EventArgs e) { if (competitorsToolStripMenuItem.Checked) return; priceActionToolStripMenuItem.Checked = false; competitorsToolStripMenuItem.Checked = true; _similarControl.SetViewMode(SimilarControl.ViewMode.Competitor); //_similarTab.getTopListPanel().setViewMode(TopListPanel.ViewMode.Competitor); } private void priceActionToolStripMenuItem_Click(object sender, EventArgs e) { if (priceActionToolStripMenuItem.Checked) return; competitorsToolStripMenuItem.Checked = false; priceActionToolStripMenuItem.Checked = true; _similarControl.SetViewMode(SimilarControl.ViewMode.PriceAction); //_similarTab.getTopListPanel().setViewMode(TopListPanel.ViewMode.PriceAction); } public void selectTheFont() { //Font = GuiEnvironment.FontSettings; contextMenuStrip1.Font = GuiEnvironment.FontSettings; _similarControl.Font = GuiEnvironment.FontSettings; _newsControl.selectTheFont(); _profileControl.SetFontSize(_selectedFontSize); if (_useBrowserInterface) { if (null != _chromiumDetailsControl) _chromiumDetailsControl.SetFontSize(_selectedFontSize); } else _detailsControl.SetFontSize(_selectedFontSize); DataGridViewHelper.SetRowHeight(_similarControl.GetDataGridView(), _similarControl.SymbolPlusLayout); } public void chooseRowSelect() { _similarControl.ChooseRowSelect(); //_similarTab.getTopListPanel().chooseRowSelect(); } private IDockContent GetContentFromPersistString(string persistString) { // WindowDocumentDock overrides GetPersistString to add extra information into persistString. // Any DockContent may override this value to add any needed information for deserialization. string[] parsedStrings = persistString.Split(new char[] { ',' }); if (parsedStrings.Length != 3) return null; if (parsedStrings[0] == typeof(WindowDocumentDock).ToString()) { WindowDocumentDock newDock = new WindowDocumentDock(null, parsedStrings[1]); newDock.DockAreas = DockAreas.DockLeft | DockAreas.Document; return newDock; } else { return null; } } public List ChildControls { get { return _childControls; } set { _childControls = value; } } public void AddChildControl(System.Windows.Forms.Control childControl, string controlText, string id) { // Add child control _childControls.Add(childControl); // add text changed event handler //childControl.TextChanged -= tab_TextChanged; //childControl.TextChanged += tab_TextChanged; // find WindowDocumentDock by ID first // if found add childForm to it WindowDocumentDock findFormDock = null; // if id is blank, then get the last id from the dock panels if (string.IsNullOrEmpty(id)) { int lastID = GetLastID(); id = (lastID + 1).ToString(); } else { // see if there is already a dock panel with this id if (!string.IsNullOrEmpty(id)) findFormDock = FindDocumentByID(id); } if (findFormDock != null) { childControl.Top = 0; childControl.Left = 0; findFormDock.Controls.Clear(); findFormDock.Controls.Add(childControl); findFormDock.ChildControl = childControl; findFormDock.Text = controlText; // disable and hide close button findFormDock.CloseButton = false; findFormDock.CloseButtonVisible = false; findFormDock.ForceResize(); } else { // Create new WindowDocumentDock (DockContent) form WindowDocumentDock newFormDock = CreateNewDocument(childControl, controlText, id); //mainFormDock2.DockHandler.AllowEndUserDocking = false; if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { newFormDock.MdiParent = this; newFormDock.Show(); } else { childControl.Top = 0; childControl.Left = 0; newFormDock.Controls.Add(childControl); newFormDock.Show(dockPanel); } } } private WindowDocumentDock CreateNewDocument(System.Windows.Forms.Control childControl, string text, string id) { WindowDocumentDock newDoc = new WindowDocumentDock(childControl, id); newDoc.DockAreas = DockAreas.Document | DockAreas.DockLeft; newDoc.Text = text; // disable and hide close button newDoc.CloseButton = false; newDoc.CloseButtonVisible = false; return newDoc; } private WindowDocumentDock FindDocumentByID(string id) { return dockPanel.Documents.OfType() .Concat(dockPanel.Contents.OfType()) .FirstOrDefault(doc => doc.ID == id); } private int GetLastID() { int id = -1; foreach (IDockContent content in dockPanel.Contents) { if (content is WindowDocumentDock) { string strID = ((WindowDocumentDock)content).ID; int thisID = 0; int.TryParse(strID, out thisID); if (thisID > id) id = thisID; } } return id; } private void SetDocumentFocus(string id) { foreach (IDockContent content in dockPanel.Contents) { if (content is WindowDocumentDock) { if (((WindowDocumentDock)content).ID == id) { content.DockHandler.Activate(); break; } } } } private string GetDocumentFocusID() { string id = ""; WindowDocumentDock windowDocumentDock = dockPanel.ActiveDocument as WindowDocumentDock; if (windowDocumentDock != null) id = windowDocumentDock.ID; //foreach (IDockContent content in dockPanel.Contents) //{ // if (content is WindowDocumentDock) // { // if (((WindowDocumentDock)content).IsActivated) // { // id = ((WindowDocumentDock)content).ID; // break; // } // } //} return id; } private string SaveDockPanelLayout() { string xmlLayout = ""; // save to a stream using (MemoryStream stream = new MemoryStream()) { Encoding encoding = new ASCIIEncoding(); this.dockPanel.SaveAsXml(stream, encoding); using (StreamReader reader = new StreamReader(stream)) { stream.Position = 0; reader.DiscardBufferedData(); xmlLayout = reader.ReadToEnd(); } } return xmlLayout; } public void LoadDockPanelLayoutFromString(string xmlLayout) { using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(xmlLayout))) { this.dockPanel.LoadFromXml(stream, _deserializeDockContent); } } private void CloseAllDocuments() { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { foreach (Form form in MdiChildren) form.Close(); } else { List dockContentsToDelete = new List(); foreach (IDockContent document in dockPanel.Contents) { dockContentsToDelete.Add(document); } foreach (IDockContent document in dockContentsToDelete) { // IMPORANT: dispose all panes. document.DockHandler.DockPanel = null; document.DockHandler.Close(); } } } public void OnRowData(List rows, DateTime? start, DateTime? end, TopListRequest.Token token) { this.InvokeIfRequired((MethodInvoker)delegate { if (_topList == token) OnRowData(rows, start, end); }); } public void OnMetaData(TopListRequest.Token token) { // Ignore this event. Look for the meta data when we receive the row data. } public void OnDisconnect(TopListRequest.Token token) { if (_topList == token) // Unexpected disconnect. We still want to listen. _topList = _topList.GetRequest().Send(_connectionMaster.SendManager, this); } private void OnRowData(List rows, DateTime? start, DateTime? end) //Details tab will be listening on this.. { //we'll "display" one row. This row has all of the pertinent data that will be displayed //in the Single Stock Detail tab. TopListInfo metaData = _topList.GetMetaData(); if ((rows.Count == 1) && (null != metaData)) { // block out code that isn't needed - RVH20210622 if (_similarControl != null) { _similarControl.SetValidSymbolStatus(true); } //similarTab.setValidSymbolStatus(true); _startSymbolTally++; _topList.GetRequest().LastUpdate = DateTime.Now; if (_similarControl != null) { _similarControl.SetStartSymbolTally(_startSymbolTally); } //similarTab.setStartSymbolTally(startSymbolTally); // The detailsControl may still be null under custom display scaling. if (_useBrowserInterface) { if (null != _chromiumDetailsControl) _chromiumDetailsControl.SetValidSymbol(true); } else { if (null != _detailsControl) _detailsControl.SetValidSymbol(true); } //changeBackGroundColorOfCombobox(Brushes.White); RowData data = rows[0]; //_companyProfileManager.RequestNow(_currentSymbol); //_insidersManager.RequestNow(_currentSymbol); //SGEN if (data.GetAsString("c_D_SubIndustry", "") != "") { _windowNameString = data.GetCompanyName() + " - " + data.GetAsString("c_D_SubIndustry", ""); } else if (data.GetAsString("c_D_SubIndustry", "") == "" && data.GetAsString("c_D_Industry", "") != "") { _windowNameString = data.GetCompanyName() + " - " + data.GetAsString("c_D_Industry", ""); } else if (data.GetAsString("c_D_SubIndustry", "") == "" && data.GetAsString("c_D_Industry", "") == "" && data.GetAsString("c_D_IndGrp", "") != "") { _windowNameString = data.GetCompanyName() + " - " + data.GetAsString("c_D_IndGrp", ""); } else if (data.GetAsString("c_D_SubIndustry", "") == "" && data.GetAsString("c_D_Industry", "") == "" && data.GetAsString("c_D_IndGrp", "") == "" && data.GetAsString("c_D_SubSector", "") != "") { _windowNameString = data.GetCompanyName() + " - " + data.GetAsString("c_D_SubSector", ""); } else { _windowNameString = data.GetCompanyName() + " - " + data.GetAsString("c_D_Sector", ""); } if (onWindowNameUpdate != null) onWindowNameUpdate(_windowNameString); if (receiveTopListDataEvent != null) receiveTopListDataEvent(metaData, data, start, end, true); if (subIndustryReceivedEvent != null) subIndustryReceivedEvent(data.GetAsString("c_D_SubIndustry", ""), data.GetAsString("c_D_Industry", ""), data.GetAsString("c_D_IndGrp", ""), data.GetAsString("c_D_SubSector", ""), data.GetAsString("c_D_Sector", "")); if (onPriceActionDataReceived != null) onPriceActionDataReceived(data.GetAsDouble("c_RY", -1), data.GetAsDouble("c_RV", -1), data.GetAsDouble("c_FCP", Double.NaN), data.GetAsDouble("c_R10D", -1), data.GetAsDouble("c_R3MO", -1), data.GetAsDouble("c_R6MO", -1)); if (onSymbolUpdate != null) onSymbolUpdate(_currentSymbol); } else { _similarControl.SetValidSymbolStatus(false); //similarTab.setValidSymbolStatus(false); // The detailsControl may still be null under custom display scaling. if (_useBrowserInterface) { if (null != _chromiumDetailsControl) { _chromiumDetailsControl.SetValidSymbol(false); _chromiumDetailsControl.ShowSymbolOnlyHeader(_currentSymbol); } } else { if (null != _detailsControl) _detailsControl.SetValidSymbol(false); } //Brush b = new SolidColorBrush(Color.FromRgb(249, 167, 175)); //changeBackGroundColorOfCombobox(b); if (onWindowNameUpdate != null) onWindowNameUpdate("No data available"); if (receiveTopListDataEvent != null) receiveTopListDataEvent(null, null, start, end, false); _similarControl.ClearData(); //similarTab.clearData(); } } private static readonly string[] EXTRA_FIELDS = new string[] { "D_Name", "D_SubSector", "D_SubIndustry", "D_Exch", "D_Sector", "D_Industry", "D_IndGrp", "Price", "FCP", "FCD", "RV", "TV","RY","R10D","R3MO","R6MO","FOP" }; public void SetConfiguration(string config) { _config = config; if (null != _topList) { _topList.Cancel(); _topList = null; } if (_useBrowserInterface) { if (_chromiumDetailsControl != null && (!string.IsNullOrEmpty(_currentSymbol))) _chromiumDetailsControl.Symbol = _currentSymbol; } else { if (_detailsControl != null && (!string.IsNullOrEmpty(_currentSymbol))) _detailsControl.Symbol = _currentSymbol; } if (!string.IsNullOrEmpty(config) && (!string.IsNullOrEmpty(_currentSymbol))) { // If config is missing, we're probably trying to shut this down. If symbol is // missing, but you try send the request anyway, you might get strange results. TopListRequest request = new TopListRequest(); foreach (string internalCode in EXTRA_FIELDS) request.AddExtraColumn(internalCode); request.Collaborate = config; request.OutsideMarketHours = _outsideMarketHours; request.SaveToMru = false; // Use the value set in the collaborate string. I have verified that the server // gets that info and is using it right. Not only do we see the data for this // symbol, but we are in the "fast" queue on the server. Single symbol top list // requests are handled differently for performance reasons. //request.SingleSymbol request.SkipMetaData = false; request.SortFormula = "1"; // Always display the data even if one field is null. request.Streaming = true; // Always display the data even if one field is null, we didn't list the exchanges right, etc. request.WhereFormula = "1"; request.SingleSymbol = _currentSymbol; _topList = request.Send(_connectionMaster.SendManager, this); } // Clear stale data in tabs when user enters an empty string as a symbol. if (string.IsNullOrWhiteSpace(_currentSymbol)) { ClearAllTabData(); } } private void ClearAllTabData() { Text = ""; if (_useBrowserInterface) _chromiumDetailsControl?.ClearDetails(); else _detailsControl?.ClearDetails(); _profileControl?.ClearLabelData(); _newsControl?.ClearArticles(); _similarControl?.ClearData(); } void CompanyProfileManager_ProfileReceived(CompanyProfileInfo profileInfo) { if (onCompanyProfileInfo != null && _currentSymbol == profileInfo.Symbol) { onCompanyProfileInfo(profileInfo); } } void InsidersManager_InsidersReceived(List trades) { if (onInsiderDataReceived != null) onInsiderDataReceived(trades, _id); } private void singleColumnToolStripMenuItem_Click(object sender, EventArgs e) { _newsControl.SingleColumn = ((ToolStripMenuItem)sender).Checked; } private void priceActionToolStripMenuItem1_Click(object sender, EventArgs e) { if (((ToolStripMenuItem)sender).Checked) { // set to Price Action _similarControl.UpdateColumnListStateOnLostFocus(); _similarControl.SetViewMode(SimilarControl.ViewMode.PriceAction); competitorsToolStripMenuItem1.Checked = false; } else { // set to Competitor _similarControl.UpdateColumnListStateOnLostFocus(); _similarControl.SetViewMode(SimilarControl.ViewMode.Competitor); competitorsToolStripMenuItem1.Checked = true; } // Update tab title. _similarControl.UpdateTabText(); } private void competitorsToolStripMenuItem1_Click(object sender, EventArgs e) { if (((ToolStripMenuItem)sender).Checked) { // set to Competitor _similarControl.UpdateColumnListStateOnLostFocus(); _similarControl.SetViewMode(SimilarControl.ViewMode.Competitor); priceActionToolStripMenuItem1.Checked = false; } else { // set to Price Action _similarControl.UpdateColumnListStateOnLostFocus(); _similarControl.SetViewMode(SimilarControl.ViewMode.PriceAction); priceActionToolStripMenuItem1.Checked = true; } // Update tab title. _similarControl.UpdateTabText(); } private void EnhancedSingleStockDockWindow_Move(object sender, EventArgs e) { // TAKE OUT FOR NOW - RVH20210729 //if (_symbolLookupForm != null && _symbolLookupControl != null) //{ // if (_symbolLookupControl.AutoCompleteShown) // { // System.Drawing.Point location = _symbolLookupControl.PointToScreen(System.Drawing.Point.Empty); // _symbolLookupForm.Top = location.Y + _symbolLookupControl.Height; // _symbolLookupForm.Left = location.X; // } //} } // TAKE OUT FOR NOW - RVH20210729 /* private SymbolLookup _symbolLookupControl; private Form _symbolLookupForm; private void FindSymbolLookupControl(Control.ControlCollection controlCollection) { foreach (Control control in controlCollection) { SymbolLookup symbolLookup = control as SymbolLookup; if (symbolLookup != null) { // found symbol control on this form _symbolLookupControl = symbolLookup; _symbolLookupForm = symbolLookup.AutoCompleteForm; break; } else { FindSymbolLookupControl(control.Controls); } } } */ private void EnhancedSingleStockDockWindow_Deactivate(object sender, EventArgs e) { //if (_symbolLookupForm != null && _symbolLookupControl != null) //{ // if (_symbolLookupControl.AutoCompleteShown && !_symbolLookupForm.Focused) // { // _symbolLookupControl.HideAutoComplete(); // } //} } private static EnhancedSingleStockDockWindow _instance; private static void MainMouseLeave() { if (_instance.SymbolLinkingEnabled) _instance.UnPauseSurfing(); } private static void MainMouseEnter() { if (_instance.SymbolLinkingEnabled) _instance.PauseSurfing(); } private MouseMoveMessageFilter mouseMessageFilter; private static bool _mouseEntered = false; protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.mouseMessageFilter = new MouseMoveMessageFilter(); this.mouseMessageFilter.TargetForm = this; System.Windows.Forms.Application.AddMessageFilter(this.mouseMessageFilter); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); this.mouseMessageFilter.TargetForm = null; System.Windows.Forms.Application.RemoveMessageFilter(this.mouseMessageFilter); } private class MouseMoveMessageFilter : IMessageFilter { public Form TargetForm { get; set; } public bool PreFilterMessage(ref Message m) { int numMsg = m.Msg; if (numMsg == 0x0200 /*WM_MOUSEMOVE*/) { try { //Debug.WriteLine(TargetForm.PointToClient(Cursor.Position).ToString()); //Debug.WriteLine(TargetForm.ClientRectangle.Contains(TargetForm.PointToClient(Cursor.Position)).ToString()); if (!_mouseEntered && TargetForm != null && TargetForm.ClientRectangle.Contains(TargetForm.PointToClient(Cursor.Position))) { _mouseEntered = true; MainMouseEnter(); //Debug.WriteLine("mouse entered " + DateTime.Now.ToString()); //Debug.WriteLine(TargetForm.ClientRectangle.ToString()); //Debug.WriteLine(TargetForm.DisplayRectangle.ToString()); //Debug.WriteLine(TargetForm.PointToClient(Cursor.Position).ToString()); //Debug.WriteLine(TargetForm.ClientRectangle.Contains(TargetForm.PointToClient(Cursor.Position)).ToString()); } } catch { } // Ignore exceptions in this logic. } else if (numMsg == 0x02A3 /*WM_MOUSELEAVE*/) { if (_mouseEntered) // && !TargetForm.ClientRectangle.Contains(TargetForm.PointToClient(Cursor.Position))) { _mouseEntered = false; MainMouseLeave(); //Debug.WriteLine("mouse leave " + DateTime.Now.ToString()); } } //Debug.WriteLine(string.Format($"X:{Control.MousePosition.X}, Y:{Control.MousePosition.Y}")); //this.TargetForm.Text = string.Format($"X:{Control.MousePosition.X}, Y:{Control.MousePosition.Y}"); return false; } } private const int _minDockWindowWidth = 75; private const int _minDockWindowHeight = 5; //private int _lastDockWindowWidth; //private int _lastDockWindowHeight; //private bool _resizingDockWindow = false; private bool DockedWindowsTooSmall(out bool widthTooSmall, out bool heightTooSmall) { widthTooSmall = false; heightTooSmall = false; bool tooSmall = false; foreach (WindowDocumentDock document in dockPanel.Contents) { if (document.Width <= _minDockWindowWidth || document.Height <= _minDockWindowHeight) { tooSmall = true; if (document.Width <= _minDockWindowWidth) widthTooSmall = true; if (document.Height <= _minDockWindowHeight) heightTooSmall = true; break; } } return tooSmall; } private void EnhancedSingleStockDockWindow_Resize(object sender, EventArgs e) { // new code to keep the window from being resized too small - RVH20210922 //if (_resizingDockWindow) // return; //if (WindowState != FormWindowState.Minimized) //{ // bool widthTooSmall = false; // bool heightTooSmall = false; // bool tooSmall = DockedWindowsTooSmall(out widthTooSmall, out heightTooSmall); // if (tooSmall) // { // _resizingDockWindow = true; // this.Width = _lastDockWindowWidth + (widthTooSmall ? 10 : 0); // this.Height = _lastDockWindowHeight + (heightTooSmall ? 10 : 0); // System.Windows.Forms.MessageBox.Show("You are trying to resize this window to a size too small to view all content.", "Trade-Ideas Pro", MessageBoxButtons.OK); // _resizingDockWindow = false; // } // else // { // _resizingDockWindow = false; // } // _lastDockWindowWidth = this.Width; // _lastDockWindowHeight = this.Height; // //Debug.WriteLine($"Windows too small: {tooSmall}"); //} } #region Market Data /// /// Starts the Market Data Service for this form. /// Add callbacks for the Real Time Trade and on connection fails to the Market Data Service. /// private void InitializeMarketDataClient() { try { if (MarketDataClient.Created) MarketDataClient.Instance.AddCallbacks(UpdateFromRealTimeTrade, OnMarketDataClientConnectionFailed); } catch (Exception ex) { TILogger.Error($"Unable to start Market Data service: {ex.Message}", ex); } } /// /// Returns the name of the client source that can be used /// to subscribe to the Market Data Service /// private string _marketDataClientSource => $"single-stock-window-{_id}"; /// /// Ends the subscription to the Market Data Service removing the client source /// and the data update callback /// private void UnsubscribeMarketDataClientOnFormClose() { if (MarketDataClient.Created) { MarketDataClient.Instance.UnsubscribeSource(_marketDataClientSource); MarketDataClient.Instance.OnTradeQuoteRemove(UpdateFromRealTimeTrade); } } /// /// Ends the subscription to the Market Data Service keeping the client source. /// This is valid for replacing the symbol in the current subscription. /// private void UnsubscribeMarketDataClient() { if (MarketDataClient.Created) MarketDataClient.Instance.UnSubscribeTradeQuote(_marketDataClientSource, new List { _currentSymbol }); } /// /// Initiates subscription to the Market Data Service with a given symbol /// private void SubscribeMarketDataClient() { if (MarketDataClient.Created) MarketDataClient.Instance.SubscribeTradeQuote(_marketDataClientSource, _currentSymbol); } /// /// Receives real time data from the Market Data Service. /// It is currently used to get the last price in real time. /// /// The real time trade information received from the Market Data Service private void UpdateFromRealTimeTrade(TradeQuote realTimeTrade) { this.BeginInvokeIfRequired(delegate { if (realTimeTrade.Symbol != _currentSymbol) return; var now = ServerFormats.Now; var marketOpenLocal = GuiEnvironment.GetMarketOpenLocalTime(); var marketCloseLocal = GuiEnvironment.GetMarketCloseLocalTime(); var isMarketOpen = now > marketOpenLocal && now < marketCloseLocal; var isPreMarket = _outsideMarketHours && now.IsPreMarketWithTimeCheck(); var isPostMarket = _outsideMarketHours && now.IsPostMarketWithTimeCheck(); if (null != _detailsControl && (isMarketOpen || isPreMarket || isPostMarket)) _detailsControl.SetLastPriceOnDisplay((double)realTimeTrade.TradePrice); else if (null != _chromiumDetailsControl && (isMarketOpen || isPreMarket || isPostMarket)) _chromiumDetailsControl.SetLastPrice((double)realTimeTrade.TradePrice); }); } /// /// This method callback captures the connection errors with the Market Data Service /// /// The error message sent by the Market Data Service private void OnMarketDataClientConnectionFailed(string message) => TILogger.Error($"Market Data service connection failed: {message}", null); #endregion /// /// Make Show Chrome Dev Tools menu item visible if in Development mode. /// public void EnableShowChromeDevToolsMenuItem() { this.InvokeIfRequired(delegate () { if (GuiEnvironment.DevelopmentMode) showChromeDevToolsToolStripMenuItem.Visible = true; }); } private void showChromeDevToolsToolStripMenuItem_Click(object sender, EventArgs e) { if (null != _chromiumDetailsControl) _chromiumDetailsControl.ShowDevTools(); } } public enum FontSize { SMALL, NORMAL, LARGE } }