private void btnCreateSimulatedData_Click(object sender, RoutedEventArgs e)
        {
            var wnd = new wndCreateSimulatedData();
            var res = wnd.ShowDialog();

            if (!res.HasValue || !res.Value)
            {
                return;
            }

            if (HistoricalData.Any(p => p.Symbol.Equals(wnd.Symbol) && p.DataFeed.Equals(wnd.DataFeed) &&
                                   p.Periodicity == wnd.Periodicity && p.Interval == wnd.Interval))
            {
                MessageBox.Show("Historical data with same parameters already loaded",
                                "Info", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var data = GlobalHelper.CreateSimulated(new SimulatedDataParameters
            {
                Symbol       = wnd.Symbol,
                SecurityId   = wnd.SecurityID,
                DataFeed     = wnd.DataFeed,
                Periodicity  = wnd.Periodicity,
                Interval     = wnd.Interval,
                BarsCount    = wnd.BarsCount,
                TicksCount   = wnd.TicksCount,
                MarketLevels = wnd.MarketLevels,
                PriceMax     = wnd.PriceMax,
                PriceMin     = wnd.PriceMin,
                Slot         = wnd.Slot
            });

            ////optional
            //var questionResult = MessageBox.Show("Save simulated data to CSV file?", "Question",
            //    MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
            //if (questionResult == MessageBoxResult.Yes)
            //{
            //    var saveFileDialog = new SaveFileDialog();
            //    saveFileDialog.Filter = "CSV Files|*.csv";
            //    saveFileDialog.FilterIndex = 1;
            //    saveFileDialog.RestoreDirectory = true;
            //    saveFileDialog.FileName = data.ToString().Replace('/', '-');
            //    if (saveFileDialog.ShowDialog().Value)
            //    {
            //        using (var writer = File.CreateText(saveFileDialog.FileName))
            //            writer.Write(GlobalHelper.CreateCSV(data));
            //    }
            //}

            HistoricalData.Add(data);
        }
        public override Task <bool?> ShouldBuyStock(StockInput newData)
        {
            HistoricalData.Add(newData);
            var modelBuilder = new ModelBuilder(_config);
            var model        = modelBuilder.BuildModel(HistoricalData.Select(x => new ModelInput
            {
                PriceDiffrence = (float)((x.ClosingPrice - HistoricalData.Last().ClosingPrice) / HistoricalData.Last().ClosingPrice),
                Time           = x.Time
            }).ToList());
            var result = model.Predict();

            return(Task.FromResult((bool?)(result.ForecastedPriceDiffrence[0] > 0)));
        }
        public override Task <bool?> ShouldBuyStock(StockInput newData)
        {
            HistoricalData.Add(newData);
            if (HistoricalData.Count > 20)
            {
                HistoricalData = HistoricalData.OrderByDescending(x => x.Time).Take(20).ToList();

                var avg  = HistoricalData.Select(x => x.ClosingPrice).Average();
                var diff = avg - newData.ClosingPrice;

                return(Task.FromResult <bool?>(diff >= 0));
            }
            else
            {
                Console.WriteLine($"Waiting on more data for {GetType().Name}.");
                return(Task.FromResult <bool?>(null));
            }
        }
        private void btnLoadFile_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "CSV Files|*.csv|Text Files|*.txt";
            var dialogResult = openFileDialog.ShowDialog();

            if (!dialogResult.HasValue || !dialogResult.Value)
            {
                return;
            }
            var fileName = openFileDialog.FileName;

            if (String.IsNullOrEmpty(fileName))
            {
                return;
            }

            var result = GlobalHelper.LoadDataFromCSV(fileName);

            if (result == null)
            {
                MessageBox.Show("Failed to load data from file " + fileName,
                                "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                if (HistoricalData.Any(p => p.Symbol.Equals(result.Symbol) && p.DataFeed.Equals(result.DataFeed) &&
                                       p.Periodicity == result.Periodicity && p.Interval == result.Interval))
                {
                    MessageBox.Show("Historical data with same parameters already loaded",
                                    "Info", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                HistoricalData.Add(result);
            }
        }
        public override Task <bool?> ShouldBuyStock(StockInput newData)
        {
            HistoricalData.Add(newData);
            HistoricalData = HistoricalData.OrderByDescending(x => x.Time).Take(3).ToList();

            var last3Values = HistoricalData.Select(x => x.ClosingPrice).ToList();

            //Default to hold
            var result = (bool?)null;

            if (last3Values.Count >= 3 && last3Values[0] > last3Values[1] && last3Values[1] > last3Values[2])
            {
                //Buy if we have 2 mins of increase
                result = true;
            }
            else if (last3Values.Count >= 3 && (last3Values[0] < last3Values[1] || last3Values[1] < last3Values[2]))
            {
                //Sell if any decrease in price
                result = false;
            }

            return(Task.FromResult(result));
        }
        public override void ProcessResponse(Session session, Message message, bool isPartialResponse, Action <Session, Message, Exception> onFailure)
        {
            IObserver <HistoricalDataResponse> observer;

            if (!TryGet(message.CorrelationID, out observer))
            {
                onFailure(session, message, new Exception("Unable to find handler for correlation id: " + message.CorrelationID));
                return;
            }

            if (message.HasElement(ElementNames.ResponseError))
            {
                var responseErrorElement = message.GetElement(ElementNames.ResponseError);
                var error = new ResponseError(
                    responseErrorElement.GetElementAsString(ElementNames.Source),
                    responseErrorElement.GetElementAsString(ElementNames.Category),
                    responseErrorElement.GetElementAsString(ElementNames.SubCategory),
                    responseErrorElement.GetElementAsInt32(ElementNames.Code),
                    responseErrorElement.GetElementAsString(ElementNames.Message));
                observer.OnError(new ContentException <ResponseError>(error));
                // We assume that no more messages will be sent on this correlation id.
                Remove(message.CorrelationID);
                return;
            }

            var historicalDataResponse = new HistoricalDataResponse();

            var securityDataArrayElement = message.GetElement(ElementNames.SecurityData);

            for (var securityIndex = 0; securityIndex < securityDataArrayElement.NumValues; ++securityIndex)
            {
                var securityDataElement = securityDataArrayElement.GetElement(securityIndex);
                var ticker = securityDataElement.GetValueAsString();

                if (securityDataArrayElement.HasElement(ElementNames.SecurityError))
                {
                    var securityErrorElement = securityDataArrayElement.GetElement(ElementNames.SecurityError);
                    var responseError        = new ResponseError(
                        securityErrorElement.GetElementAsString(ElementNames.Source),
                        securityErrorElement.GetElementAsString(ElementNames.Category),
                        securityErrorElement.GetElementAsString(ElementNames.SubCategory),
                        securityErrorElement.GetElementAsInt32(ElementNames.Code),
                        securityErrorElement.GetElementAsString(ElementNames.Message));

                    historicalDataResponse.Add(ticker, Either.Left <ResponseError, HistoricalData>(responseError));
                    continue;
                }

                var historicalData = new HistoricalData();

                var fieldDataArrayElement = securityDataArrayElement.GetElement(ElementNames.FieldData);

                for (var fieldDataIndex = 0; fieldDataIndex < fieldDataArrayElement.NumValues; ++fieldDataIndex)
                {
                    var data             = new Dictionary <string, object>();
                    var fieldDataElement = fieldDataArrayElement.GetValueAsElement(fieldDataIndex);

                    for (var i = 0; i < fieldDataElement.NumElements; ++i)
                    {
                        var fieldElement = fieldDataElement.GetElement(i);
                        var name         = fieldElement.Name.ToString();
                        var value        = fieldElement.GetFieldValue();
                        if (data.ContainsKey(name))
                        {
                            data[name] = value;
                        }
                        else
                        {
                            data.Add(name, value);
                        }
                    }

                    if (data.ContainsKey("date"))
                    {
                        var date = (DateTime)data["date"];
                        data.Remove("date");
                        historicalData.Add(new KeyValuePair <DateTime, IDictionary <string, object> >(date, data));
                    }
                }

                historicalDataResponse.Add(ticker, Either.Right <ResponseError, HistoricalData>(historicalData));
            }

            observer.OnNext(historicalDataResponse);

            if (!isPartialResponse)
            {
                observer.OnCompleted();
                Remove(message.CorrelationID);
            }
        }