Пример #1
0
        public void RequestsFrontContractFromCFBrokerForContinuousFuturesRequests()
        {
            var cf = new ContinuousFuture()
            {
                ID               = 1,
                InstrumentID     = 1,
                Month            = 1,
                UnderlyingSymbol = new UnderlyingSymbol
                {
                    ID     = 1,
                    Symbol = "VIX",
                    Rule   = new ExpirationRule()
                }
            };

            var inst = new Instrument
            {
                ID                 = 1,
                Symbol             = "VIXCONTFUT",
                IsContinuousFuture = true,
                ContinuousFuture   = cf,
                Datasource         = new Datasource {
                    ID = 999, Name = "MockSource"
                }
            };

            var req = new RealTimeDataRequest(inst, BarSize.FiveSeconds);

            _cfBrokerMock.Setup(x => x.RequestFrontContract(It.IsAny <Instrument>(), It.IsAny <DateTime?>())).Returns(0);

            _broker.RequestRealTimeData(req);

            _cfBrokerMock.Verify(x => x.RequestFrontContract(It.IsAny <Instrument>(), It.IsAny <DateTime?>()));
        }
Пример #2
0
        public void RaisesDataEventWithTheContinuousFuturesAlias()
        {
            var cf = new ContinuousFuture()
            {
                ID               = 1,
                InstrumentID     = 1,
                Month            = 1,
                UnderlyingSymbol = new UnderlyingSymbol
                {
                    ID     = 1,
                    Symbol = "VIX",
                    Rule   = new ExpirationRule()
                }
            };

            var inst = new Instrument
            {
                ID                 = 1,
                Symbol             = "VIXCONTFUT",
                IsContinuousFuture = true,
                ContinuousFuture   = cf,
                Datasource         = new Datasource {
                    ID = 999, Name = "MockSource"
                }
            };

            var req = new RealTimeDataRequest(inst, BarSize.FiveSeconds);

            _cfBrokerMock.Setup(x => x.RequestFrontContract(It.IsAny <Instrument>(), It.IsAny <DateTime?>())).Returns(0);
            int assignedID = 0;

            _dataSourceMock.Setup(x => x.RequestRealTimeData(It.IsAny <RealTimeDataRequest>())).Callback <RealTimeDataRequest>(r => assignedID = r.AssignedID);

            bool raisedCorrectSymbol = false;

            _broker.RealTimeDataArrived += (sender, e) =>
                                           raisedCorrectSymbol = raisedCorrectSymbol ? raisedCorrectSymbol : e.InstrumentID == 1;
            _broker.RequestRealTimeData(req);

            var frontFutureInstrument = new Instrument
            {
                Symbol     = "VXF4",
                ID         = 2,
                Datasource = new Datasource {
                    ID = 999, Name = "MockSource"
                }
            };

            _cfBrokerMock.Raise(x => x.FoundFrontContract += null, new FoundFrontContractEventArgs(0, frontFutureInstrument, DateTime.Now));

            _dataSourceMock.Raise(x => x.DataReceived += null,
                                  new RealTimeDataEventArgs(2, MyUtils.ConvertToTimestamp(DateTime.Now), 100, 100, 100, 100, 50, 100, 2, assignedID));

            Thread.Sleep(50);

            Assert.IsTrue(raisedCorrectSymbol);
        }
Пример #3
0
        public void UseMonthSerializesCorrectlyWhenSetToFalse()
        {
            var ms = new MemoryStream();
            var cf = new ContinuousFuture();

            cf.UseDec = false;
            var serialized = MyUtils.ProtoBufSerialize(cf, ms);
            var cf2        = MyUtils.ProtoBufDeserialize <ContinuousFuture>(serialized, ms);

            Assert.AreEqual(false, cf2.UseDec);
        }
Пример #4
0
        public void RequestsCorrectFuturesContractForContinuousFutures()
        {
            var cf = new ContinuousFuture()
            {
                ID               = 1,
                InstrumentID     = 1,
                Month            = 1,
                UnderlyingSymbol = new UnderlyingSymbol
                {
                    ID     = 1,
                    Symbol = "VIX",
                    Rule   = new ExpirationRule()
                }
            };

            var inst = new Instrument
            {
                ID                 = 1,
                Symbol             = "VIXCONTFUT",
                IsContinuousFuture = true,
                ContinuousFuture   = cf,
                Datasource         = new Datasource {
                    ID = 999, Name = "MockSource"
                }
            };

            var req = new RealTimeDataRequest(inst, BarSize.FiveSeconds);

            _cfBrokerMock.Setup(x => x.RequestFrontContract(It.IsAny <Instrument>(), It.IsAny <DateTime?>())).Returns(0);

            _broker.RequestRealTimeData(req);

            var frontFutureInstrument = new Instrument
            {
                Symbol     = "VXF4",
                ID         = 2,
                Datasource = new Datasource {
                    ID = 999, Name = "MockSource"
                }
            };

            _cfBrokerMock.Raise(x => x.FoundFrontContract += null, new FoundFrontContractEventArgs(0, frontFutureInstrument, DateTime.Now));

            _dataSourceMock.Verify(x => x.RequestRealTimeData(
                                       It.Is <RealTimeDataRequest>(y =>
                                                                   y.Instrument.ID == 2)), Times.Once);
        }
Пример #5
0
        /// <summary>
        /// Add a new instrument
        /// </summary>
        /// <param name="instrument"></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>
        /// <exception cref="ArgumentException"></exception>
        public async Task <Instrument> AddInstrument(Instrument instrument, bool saveChanges = true)
        {
            //Check if an instrument with these unique constraints already exists
            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 &&
                                                                          x.Type == instrument.Type));

            if (existingInstrument != null)
            {
                //throw new ArgumentException("Unique constraint violation");
            }

            ValidateInstrument(instrument);

            //All this stuff is detached, so we need to get the attached objects
            instrument.Datasource      = Context.GetAttachedEntity(instrument.Datasource);
            instrument.Exchange        = Context.GetAttachedEntity(instrument.Exchange);
            instrument.PrimaryExchange = Context.GetAttachedEntity(instrument.PrimaryExchange);
            instrument.Tags            = instrument.Tags != null
                ? new List <Tag>(instrument.Tags.Select(Context.GetAttachedEntity).ToList())
                : new List <Tag>();

            //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(x => x.Sessions).FirstOrDefault(x => x.ID == instrument.SessionTemplateID);
                if (template != null)
                {
                    foreach (TemplateSession s in template.Sessions)
                    {
                        instrument.Sessions.Add(s.ToInstrumentSession());
                    }
                }
            }

            //Continuous future requires a bit of a workaround
            ContinuousFuture tmpCf = null;

            if (instrument.IsContinuousFuture)
            {
                tmpCf = instrument.ContinuousFuture; //EF can't handle circular references, so we hack around it
                instrument.ContinuousFuture   = null;
                instrument.ContinuousFutureID = null;
            }

            Context.Instruments.Add(instrument);
            if (saveChanges)
            {
                await Context.SaveChangesAsync().ConfigureAwait(false);
            }

            if (tmpCf != null)
            {
                tmpCf.UnderlyingSymbol = Context.GetAttachedEntity(tmpCf.UnderlyingSymbol);

                instrument.ContinuousFuture              = tmpCf;
                instrument.ContinuousFuture.Instrument   = instrument;
                instrument.ContinuousFuture.InstrumentID = instrument.ID.Value;
                if (saveChanges)
                {
                    await Context.SaveChangesAsync().ConfigureAwait(false);
                }
            }

            _logger.Info($"Instrument Manager: successfully added instrument {instrument}");

            return(instrument);
        }
Пример #6
0
        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            if (_addingNew &&
                _context.Instruments.Any(
                    x => x.DatasourceID == TheInstrument.DatasourceID &&
                    x.ExchangeID == TheInstrument.ExchangeID &&
                    x.Symbol == TheInstrument.Symbol &&
                    x.Expiration == TheInstrument.Expiration)
                )
            {
                //there's already an instrument with this key
                MessageBox.Show("Instrument already exists. Change datasource, exchange, or symbol.");
                return;
            }

            //check that if the user picked a template-based session set, he actually selected one of the templates
            if (TheInstrument.SessionsSource == SessionsSource.Template && TheInstrument.SessionTemplateID == -1)
            {
                MessageBox.Show("You must pick a session template.");
                return;
            }

            if (TheInstrument.IsContinuousFuture && TheInstrument.Type != InstrumentType.Future)
            {
                MessageBox.Show("Continuous futures type must be Future.");
                return;
            }

            if (TheInstrument.Datasource == null)
            {
                MessageBox.Show("You must select a data source.");
                return;
            }

            if (TheInstrument.Multiplier == null)
            {
                MessageBox.Show("Must have a multiplier value.");
                return;
            }

            //Validate the sessions
            if (SelectedSessions.Count > 0)
            {
                try
                {
                    MyUtils.ValidateSessions(SelectedSessions.ToList <ISession>());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }

            //move selected sessions to the instrument
            TheInstrument.Sessions.Clear();
            foreach (InstrumentSession s in SelectedSessions)
            {
                //need to attach?
                TheInstrument.Sessions.Add(s);
            }

            TheInstrument.Tags.Clear();

            foreach (Tag t in Tags.Where(x => x.IsChecked).Select(x => x.Item))
            {
                _context.Tags.Attach(t);
                TheInstrument.Tags.Add(t);
            }

            ContinuousFuture tmpCF = null;

            if (_addingNew)
            {
                if (TheInstrument.Exchange != null)
                {
                    _context.Exchanges.Attach(TheInstrument.Exchange);
                }
                if (TheInstrument.PrimaryExchange != null)
                {
                    _context.Exchanges.Attach(TheInstrument.PrimaryExchange);
                }
                _context.Datasources.Attach(TheInstrument.Datasource);

                if (TheInstrument.IsContinuousFuture)
                {
                    tmpCF = TheInstrument.ContinuousFuture; //EF can't handle circular references, so we hack around it
                    TheInstrument.ContinuousFuture   = null;
                    TheInstrument.ContinuousFutureID = null;
                }
                _context.Instruments.Add(TheInstrument);
            }
            else //simply manipulating an existing instrument
            {
                //make sure any "loose" sessions are deleted
                if (!_addingNew)
                {
                    foreach (InstrumentSession s in _originalSessions.Where(s => !TheInstrument.Sessions.Any(x => x.ID == s.ID)))
                    {
                        _context.InstrumentSessions.Remove(s);
                    }
                }
            }

            _context.Database.Connection.Open();
            _context.SaveChanges();

            if (tmpCF != null)
            {
                _context.UnderlyingSymbols.Attach(tmpCF.UnderlyingSymbol);

                TheInstrument.ContinuousFuture              = tmpCF;
                TheInstrument.ContinuousFuture.Instrument   = TheInstrument;
                TheInstrument.ContinuousFuture.InstrumentID = TheInstrument.ID.Value;
                _context.SaveChanges();
            }

            InstrumentAdded = true;
            Hide();
        }