예제 #1
0
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        //
        public TestMarket()
        {
            InitializeComponent();

            // Set application information - do this before hubs are instantiated.
            string  basePath = UV.Lib.IO.FilesIO.GetPathToDirName(System.IO.Directory.GetCurrentDirectory(), "Ambre", true);
            AppInfo info     = AppInfo.GetInstance();

            info.BasePath     = basePath;
            info.LogDirectory = string.Format("{0}{1}", info.LogDirectory, UV.Lib.IO.FilesIO.GetTodaysLogDirAndClean(info.LogPath));


            // Instantiate the API.
            m_TTServices = TTApiService.GetInstance();
            m_TTServices.ServiceStateChanged += new EventHandler(TTServices_ServiceStateChanged);


            // Instantiate hubs
            //  but do not Connect until the user name/pw has been authenticated.
            m_Market = new Markets.MarketTTAPI();
            m_Market.Start();
            //m_Market.MarketStatusChanged += new EventHandler<UVLib.MarketHubs.MarketStatusChangedEventArg>(Market_MarketStatusChanged);
            //m_Market.FoundServiceResource += new EventHandler<MarketFoundServiceResource>(Market_MarketFoundServiceResource);
            m_Market.MarketStatusChanged += new EventHandler(Market_MarketStatusChanged);
            m_Market.FoundResource       += new EventHandler(Market_MarketFoundServiceResource);

            timer1.Tick    += new EventHandler(timer1_Tick);
            timer1.Interval = 1000;
        }
예제 #2
0
        //
        //
        #endregion// members


        #region Constructors
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        //
        public Monitor()
        {
            InitializeComponent();

            //Misty.Lib.Application.AppInfo appInfo = Misty.Lib.Application.AppInfo.GetInstance("Monitor",true);
            string currentPath = System.IO.Directory.GetCurrentDirectory();

            Log = new LogHub("Monitor", string.Format("{0}\\Logs\\", currentPath), true, LogLevel.ShowAllMessages);
            DateTime now = Log.GetTime();

            m_Writer = new DropQueueWriter(string.Format("{0}\\Logs\\", currentPath), string.Format("data_{0}_{1}.txt", now.ToString("yyyyMMdd"), now.ToString("HHmmss")), this.Log);
            m_Writer.Start();

            string s = string.Format("{0}\\user_female.ico", currentPath);

            if (System.IO.File.Exists(s))
            {
                this.Icon = Icon.ExtractAssociatedIcon(s);
            }

            // Instantiate TT API.
            m_TTService = TTServices.TTApiService.GetInstance();
            m_TTService.ServiceStateChanged += new EventHandler(TTService_ServiceStateChanged);
            m_TTService.Start(true);
        }
예제 #3
0
        }//SetText()

        //
        //
        #endregion//Private Methods


        #region External Service Event Handlers
        // *****************************************************************
        // ****                Form Event Handlers                     ****
        // *****************************************************************
        //
        //
        //
        // ****         TTServices_ServiceStateChanged()            ****
        //
        private void TTServices_ServiceStateChanged(object sender, EventArgs eventArgs)
        {
            if (m_IsAppShuttingDown)
            {
                return;
            }
            if (eventArgs is TTServices.TTApiService.ServiceStatusChangeEventArgs)
            {
                TTServices.TTApiService.ServiceStatusChangeEventArgs e = (TTServices.TTApiService.ServiceStatusChangeEventArgs)eventArgs;
                if (e.IsConnected)
                {
                    Log.NewEntry(Misty.Lib.Hubs.LogLevel.Major, "TTServices connected.");
                    SetText(txtAPIConnected, "connected");
                    if (m_MarketHub != null)
                    {
                        m_MarketHub.Connect();
                    }
                    if (m_FillHub != null)
                    {
                        m_FillHub.Connect();
                    }
                }
                else
                {
                    Log.NewEntry(Misty.Lib.Hubs.LogLevel.Major, "TTServices disconnected.");
                    //SetText(txtAPIConnected, "disconnected");
                    if (m_TTServices != null)
                    {
                        m_TTServices.Dispose();
                        m_TTServices = null;
                    }
                }
            }
        }// TTServices_ServiceStateChanged()
예제 #4
0
        //
        //
        #endregion//Private Event Handlers


        #region Form Event Handlers
        // *****************************************************************
        // ****                     Event Handlers                     ****
        // *****************************************************************
        //
        //
        private void button_Click(object sender, EventArgs e)
        {
            // Validate
            if (!(sender is Button))
            {
                return;
            }
            Button button = (Button)sender;

            //
            // Process button click
            //
            if (button == buttonStart)
            {
                TTApiService service = TTApiService.GetInstance();
                service.Start(this.checkBoxUseXTraderFollowLogin.Checked);
            }
            else if (button == buttonGetProducts)
            {
                int selectedIndex = listBoxMarkets.SelectedIndex;
                if (selectedIndex >= 0 && selectedIndex < listBoxMarkets.Items.Count)
                {
                    listBoxProducts.ClearSelected();                               // deselect any selected products.
                    listBoxProducts.Items.Clear();                                 // remove products from list.
                    m_Market.RequestProducts((string)listBoxMarkets.SelectedItem); // Request new products.
                }
            }
            else if (button == buttonGetInstruments)
            {
                int selectedIndex = listBoxProducts.SelectedIndex;
                if (selectedIndex >= 0 && selectedIndex < listBoxProducts.Items.Count)
                {
                    listBoxInstruments.ClearSelected();                                 // deselect any selected products.
                    listBoxInstruments.Items.Clear();                                   // remove products from list.
                    string  productUniqueName = ((string)listBoxProducts.SelectedItem); // Request new products.
                    Product product;
                    if (m_Products.TryGetValue(productUniqueName, out product))
                    {
                        m_Market.RequestInstruments(product);
                    }
                }
            }
            else if (button == buttonStop)
            {
            }
            else if (button == buttonExit)
            {
                Shutdown();
                this.Close();
            }
            else if (button == buttonUpdate)
            {
                ToggleUpdateState();
                //UpdateMarket();
            }
            else
            {   // unknown button
                return;
            }
        }
예제 #5
0
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        //
        //
        //
        public HedgeOptionsDatabaseWriterTest()
        {
            m_Log = new LogHub("BRELibLog", string.Format("{0}{1}", UV.Lib.Application.AppInfo.GetInstance().BasePath,
                                                          UV.Lib.Application.AppInfo.GetInstance().LogDirectory), true, LogLevel.ShowAllMessages);
            InitializeComponent();
            m_UIDispatcher = Dispatcher.CurrentDispatcher;

            DatabaseInfo dbInfo = DatabaseInfo.Create(DatabaseInfo.DatabaseLocation.bredev);

            dbInfo.UserName        = "******";
            dbInfo.UserPW          = "test";
            m_DatabaseReaderWriter = new DatabaseReaderWriter(dbInfo);
            m_DatabaseReaderWriter.QueryResponse += new EventHandler(DatabaseReaderWriter_QueryResponse);

            this.textBoxExchangeName.Text = "CME";
            this.textBoxProductName.Text  = "GE";
            this.textBoxProductType.Text  = "Spread";

            m_TTAPIService = TTApiService.GetInstance();
            m_TTAPIService.ServiceStateChanged += new EventHandler(TTApiService_ServiceStateChanged);
            m_TTAPIService.Start(true);

            m_Market = new MarketTTAPI();
            m_Market.MarketStatusChanged += new EventHandler(MarketTTAPI_MarketStatusChanged);
            m_Market.FoundResource       += new EventHandler(MarketTTAPI_MarketFoundServiceResource);
            m_Market.Start();
            m_Market.Connect();                             // initialize connection to API.
        }
예제 #6
0
        //
        #endregion// members


        #region Constructors
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        /// <summary>
        /// Immediately starts the thread.  A TT Session must already exist when this is created.
        /// </summary>
        /// <param name="listenerName"></param>
        /// <param name="aLog"></param>
        public OrderListener(string listenerName, Hub parentHub)
        {
            m_ParentHub = parentHub;
            this.Log    = m_ParentHub.Log;
            this.m_Name = listenerName;
            m_TTService = TTApiService.GetInstance();
        }
예제 #7
0
        //
        //
        #endregion//Constructors


        #region Properties
        // *****************************************************************
        // ****                     Properties                          ****
        // *****************************************************************
        //
        //
        #endregion//Properties


        #region Public Methods
        // *****************************************************************
        // ****                     Public Methods                      ****
        // *****************************************************************
        //
        //
        //
        //
        //
        //
        #endregion//Public Methods


        #region Private Methods
        // *****************************************************************
        // ****                     Private Methods                     ****
        // *****************************************************************
        //

        //
        private void Shutdown()
        {
            m_IsShuttingDown = true;
            if (m_Writer != null)
            {
                m_Writer.RequestStop();
                m_Writer = null;
            }
            if (m_TTService != null)
            {
                m_TTService.Dispose();
                m_TTService = null;
            }
            if (m_PriceListener != null)
            {
                m_PriceListener.Dispose();
                m_PriceListener = null;
            }
            if (m_FillListener != null)
            {
                m_FillListener.Dispose();
                m_FillListener = null;
            }
            if (m_OrderListener != null)
            {
                m_OrderListener.Dispose();
                m_OrderListener = null;
            }
            if (Log != null)
            {
                Log.RequestStop();
                Log = null;
            }
        }
예제 #8
0
 //
 //
 public override void Start()
 {
     // Locate required services
     Misty.Lib.Application.AppServices appServices = Misty.Lib.Application.AppServices.GetInstance();
     foreach (Misty.Lib.Application.IService service in appServices.GetServices(typeof(Markets.MarketTTAPI)))
     {
         this.AddHub((Markets.MarketTTAPI)service);
         break;
     }
     //foreach (Misty.Lib.Application.IService service in appServices.Services.Values)
     //    if (service is Markets.MarketTTAPI)
     //    {
     //        this.AddHub((Markets.MarketTTAPI)service);
     //        break;
     //    }
     if (m_Market == null)
     {
         throw new Exception("Failed to find required service.");
     }
     // Subscribe to TTApi
     if (m_TTService == null)
     {
         m_TTService = TTApiService.GetInstance();
         m_TTService.ServiceStateChanged += new EventHandler(TTService_ServiceStatusChanged);
     }
     base.Start();
 }//Start()
예제 #9
0
        //
        //
        #endregion// members


        #region Constructors
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        /// <summary>
        /// After constructing the drop rules, one can load a previous file or change
        /// parameters before writing.  The writers are created only after calling "Start()".
        /// </summary>
        /// <param name="fillHub"></param>
        public DropRules(FillHub fillHub)
        {
            // Create the unique user name.
            // UserLoginID + FillHubName (usually acct#)
            //
            TTApiService api = TTApiService.GetInstance();

            this.UniqueUserName = string.Format("{0}_{1}", api.LoginUserName, fillHub.Name);
            //this.UniqueUserName = fillHub.Name;
            this.m_FillHub             = fillHub;
            this.DropFileStartDateTime = fillHub.Log.GetTime();               // time stamp "label" used for archiving current drop file.

            m_StringifyOverrideTable = new Dictionary <Type, string[]>();
            m_StringifyOverrideTable.Add(m_FillHub.GetType(), new string[] { string.Empty, "GetAttributesDrop", "GetElementsDrop" });


            //#if (DEBUG)
            //BookDropPeriod = new TimeSpan(0, 5, 0);
            //PushToRepository = false;
            //#endif

            this.LastBookDrop    = fillHub.Log.GetTime().Subtract(this.BookDropPeriod).AddMinutes(5.0);
            this.m_LocalTimeLast = this.LastBookDrop;
            //this.NextResetDateTime = this.NextResetDateTime.Subtract(this.NextResetDateTime.TimeOfDay).Add(ResetTimeOfDay);
        }
        /// <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()
        }//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()
예제 #12
0
        //
        //
        #endregion// members


        #region Constructors
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        /// <summary>
        /// After constructing the drop rules, one can load a previous file or change
        /// parameters before writing.  The writers are created only after calling "Start()".
        /// </summary>
        /// <param name="fillHub"></param>
        public DropSimple(FillHub fillHub)
        {
            // Create the unique user name.
            TTApiService api = TTApiService.GetInstance();

            this.UniqueUserName        = string.Format("{0}_{1}", api.LoginUserName, fillHub.Name);
            this.m_FillHub             = fillHub;
            this.DropFileStartDateTime = fillHub.Log.GetTime();               // time stamp "label" used for archiving current drop file.

            m_StringifyOverrideTable = new Dictionary <Type, string[]>();
            m_StringifyOverrideTable.Add(m_FillHub.GetType(), new string[] { string.Empty, "GetAttributesDrop", "GetElementsDrop" });

            this.LastBookDrop    = fillHub.Log.GetTime().Subtract(this.BookDropPeriod).AddMinutes(5.0);
            this.m_LocalTimeLast = this.LastBookDrop;
        }
예제 #13
0
        }//Service_ServiceStopped()

        /// <summary>
        /// When the TT gets connected, notify the users.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private void Service_ServiceStateChanged(object sender, EventArgs eventArgs)
        {
            if (sender is TTApiService)
            {
                TTApiService ttApi = (TTApiService)sender;

                // Notify the user the TT API is connected successfully or not.
                if (ttApi.IsRunning)
                {
                    Log.NewEntry(LogLevel.Major, "TT API connected successfully!");
                }
                else
                {
                    Log.NewEntry(LogLevel.Warning, "TT API connecting failed!");
                }
            }
        }//Service_ServiceStateChanged()
예제 #14
0
        //
        //
        //
        #endregion//Constructors



        #region no Public Methods
        // *****************************************************************
        // ****                     Public Methods                      ****
        // *****************************************************************
        //
        //
        //
        //
        //
        //
        #endregion//Public Methods


        #region Private Methods
        // *****************************************************************
        // ****                     Private Methods                     ****
        // *****************************************************************
        //
        //
        //
        // ****             Shutdown()              ****
        //
        /// <summary>
        /// Complete shutdown of all hubs and their threads.
        /// </summary>
        private void Shutdown()
        {
            if (m_Market != null)
            {
                m_Market.RequestStop();
            }
            TTApiService ttService = TTApiService.GetInstance();

            if (ttService != null)
            {
                ttService.Dispose();
            }
            if (timer1 != null)
            {
                timer1.Stop();
                timer1.Enabled = false;
                timer1.Dispose();
            }
        }// Shutdown()
예제 #15
0
        // *****************************************************************
        // ****                     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().
예제 #16
0
        }//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();
        }
예제 #17
0
        //
        #endregion// members


        #region Constructors
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        /// <summary>
        /// Immediately starts the thread.  A TT Session must already exist when this is created.
        /// </summary>
        /// <param name="listenerName"></param>
        /// <param name="aLog"></param>
        public OrderListenerMsgr(string listenerName, LogHub aLog)
        {
            this.Log    = aLog;
            this.m_Name = listenerName;
            m_TTService = TTApiService.GetInstance();
        }
예제 #18
0
        private ConcurrentQueue <Job> m_InQueue = new ConcurrentQueue <Job>();  // In-Out queue, Jobs pushed from outsider threads.

        //
        #endregion// members


        #region Constructors
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        public PriceListener(string priceListenerName, LogHub aLog)
        {
            this.Log     = aLog;
            m_TTServices = TTApiService.GetInstance();
            m_Name       = priceListenerName;
        }
예제 #19
0
        }// 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()
예제 #20
0
        }     //TryGetProduct()

        //
        // *****************************************************************
        // ****                     Start()                             ****
        // *****************************************************************
        /// <summary>
        /// This is called after all services exist, but before any services is connected.
        /// </summary>
        public override void Start()
        {
            m_TTService = TTApiService.GetInstance();
            m_TTService.ServiceStateChanged += new EventHandler(this.HubEventEnqueue); // Once TTAPI is connected, I can connect automatically.
            base.Start();
        }//Start().
예제 #21
0
 public FillListener()
 {
     this.Name   = "FillListener";
     m_TTService = TTApiService.GetInstance();
 }
예제 #22
0
        public FilterType m_FilterType;                       // The filter type in the last recent book.
        #endregion                                            // members


        #region Constructors
        // *****************************************************************
        // ****                     Constructors                        ****
        // *****************************************************************
        /// <summary>
        /// Immediately starts the thread.  A TT Session must already exist when this is created.
        /// </summary>
        /// <param name="listenerName"></param>
        /// <param name="aLog"></param>
        public FillListener(string listenerName)
        {
            this.Name   = listenerName;
            m_TTService = TTApiService.GetInstance();
        }