Exemplo n.º 1
0
        public void DockInstrument(Instrument dockedInstrument)
        {
            InstrumentUpgradeError          = false;
            BadGasHookup                    = false;
            BadPumpTubingDetectedDuringBump = false;
            BadPumpTubingDetectedDuringCal  = false;
            IsInstrumentReplaced            = false;

            if (dockedInstrument != null)   // docked
            {
                Instrument = (Instrument)dockedInstrument.Clone();

                DockedTime     = DateTime.UtcNow;
                DockProcessing = true;

                Log.TimingBegin("DOCK TO GREEN");
            }
            else             // undocked
            {
                Instrument = new Instrument();

                InitialInstrumentSettingsNeeded = true;
                NextUtcCalibrationDate          = NextUtcBumpDate = null;
                IsInstrumentInSystemAlarm       = false;

                DockedTime     = DateTime.SpecifyKind(DomainModelConstant.NullDateTime, DateTimeKind.Utc);
                DockProcessing = false;
            }
        }
Exemplo n.º 2
0
        public USeMarketData Clone()
        {
            USeMarketData clone = new USeMarketData();

            clone.Instrument         = Instrument.Clone();
            clone.AskPrice           = AskPrice;
            clone.AskSize            = AskSize;
            clone.BidPrice           = BidPrice;
            clone.BidSize            = BidSize;
            clone.OpenPrice          = OpenPrice;
            clone.HighPrice          = HighPrice;
            clone.LowPrice           = LowPrice;
            clone.LastPrice          = LastPrice;
            clone.ClosePrice         = ClosePrice;
            clone.PreClosePrice      = PreClosePrice;
            clone.UpperLimitPrice    = UpperLimitPrice;
            clone.LowerLimitPrice    = LowerLimitPrice;
            clone.PreSettlementPrice = PreSettlementPrice;
            clone.SettlementPrice    = this.SettlementPrice;
            clone.OpenInterest       = this.OpenInterest;
            clone.Volume             = Volume;
            clone.Turnover           = Turnover;
            clone.UpdateTime         = UpdateTime;
            clone.QuoteDay           = this.QuoteDay;
            clone.QuoteTime          = this.QuoteTime;
            clone.AvgPrice           = this.AvgPrice;
            clone.SpeculateRadio     = this.SpeculateRadio;
            return(clone);
        }
Exemplo n.º 3
0
        public AlgoParams Clone()
        {
            var Clone = new AlgoParams();

            Clone.I                             = I == null ? null : I.Clone();
            Clone.R1                            = R1;
            Clone.R2                            = R2;
            Clone.IsMock                        = IsMock;
            Clone.IsReplayMode                  = IsReplayMode;
            Clone.IsHedgeAlgo                   = IsHedgeAlgo;
            Clone.ReplayTickFile                = ReplayTickFile;
            Clone.PositionsFile                 = PositionsFile;
            Clone.StateFile                     = StateFile;
            Clone.AlgoId                        = AlgoId;
            Clone.UseProbableTradeValue         = UseProbableTradeValue;
            Clone.IsMarketClosingSquareOff      = IsMarketClosingSquareOff;
            Clone.IsSquareOffTrigger            = IsSquareOffTrigger;
            Clone.IsMinProfitMust               = IsMinProfitMust;
            Clone.PercMarketDirectionChange     = PercMarketDirectionChange;
            Clone.PercSquareOffThreshold        = PercSquareOffThreshold;
            Clone.PercStoploss                  = PercStoploss;
            Clone.PercMinProfit                 = PercMinProfit;
            Clone.AllowShort                    = AllowShort;
            Clone.AllowLong                     = AllowLong;
            Clone.StartOrders                   = StartOrders == null ? null : new List <StockOrder>(StartOrders);
            Clone.StartOrdersCall               = StartOrdersCall == null ? null : new List <StockOrder>(StartOrdersCall);
            Clone.StartOrdersPut                = StartOrdersPut == null ? null : new List <StockOrder>(StartOrdersPut);
            Clone.Broker                        = Broker;
            Clone.MaxTotalPositions             = MaxTotalPositions;
            Clone.MaxLongPositions              = MaxLongPositions;
            Clone.MaxShortPositions             = MaxShortPositions;
            Clone.LongCeilingPrice              = LongCeilingPrice;
            Clone.ShortFloorPrice               = ShortFloorPrice;
            Clone.PercPositionSpacing           = PercPositionSpacing;
            Clone.OptionsIntradayBrokerage      = OptionsIntradayBrokerage;
            Clone.PercBrokerage                 = PercBrokerage;
            Clone.SquareOffBrokerageFactor      = SquareOffBrokerageFactor;
            Clone.MarginFraction                = MarginFraction;
            Clone.PercLossStopForDay            = PercLossStopForDay;
            Clone.NumNettLossTradesStopForDay   = NumNettLossTradesStopForDay;
            Clone.IsLimitLossPerDay             = IsLimitLossPerDay;
            Clone.NumTradesStopForDay           = NumTradesStopForDay;
            Clone.AlgoIntervalInSeconds         = AlgoIntervalInSeconds;
            Clone.IsConsiderPrevClosing         = IsConsiderPrevClosing;
            Clone.AllowInitialTickStabilization = AllowInitialTickStabilization;
            return(Clone);
        }
Exemplo n.º 4
0
        public USeMarketData2 Clone()
        {
            USeMarketData2 clone = new USeMarketData2();

            clone.Instrument         = Instrument.Clone();
            clone.AskPrice1          = AskPrice1;
            clone.AskSize1           = AskSize1;
            clone.BidPrice1          = BidPrice1;
            clone.BidSize1           = BidSize1;
            clone.AskPrice2          = AskPrice2;
            clone.AskSize2           = AskSize2;
            clone.BidPrice2          = BidPrice2;
            clone.BidSize2           = BidSize2;
            clone.AskPrice3          = AskPrice3;
            clone.AskSize3           = AskSize3;
            clone.BidPrice3          = BidPrice3;
            clone.BidSize3           = BidSize3;
            clone.AskPrice4          = AskPrice4;
            clone.AskSize4           = AskSize4;
            clone.BidPrice4          = BidPrice4;
            clone.BidSize4           = BidSize4;
            clone.AskPrice5          = AskPrice5;
            clone.AskSize5           = AskSize5;
            clone.BidPrice5          = BidPrice5;
            clone.BidSize5           = BidSize5;
            clone.OpenPrice          = OpenPrice;
            clone.HighPrice          = HighPrice;
            clone.LowPrice           = LowPrice;
            clone.LastPrice          = LastPrice;
            clone.ClosePrice         = ClosePrice;
            clone.PreClosePrice      = PreClosePrice;
            clone.UpperLimitPrice    = UpperLimitPrice;
            clone.LowerLimitPrice    = LowerLimitPrice;
            clone.PreSettlementPrice = PreSettlementPrice;
            clone.SettlementPrice    = this.SettlementPrice;
            clone.Volume             = Volume;
            clone.Turnover           = Turnover;
            clone.UpdateTime         = UpdateTime;

            return(clone);
        }
Exemplo n.º 5
0
        ///  <summary>
        ///
        ///  </summary>
        /// <param name="client"></param>
        /// <param name="instrument">If we're updating or cloning an instrument, pass it here.</param>
        ///  <param name="addingNew">True if adding a new instrument. False if we're updating an instrument.</param>
        ///  <param name="addingContFut">True if adding a continuous futures instrument.</param>
        public AddInstrumentManuallyWindow(IDataClient client, Instrument instrument = null, bool addingNew = true, bool addingContFut = false)
        {
            InitializeComponent();
            //make a clone for the editing
            Instrument inst;

            if (addingNew)
            {
                if (instrument == null)
                {
                    //brand new instrument
                    inst = new Instrument();
                    if (addingContFut)
                    {
                        inst.IsContinuousFuture = true;
                        inst.Type             = InstrumentType.Future;
                        inst.ContinuousFuture = new ContinuousFuture();
                    }
                }
                else
                {
                    //in this case we are cloning an existing instrument
                    inst    = (Instrument)instrument.Clone();
                    inst.ID = null;
                }
            }
            else
            {
                inst = (Instrument)instrument.Clone();
            }

            ViewModel   = new EditInstrumentViewModel(inst, client, this, DialogCoordinator.Instance);
            DataContext = ViewModel;

            //Window title
            if (addingNew)
            {
                Title          = "Add New Instrument";
                AddBtn.Content = "Add";
            }
            else
            {
                Title          = "Modify Instrument";
                AddBtn.Content = "Modify";
            }

            //sort the sessions so they're ordered properly...
            SessionsGrid.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("OpeningDay", System.ComponentModel.ListSortDirection.Ascending));

            //fill the RolloverRuleType combobox
            var rolloverTypes = MyUtils.GetEnumValues <ContinuousFuturesRolloverType>();

            foreach (ContinuousFuturesRolloverType t in rolloverTypes)
            {
                if (t != ContinuousFuturesRolloverType.Time)
                {
                    RolloverRuleType.Items.Add(t);
                }
            }

            //reactive bindings
            this.WhenActivated(d =>
            {
                d(this.OneWayBind(this.ViewModel,
                                  x => x.IsContinuousFuture,
                                  x => x.ContFutTabItem.Visibility,
                                  x => x ? Visibility.Visible : Visibility.Hidden));
            });
        }
Exemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="instrument">If we're updating or cloning an instrument, pass it here.</param>
        /// <param name="addingNew">True if adding a new instrument. False if we're updating an instrument.</param>
        /// <param name="addingContFut">True if adding a continuous futures instrument.</param>
        public AddInstrumentManuallyWindow(Instrument instrument = null, bool addingNew = true, bool addingContFut = false)
        {
            InitializeComponent();

            //If it's a continuous future, make the continuous future tab visible
            if ((instrument != null && instrument.IsContinuousFuture) ||
                addingContFut)
            {
                ContFutTabItem.Visibility = Visibility.Visible;
                TypeComboBox.IsEnabled    = false;
            }
            else
            {
                ContFutTabItem.Visibility = Visibility.Hidden;
            }

            DataContext = this;
            _addingNew  = addingNew;

            _context = new MyDBContext();

            if (instrument != null)
            {
                _context.Instruments.Attach(instrument);
                _context.Entry(instrument).Reload();
                if (instrument.Exchange != null)
                {
                    _context.Entry(instrument.Exchange).Reload();
                }

                if (instrument.ContinuousFuture != null)
                {
                    _context.ContinuousFutures.Attach(instrument.ContinuousFuture);
                    _context.Entry(instrument.ContinuousFuture).Reload();
                }

                if (!addingNew)
                {
                    if (instrument.Tags != null)
                    {
                        foreach (Tag tag in instrument.Tags)
                        {
                            _context.Tags.Attach(tag);
                        }
                    }

                    if (instrument.Sessions != null)
                    {
                        foreach (InstrumentSession session in instrument.Sessions)
                        {
                            _context.InstrumentSessions.Attach(session);
                        }
                    }
                }

                TheInstrument = addingNew ? (Instrument)instrument.Clone() : instrument;
                if (TheInstrument.Tags == null)
                {
                    TheInstrument.Tags = new List <Tag>();
                }
                if (TheInstrument.Sessions == null)
                {
                    TheInstrument.Sessions = new List <InstrumentSession>();
                }

                TheInstrument.Sessions = TheInstrument.Sessions.OrderBy(x => x.OpeningDay).ThenBy(x => x.OpeningTime).ToList();

                _originalSessions = new List <InstrumentSession>(TheInstrument.Sessions);
            }
            else
            {
                TheInstrument = new Instrument
                {
                    Tags     = new List <Tag>(),
                    Sessions = new List <InstrumentSession>()
                };

                //need to do some extra stuff if it's a continuous future
                if (addingContFut)
                {
                    TheInstrument.ContinuousFuture   = new ContinuousFuture();
                    TheInstrument.Type               = InstrumentType.Future;
                    TheInstrument.IsContinuousFuture = true;
                }

                CustomRadioBtn.IsChecked = true;
            }

            //Tags
            Tags = new ObservableCollection <CheckBoxTag>();
            foreach (Tag t in _context.Tags)
            {
                Tags.Add(new CheckBoxTag(t, TheInstrument.Tags.Contains(t)));
            }

            //Sessions
            SelectedSessions = new ObservableCollection <InstrumentSession>(TheInstrument.Sessions);

            //Window title
            if (addingNew)
            {
                Title          = "Add New Instrument";
                AddBtn.Content = "Add";
            }
            else
            {
                Title          = "Modify Instrument";
                AddBtn.Content = "Modify";
            }

            Exchanges = new ObservableCollection <Exchange>();

            var exchangeList = _context.Exchanges.AsEnumerable().OrderBy(x => x.Name);

            foreach (Exchange e in exchangeList)
            {
                Exchanges.Add(e);
            }

            //fill template box
            var templates = _context.SessionTemplates.Include("Sessions").ToList();

            foreach (SessionTemplate t in templates)
            {
                TemplateComboBox.Items.Add(t);
            }
            if (TheInstrument.SessionsSource == SessionsSource.Template)
            {
                TemplateComboBox.SelectedItem = templates.First(x => x.ID == TheInstrument.SessionTemplateID);
            }

            //set the right radio button...
            CustomRadioBtn.IsChecked   = TheInstrument.SessionsSource == SessionsSource.Custom;
            TemplateRadioBtn.IsChecked = TheInstrument.SessionsSource == SessionsSource.Template;
            ExchangeRadioBtn.IsChecked = TheInstrument.SessionsSource == SessionsSource.Exchange;

            //populate instrument type combobox with enum values
            var instrumentTypeValues = MyUtils.GetEnumValues <InstrumentType>();

            foreach (InstrumentType t in instrumentTypeValues)
            {
                TypeComboBox.Items.Add(t);
            }

            //populate option type combobox with enum values
            var optionTypeValues = MyUtils.GetEnumValues <OptionType>();

            foreach (OptionType t in optionTypeValues)
            {
                OptionTypeComboBox.Items.Add(t);
            }

            var dataSources = _context.Datasources.AsEnumerable();

            foreach (Datasource d in dataSources)
            {
                DatasourceComboBox.Items.Add(d);
            }

            //sort the sessions so they're ordered properly...
            SessionsGrid.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("OpeningDay", System.ComponentModel.ListSortDirection.Ascending));

            //fill the RolloverRuleType combobox
            var rolloverTypes = MyUtils.GetEnumValues <ContinuousFuturesRolloverType>();

            foreach (ContinuousFuturesRolloverType t in rolloverTypes)
            {
                if (t != ContinuousFuturesRolloverType.Time)
                {
                    RolloverRuleType.Items.Add(t);
                }
            }

            //fill the RootSymbolComboBox
            foreach (UnderlyingSymbol s in _context.UnderlyingSymbols)
            {
                RootSymbolComboBox.Items.Add(s);
            }

            ContractMonths = new ObservableCollection <KeyValuePair <int, string> >();
            //fill the continuous futures contrat month combobox
            for (int i = 1; i < 10; i++)
            {
                ContractMonths.Add(new KeyValuePair <int, string>(i, MyUtils.Ordinal(i) + " Contract"));
            }

            //time or rule-based rollover, set the radio button check
            if (TheInstrument.ContinuousFuture != null)
            {
                if (TheInstrument.ContinuousFuture.RolloverType == ContinuousFuturesRolloverType.Time)
                {
                    RolloverTime.IsChecked = true;
                }
                else
                {
                    RolloverRule.IsChecked = true;
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Set the docked instrument's values.
        /// </summary>
        /// <param name="settings">The values to place on the docked instrument.</param>
        private Instrument UpdateInstrument(Instrument settings, string expectedSerialNumber)
        {
            Log.Debug(string.Format("{0}.UpdateInstrument", Name));

            if (!Controller.IsDocked())   // Determine if there is an instrument to read.
            {
                return(null);
            }

            string tmpString = _instCtrlr.GetSerialNumber();

            if (tmpString == string.Empty)
            {
                Log.Warning("GetSerialNumber returned empty string!");
            }

            Log.Debug(string.Format("Updating with {0} settings (RefId={1})",
                                    (settings.SerialNumber == string.Empty) ? "default instrument" : "instrument-specific", settings.RefId));

            // Check to see if we are modifying the correct instrument.
            if (expectedSerialNumber != tmpString)
            {
                string msg = string.Format("Instrument S/N mismatch. expected=\"{0}\" actual=\"{1}\"", expectedSerialNumber, tmpString);
                Log.Error(msg);
                throw new ApplicationException(msg);
            }

            // Check to see if we are modifying the correct instrument type.
            DeviceType tmpType = Master.Instance.SwitchService.Instrument.Type;

            if (settings.Type != tmpType)
            {
                string msg = string.Format("Instrument Type mismatch. expected=\"{0}\" actual=\"{1}\"", settings.Type.ToString(), tmpType.ToString());
                Log.Error(msg);
                throw new ApplicationException(msg);
            }

            // We already verified that the type of the settings match the type of the docked instrument.
            // Now we verify that the type is supported by this type of docking station.
            if (settings.Type != Configuration.DockingStation.Type)
            {
                // VPRO instruments are supported by MX4 docking stations.
                if (!(settings.Type == DeviceType.VPRO && Configuration.DockingStation.Type == DeviceType.MX4))
                {
                    string msg = string.Format("Instrument {0} is of the wrong type (\"{1}\")", tmpString, settings.Type.ToString());
                    Log.Error(msg);
                    throw new ApplicationException(msg);
                }
            }

            // Temp variables
            int    tmpInt;
            short  tmpShort;
            double tmpDouble;

            // AccessCode will be an empty string if it should be set to the default.
            if (settings.AccessCode == string.Empty)
            {
                settings.AccessCode = _instCtrlr.Driver.Definition.DefaultSecurityCode;
            }

            // Instrument security or access code setting.
            tmpString = Master.Instance.SwitchService.Instrument.AccessCode;
            if (settings.AccessCode != tmpString)
            {
#if DEBUG // don't show access codes in release builds.
                LogUpdate("AccessCode", settings.AccessCode, tmpString);
#else
                LogUpdate("AccessCode", string.Empty.PadRight(settings.AccessCode.Length, '*'), string.Empty.PadRight(tmpString.Length, '*'));
#endif
                _instCtrlr.SetAccessCode(settings.AccessCode);
                Master.Instance.SwitchService.Instrument.AccessCode = settings.AccessCode;
            }

            // Recording interval setting (in seconds) for datalog.
            // Note that RecordingIntervalIncrement will return zero if instrument
            // doesn't allow its recording interval to be changed.
            if (_instCtrlr.HasDataLoggingFeature && _instCtrlr.RecordingIntervalIncrement > 0)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.RecordingInterval;
                if (settings.RecordingInterval != tmpInt)
                {
                    LogUpdate("RecordingInterval", settings.RecordingInterval, tmpInt);
                    _instCtrlr.SetRecordingInterval(settings.RecordingInterval);
                    Master.Instance.SwitchService.Instrument.RecordingInterval = settings.RecordingInterval;
                }
            }

            // TWA Time Base setting.
            if (_instCtrlr.HasTwaFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.TWATimeBase;
                if (settings.TWATimeBase != tmpInt)
                {
                    LogUpdate("TWATimeBase", settings.TWATimeBase, tmpInt);
                    _instCtrlr.SetTwaTimeBase(settings.TWATimeBase);
                    Master.Instance.SwitchService.Instrument.TWATimeBase = settings.TWATimeBase;
                }
            }

            // Out-of-Motion (Man Down) Warning Interval setting
            if (_instCtrlr.HasOomWarningIntervalFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.OomWarningInterval;
                if (settings.OomWarningInterval != tmpInt)
                {
                    LogUpdate("OomWarningInterval", settings.OomWarningInterval, tmpInt);
                    _instCtrlr.SetOomWarningInterval(settings.OomWarningInterval);
                    Master.Instance.SwitchService.Instrument.OomWarningInterval = settings.OomWarningInterval;
                }
            }

            // Dock Overdue Interval setting
            if (_instCtrlr.HasDockIntervalFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.DockInterval;
                if (settings.DockInterval != tmpInt)
                {
                    LogUpdate("DockInterval", settings.DockInterval, tmpInt);
                    _instCtrlr.SetDockInterval(settings.DockInterval);
                    Master.Instance.SwitchService.Instrument.DockInterval = settings.DockInterval;
                }
            }

            // Maintenance Interval setting
            if (_instCtrlr.HasMaintenanceIntervalFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.MaintenanceInterval;
                if (settings.MaintenanceInterval != tmpInt)
                {
                    LogUpdate("MaintenanceInterval", settings.MaintenanceInterval, tmpInt);
                    _instCtrlr.SetMaintenanceInterval(settings.MaintenanceInterval);
                    Master.Instance.SwitchService.Instrument.MaintenanceInterval = settings.MaintenanceInterval;
                }
            }

            // Calibration Interval setting
            if (_instCtrlr.HasCalibrationIntervalFeature)
            {
                tmpShort = Master.Instance.SwitchService.Instrument.CalibrationInterval;
                if (settings.CalibrationInterval != tmpShort)
                {
                    LogUpdate("CalibrationInterval", settings.CalibrationInterval, tmpShort);
                    _instCtrlr.SetCalibrationInterval(settings.CalibrationInterval);
                    Master.Instance.SwitchService.Instrument.CalibrationInterval = settings.CalibrationInterval;
                }
            }

            // Bump Interval setting
            if (_instCtrlr.HasBumpIntervalFeature)
            {
                tmpDouble = Master.Instance.SwitchService.Instrument.BumpInterval;
                if (settings.BumpInterval != tmpDouble)
                {
                    LogUpdate("BumpInterval", settings.BumpInterval, tmpDouble);
                    _instCtrlr.SetBumpInterval(settings.BumpInterval);
                    Master.Instance.SwitchService.Instrument.BumpInterval = settings.BumpInterval;
                }
            }

            // instrument controller will return -1 if instrument does not support bump thresholding.
            if (_instCtrlr.HasBumpThresholdFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.BumpThreshold;
                if (settings.BumpThreshold != tmpInt)
                {
                    LogUpdate("BumpThreshold", settings.BumpThreshold, tmpInt);
                    _instCtrlr.SetBumpThreshold(settings.BumpThreshold);
                    Master.Instance.SwitchService.Instrument.BumpThreshold = settings.BumpThreshold;
                }
            }

            if (_instCtrlr.HasBumpTimeoutFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.BumpTimeout;
                if (settings.BumpTimeout != tmpInt)
                {
                    LogUpdate("BumpTimeout", settings.BumpTimeout, tmpInt);
                    _instCtrlr.SetBumpTimeout(settings.BumpTimeout);
                    Master.Instance.SwitchService.Instrument.BumpTimeout = settings.BumpTimeout;
                }
            }

            UpdateLanguage(settings, Master.Instance.SwitchService.Instrument);

            if (_instCtrlr.HasMagneticFieldDurationFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.MagneticFieldDuration;
                if (settings.MagneticFieldDuration != tmpInt)
                {
                    LogUpdate("MagneticFieldDuration", settings.MagneticFieldDuration, tmpInt);
                    _instCtrlr.SetMagneticFieldDuration(settings.MagneticFieldDuration);
                    Master.Instance.SwitchService.Instrument.MagneticFieldDuration = settings.MagneticFieldDuration;
                }
            }

            if (_instCtrlr.HasCompanyNameFeature)
            {
                tmpString = Master.Instance.SwitchService.Instrument.CompanyName;
                if (settings.CompanyName != tmpString)
                {
                    LogUpdate("CompanyName", settings.CompanyName, tmpString);
                    _instCtrlr.SetCompanyName(settings.CompanyName);
                    Master.Instance.SwitchService.Instrument.CompanyName = settings.CompanyName;
                }
            }

            if (_instCtrlr.HasCompanyMessageFeature)
            {
                tmpString = Master.Instance.SwitchService.Instrument.CompanyMessage;
                if (settings.CompanyMessage != tmpString)
                {
                    LogUpdate("CompanyMessage", settings.CompanyMessage, tmpString);
                    _instCtrlr.SetCompanyMessage(settings.CompanyMessage);
                    Master.Instance.SwitchService.Instrument.CompanyMessage = settings.CompanyMessage;
                }
            }

            UpdateAlarmActionMessages(settings);

            // The GBPRO has no backlight settings
            // 11/13/07 - GBPlus also has no backlight settings.
            // 4/30/10 - Currently, None of the modbus instrument have a backlight setting.
            if (settings.Backlight != BacklightSetting.Unknown)
            {
                // Retrieve instrument's current backlight setting.
                BacklightSetting tmpBacklightSettings = Master.Instance.SwitchService.Instrument.Backlight;
                if (settings.Backlight != tmpBacklightSettings)
                {
                    LogUpdate("Backlight", settings.Backlight.ToString(), tmpBacklightSettings.ToString());
                    _instCtrlr.SetBacklightSetting(settings.Backlight);
                    Master.Instance.SwitchService.Instrument.Backlight = settings.Backlight;
                }
            }

            //Suresh 30-SEPTEMBER-2011 INS-2277
            if (_instCtrlr.HasBacklightTimeoutConfigFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.BacklightTimeout;
                if (settings.BacklightTimeout != tmpInt)
                {
                    LogUpdate("BackLightTimeout", settings.BacklightTimeout, tmpInt);
                    _instCtrlr.SetBacklightTimeout(settings.BacklightTimeout);
                    Master.Instance.SwitchService.Instrument.BacklightTimeout = settings.BacklightTimeout;
                }
            }

            // Synch instrument's clock with docking station's clock.
            if (settings.Type != DeviceType.GBPLS)   // GBPlus has no clock.
            {
                DateTime instTime = _instCtrlr.GetTime();
                DateTime localNow = Configuration.GetLocalTime();

                // Round times to nearest second.
                localNow = new DateTime(localNow.Year, localNow.Month, localNow.Day, localNow.Hour, localNow.Minute, localNow.Second);
                instTime = new DateTime(instTime.Year, instTime.Month, instTime.Day, instTime.Hour, instTime.Minute, instTime.Second);

                if (localNow != instTime)
                {
                    const string dateTimeFormat = "HH:mm:ss MM/dd/yyyy";
                    LogUpdate("Time", localNow.ToString(dateTimeFormat), instTime.ToString(dateTimeFormat));
                    _instCtrlr.SetTime(localNow);
                }
            }

            // Custom response factors NEED to be set here BEFORE we update the sensors.

            _instCtrlr.SetCustomPidFactors(settings.CustomPidFactors);
            Master.Instance.SwitchService.Instrument.CustomPidFactors = settings.CustomPidFactors;

            _instCtrlr.SetFavoritePidFactors(settings.FavoritePidFactors);
            Master.Instance.SwitchService.Instrument.FavoritePidFactors = settings.FavoritePidFactors;

            for (int pos = 1; pos <= _instCtrlr.Driver.Definition.MaxSensorCapacity; pos++)
            {
                InstalledComponent component = Master.Instance.SwitchService.Instrument.InstalledComponents.Find(ic => ic.Position == pos);

                if (component == null || !(component.Component is Sensor))
                {
                    Log.Warning("No sensor installed at position " + pos);
                }
                else
                {
                    UpdateSensor(pos, (Sensor)component.Component, settings.SensorSettings);
                }
            }

            UpdateUsersAndSites(settings);

            // Set the instrument's enabled options.  Although we pass into the method only those
            // options that should be enabled, it returns the state (enabled or disabled) of ALL options.
            // We update the switch service's cached instrument with the list of All options.
            List <DeviceOption> deviceOptions = _instCtrlr.SetInstrumentOptions(settings.Options);
            Master.Instance.SwitchService.Instrument.Options = deviceOptions;

            // instrument level wireless settings
            if (_instCtrlr.Driver.Definition.HasWirelessFeature && (settings.Type == DeviceType.SC || settings.Type == DeviceType.VPRO))
            {
                tmpInt = Master.Instance.SwitchService.Instrument.WirelessPeerLostThreshold;
                if (settings.WirelessPeerLostThreshold != tmpInt)
                {
                    LogUpdate("WirelessPeerLostThreshold", settings.WirelessPeerLostThreshold, tmpInt);
                    _instCtrlr.Driver.setWirelessPeerLostThreshold(settings.WirelessPeerLostThreshold);
                    Master.Instance.SwitchService.Instrument.WirelessPeerLostThreshold = settings.WirelessPeerLostThreshold;
                }

                tmpInt = Master.Instance.SwitchService.Instrument.WirelessNetworkLostThreshold;
                if (settings.WirelessNetworkLostThreshold != tmpInt)
                {
                    LogUpdate("WirelessNetworkLostThreshold", settings.WirelessNetworkLostThreshold, tmpInt);
                    _instCtrlr.Driver.setWirelessNetworkLostThreshold(settings.WirelessNetworkLostThreshold);
                    Master.Instance.SwitchService.Instrument.WirelessNetworkLostThreshold = settings.WirelessNetworkLostThreshold;
                }

                if (_instCtrlr.Driver.Definition.HasWirelessNetworkDisconnectDelayConfigFeature)
                {
                    tmpInt = Master.Instance.SwitchService.Instrument.WirelessNetworkDisconnectDelay;
                    if (settings.WirelessNetworkDisconnectDelay != tmpInt)
                    {
                        LogUpdate("WirelessNetworkDisconnectDelay", settings.WirelessNetworkDisconnectDelay, tmpInt);
                        _instCtrlr.Driver.setWirelessNetworkDisconnectDelay(settings.WirelessNetworkDisconnectDelay);
                        Master.Instance.SwitchService.Instrument.WirelessNetworkDisconnectDelay = settings.WirelessNetworkDisconnectDelay;
                    }
                }

                tmpInt = Master.Instance.SwitchService.Instrument.WirelessReadingsDeadband;
                if (settings.WirelessReadingsDeadband != tmpInt)
                {
                    LogUpdate("WirelessReadingsDeadband", settings.WirelessReadingsDeadband, tmpInt);
                    _instCtrlr.Driver.setWirelessReadingsDeadband(settings.WirelessReadingsDeadband);
                    Master.Instance.SwitchService.Instrument.WirelessReadingsDeadband = settings.WirelessReadingsDeadband;
                }

                if (_instCtrlr.Driver.Definition.HasBluetoothFeature)
                {
                    tmpInt = Master.Instance.SwitchService.Instrument.LoneWorkerOkMessageInterval;
                    if (settings.LoneWorkerOkMessageInterval != tmpInt)
                    {
                        LogUpdate("BluetoothLoneWorkerOkMessageInterval", settings.LoneWorkerOkMessageInterval, tmpInt);
                        _instCtrlr.Driver.setBluetoothLoneWorkerOkMessageInterval(settings.LoneWorkerOkMessageInterval);
                        Master.Instance.SwitchService.Instrument.LoneWorkerOkMessageInterval = settings.LoneWorkerOkMessageInterval;
                    }

                    //INS-7908 -- To handle for the Ventis Pro Instrument, which has already upgraded to latest firmware, but the bluetooth feature has not been enabled in it.
                    //As of now, only VPRO instrument has bluetooth feature from v2.0 and above versions (HasBluetoothFeature determines that).
                    //The below check for VPRO is done specifically, because in future if any instrument has bluetooth feature, we may need to handle that in a better way.
                    if (settings.Type == DeviceType.VPRO && !_instCtrlr.Driver.isBluetoothFeatureEnabled())
                    {
                        //Note: Do we need to check the BluetoothFeatureActivated in settings and allow to override here? as of now, ignoring the settings value for the bluetooth, since by default its disabled now but we need to make enable by default.
                        //Why we are not enabling the feature at the factory/account/settings/instrument level enable by default and set the value based on that??
                        LogUpdate("BluetoothFeatureEnabled", true, Master.Instance.SwitchService.Instrument.BluetoothFeatureActivated);
                        _instCtrlr.Driver.enableBluetoothFeature(true);
                        Master.Instance.SwitchService.Instrument.BluetoothFeatureActivated = true;
                    }
                }
            }

            UpdateWirelessModule(settings, Master.Instance.SwitchService.Instrument.WirelessModule);

            if (_instCtrlr.Driver.Definition.HasGpsFeature)
            {
                tmpInt = Master.Instance.SwitchService.Instrument.GpsReadingInterval;
                if (settings.GpsReadingInterval != tmpInt)
                {
                    LogUpdate("GpsReadingInterval", settings.GpsReadingInterval, tmpInt);
                    _instCtrlr.Driver.setGpsReadingInterval(settings.GpsReadingInterval);
                    Master.Instance.SwitchService.Instrument.GpsReadingInterval = settings.GpsReadingInterval;
                }
            }

            // After updating all the instrument settings we need to send a command to the instrument
            // to have it persist the settings so they will be retained after power is lost.
            // Only SafeCore needs this command.
            _instCtrlr.Driver.saveInstrumentSettings();

            // Read all settings fresh from the docked instrument to ensure accurate instrument
            // settings are cached as well as uploaded to iNet.  Reading all settings during the
            // instrument settings update operation does not incur an extra time penalty for
            // re-establishing communication with the docked instrument like it would in a
            // follow-up instrument settings read operation.
            Instrument returnInstrument = _instCtrlr.DiscoverDockedInstrument(false);

            if (returnInstrument == null || returnInstrument.SerialNumber.Length == 0)
            {
                throw new InstrumentNotDockedException();
            }

            Master.Instance.SwitchService.Instrument = (Instrument)returnInstrument.Clone();

            return(returnInstrument);
        }