/// <summary> /// GUI constructor to have both of the paths as members and log as well as drop file player, audit trail player. /// </summary> public AmbreRecoveryViewer() { InitializeComponent(); typeof(MarketTTAPI).ToString(); // Create log viewer. bool isLogViewerVisible = true; Log = new LogHub(ApplicationName, AppInfo.GetInstance().LogPath, isLogViewerVisible, LogLevel.ShowAllMessages); // Create app service and get useful paths. AppServices appAmbreMaintenanceServices = AppServices.GetInstance(ApplicationName, true); m_RepositoryDropFilePath = appAmbreMaintenanceServices.Info.DropPath; m_AuditTrailFilePath = appAmbreMaintenanceServices.Info.DropPath; if (m_DebugMode) { m_ReferenceDropFilePath = m_RepositoryDropFilePath.Replace(ApplicationName, ReferenceApplicationName); } else { m_ReferenceDropFilePath = m_RepositoryDropFilePath.Replace(string.Format("\\{0}", ApplicationName), ""); } Log.NewEntry(LogLevel.Minor, "The default paths to operate are {0} and {1}.", m_RepositoryDropFilePath, m_ReferenceDropFilePath); if (!System.IO.Directory.Exists(m_ReferenceDropFilePath)) { m_ReferenceDropFilePath = m_RepositoryDropFilePath.Replace(ApplicationName, "Ambre"); Log.NewEntry(LogLevel.Major, "The default path for reference Ambre system does not exist, and the operating path becomes {0}.", m_ReferenceDropFilePath); if (!System.IO.Directory.Exists(m_ReferenceDropFilePath)) { Log.NewEntry(LogLevel.Major, "The changed path still does not exist. and the program can not proceed."); return; } } // Create market tt api service and tt api service. m_MarketTTAPIService = new MarketTTAPI(); m_MarketTTAPIService.Start(); m_TTAPIService = TTApiService.GetInstance(); m_TTAPIService.Log = this.Log; m_TTAPIService.ServiceStateChanged += new EventHandler(TTAPIService_ServiceStateChanged); m_TTAPIService.Start(); // Sample for the user login name and fill hub name. textBoxUserName.Text = "BETSIM"; textBoxFillHubName.Text = "2014"; m_UserName = textBoxUserName.Text; m_FillHubOrFillManagerName = textBoxFillHubName.Text; // Create file players. m_DropFilePlayer = new DropFilePlayer(m_ReferenceDropFilePath, Log); // Add closing form event trigger. this.FormClosing += new FormClosingEventHandler(AmbreRecoveryViewer_Closing); // Find all existing audit trail files. Also in this block, toggle the earliest and latest date time to the GUI. m_RepoFileList = new List <string>(); LoadAllAuditTrailFiles(); }//AmbreRecoveryViewer()
private List <string> m_PropertyFormat = new List <string>(); // column formats // // // #endregion// members #region Constructors // ***************************************************************** // **** Constructors **** // ***************************************************************** public FormFillBookViewer(Ambre.TTServices.Markets.MarketTTAPI priceHub, FillHub aFillHub) { InitializeComponent(); Log = aFillHub.Log; m_FillHub = aFillHub; m_Market = priceHub; UpdateNewFills(); }// FormFillBookViewer()
}//buttonExit_Click() /// <summary> /// Form closing event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AmbreRecoveryViewer_Closing(object sender, FormClosingEventArgs e) { // Exit. this.FormClosing -= new FormClosingEventHandler(AmbreRecoveryViewer_Closing); // Delete the files we copied. if (m_RepoFileList.Count > 0) { try { foreach (string filePath in m_RepoFileList) { System.IO.File.Delete(filePath); } } catch (Exception ex) { Log.NewEntry(LogLevel.Major, "Failed to delete copied files and the error is {0}.", ex); } } // Shut down the fill hub. if (m_AuditTrailFillHub != null) { m_AuditTrailFillHub.RequestSubstractEventHandler(); m_AuditTrailFillHub.RequestStop(); m_AuditTrailFillHub = null; } // Shut down the services. if (m_MarketTTAPIService != null) { m_MarketTTAPIService.RequestStop(); m_MarketTTAPIService = null; } if (m_TTAPIService != null) { m_TTAPIService.ServiceStateChanged -= new EventHandler(TTAPIService_ServiceStateChanged); m_TTAPIService.RequestStop(); m_TTAPIService = null; } // Shut down the log. if (Log != null) { Log.NewEntry(LogLevel.Minor, "The form is closing."); Log.Flush(); Log.RequestStop(); Log = null; } }//Form_Closing()
/// <summary> /// In the time to not connect to TT, the developer may choose this method to create books. /// </summary> public void CreateBooksStatic(MarketTTAPI marketTTAPI) { // Create books for all the instruments without connecting to TT and using start method. MarketHub = marketTTAPI; foreach (BookLifo book in m_FillBooks.Values) { PositionBookChangedEventArgs eventArgs = new PositionBookChangedEventArgs(); eventArgs.Instrument = book.Name; eventArgs.Sender = this; OnPositionBookCreated(eventArgs); MarketHub.RequestInstruments(m_BookNameMap[book.Name].Key); } }
// ***************************************************************** // **** Private Methods **** // ***************************************************************** // // // // // // **** ShutDown() **** // /// <summary> /// Called when the form is about to close to release resources nicely. /// </summary> private void ShutDown() { if (!m_IsAppShuttingDown) { m_IsAppShuttingDown = true; if (Log != null) { Log.RequestStop(); Log = null; } if (m_FillHub != null) { //m_FillHub.PositionBookCreated -= new EventHandler(FillHub_PositionBookCreated); //m_FillHub.PositionBookChanged -= new EventHandler(FillHub_PositionBookChanged); //m_FillHub.PositionBookPnLChanged -= new EventHandler(FillHub_PositionBookPnLChanged); m_FillHub.Request(new Misty.Lib.OrderHubs.OrderHubRequest(Misty.Lib.OrderHubs.OrderHubRequest.RequestType.RequestShutdown)); m_FillHub = null; } if (m_MarketHub != null) { m_MarketHub.RequestStop(); m_MarketHub = null; } if (m_TTServices != null) { m_TTServices.ServiceStateChanged -= new EventHandler(TTServices_ServiceStateChanged); m_TTServices.Dispose(); m_TTServices = null; } if (m_TalkerHub != null) { m_TalkerHub.ServiceStateChanged -= new EventHandler(TalkerHub_ServiceStateChanged); m_TalkerHub.Request(TalkerHubRequest.StopService); //m_TalkerHub = null; } } }//Shutdown().
}//constructor // // private void InitializeServices() { AppInfo info = AppInfo.GetInstance("Bret"); bool isLogViewerVisible = false; #if (DEBUG) isLogViewerVisible = true; #endif Log = new LogHub("TalkerForm", info.LogPath, isLogViewerVisible, LogLevel.ShowAllMessages); // Instantiate TT API. m_TTServices = TTServices.TTApiService.GetInstance(); m_TTServices.ServiceStateChanged += new EventHandler(TTServices_ServiceStateChanged); m_TTServices.Start(true); // Instantiate hubs m_MarketHub = new MarketTTAPI(); m_MarketHub.Log.IsViewActive = isLogViewerVisible; //m_MarketHub.InstrumentChanged += new EventHandler(MarketHub_InstrumentChanged); m_MarketHub.Start(); m_FillHub = new FillHub(string.Empty, isLogViewerVisible); m_FillHub.MarketHub = m_MarketHub; //m_FillHub.PositionBookCreated += new EventHandler(FillHub_PositionBookCreated); //m_FillHub.PositionBookChanged += new EventHandler(FillHub_PositionBookChanged); //m_FillHub.PositionBookPnLChanged += new EventHandler(FillHub_PositionBookPnLChanged); m_FillHub.Start(); m_TalkerHub = new TalkerHub(isLogViewerVisible); m_TalkerHub.ServiceStateChanged += new EventHandler(TalkerHub_ServiceStateChanged); m_TalkerHub.RequestAddHub(m_FillHub); m_TalkerHub.Start(); }
// ***************************************************************** // **** Constructors **** // ***************************************************************** // // // public SpreadViewer() { InitializeComponent(); this.FormClosing += new FormClosingEventHandler(FormClosedByUser); // Create the needed services. typeof(MarketTTAPI).ToString(); AppServices appServices = AppServices.GetInstance("SpreadPriceGenerator"); appServices.Info.RequestShutdownAddHandler(new EventHandler(this.RequestShutdown)); appServices.ServiceStopped += new EventHandler(Service_ServiceStopped); // Write service names to config gile if it does not exist. string configPath = string.Format("{0}{1}", appServices.Info.UserConfigPath, m_ConfigFileName); if (!System.IO.File.Exists(configPath)) { DialogResult result = System.Windows.Forms.DialogResult.Abort; result = MessageBox.Show(string.Format("Config file does not exist! \r\nFile: {0}\r\nDir: {1}\r\nShould I create an empty one?", m_ConfigFileName, appServices.Info.UserConfigPath), "Config file not found", MessageBoxButtons.YesNo); if (result == System.Windows.Forms.DialogResult.Yes) { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(configPath, false)) { writer.WriteLine("<Ambre.TTServices.Markets.MarketTTAPI/>"); writer.WriteLine("<Ambre.TTServices.TTApiService FollowXTrader=True/>"); writer.Close(); } } } // Create logs. bool isLogViewerVisible = true; Log = new LogHub("SpreadProjectLogs", AppInfo.GetInstance().LogPath, isLogViewerVisible, LogLevel.ShowAllMessages); // Load the services from config file and start services. appServices.LoadServicesFromFile(m_ConfigFileName); foreach (IService service in appServices.GetServices()) { this.AddService(service); } string filePath = AppServices.GetInstance().Info.UserPath; filePath = string.Format("{0}ProductSpreadInfo.csv", filePath); SpreadInfoReader.TryReadSpreadInfoTable(filePath, Log, out m_CSVSpreadInfoReader); // Get the market tt api service. IService iService = null; if (!appServices.TryGetService("MarketTTAPI", out iService)) { Log.NewEntry(LogLevel.Warning, "Failed to find the market tt api service."); return; } m_MarketTTAPI = (MarketTTAPI)iService; // Set market reading timer. m_MarketReadTimer = new System.Timers.Timer(); m_MarketReadTimer.Interval = 2000; m_MarketReadTimer.Elapsed += new System.Timers.ElapsedEventHandler(MarketReadingTimer_Elapsed); m_MarketReadTimer.Start(); // Start and connect all the services. appServices.Start(); appServices.Connect(); }//SpreadViewer()
}//HubEventHandler() // // // ********************************************************* // **** Process Hub Request **** // ********************************************************* /// <summary> /// Direct requests from outsiders for managing this TalkerHub. /// </summary> private void ProcessRequest(TalkerHubEventArg eventArg) { switch (eventArg.Request) { case TalkerHubRequest.AmberXLConnect: // try to connect to Excel if (m_SocketBreTalker == null) { m_SocketBreTalker = new SocketManager(); m_SocketBreTalker.Connected += new EventHandler(HubEventEnqueue); m_SocketBreTalker.Disconnected += new EventHandler(HubEventEnqueue); m_SocketBreTalker.MessageReceived += new EventHandler(HubEventEnqueue); } if (!TryToConnectToExcel()) { // Failed to connect. // TODO: Put this request in our waiting queue and try again periodically. m_AmbreXLReconnectFailureCount++; m_AmbreXLReconnectCounter = Math.Min(AmbreXLReconnectCounterMin * m_AmbreXLReconnectFailureCount, AmbreXLReconnectCounterMax); Log.NewEntry(LogLevel.Major, "ProcessRequest: Failed {0} times to connect to socket. Try again in {1:0.0} seconds.", m_AmbreXLReconnectFailureCount, (m_AmbreXLReconnectCounter / 1000.0)); } else { Log.NewEntry(LogLevel.Major, "ProcessRequest: Connected to Socket."); } break; case TalkerHubRequest.AmbreXLDisconnect: m_SocketBreTalker.StopConversation(); break; case TalkerHubRequest.StopService: if (m_SocketBreTalker != null) { m_SocketBreTalker.StopConversation(); if (m_SocketBreTalker.IsServing) { m_SocketBreTalker.StopServer(); } } this.Stop(); break; case TalkerHubRequest.RequestAddHub: if (eventArg.Data != null) { foreach (object newHub in eventArg.Data) { if (newHub is FillHub) { FillHub newFillHub = (FillHub)newHub; FillHub oldFillHub; if (m_FillHubs.TryGetValue(newFillHub.Name, out oldFillHub)) { // User must want to replace fill hub with same name... m_FillHubs.Remove(oldFillHub.Name); oldFillHub.PositionBookCreated -= new EventHandler(HubEventEnqueue); // unsubscribe to this old hub oldFillHub.PositionBookChanged -= new EventHandler(HubEventEnqueue); oldFillHub.PositionBookDeleted -= new EventHandler(HubEventEnqueue); } m_FillHubs.Add(newFillHub.Name, newFillHub); newFillHub.PositionBookCreated += new EventHandler(HubEventEnqueue); // subscribe to this new hub newFillHub.PositionBookChanged += new EventHandler(HubEventEnqueue); newFillHub.PositionBookDeleted += new EventHandler(HubEventEnqueue); } // if new hub is FillHub type. else if (newHub is MarketTTAPI) { //UV.Lib.MarketHubs.MarketHub marketHub = (UV.Lib.MarketHubs.MarketHub)newHub; MarketTTAPI marketHub = (MarketTTAPI)newHub; m_MarketHub = marketHub; } } //for each hub passed to us. } // if request contains data. break; default: break; } }//ProcessRequest()
}// ProcessCreateBook() // // // ********************************************* // **** ProcessServiceStateChange() **** // ********************************************* /// <summary> /// Called when someone (us or external user) wants to /// change our current ServiceState. /// Notes: /// 1) The states are processed in reverse order so that if/when other states are included /// in the enum, we will consider ourselves in that state if its higher or equal to the ones implemented. /// </summary> /// <param name="request"></param> private void ProcessServiceStateChange(RequestEventArg <RequestCode> request) { ServiceStates nextState = m_ServiceState; // change this if you want to move to a new state. ServiceStates requestedState = (ServiceStates)request.Data[0]; Log.NewEntry(LogLevel.Warning, "ProcessStateChange: [{1}] Processing {0}.", request, m_ServiceState); if (m_ServiceState >= ServiceStates.Stopped) { // Ok. We must shut down now. m_Requests.Recycle(request); base.Stop(); } else if (m_ServiceState >= ServiceStates.Stopping) { // We are trying to stop. But havent stopped yet. // Check that we can stop now. bool isReadyToStop = true; // todo: do the needed checks here. if (isReadyToStop) { m_Listener.Dispose(); nextState = ServiceStates.Stopped; // Okay. We can stop - set my state. this.HubEventEnqueue(request); // pulse this request again immediately. } else { m_PendingQueue.AddPending(request, 1); // wait, then try to stop again. } } else if (m_ServiceState >= ServiceStates.Running) { // Here we are in Running state or better. if (requestedState >= ServiceStates.Stopping) { // user wants to stop now. nextState = ServiceStates.Stopping; this.HubEventEnqueue(m_Requests.Get(RequestCode.ServiceStateChange, ServiceStates.Stopped)); } else { // Right now this is the only active state. // However, we could go onto other states.. like paused, if desired in future. Log.NewEntry(LogLevel.Warning, "ProcessStateChange: Ignoring request {0}", request); m_Requests.Recycle(request); } } else if (m_ServiceState >= ServiceStates.Started) { // We are atleast started now. if (requestedState >= ServiceStates.Stopping) { // User wants to stop. Thats okay. nextState = ServiceStates.Stopping; this.HubEventEnqueue(m_Requests.Get(RequestCode.ServiceStateChange, ServiceStates.Stopped)); } else if (requestedState >= ServiceStates.Running) { // Try to connect all services we need to be running. // Locate services now. List <IService> iServices; if (m_TTService == null) { iServices = m_Services.GetServices(typeof(TTApiService)); if (iServices.Count > 0) { Log.NewEntry(LogLevel.Major, "ProcessStateChange: Starting. Found TTAPI service. "); m_TTService = (TTApiService)iServices[0]; } else { Log.NewEntry(LogLevel.Error, "ProcessStateChange: Failed to locate TTAPI Service."); } } if (m_Market == null) { Log.NewEntry(LogLevel.Major, "ProcessStateChange: Starting. Found TT Market. "); iServices = m_Services.GetServices(typeof(MarketTTAPI)); if (iServices.Count > 0) { m_Market = (MarketTTAPI)iServices[0]; m_Market.FoundResource += new EventHandler(HubEventEnqueue); // subscribe to found resources. } else { Log.NewEntry(LogLevel.Error, "ProcessStateChange: Failed to locate TTAPI Market hub."); } } // TODO: Continue to do connections here. if (m_Market != null && m_TTService != null) { if (m_Listener == null) { m_Listener = new OrderListener("Listener", this); m_Listener.Start(); } } // Try to connect. bool isReadyToRun = true; isReadyToRun = (m_TTService != null && m_TTService.IsRunning) && isReadyToRun; // non-Lazy isReadyToRun = (m_Market != null) && isReadyToRun; if (isReadyToRun) { // Transition to Running state! nextState = ServiceStates.Running; if (requestedState > ServiceStates.Running) { HubEventEnqueue(request); // resubmit request since its more than Running. } else { m_Requests.Recycle(request); } } else { Log.NewEntry(LogLevel.Major, "ProcessStateChange: Cannot proceed to state {0}. Not connected. Wait and try again.", requestedState); m_PendingQueue.AddPending(request, 2); } } else { } } else if (m_ServiceState >= ServiceStates.Unstarted) { // We are marked as unstarted, but since we are here, we must at least be started. nextState = ServiceStates.Started; if (requestedState > ServiceStates.Started) { this.HubEventEnqueue(request); // resubmit this request since user requested more. } else { m_Requests.Recycle(request); } } else { Log.NewEntry(LogLevel.Warning, "ProcessStateChange: Unknown service state {0}", m_ServiceState);// This should never happen } // Exit - report service state change if any. if (m_ServiceState != nextState) { // Our service state has changed. ServiceStates prevState = m_ServiceState; // save previous state. m_ServiceState = nextState; // accept new state. OnServiceStateChanged(prevState, m_ServiceState); } }//ProcessServiceStateChange()