public AddInstrumentQuandlWindow()
        {
            DataContext = this;

            AddedInstruments = new List<Instrument>();
            Exchanges = new ObservableCollection<Exchange>();

            Instruments = new ObservableCollection<Instrument>();

            InitializeComponent();

            ExchangeComboBox.ItemsSource = Exchanges;
            PrimaryExchangeComboBox.ItemsSource = Exchanges;

            using (var entityContext = new MyDBContext())
            {
                _thisDS = entityContext.Datasources.First(x => x.Name == "Quandl");
                foreach (Exchange e in entityContext.Exchanges.Include(x => x.Sessions))
                {
                    Exchanges.Add(e);
                }
            }

            

            ShowDialog();
        }
Example #2
0
        public DataImportWindow(Instrument instrument)
        {
            InitializeComponent();

            //reload the instrument first to make sure we have up-to-date data
            using (var context = new MyDBContext())
            {
                context.Instruments.Attach(instrument);
                context.Entry(instrument).Reload();
                _instrument = instrument;
            }

            Title += " - " + _instrument.Symbol;

            //fill frequency combo box
            var values = MyUtils.GetEnumValues<BarSize>();
            foreach (BarSize s in values)
            {
                FrequencyComboBox.Items.Add(s);
            }
            FrequencyComboBox.SelectedItem = BarSize.OneDay;

            MinDT.Value = new DateTime(1950, 1, 1);
            MaxDT.Value = DateTime.Now;
        }
Example #3
0
        public ScheduledJobsWindow()
        {
            InitializeComponent();
            DataContext = this;

            Jobs = new ObservableCollection<DataUpdateJobDetails>();
            Tags = new ObservableCollection<Tag>();
            Instruments = new ObservableCollection<Instrument>();

            using (var context = new MyDBContext())
            {
                var jobs = context.DataUpdateJobs.ToList();
                foreach (DataUpdateJobDetails job in jobs)
                {
                    Jobs.Add(job);
                }

                var tags = context.Tags.ToList();
                foreach (Tag tag in tags)
                {
                    Tags.Add(tag);
                }

                var im = new InstrumentManager();

                List<Instrument> instruments = im.FindInstruments(context);
                foreach (Instrument i in instruments)
                {
                    Instruments.Add(i);
                }
            }
        }
Example #4
0
        /// <summary>
        /// Delete an instrument and all locally stored data.
        /// </summary>
        public static void RemoveInstrument(Instrument instrument)
        {
            using (var entityContext = new MyDBContext())
            {
                //hacking around the circular reference issue
                if (instrument.IsContinuousFuture)
                {
                    entityContext.Instruments.Attach(instrument);
                    var tmpCF = instrument.ContinuousFuture;
                    instrument.ContinuousFuture = null;
                    instrument.ContinuousFutureID = null;
                    entityContext.SaveChanges();

                    entityContext.ContinuousFutures.Attach(tmpCF);
                    entityContext.ContinuousFutures.Remove(tmpCF);
                    entityContext.SaveChanges();
                }

                entityContext.Instruments.Attach(instrument);
                entityContext.Instruments.Remove(instrument);
                entityContext.SaveChanges();
            }

            using (var localStorage = DataStorageFactory.Get())
            {
                localStorage.Connect();

                localStorage.DeleteAllInstrumentData(instrument);
            }
        }
Example #5
0
        public ExchangesWindow()
        {
            InitializeComponent();
            DataContext = this;

            Exchanges = new ObservableCollection<Exchange>();

            List<Exchange> tmpExchanges;
            using (var entityContext = new MyDBContext())
            {
                tmpExchanges = entityContext.Exchanges.Include("Sessions").OrderBy(x => x.Name).ToList();
            }
            foreach (Exchange e in tmpExchanges)
            {
                Exchanges.Add(e);
            }

            ExchangesGrid.ItemsSource = Exchanges;

            _filterTimer = new Timer();
            _filterTimer.Enabled = false;
            _filterTimer.AutoReset = false;
            _filterTimer.Interval = 100; //milliseconds
            _filterTimer.Elapsed += _filterTimer_Elapsed;
        }
Example #6
0
        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            var selectedSymbol = (UnderlyingSymbol)SymbolsGrid.SelectedItem;
            if (selectedSymbol == null) return;

            using (var context = new MyDBContext())
            {
                var instrumentCount = context.Instruments.Count(x => x.SessionTemplateID == selectedSymbol.ID && x.SessionsSource == SessionsSource.Template);
                if (instrumentCount > 0)
                {
                    MessageBox.Show(string.Format("Can't delete this template it has {0} instruments assigned to it.", instrumentCount));
                    return;
                }
            }

            var result = MessageBox.Show(string.Format("Are you sure you want to delete {0}?", selectedSymbol.Symbol), "Delete", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.No) return;

            using (var entityContext = new MyDBContext())
            {
                entityContext.UnderlyingSymbols.Attach(selectedSymbol);
                entityContext.UnderlyingSymbols.Remove(selectedSymbol);
                entityContext.SaveChanges();
            }

            Symbols.Remove(selectedSymbol);
            CollectionViewSource.GetDefaultView(SymbolsGrid.ItemsSource).Refresh();
        }
        public AddInstrumentInteractiveBrokersWindow()
        {
            Random r = new Random();
            _client = new IBClient();

            try
            {
                //random connection id for this one...
                _client.Connect(Properties.Settings.Default.ibClientHost, Properties.Settings.Default.ibClientPort, r.Next(1000, 200000));
            }
            catch (Exception e)
            {
                MessageBox.Show("Could not connect to TWS: " + e.Message, "Error");
                Close();
                return;
            }

            AddedInstruments = new List<Instrument>();

            _client.NextValidId += _client_NextValidId;
            _client.ContractDetails += _client_ContractDetails;
            _client.Error += _client_Error;
            _client.ConnectionClosed += _client_ConnectionClosed;
            _client.ContractDetailsEnd += _client_ContractDetailsEnd;

            Exchanges = new ObservableCollection<KeyValuePair<int, string>> { new KeyValuePair<int, string>(0, "All") };
            _exchanges = new Dictionary<string, Exchange>();

            using (var context = new MyDBContext())
            {
                _thisDS = context.Datasources.First(x => x.Name == "Interactive Brokers");

                foreach (Exchange e in context.Exchanges)
                {
                    Exchanges.Add(new KeyValuePair<int, string>(e.ID, e.Name));
                    _exchanges.Add(e.Name, e);
                }
            }

            InitializeComponent();
            DataContext = this;

            Instruments = new ObservableCollection<Instrument>();
            InstrumentTypes = new ObservableCollection<InstrumentType>();

            //list the available types from our enum
            var values = MyUtils.GetEnumValues<InstrumentType>();
            foreach (var val in values)
            {
                InstrumentTypes.Add(val);
            }

            ShowDialog();
        }
Example #8
0
        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            var job = new DataUpdateJobDetails { Name = "NewJob", UseTag = true, Frequency = BarSize.OneDay, Time = new TimeSpan(8, 0, 0), WeekDaysOnly = true };
            Jobs.Add(job);
            JobsGrid.SelectedItem = job;

            using (var context = new MyDBContext())
            {
                context.DataUpdateJobs.Add(job);
                context.SaveChanges();
            }
        }
Example #9
0
File: Seed.cs Project: QANTau/QDMS
        public static void SeedDatasources(MyDBContext context)
        {
            var ib = new Datasource { Name = "Interactive Brokers" };
            var yahoo = new Datasource { Name = "Yahoo" };
            var quandl = new Datasource { Name = "Quandl" };
            var fred = new Datasource { Name = "FRED" };
            var google = new Datasource { Name = "Google" };

            context.Datasources.AddOrUpdate(x => x.Name, ib, yahoo, quandl, fred, google);

            context.SaveChanges();
        }
Example #10
0
        public void RefreshCollections()
        {
            Tags.Clear();
            Instruments.Clear();

            using (var context = new MyDBContext())
            {
                Tags.AddRange(context.Tags.ToList());

                var im = new InstrumentManager();
                Instruments.AddRange(im.FindInstruments(context));
            }
        }
Example #11
0
        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            var window = new EditRootSymbolWindow(null);
            window.ShowDialog();

            if (window.SymbolAdded)
            {
                using (var entityContext = new MyDBContext())
                {
                    Symbols.Add(entityContext.UnderlyingSymbols.First(x => x.Symbol == window.TheSymbol.Symbol));
                }
            }
        }
        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            var window = new EditSessionTemplateWindow(null);
            window.ShowDialog();

            if (window.TemplateAdded)
            {
                using (var entityContext = new MyDBContext())
                {
                    Templates.Add(entityContext.SessionTemplates.Include("Sessions").First(x => x.Name == window.TheTemplate.Name));
                }
            }
        }
        public AddInstrumentFredWindow(MyDBContext context)
        {
            DataContext = this;

            AddedInstruments = new List<Instrument>();

            Series = new ObservableCollection<FredUtils.FredSeries>();

            InitializeComponent();

            _thisDS = context.Datasources.First(x => x.Name == "FRED");

            ShowDialog();
        }
Example #14
0
        /// <summary>
        /// Add a new instrument or update an existing instrument in the database.
        /// </summary>
        /// <param name="instrument"></param>
        /// <param name="updateIfExists"></param>
        /// <param name="saveChanges">Set to true if saving to db should be done.</param>
        /// <returns>True if the insertion or update succeeded. False if it did not.</returns>
        public static bool AddInstrument(Instrument instrument, bool updateIfExists = false, bool saveChanges = true)
        {
            if (instrument.IsContinuousFuture)
            {
                throw new Exception("Cannot add continuous futures using this method");
            }

            using (var context = new MyDBContext())
            {
                var existingInstrument = context.Instruments.SingleOrDefault(x =>
                    (x.ID == instrument.ID) ||
                    (x.Symbol == instrument.Symbol && x.DatasourceID == instrument.DatasourceID && x.ExchangeID == instrument.ExchangeID));

                if (existingInstrument == null) //object doesn't exist, so we add it
                {
                    //if necessary, load sessions from teplate or exchange
                    if (instrument.SessionsSource == SessionsSource.Exchange)
                    {
                        instrument.Sessions = new List<InstrumentSession>();
                        var exchange = context.Exchanges.Include("Sessions").First(x => x.ID == instrument.ExchangeID);
                        foreach (ExchangeSession s in exchange.Sessions)
                        {
                            instrument.Sessions.Add(MyUtils.SessionConverter(s));
                        }
                    }
                    else if (instrument.SessionsSource == SessionsSource.Template)
                    {
                        instrument.Sessions = new List<InstrumentSession>();
                        var template = context.SessionTemplates.Include("Sessions").First(x => x.ID == instrument.SessionTemplateID);
                        foreach (TemplateSession s in template.Sessions)
                        {
                            instrument.Sessions.Add(MyUtils.SessionConverter(s));
                        }
                    }

                    context.Instruments.Add(instrument);
                    context.Database.Connection.Open();
                    if (saveChanges) context.SaveChanges();
                    return true;
                }
                else if (updateIfExists) //object exist, but we want to update it
                {
                    context.Entry(existingInstrument).CurrentValues.SetValues(instrument);
                    if (saveChanges) context.SaveChanges();
                    return true;
                }
            }
            return false; //object exists and we don't update it
        }
        public SessionTemplatesWindow()
        {
            InitializeComponent();
            DataContext = this;

            Templates = new ObservableCollection<SessionTemplate>();

            using (var context = new MyDBContext())
            {
                var templates = context.SessionTemplates.Include("Sessions").ToList().OrderBy(x => x.Name);
                foreach (SessionTemplate s in templates)
                {
                    Templates.Add(s);
                }
            }
        }
Example #16
0
        public RootSymbolsWindow()
        {
            InitializeComponent();
            DataContext = this;

            Symbols = new ObservableCollection<UnderlyingSymbol>();

            using (var context = new MyDBContext())
            {
                var templates = context.UnderlyingSymbols.OrderBy(x => x.Symbol);
                foreach (UnderlyingSymbol s in templates)
                {
                    Symbols.Add(s);
                }
            }
        }
Example #17
0
        public DataEditWindow(Instrument instrument)
        {
            InitializeComponent();
            DataContext = this;

            Data = new ObservableCollection<OHLCBar>();

            //grab and update the instrument
            using (var context = new MyDBContext())
            {
                context.Instruments.Attach(instrument);
                context.Entry(instrument).Reload();
                TheInstrument = instrument;
            }

            string timezone = TheInstrument.Exchange == null ? "UTC" : TheInstrument.Exchange.Timezone;
            _tzInfo = TimeZoneInfo.FindSystemTimeZoneById(timezone);

            StartTime = new DateTime(1950, 1, 1, 0, 0, 0, 0);
            EndTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0);

            if (!TheInstrument.ID.HasValue) return;

            //grab the data info
            using (var localStorage = DataStorageFactory.Get())
            {
                var storageInfo = localStorage.GetStorageInfo(TheInstrument.ID.Value);

                if (storageInfo.Count == 0) //if it doesn't have any data, we just exit
                {
                    MessageBox.Show("This instrument has no data.");
                    Hide();
                }
                else
                {
                    foreach (StoredDataInfo s in storageInfo) //fill the resolution box
                    {
                        ResolutionComboBox.Items.Add(s.Frequency);
                    }
                }
            }

            
            
        }
Example #18
0
        public SchedulerViewModel(IScheduler scheduler, IDialogCoordinator dialogService)
        {
            _scheduler = scheduler;
            DialogService = dialogService;

            using (var entityContext = new MyDBContext())
            {
                Jobs = new ObservableCollection<DataUpdateJobDetailsViewModel>(
                    entityContext
                    .DataUpdateJobs
                    .Include(t => t.Instrument)
                    .Include(t => t.Tag)
                    .ToList()
                    .Select(x => new DataUpdateJobDetailsViewModel(x)));
            }

            Tags = new ReactiveList<Tag>();
            Instruments = new ReactiveList<Instrument>();
            RefreshCollections();
            CreateCommands();
        }
        private void ExecuteSave()
        {
            using (var context = new MyDBContext())
            {
                if (Job.UseTag)
                {
                    Job.Instrument = null;
                    Job.InstrumentID = null;
                    Job.TagID = Job.Tag.ID;
                }
                else //Job is for a specific instrument, not a tag
                {
                    Job.InstrumentID = Job.Instrument.ID;
                    Job.Tag = null;
                    Job.TagID = null;
                }

                context.DataUpdateJobs.Attach(Job);
                context.Entry(Job).State = EntityState.Modified;
                context.SaveChanges();
            }
        }
Example #20
0
        /// <summary>
        /// Updates the instrument with new values. Instrument must have an ID.
        /// </summary>
        public static void UpdateInstrument(Instrument instrument)
        {
            if(!instrument.ID.HasValue) return;

            using (var context = new MyDBContext())
            {
                try
                {
                    //find it
                    Instrument instrumentFromDB = context.Instruments.First(x => x.ID == instrument.ID);
                    //update it
                    context.Entry(instrumentFromDB).CurrentValues.SetValues(instrument); //perhaps update all the underlying collections as well?

                    //save it
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Update instrument error: " + ex.Message);
                }

            }
        }
Example #21
0
        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if(JobsGrid.SelectedItems.Count != 1) return;

            var selectedJob = (DataUpdateJobDetails)JobsGrid.SelectedItem;

            var dialogResult = MessageBox.Show(string.Format("Are you sure you want to delete {0}?", selectedJob.Name), "Delete Job", MessageBoxButton.YesNo);
            if (dialogResult != MessageBoxResult.Yes) return;

            using (var context = new MyDBContext())
            {
                var job = context.DataUpdateJobs.FirstOrDefault(x => x.ID == selectedJob.ID);
                if (job == null) return;

                context.DataUpdateJobs.Remove(job);

                context.SaveChanges();
            }

            Jobs.Remove(selectedJob);

            CollectionViewSource.GetDefaultView(JobsGrid.ItemsSource).Refresh();
        }
Example #22
0
        private void ModifyBtn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TheSymbol.Symbol))
            {
                MessageBox.Show("Must have a symbol.");
                return;
            }

            
            using (var entityContext = new MyDBContext())
            {
                //check that the symbol doesn't already exist
                bool symbolExists = entityContext.UnderlyingSymbols.Count(x => x.Symbol == TheSymbol.Symbol) > 0;
                bool addingNew = TheSymbol.ID == -1;

                if (symbolExists && addingNew)
                {
                    MessageBox.Show("Must have a symbol.");
                    return;
                }

                if (addingNew)
                {
                    entityContext.UnderlyingSymbols.Add(TheSymbol);
                }
                else
                {
                    entityContext.UnderlyingSymbols.Attach(_originalSymbol);
                    entityContext.Entry(_originalSymbol).CurrentValues.SetValues(TheSymbol);
                }

                entityContext.SaveChanges();
            }

            SymbolAdded = true;
            Hide();
        }
Example #23
0
        public void MySqlDbIsCreatedSuccessfully()
        {
            using (var conn = new MySqlConnection(GetMySqlConnString(_mySqlUsername, _mySqlPassword, _mySqlHost)))
            {
                conn.Open();
                using (var cmd = new MySqlCommand("", conn))
                {
                    cmd.CommandText = @"DROP DATABASE IF EXISTS qdms_test;
                                        CREATE DATABASE qdms_test;
                                        DROP DATABASE IF EXISTS qdmsdata_test;
                                        CREATE DATABASE qdmsdata_test;";
                    cmd.ExecuteNonQuery();
                }
            }

            SetConnectionString("qdmsEntities", GetMySqlConnString(_mySqlUsername, _mySqlPassword, _mySqlHost, "qdms_test"), "MySql.Data.MySqlClient");
            SetConnectionString("qdmsDataEntities", GetMySqlConnString(_mySqlUsername, _mySqlPassword, _mySqlHost, "qdmsdata_test"), "MySql.Data.MySqlClient");

            ConfigurationManager.RefreshSection("connectionStrings");

            DbConfiguration.SetConfiguration(new MySqlEFConfiguration());

            using (var ctx = new MyDBContext())
            {
                ctx.Database.Initialize(true);
                Seed.SeedDatasources(ctx);
                Seed.DoSeed();
            }

            

            using (var ctx = new DataDBContext())
            {
                ctx.Database.Initialize(true);
            }
        }
        /// <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;
                }
            }
        }
Example #25
0
        private void ModifyBtn_Click(object sender, RoutedEventArgs e)
        {
            using (var entityContext = new MyDBContext())
            {
                bool nameExists = entityContext.Exchanges.Any(x => x.Name == TheExchange.Name);
                if (nameExists && (_addingNew || _originalExchange.Name != TheExchange.Name))
                {
                    MessageBox.Show("Name already exists, please change it.");
                    return;
                }

                if (_addingNew)
                {
                    entityContext.Exchanges.Add(TheExchange);
                }
                else
                {
                    entityContext.Exchanges.Attach(_originalExchange);
                    entityContext.Entry(_originalExchange).CurrentValues.SetValues(TheExchange);
                }

                entityContext.SaveChanges();

                //find removed sessions and mark them as deleted
                var removedSessions = _originalExchange.Sessions.Where(x => !TheExchange.Sessions.Any(y => y.ID == x.ID)).ToList();
                for (int i = 0; i < removedSessions.Count; i++)
                {
                    entityContext.Entry(removedSessions[i]).State = System.Data.Entity.EntityState.Deleted;
                }

                //find the ones that overlap and modify them, if not add them
                foreach (ExchangeSession s in TheExchange.Sessions)
                {
                    if (s.ID != 0) //this means it's not newly added
                    {
                        var session = _originalExchange.Sessions.First(x => x.ID == s.ID);
                        entityContext.ExchangeSessions.Attach(session);
                        entityContext.Entry(session).CurrentValues.SetValues(s);
                    }
                    else //completely new
                    {
                        _originalExchange.Sessions.Add(s);
                    }
                }

                entityContext.SaveChanges();

                //find instruments using this exchange as session source, and update their sessions
                if (TheExchange.ID != -1)
                {
                    var instruments = entityContext.Instruments.Where(x => x.SessionsSource == SessionsSource.Exchange && x.ExchangeID == TheExchange.ID).ToList();
                    foreach (Instrument i in instruments)
                    {
                        entityContext.InstrumentSessions.RemoveRange(i.Sessions);
                        i.Sessions.Clear();

                        foreach (ExchangeSession s in TheExchange.Sessions)
                        {
                            i.Sessions.Add(MyUtils.SessionConverter(s));
                        }
                    }
                }

                entityContext.SaveChanges();
            }
            ExchangeAdded = true;

            Hide();
        }
Example #26
0
        public void Initialisize()
        {
            _log.Info($"Server is initialisizing ...");

            //create data db if it doesn't exist
            DataDBContext dataContext;
            try
            {
                dataContext = new DataDBContext(_config.LocalStorage.ConnectionString);
                dataContext.Database.Initialize(false);
            }
            catch (System.Data.Entity.Core.ProviderIncompatibleException ex)
            {
                throw new NotSupportedException("Could not connect to context DataDB!", ex);
            }
            dataContext.Dispose();

            MyDBContext entityContext;
            try
            {
                entityContext = new MyDBContext(_config.DataStorage.ConnectionString);
                entityContext.Database.Initialize(false);
            }
            catch (System.Data.Entity.Core.ProviderIncompatibleException ex)
            {
                throw new NotSupportedException("Could not connect to context MyDB!", ex);
            }

            // initialisize helper classes
            _instrumentManager = new InstrumentManager();

            var cfRealtimeBroker = new ContinuousFuturesBroker(new QDMSClient.QDMSClient("RTDBCFClient", "127.0.0.1",
                _config.RealtimeDataService.RequestPort, _config.RealtimeDataService.PublisherPort,
                _config.InstrumentService.Port, _config.HistoricalDataService.Port), _instrumentManager, false);
            var cfHistoricalBroker = new ContinuousFuturesBroker(new QDMSClient.QDMSClient("HDBCFClient", "127.0.0.1",
                _config.RealtimeDataService.RequestPort, _config.RealtimeDataService.PublisherPort,
                _config.InstrumentService.Port, _config.HistoricalDataService.Port), _instrumentManager, false);

            IDataStorage localStorage;

            switch (_config.LocalStorage.Type)
            {
                case Config.LocalStorageType.MySql:
                    localStorage = new QDMSServer.DataSources.MySQLStorage(_config.LocalStorage.ConnectionString);
                    break;
                case Config.LocalStorageType.SqlServer:
                    localStorage = new QDMSServer.DataSources.SqlServerStorage(_config.LocalStorage.ConnectionString);
                    break;
                default:
                    throw new NotSupportedException("Not supported local storage type: " + _config.LocalStorage.Type);
            }

            // create brokers
            _historicalDataBroker = new HistoricalDataBroker(cfHistoricalBroker, localStorage, new IHistoricalDataSource[] {
                // @todo please add here some historical data sources the service should provide
            });
            _realTimeDataBroker = new RealTimeDataBroker(cfRealtimeBroker, localStorage, new IRealTimeDataSource[] {
                // @todo please add here some real time data sources the service should provide
            });

            // create servers
            _instrumentsServer = new InstrumentsServer(_config.InstrumentService.Port, _instrumentManager);
            _historicalDataServer = new HistoricalDataServer(_config.HistoricalDataService.Port, _historicalDataBroker);
            _realTimeDataServer = new RealTimeDataServer(_config.RealtimeDataService.PublisherPort, _config.RealtimeDataService.RequestPort, _realTimeDataBroker);

            // ... start the servers
            _instrumentsServer.StartServer();
            _historicalDataServer.StartServer();
            _realTimeDataServer.StartServer();

            _log.Info($"Server is ready.");
        }
Example #27
0
 private void AddBtn_Click(object sender, RoutedEventArgs e)
 {
     var window = new EditExchangeWindow(null);
     window.ShowDialog();
     
     if (window.ExchangeAdded)
     {
         using (var entityContext = new MyDBContext())
         {
             Exchanges.Add(entityContext.Exchanges.First(x => x.Name == window.TheExchange.Name));
         }
     }
 }
Example #28
0
 private static List<Instrument> FindAllInstruments(MyDBContext context, IQueryable<Instrument> query)
 {
     var allExchanges = context.Exchanges.Include(x => x.Sessions).ToList();
     var allInstruments = query.ToList();
     return allInstruments;
 }
Example #29
0
        /// <summary>
        /// Search for instruments.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="search">Any properties set on this instrument are used as search parameters.
        /// If null, all instruments are returned.</param>
        /// <param name="pred">A predicate to use directly in the instrument search.</param>
        /// <returns>A list of instruments matching the criteria.</returns>
        public List<Instrument> FindInstruments(MyDBContext context = null, Instrument search = null, Func<Instrument, bool> pred = null)
        {
            if (context == null) context = new MyDBContext();

            IQueryable<Instrument> query = context.Instruments
                .Include(x => x.Tags)
                .Include(x => x.Exchange)
                .Include(x => x.PrimaryExchange)
                .Include(x => x.Datasource)
                .Include(x => x.Sessions)
                //.Include(x => x.Exchange.Sessions)
                //.Include(x => x.PrimaryExchange.Sessions)
                .Include(x => x.ContinuousFuture)
                .Include(x => x.ContinuousFuture.UnderlyingSymbol)
                .AsQueryable();
            //there's a bug in the mysql connector that prevents us from including those session collections right here
            //it just crashes if you do. Devart connector works perfectly fine.
            //We just hack around it by loading up the session collections separately.

            if (pred != null)
            {
                return FindInstrumentsWithPredicate(pred, query);
            }
            else if (search == null)
            {
                return FindAllInstruments(context, query);
            }
            else
            {
                //first handle the cases where there is a single, unique instrument to return
                if (search.ID != null)
                {
                    query = query.Where(x => x.ID == search.ID);
                }
                else if (search.Symbol != null && search.DatasourceID.HasValue && search.ExchangeID.HasValue && search.Expiration.HasValue)
                {
                    query = query.Where(x => x.Symbol == search.Symbol
                        && x.DatasourceID == search.DatasourceID
                        && x.ExchangeID == search.ExchangeID
                        && x.Expiration == search.Expiration);
                }
                else if (search.ContinuousFutureID.HasValue)
                {
                    query = query.Where(x => x.ContinuousFutureID == search.ContinuousFutureID);
                }
                else //no unique cases, so just add the restrictions where applicable
                {
                    BuildQueryFromSearchInstrument(search, ref query);
                }
            }
            var instrumentList =  query.ToList();
            //see comment above, we can't include these in the original query due to a bug
            //and we can't allow lazy loading of the sessions
            //so we force them to be loaded right now
            foreach (Instrument i in instrumentList.Where((x => x.Exchange != null && x.Exchange.Sessions != null)))
            {
                i.Exchange.Sessions.ToList();
            }
            return instrumentList;
        }
Example #30
0
        /// <summary>
        /// Add a new instrument or update an existing instrument in the database.
        /// </summary>
        /// <param name="instrument"></param>
        /// <param name="updateIfExists"></param>
        /// <param name="saveChanges">Set to true if saving to db should be done.</param>
        /// <returns>True if the insertion or update succeeded. False if it did not.</returns>
        public Instrument AddInstrument(Instrument instrument, bool updateIfExists = false, bool saveChanges = true)
        {
            if (instrument.IsContinuousFuture)
            {
                throw new Exception("Cannot add continuous futures using this method.");
            }

            using (var context = new MyDBContext())
            {
                //make sure data source is set and exists
                if(instrument.Datasource == null || !context.Datasources.Any(x => x.Name == instrument.Datasource.Name))
                {
                    throw new Exception("Failed to add instrument: invalid datasource.");
                }

                //make sure exchange exists, if it is set
                if(instrument.Exchange != null && !context.Exchanges.Any(x => x.Name == instrument.Exchange.Name))
                {
                    throw new Exception("Failed to add instrument: exchange does not exist.");
                }
                if (instrument.PrimaryExchange != null && !context.Exchanges.Any(x => x.Name == instrument.PrimaryExchange.Name))
                {
                    throw new Exception("Failed to add instrument: primary exchange does not exist.");
                }

                //check if the instrument already exists in the database or not
                var existingInstrument = context.Instruments.SingleOrDefault(x =>
                    (x.ID == instrument.ID) ||
                    (x.Symbol == instrument.Symbol &&
                    x.DatasourceID == instrument.DatasourceID &&
                    x.ExchangeID == instrument.ExchangeID &&
                    x.Expiration == instrument.Expiration));

                if (existingInstrument == null) //object doesn't exist, so we add it
                {
                    //attach the datasource, exchanges, etc. so it doesn't try to add them
                    //also load sessions at the same time
                    context.Datasources.Attach(instrument.Datasource);
                    if (instrument.PrimaryExchange != null)
                    {
                        context.Exchanges.Attach(instrument.PrimaryExchange);
                        context.Entry(instrument.PrimaryExchange).Collection(x => x.Sessions).Load();
                    }
                    if (instrument.PrimaryExchangeID != instrument.ExchangeID && instrument.Exchange != null)
                    {
                        context.Exchanges.Attach(instrument.Exchange);
                        context.Entry(instrument.Exchange).Collection(x => x.Sessions).Load();
                    }

                    //if necessary, load sessions from teplate or exchange
                    if (instrument.SessionsSource == SessionsSource.Exchange && instrument.Exchange != null)
                    {
                        instrument.Sessions = instrument.Exchange.Sessions.Select(x => x.ToInstrumentSession()).ToList();
                    }
                    else if (instrument.SessionsSource == SessionsSource.Exchange && instrument.Exchange == null)
                    {
                        instrument.SessionsSource = SessionsSource.Custom;
                        instrument.Sessions = new List<InstrumentSession>();
                    }
                    else if (instrument.SessionsSource == SessionsSource.Template)
                    {
                        instrument.Sessions = new List<InstrumentSession>();
                        var template = context.SessionTemplates.Include("Sessions").FirstOrDefault(x => x.ID == instrument.SessionTemplateID);
                        if (template != null)
                        {
                            foreach (TemplateSession s in template.Sessions)
                            {
                                instrument.Sessions.Add(s.ToInstrumentSession());
                            }
                        }
                    }

                    context.Instruments.Add(instrument);
                    context.Database.Connection.Open();
                    if (saveChanges) context.SaveChanges();

                    Log(LogLevel.Info, string.Format("Instrument Manager: successfully added instrument {0}", instrument));

                    return instrument;
                }
                else if (updateIfExists) //object exist, but we want to update it
                {
                    Log(LogLevel.Info, string.Format("Instrument Manager: updating existing instrument ID {0} with the following details: {1}",
                        existingInstrument.ID,
                        instrument));

                    context.Entry(existingInstrument).CurrentValues.SetValues(instrument);
                    if (saveChanges) context.SaveChanges();
                    return existingInstrument;
                }
            }
            return null; //object exists and we don't update it
        }