private static string GetFormattedMessage(string source, Instrument instrument, string message)
 {
     string prefix = string.Format("[{0}  |  {1}]", instrument.Symbol.ToUpper(), source.ToUpper());
     string datePart = string.Format("[{0:dd-MMM-yyyy hh:mm:ss.fff tt}]", DateTime.Now);
     const string formattedString = "{0} -- {1} -- {2}";
     return string.Format(formattedString, prefix, datePart, message);
 }
Beispiel #2
0
		///<summary>
		///  Returns bar series by instrument 
		///</summary>
		public BarSeries this [Instrument instrument]
		{
			get
			{
				return new BarSeries(FreeQuant.Instruments.DataManager.Bars[Map.OQ_FQ_Instrument[(object)instrument] as FreeQuant.Instruments.Instrument]);
			}
		}
Beispiel #3
0
		///<summary>
		///  Gets bar series by instrument, bar type and bar size
		///</summary>
		public BarSeries this [Instrument instrument, BarType barType, long barSize]
		{
			get
			{
				return new BarSeries(FreeQuant.Instruments.DataManager.Bars[Map.OQ_FQ_Instrument[(object)instrument] as FreeQuant.Instruments.Instrument, EnumConverter.Convert(barType), barSize]);
			}
		}
        internal static void WriteTraceLog(this Logger log, string source, Instrument instrument, string message)
        {
            if (!log.IsTraceEnabled)
                return;

            log.Trace(GetFormattedMessage(source, instrument, message));
        }
		public BarSeries this[Instrument instrument]
		{
			get
			{
				SmartQuant.Instruments.Instrument instrument2 = Map.OQ_SQ_Instrument[instrument] as SmartQuant.Instruments.Instrument;
				return new BarSeries(SmartQuant.Instruments.DataManager.Bars[instrument2]);
			}
		}
		public BarSeries this[Instrument instrument, BarType barType, long barSize]
		{
			get
			{
				SmartQuant.Instruments.Instrument instrument2 = Map.OQ_SQ_Instrument[instrument] as SmartQuant.Instruments.Instrument;
				return new BarSeries(SmartQuant.Instruments.DataManager.Bars[instrument2, EnumConverter.Convert(barType), barSize]);
			}
		}
Beispiel #7
0
		public static BarSeries GetHistoricalBars(Instrument instrument, DateTime begin, DateTime end, BarType barType, long barSize)
		{
			FreeQuant.Instruments.Instrument instrument1 = Map.OQ_FQ_Instrument[(object)instrument] as FreeQuant.Instruments.Instrument;
			if (barSize == 86400)
				return new BarSeries((FreeQuant.Series.BarSeries)FreeQuant.Instruments.DataManager.GetDailySeries(instrument1, begin, end));
			else
				return new BarSeries(FreeQuant.Instruments.DataManager.GetBarSeries(instrument1, begin, end, EnumConverter.Convert(barType), barSize));
		}
		public static BarSeries GetHistoricalBars(Instrument instrument, DateTime begin, DateTime end, BarType barType, long barSize)
		{
			SmartQuant.Instruments.Instrument instrument2 = Map.OQ_SQ_Instrument[instrument] as SmartQuant.Instruments.Instrument;
			if (barSize == 86400L)
			{
				return new BarSeries(SmartQuant.Instruments.DataManager.GetDailySeries(instrument2, begin, end));
			}
			return new BarSeries(SmartQuant.Instruments.DataManager.GetBarSeries(instrument2, begin, end, EnumConverter.Convert(barType), barSize));
		}
Beispiel #9
0
		public static TradeSeries GetHistoricalTrades(string provider, Instrument instrument, DateTime begin, DateTime end)
		{
			TradeSeries tradeSeries = new TradeSeries();
			if (FreeQuant.Providers.ProviderManager.HistoricalDataProviders.Contains(provider))
			{
				foreach (FreeQuant.Data.Trade trade in (DataArray) FreeQuant.Instruments.DataManager.GetHistoricalTrades(FreeQuant.Providers.ProviderManager.HistoricalDataProviders[provider], instrument.instrument, begin, end))
					tradeSeries.series.Add((IDataObject)trade);
			}
			return tradeSeries;
		}
Beispiel #10
0
		public static QuoteSeries GetHistoricalQuotes(string provider, Instrument instrument, DateTime begin, DateTime end)
		{
			QuoteSeries quoteSeries = new QuoteSeries();
			if (FreeQuant.Providers.ProviderManager.HistoricalDataProviders.Contains(provider))
			{
				foreach (FreeQuant.Data.Quote quote in (DataArray) FreeQuant.Instruments.DataManager.GetHistoricalQuotes(FreeQuant.Providers.ProviderManager.HistoricalDataProviders[provider], instrument.instrument, begin, end))
					quoteSeries.series.Add((IDataObject)quote);
			}
			return quoteSeries;
		}
Beispiel #11
0
 public Position this[Instrument instrument]
 {
   get
   {
     FreeQuant.Instruments.Position position = this.positionList[instrument.instrument];
     if (position != null)
       return new Position(position);
     else
       return (Position) null;
   }
 }
Beispiel #12
0
		public static BarSeries GetHistoricalBars(string provider, Instrument instrument, DateTime begin, DateTime end, int size)
		{
			BarSeries barSeries = new BarSeries();
			if (FreeQuant.Providers.ProviderManager.HistoricalDataProviders.Contains(provider))
			{
				IHistoricalDataProvider provider1 = FreeQuant.Providers.ProviderManager.HistoricalDataProviders[provider];
				foreach (FreeQuant.Data.Bar bar in size != 86400 ? (FreeQuant.Series.TimeSeries) FreeQuant.Instruments.DataManager.GetHistoricalBars(provider1, instrument.instrument, begin, end, (long) size) : (FreeQuant.Series.TimeSeries) FreeQuant.Instruments.DataManager.GetHistoricalDailies(provider1, instrument.instrument, begin, end))
					barSeries.series.Add(bar);
			}
			return barSeries;
		}
		public Position this[Instrument instrument]
		{
			get
			{
				SmartQuant.Instruments.Position position = this.positionList[instrument.instrument];
				if (position != null)
				{
					return new Position(position);
				}
				return null;
			}
		}
Beispiel #14
0
		public static QuoteSeries GetHistoricalQuotes(string provider, Instrument instrument, DateTime begin, DateTime end)
		{
			QuoteSeries quoteSeries = new QuoteSeries();
			if (SmartQuant.Providers.ProviderManager.HistoricalDataProviders.Contains(provider))
			{
				QuoteArray historicalQuotes = SmartQuant.Instruments.DataManager.GetHistoricalQuotes(SmartQuant.Providers.ProviderManager.HistoricalDataProviders[provider], instrument.instrument, begin, end);
				foreach (SmartQuant.Data.Quote obj in historicalQuotes)
				{
					quoteSeries.series.Add(obj);
				}
			}
			return quoteSeries;
		}
        public QuantityTradeLeg(int idx, Instrument instrument, OrderSide orderSide, double qty)
            : base(idx, instrument, orderSide)
        {
            this.QuantityToFill = qty;
            this.LegName = string.Format("Q{0}.{1}.{2}.{3}",
                this.Index,
                this.Instrument.Symbol.ToUpper(),
                this.OrderSide,
                this.QuantityToFill);

            Log.WriteInfoLog(LegName,
               this.Instrument,
               string.Format("Quantity leg generated to {0} {1:N2} units", this.OrderSide.ToString().ToUpper(), this.QuantityToFill));
        }
        public AmountTradeLeg(int idx, Instrument instrument, OrderSide orderSide, double amt)
            : base(idx, instrument, orderSide)
        {
            this.AmountToFill = amt;
            this.LegName = string.Format("A{0}.{1}.{2}.{3:c}",
                this.Index,
                this.Instrument.Symbol.ToUpper(),
                this.OrderSide,
                this.AmountToFill);

            Log.WriteInfoLog(LegName,
               this.Instrument,
               string.Format("Amount leg generated to {0} {1:c2}", this.OrderSide.ToString().ToUpper(), this.AmountToFill));
        }
		private double GetAmount(Instrument instrument, double amount)
		{
			if (instrument.Quote.DateTime != DateTime.MinValue)
			{
				return (instrument.Quote.Ask + instrument.Quote.Bid) / 2.0;
			}
			if (instrument.Trade.DateTime != DateTime.MinValue && instrument.Trade.DateTime >= instrument.Bar.DateTime)
			{
				return instrument.Trade.Price;
			}
			if (instrument.Bar.DateTime != DateTime.MinValue)
			{
				return instrument.Bar.Close;
			}
			return 1.0;
		}
Beispiel #18
0
        public override void OnStrategyStart()
        {
            if (Instrument1 == null)
            {
                Instrument1 = Instrument;
            }
            else if (Instrument2 == null)
            {
                Instrument2 = Instrument;
            }

            barSize = long.MaxValue;
            foreach (BarRequest barRequest in DataRequests.BarRequests)
            {
                barSize = Math.Min(barSize, barRequest.BarSize);
            }
            Console.WriteLine("barSize = {0}", barSize);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private double GetPriceStep(double input, Instrument instrument)
        {
            double retValue = 0.01;
            if (instrument.Type == InstrumentType.Futures)
            {
                if (string.Compare(instrument.Symbol, "ES", true) == 0)
                {
                    retValue = 0.25;
                }
            }
            else if (instrument.Type == InstrumentType.Stock)
            {
                if (input < 1)
                    retValue = 0.001;
            }

            return retValue;
        }
Beispiel #20
0
		public void Add(DateTime datetime, TransactionSide side, double qty, Instrument instrument, double price, string text)
		{
			Side side2;
			switch (side)
			{
			case TransactionSide.Buy:
				side2 = Side.Buy;
				break;
			case TransactionSide.Sell:
				side2 = Side.Sell;
				break;
			default:
				throw new ArgumentException(string.Format("Unknown TransactionSide - {0} ", side));
			}
			SmartQuant.Instruments.Transaction transaction = new SmartQuant.Instruments.Transaction(datetime, side2, qty, instrument.instrument, price);
			transaction.Currency = CurrencyManager.Currencies[instrument.instrument.Currency];
			if (text != null)
			{
				transaction.Text = text;
			}
			this.portfolio.Add(transaction);
		}
Beispiel #21
0
		public static BarSeries GetHistoricalBars(string provider, Instrument instrument, DateTime begin, DateTime end, int size)
		{
			BarSeries barSeries = new BarSeries();
			if (SmartQuant.Providers.ProviderManager.HistoricalDataProviders.Contains(provider))
			{
				IHistoricalDataProvider provider2 = SmartQuant.Providers.ProviderManager.HistoricalDataProviders[provider];
				SmartQuant.Series.BarSeries barSeries2;
				if (size == 86400)
				{
					barSeries2 = SmartQuant.Instruments.DataManager.GetHistoricalDailies(provider2, instrument.instrument, begin, end);
				}
				else
				{
					barSeries2 = SmartQuant.Instruments.DataManager.GetHistoricalBars(provider2, instrument.instrument, begin, end, (long)size);
				}
				foreach (SmartQuant.Data.Bar bar in barSeries2)
				{
					barSeries.series.Add(bar);
				}
			}
			return barSeries;
		}
 internal static void WriteHorizontalBreak(this Logger log, string source, Instrument instrument)
 {
     WriteInfoLog(log, source, instrument, "----------------------------");
 }
        protected ATR GetAtr(Instrument instrument, int period)
        {
            BarSeries dailyBarSeries = null;

            string instId = instrument.ToIdentifier();
            dailyBarSeriesDictionary.TryGetValue(instId, out dailyBarSeries);

            if (dailyBarSeries == null || dailyBarSeries.Count <= 0)
                throw new ApplicationException("Daily bar series has not been initialized");

            string atrId = string.Format("{0}:{1}", instId, period);

            if (!atrDictionary.ContainsKey(atrId))
            {
                lock (LockObject)
                {
                    if (!atrDictionary.ContainsKey(atrId))
                    {
                        ATR atr = new ATR(dailyBarSeries, period);
                        atrDictionary.Add(atrId, atr);
                    }
                }
            }

            return atrDictionary[atrId];
        }
Beispiel #24
0
 internal void Remove(Instrument instrument)
 {
     this.list.Remove(instrument.Symbol);
 }
        private void AttachInstrument(Project prj, string symbol)
        {
            if (string.IsNullOrEmpty(symbol))
                return;

            string trimmedSymbol = symbol.Trim();
            string normalizedSymbol = string.Empty;

            if (trimmedSymbol.Length > 0)
            {
                normalizedSymbol = trimmedSymbol.Replace(".", "");
                Instrument currentIns = InstrumentManager.Instruments[normalizedSymbol];

                if (null == currentIns || currentIns.Type != InstrumentType.Stock)
                {
                    Console.WriteLine("ADDING SYMBOL -- " + trimmedSymbol);
                    Instrument newInstrument = new Instrument(InstrumentType.Stock, normalizedSymbol);
                    newInstrument.Currency = defaultCurrency;
                    newInstrument.Exchange = defaultExchange;

                    int dotIdx = trimmedSymbol.IndexOf('.');
                    if (dotIdx > -1)
                    {
                        AltIDGroup ibAltIdGroup = newInstrument.AltIDGroups.Add("IB");
                        ibAltIdGroup.AltSource = "IB";
                        ibAltIdGroup.AltSymbol = trimmedSymbol.Replace(".", " ");
                    }
                }

                currentIns = InstrumentManager.Instruments[normalizedSymbol];
                if (null != currentIns)
                    prj.AddInstrument(currentIns);

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="instrument"></param>
        /// <param name="atrPeriod"></param>
        /// <param name="triggerTime"></param>
        /// <returns></returns>
        protected double GetAtrValue(Instrument instrument, int atrPeriod, DateTime triggerTime)
        {
            ATR atr = GetAtr(instrument, atrPeriod);
            double returnValue = 0;
            int idx = atr.Count - 1;
            bool found = false;

            while (!found && idx >= 0)
            {
                if (atr.GetDateTime(idx) < triggerTime)
                {
                    found = true;
                    returnValue = atr[idx];
                    break;
                }
                idx--;
            }

            if (!found || returnValue <= 0)
                throw new ApplicationException(string.Format("Count not retrieve an ATR for {0} before bar {1}", instrument.Symbol, triggerTime));

            LoggingUtility.WriteInfo(LoggingConfig, string.Format("Found ATR value of {0:c} as of {1}", returnValue, atr.GetDateTime(idx)));

            return returnValue;
        }
        private void PreLoadDailyDataImpl(Instrument instrument, BarDuration  duration)
        {
            BarSeries series = null;
            string id = instrument.ToIdentifier();
            Dictionary<string, BarSeries> dictionaryToUse = null;

            if (duration == BarDuration.Daily)
                dictionaryToUse = dailyBarSeriesDictionary;
            else if (duration == BarDuration.Minutely)
                dictionaryToUse = minutelyBarSeriesDictionary;
            else
                throw new ArgumentOutOfRangeException("duration", duration, "Incorrect value for duration");

            dictionaryToUse.TryGetValue(id, out series);
            if (null != series && series.Count >= 1)
                return;

            DateTime start = DateTime.Now;
            if (duration == BarDuration.Daily)
                series = GetHistoricalBars("IB", Instrument, DateTime.Now.AddDays(-60), DateTime.Now, PeriodConstants.PERIOD_DAILY);
            else if (duration == BarDuration.Minutely)
                series = GetHistoricalBars("IB", instrument, DateTime.Now.AddDays(-5), DateTime.Now, PeriodConstants.PERIOD_MINUTE);
            DateTime end = DateTime.Now;

            LoggingUtility.WriteDebug(LoggingConfig, string.Format("Took {0}ms to retrieve data from IB for {1} data", end.Subtract(start).TotalMilliseconds, duration));

            dictionaryToUse[id] = series;

            start = DateTime.Now;
            foreach (Bar currentBar in series)
            {
                Bars.Add(currentBar);
                if (PersistHistoricalData)
                    DataManager.Add(Instrument, currentBar);
            }
            end = DateTime.Now;

            LoggingUtility.WriteDebug(LoggingConfig, string.Format("Took {0}ms to load data into memory for {1} data", end.Subtract(start).TotalMilliseconds, duration));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="instrument"></param>
        protected void PreLoadBarData(Instrument instrument)
        {
            PreLoadDailyDataImpl(instrument, BarDuration.Minutely);

            PreLoadDailyDataImpl(instrument, BarDuration.Daily);
        }
        protected Bar GetPreviousDayBar(Instrument instrument)
        {
            Bar retVal = null;
            string instId = instrument.ToIdentifier();
            BarSeries barsToUse = dailyBarSeriesDictionary[instId];

            if (barsToUse.Count > 0)
            {
                int idx = 0;
                bool found = false;

                while (!found && idx <= barsToUse.Count - 1)
                {
                    Bar prevBar = barsToUse.Ago(idx);
                    if (prevBar.EndTime.Date <= DateTime.Today)
                    {
                        if (prevBar.IsWithinRegularTradingHours(Instrument.Type))
                        {
                            found = DateTime.Today.Subtract(prevBar.BeginTime.Date).TotalDays >= 1;
                            if (!found && DateTime.Now.IsPastRegularTradingHours(Instrument.Type))
                                found = DateTime.Today.Subtract(prevBar.BeginTime.Date).TotalDays >= 0;
                        }
                    }

                    if (found)
                        retVal = prevBar;
                    else
                        idx++;
                }
            }

            if (retVal == null)
                throw new ApplicationException(string.Format("Count not retreive a daily bar prior to {0}", DateTime.Today));

            LoggingUtility.WriteDebug(LoggingConfig, string.Format("Previous closing bar was {0}", retVal));

            return retVal;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bar"></param>
        /// <returns></returns>
        protected Bar GetPreviousBar(Instrument instrument, Bar bar, int period)
        {
            Bar retVal = null;
            BarSeries barsToUse = null;
            string instId = instrument.ToIdentifier();
            Dictionary<string, BarSeries> dictionaryToUse = null;

            bool isSessionOpenBar = bar.IsSessionOpenBar(Instrument.Type);
            bool isDailyPeriod = period == PeriodConstants.PERIOD_DAILY;

            if (isDailyPeriod) // || isSessionOpenBar
                dictionaryToUse = dailyBarSeriesDictionary;
            else
                dictionaryToUse = minutelyBarSeriesDictionary;

            barsToUse = dictionaryToUse[instId];

            if (barsToUse.Count > 0)
            {
                int idx = 0;
                bool found = false;

                while (!found && idx <= barsToUse.Count - 1)
                {
                    Bar prevBar = barsToUse.Ago(idx);
                    if ((prevBar.EndTime <= bar.BeginTime) && prevBar.IsWithinRegularTradingHours(Instrument.Type))
                    {
                        if (isSessionOpenBar || isDailyPeriod)
                        {
                            found = DateTime.Today.Subtract(prevBar.BeginTime.Date).TotalDays >= 1;
                            if (!found && DateTime.Now.IsPastRegularTradingHours(Instrument.Type))
                                found = DateTime.Today.Subtract(prevBar.BeginTime.Date).TotalDays >= 0;
                        }
                        else
                        {
                            found = true;
                        }
                    }

                    if (found)
                        retVal = prevBar;
                    else
                        idx++;
                }
            }

            if (retVal == null)
                throw new ApplicationException(string.Format("Count not retreive a period {0} bar to {1}", period, bar));

            LoggingUtility.WriteDebug(LoggingConfig, string.Format("Previous closing bar was {0}", retVal));

            return retVal;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 public double RoundPrice(double input, Instrument instrument)
 {
     double step = GetPriceStep(input, instrument);
     return Math.Round(input / step) * step;
 }
Beispiel #32
0
 internal void Add(string symbol, Instrument instrument)
 {
     this.list.Add(symbol, instrument);
 }