Esempio n. 1
0
        private void LoadDataBtn_Click(object sender, RoutedEventArgs e)
        {
            Data.Clear();

            //grab the data
            //todo remove dependency on DataStorageFactory
            using (var localStorage = DataStorageFactory.Get())
            {
                var bars = localStorage.GetData(TheInstrument, StartTime, EndTime, (BarSize)ResolutionComboBox.SelectedItem);

                //find largest significant decimal by sampling the prices at the start and end of the series
                var decPlaces = new List <int>();
                for (int i = 0; i < Math.Min(bars.Count, 20); i++)
                {
                    decPlaces.Add(bars[i].Open.CountDecimalPlaces());
                    decPlaces.Add(bars[bars.Count - 1 - i].Close.CountDecimalPlaces());
                }

                //set the column format to use that number so we don't get any useless trailing 0s
                SetPriceColumnFormat(decPlaces.Max());

                foreach (OHLCBar b in bars)
                {
                    //do any required time zone coversions
                    if (TimezoneComboBox.Text == "UTC")
                    {
                        b.DT = TimeZoneInfo.ConvertTimeToUtc(b.DT, _tzInfo);
                    }
                    else if (TimezoneComboBox.Text == "Local")
                    {
                        b.DT = TimeZoneInfo.ConvertTime(b.DT, _tzInfo, TimeZoneInfo.Local);
                    }
                    Data.Add(b);
                }
                _loadedFrequency = (BarSize)ResolutionComboBox.SelectedItem;
                _loadedTimeZone  = TimezoneComboBox.Text;
            }

            StatusLabel.Content = string.Format("Loaded {0} Bars", Data.Count);
        }
Esempio n. 2
0
        private void ImportBtn_Click(object sender, RoutedEventArgs e)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            //check that we've got the relevant data needed
            if (!Data.Columns.Contains("Date") && !Data.Columns.Contains("DateTime"))
            {
                MessageBox.Show("Must have a date column.");
                return;
            }

            if ((BarSize)FrequencyComboBox.SelectedItem < BarSize.OneDay && !Data.Columns.Contains("DateTime") && !Data.Columns.Contains("Time"))
            {
                MessageBox.Show("Must have time column at this frequency");
                return;
            }

            if (!Data.Columns.Contains("Open") ||
                !Data.Columns.Contains("High") ||
                !Data.Columns.Contains("Low") ||
                !Data.Columns.Contains("Close"))
            {
                MessageBox.Show("Must have all OHLC columns.");
                return;
            }

            TimeZoneInfo tzInfo = TimeZoneInfo.Utc;

            //make sure the timezone is set, and get it
            if (!string.IsNullOrEmpty(_instrument.Exchange?.Timezone))
            {
                tzInfo = TimeZoneInfo.FindSystemTimeZoneById(_instrument.Exchange.Timezone);
            }


            //get the multipliers
            decimal priceMultiplier;
            int     volumeMultiplier;
            bool    parseWorked = decimal.TryParse(PriceMultiplier.Text, out priceMultiplier);

            if (!parseWorked)
            {
                priceMultiplier = 1;
            }
            parseWorked = int.TryParse(VolumeMultiplier.Text, out volumeMultiplier);
            if (!parseWorked)
            {
                volumeMultiplier = 1;
            }

            //lines to skip
            int toSkip;

            parseWorked = int.TryParse(StartingLine.Text, out toSkip);
            if (!parseWorked)
            {
                toSkip = 1;
            }

            //get the frequency
            var frequency = (BarSize)FrequencyComboBox.SelectedItem;

            //separator
            char[] separator = DelimiterBox.Text.ToCharArray();


            List <OHLCBar> bars = new List <OHLCBar>();

            string[] columns = new string[Data.Columns.Count];
            for (int i = 0; i < Data.Columns.Count; i++)
            {
                columns[i] = Data.Columns[i].ColumnName;
            }

            //determining time: if the freq is >= one day, then the time is simply the session end for this day
            Dictionary <int, TimeSpan> sessionEndTimes = new Dictionary <int, TimeSpan>();


            //1 day and up: we can load it all in one go with no trouble, also may require adjustment
            bool    periodicSaving = frequency < BarSize.OneDay;
            OHLCBar bar;
            var     barsCount = 0;

            using (StreamReader sr = new StreamReader(FilePathTextBox.Text))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    barsCount++;
                    if (barsCount < toSkip)
                    {
                        continue;
                    }

                    try
                    {
                        bar = ParseLine(line.Split(separator), columns, priceMultiplier, volumeMultiplier);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Importing error: " + ex.Message + "\n" + line);
                        return;
                    }

                    //only add the bar if it falls within the specified date range
                    if (bar.DT >= MinDT.Value && bar.DT <= MaxDT.Value)
                    {
                        bars.Add(bar);
                    }

                    //with 30 bars, we make a check to ensure that the user has entered the correct frequency
                    if (bars.Count == 30)
                    {
                        //the reason we have to use a bunch of bars and look for the most frequent timespan between them
                        //is that session breaks, daily breaks, weekends, etc. can have different timespans despite the
                        //correct frequency being chosen
                        List <int> secDiffs = new List <int>();
                        for (int i = 1; i < bars.Count; i++)
                        {
                            secDiffs.Add((int)Math.Round((bars[i].DT - bars[i - 1].DT).TotalSeconds));
                        }

                        int mostFrequent = secDiffs.MostFrequent();
                        if ((int)Math.Round(frequency.ToTimeSpan().TotalSeconds) != Math.Abs(mostFrequent))
                        {
                            MessageBox.Show("You appear to have selected the wrong frequency.");
                            return;
                        }
                    }

                    if (periodicSaving && bars.Count > 1000)
                    {
                        //convert to exchange timezone
                        ConvertTimeZone(bars, tzInfo);

                        //low frequencies, < 1 day. No adjustment required and inserting data at intervals instead of all at once
                        IDataClient client;
                        //client.PushData(new DataAdditionRequest(frequency, _instrument, bars, OverwriteCheckbox.IsChecked.HasValue && OverwriteCheckbox.IsChecked.Value, false));
                        //todo remove dependency on DataStorageFactory
                        using (var storage = DataStorageFactory.Get())
                        {
                            try
                            {
                                storage.AddData(bars, _instrument, frequency, OverwriteCheckbox.IsChecked.HasValue && OverwriteCheckbox.IsChecked.Value, false);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error: " + ex.Message);
                            }
                        }
                        bars.Clear();
                    }
                }
            }

            if (bars.Count == 0)
            {
                return;
            }

            //convert to exchange timezone
            ConvertTimeZone(bars, tzInfo);


            //if only the date column is set, we need to get the session info and generate the closing time ourselves
            if (frequency >= BarSize.OneDay && !Data.Columns.Contains("Time") && !Data.Columns.Contains("DateTime"))
            {
                //get the closing time for every day of the week
                var dotwValues = MyUtils.GetEnumValues <DayOfTheWeek>();

                foreach (DayOfTheWeek d in dotwValues)
                {
                    if (_instrument.Sessions.Any(x => x.ClosingDay == d && x.IsSessionEnd))
                    {
                        var endTime = _instrument.Sessions.First(x => x.ClosingDay == d && x.IsSessionEnd).ClosingTime;
                        sessionEndTimes.Add((int)d, endTime);
                    }
                    else
                    {
                        sessionEndTimes.Add((int)d, TimeSpan.FromSeconds(0));
                    }
                }

                for (int i = 0; i < bars.Count; i++)
                {
                    int dayOfWeek = bars[i].DT.DayOfWeek.ToInt();
                    bars[i].DT = bars[i].DT.Date + sessionEndTimes[dayOfWeek];
                }
            }

            //if there are no dividends/splits, but there IS an adjclose column, use that to adjust data right here
            //if there are divs/splits, adjustment will be done by the local storage
            if (frequency >= BarSize.OneDay && !Data.Columns.Contains("Dividends") && !Data.Columns.Contains("Splits") && Data.Columns.Contains("AdjClose"))
            {
                //if we have an adjusted close to work off of, we just use the ratio to get the OHL
                for (int i = 0; i < bars.Count; i++)
                {
                    if (bars[i].AdjClose == null)
                    {
                        continue;
                    }

                    decimal ratio = bars[i].AdjClose.Value / bars[i].Close;
                    bars[i].AdjOpen = bars[i].Open * ratio;
                    bars[i].AdjHigh = bars[i].High * ratio;
                    bars[i].AdjLow  = bars[i].Low * ratio;
                }
            }


            //sort by date
            if (frequency >= BarSize.OneDay)
            {
                bars.Sort((x, y) => x.DT.CompareTo(y.DT));
            }

            //try to import
            //todo remove dependency on DataStorageFactory
            using (var storage = DataStorageFactory.Get())
            {
                try
                {
                    storage.AddData(bars,
                                    _instrument,
                                    frequency,
                                    OverwriteCheckbox.IsChecked.HasValue && OverwriteCheckbox.IsChecked.Value,
                                    frequency >= BarSize.OneDay);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
            sw.Stop();
            MessageBox.Show(string.Format("Imported {0} bars in {1} ms.", barsCount, sw.ElapsedMilliseconds));
        }