Esempio n. 1
0
        private void AddNewDataPoint(bool refresh = true)
        {
            double open   = Rand.NextDouble() * 50 + 100;
            double close  = open + (Rand.NextDouble() - .5) * 10;
            double low    = Math.Min(open, close) - Rand.NextDouble() * 5;
            double high   = Math.Max(open, close) + Rand.NextDouble() * 5;
            double volume = Rand.NextDouble() * 500 + 100;

            TimeSpan span = TimeSpan.FromDays(1);
            DateTime date = CandlePlot.OHLCs.Any() ? CandlePlot.OHLCs.Last().DateTime + span : new DateTime(1985, 09, 24);

            OHLC ohlc = new OHLC(open, high, low, close, date, span, volume);

            CandlePlot.Add(ohlc);

            if (refresh)
            {
                formsPlot1.Plot.AxisAuto();

                BarPlot.Replace(
                    positions: CandlePlot.OHLCs.Select(x => x.DateTime.ToOADate()).ToArray(),
                    values: CandlePlot.OHLCs.Select(x => x.Volume).ToArray());

                formsPlot2.Plot.AxisAuto();
                formsPlot2.Plot.SetAxisLimits(yMin: 0);

                formsPlot1.Refresh();
                formsPlot2.Refresh();
            }
        }
        /// <summary>
        /// Read already downloaded OHLC data
        /// </summary>
        /// <param name="curPair"></param>
        /// <param name="freq"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private GetOHLCResult ReadOHLC(CurrencyPair curPair, Frequency freq, string item = "Close")
        {
            string        pathLib = GetOHLCLibraryPath(curPair, freq);
            GetOHLCResult res     = new GetOHLCResult
            {
                Pairs = new Dictionary <string, List <OHLC> > {
                    { curPair.GetRequestID(), new List <OHLC> {
                      } }
                }
            };
            List <string[]> csv       = StaticLibrary.LoadCsvFile(pathLib);
            bool            isHeaders = true;

            string[] headers = null;
            foreach (string[] array in csv)
            {
                if (isHeaders)
                {
                    headers = array; isHeaders = false;
                }
                else
                {
                    OHLC ohlc = DataLibraryStaticLibrary.ReadOHLCItems(array, headers);
                    res.Pairs[curPair.GetRequestID()].Add(ohlc);
                }
            }
            return(res);
        }
Esempio n. 3
0
 private void Analyze(OHLC quote)
 {
     lock (_lock)
     {
         _analyzer.Analyze(quote);
     }
 }
        public override void Start()
        {
            currentIndex = 0;
            historyData.Clear();

            if (File.Exists(fileName))
            {
                foreach (var line in File.ReadAllLines(fileName))
                {
                    var flds = line.Split(',');

                    var dateComponents = flds[0].Split('.').Select(i => Convert.ToInt32(i)).ToList();
                    dateComponents.AddRange(flds[1].Split(':').Select(i => Convert.ToInt32(i)));

                    var date = new System.DateTime(dateComponents[0], dateComponents[1], dateComponents[2], dateComponents[3], dateComponents[4], 0);
                    var ohlc = new OHLC()
                               .SetTime(date)
                               .SetOpen(Convert.ToDouble(flds[2]))
                               .SetHigh(Convert.ToDouble(flds[3]))
                               .SetLow(Convert.ToDouble(flds[4]))
                               .SetClose(Convert.ToDouble(flds[5]))
                               .SetVolume(Convert.ToInt32(flds[6]));

                    historyData.Add(ohlc);
                    dataIndex.Add(date, ohlc);
                }
            }

            base.Start();
        }
Esempio n. 5
0
        public static List <OHLC> Extract(string fileName)
        {
            var lines    = File.ReadLines(fileName);
            var ohlcList = new List <OHLC>();

            decimal lastClose = 0;

            foreach (var line in lines)
            {
                var data = line.Split('\t');

                //have to replace \N with last close

                var open  = data[3] == "\\N" ? lastClose : decimal.Parse(data[3]);
                var high  = decimal.Parse(data[4]);
                var low   = decimal.Parse(data[5]);
                var close = decimal.Parse(data[6]);

                var ohlc = new OHLC(open, high, low, close);

                ohlc.Volume = double.Parse(data[7]);
                ohlc.Start  = DateTime.ParseExact(data[8], "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                ohlc.End    = DateTime.ParseExact(data[9], "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

                if (ohlc.Start > DateTime.ParseExact("2017-08-26 12:33:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture))
                {
                    ohlcList.Add(ohlc);
                }

                lastClose = close;
            }

            return(ohlcList);
        }
Esempio n. 6
0
        private void DrawIncrease(OHLC lastItem)
        {
            int xNow = mDatas.Count();

            //必选按照一个bar绘制的宽度来计算
            if (10 * xNow >= mCurveContext.BWidth - 100)
            {
                ResizeCurveImage(mCurveContext.BWidth + 1000, mCurveContext.BHeight);
            }

            if (mCurveContext.YMinPoint < 200 || mCurveContext.YMaxPoint > mCurveContext.BHeight - 200)
            {
                ResizeCurveImage(mCurveContext.BWidth, mCurveContext.BHeight + 400);

                mCurveContext.YMinPoint = mCurveContext.YMidPoint;
                mCurveContext.YMaxPoint = mCurveContext.YMidPoint;
            }

            using (Graphics gr = Graphics.FromImage(mCurveContext.mCanvas))
            {
                gr.SmoothingMode = SmoothingMode.AntiAlias;

                DrawOneBar(xNow, gr, lastItem);
            }

            FitScreen();
        }
Esempio n. 7
0
        public void Test_Finance_ColorDown()
        {
            var plt = new ScottPlot.Plot();

            var ohlcs = new OHLC[]
            {
                // open, high, low, close, time, timeSpan
                new OHLC(273, 275, 264, 265, 1, 1),
                new OHLC(267, 276, 265, 274, 2.5, 2),
                new OHLC(277, 280, 275, 278, 4, 1),
            };

            // start with default settings
            var op = new FinancePlot(ohlcs);

            plt.Add(op);
            var bmp1 = TestTools.GetLowQualityBitmap(plt);

            // change the plottable
            op.ColorDown = System.Drawing.Color.Blue;
            var bmp2 = TestTools.GetLowQualityBitmap(plt);

            // measure what changed
            //TestTools.SaveFig(bmp1, "1");
            //TestTools.SaveFig(bmp2, "2");
            var before = new MeanPixel(bmp1);
            var after  = new MeanPixel(bmp2);

            Console.WriteLine($"Before: {before}");
            Console.WriteLine($"After: {after}");

            Assert.That(after.IsMoreBlueThan(before));
        }
Esempio n. 8
0
        private List <OHLC> LoadData()
        {
            var csvParser = new CsvParser.CsvParser(',');
            IEnumerable <string[]> stockData = csvParser.ParseFile(@"D:\StockData\Maruti.csv", Encoding.Default);
            //IEnumerable<string[]> stockData = csvParser.ParseFile(@"D:\StockData\Infy.csv", Encoding.Default);
            //IEnumerable<string[]> stockData = csvParser.ParseFile(@"D:\StockData\Icicibank.csv", Encoding.Default);
            //IEnumerable<string[]> stockData = csvParser.ParseFile(@"D:\StockData\sbin.csv", Encoding.Default);
            //IEnumerable<string[]> stockData = csvParser.ParseFile(@"D:\StockData\MRF.csv", Encoding.Default);

            List <OHLC> quotes = new List <OHLC>();

            foreach (string[] record in stockData.Skip(1))
            {
                if (record.Length == 7 && record[1] != "null" && record[2] != "null" && record[3] != "null" && record[4] != "null")
                {
                    OHLC quote = new OHLC()
                    {
                        //Date = Convert.ToDateTime(record[0]),
                        Open  = Convert.ToDouble(record[1]),
                        Close = Convert.ToDouble(record[4]),
                        High  = Convert.ToDouble(record[2]),
                        Low   = Convert.ToDouble(record[3]),
                        //Volume = Convert.ToInt32(record[5]),
                        //AdjClose = Convert.ToDouble(record[6]),
                    };
                    quotes.Add(quote);
                }
            }
            return(quotes);
        }
        private void LogsOHLC()
        {
            try
            {
                var barcodeOHCL = new List <OHLC>();
                foreach (var item in barChartsResults)
                {
                    var objOHLC = new OHLC();
                    objOHLC.o      = 6538.8f;
                    objOHLC.h      = 6538.8f;
                    objOHLC.l      = 6537.9f;
                    objOHLC.c      = 0;
                    objOHLC.events = "ohlc_notify";
                    objOHLC.symbol = item.sym;

                    objOHLC.bar_num = bar_number;
                    barcodeOHCL.Add(objOHLC);
                }
                var finalResults = JsonConvert.SerializeObject(barcodeOHCL);
                Console.WriteLine("OHLC Logs {0}", finalResults);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error on LogsOHLC ");
            }
        }
Esempio n. 10
0
        private void DrawVolumnIncrease(OHLC newItem)
        {
            int xNow = mDatas.Count();

            float xOff = (xNow - 1) * 10;

            using (Graphics gr = Graphics.FromImage(mVolumnContext.Canvas))
            {
                gr.SmoothingMode = SmoothingMode.AntiAlias;


                float vRation = newItem.Volumn / mVolumnContext.MaxVolumn;

                float barHeight = mVolumnContext.Height * vRation;

                float y = mVolumnContext.Height - barHeight;

                Brush cl = Brushes.White;
                if (newItem.Open < newItem.Close)
                {
                    cl = Brushes.Red;
                }
                else if (newItem.Open > newItem.Close)
                {
                    cl = Brushes.Green;
                }
                //刷背景
                gr.FillRectangle(Brushes.Black, xOff, 2, 10, mVolumnContext.Height);

                gr.FillRectangle(cl, xOff + 2, y, 8, barHeight);
            }
        }
Esempio n. 11
0
        private string CreateOrder(OHLC ohlc, DateTime date, string type, string description = "")
        {
            var order = new Order()
            {
                Price    = ohlc.Close,
                Quantity = type == "Buy" ? (double)(Account.Euro / ohlc.Close) : (double)Account.BitCoin,
                Date     = date,
                Type     = type
            };

            Orders.Add(order);

            if (bool.Parse(ConfigurationManager.AppSettings["EmailSignals"]))
            {
                SendEmail($"{order.Type} Signal", $"{order.Type} {order.Quantity} @ {order.Price} - {order.Date}");
            }

            //Settle the account as if the order is immediately executed
            if (type == "Buy")
            {
                Account.BitCoin = (double)(Account.Euro / ohlc.Close);
                Account.Euro    = 0;
            }
            else
            {
                Account.Euro    = (decimal)Account.BitCoin * ohlc.Close;
                Account.BitCoin = 0;
            }

            var message = $"{date} {type} {order.Quantity} BTC at {order.Price}";

            Events.Add(new Event(date, type, "@" + ohlc.Close + " " + description));

            return(message);
        }
Esempio n. 12
0
 /// <summary>
 /// Add a single OHLC to the plot
 /// </summary>
 /// <param name="ohlc"></param>
 public void Add(OHLC ohlc)
 {
     if (ohlc is null)
     {
         throw new ArgumentNullException();
     }
     OHLCs.Add(ohlc);
 }
Esempio n. 13
0
 public Heiken_Ashi(OHLC parent)
 {
     input  = parent;
     opens  = input.Open;
     highs  = input.High;
     lows   = input.Low;
     closes = (input.Open + input.High + input.Low + input.Close) * 0.25;
 }
Esempio n. 14
0
 public void Start()
 {
     OHLC.Wireup();
     PriceBar.Wireup();
     Candlesticks.Wireup();
     HeikenAshi.Wireup();
     Renko.Wireup();
 }
Esempio n. 15
0
        private void MovingAverageStrategy(OHLC ohlc, DateTime date)
        {
            if (DataPoints.Count < 200)
            {
                return;
            }

            //Calculate indicators
            var direction  = CalculateMovingAverage(200);
            var correction = CalculateMovingAverage(10);

            //Long Entry
            //When the price candle closes or is already above 200 day MA, then wait for price correction until price drops to 10 day MA,
            //then when the candle closes above 10 day MA on the upside, the enter the trade. Stop loss would be when price closes below the 10 day MA.
            if (State == TradingState.Initial)
            {
                if (ohlc.High > direction)
                {
                    //wait for price correction
                    State = TradingState.WaitForUpTrendPriceCorrection;
                }
            }

            else if (State == TradingState.WaitForUpTrendPriceCorrection)
            {
                if (ohlc.Low < correction)
                {
                    State = TradingState.WaitingToBuy;
                }
            }
            else if (State == TradingState.WaitingToBuy)
            {
                if (ohlc.Close > correction)
                {
                    CreateOrder(ohlc, date, "Buy");
                    State = TradingState.MonitoringDownTrend;
                }
            }
            else if (State == TradingState.MonitoringDownTrend)
            {
                //Stop loss
                if (ohlc.Close < correction)
                {
                    CreateOrder(ohlc, date, "Sell", "Stop loss");
                    State = TradingState.Initial;
                }

                //Limit profit
                //Limit - Profit target would vary with each item. For day traders,
                //I suggest profit target of 50 % of daily Average Trading Range of that item for the last month.
                var limit = 50; //50 EUR profit limit based on daily average trading range of BTC/EUR first week of last month
                if (ohlc.Close > Orders.Last().Price + limit)
                {
                    CreateOrder(ohlc, date, "Sell", "Profit limit");
                    State = TradingState.Initial;
                }
            }
        }
Esempio n. 16
0
        public static OHLC createSecondary(OHLC parent,
                                           SecondaryOHLC type, double arg)
        {
            OHLC ans = null;

            switch (type)
            {
            case SecondaryOHLC.NONE:
                ans = parent;
                break;

            case SecondaryOHLC.HEIKEN_ASHI:
                ans = new Heiken_Ashi(parent);
                break;

            case SecondaryOHLC.DEXPMA:
                ans = new SmoothedBars(parent, RWT_MA.MAType.DEXPMA, arg);
                break;

            case SecondaryOHLC.EMA:
                ans = new SmoothedBars(parent, RWT_MA.MAType.EMA, arg);
                break;

            case SecondaryOHLC.HULL:
                ans = new SmoothedBars(parent, RWT_MA.MAType.HULL, arg);
                break;

            case SecondaryOHLC.HULLEMA:
                ans = new SmoothedBars(parent, RWT_MA.MAType.HULLEMA, arg);
                break;

            case SecondaryOHLC.KAMA210:
                ans = new SmoothedBars(parent, RWT_MA.MAType.KAMA210, arg);
                break;

            case SecondaryOHLC.SMA:
                ans = new SmoothedBars(parent, RWT_MA.MAType.SMA, arg);
                break;

            case SecondaryOHLC.WMA:
                ans = new SmoothedBars(parent, RWT_MA.MAType.WMA, arg);
                break;

            case SecondaryOHLC.MEDIANFILT:
                ans = new SmoothedBars(parent, RWT_MA.MAType.MEDIANFILT, arg);
                break;

            case SecondaryOHLC.TEMA:
                ans = new SmoothedBars(parent, RWT_MA.MAType.TEMA, arg);
                break;

            case SecondaryOHLC.DELAY:
                ans = new SmoothedBars(parent, RWT_MA.MAType.DELAY, arg);
                break;
            }
            return(ans);
        }
 public static OHLC Accumulate(OHLC state, long price)
 {
     // Take the current values & apply the price update.
     state.Open  = state.Open ?? price;
     state.High  = state.High.HasValue ? state.High > price ? state.High : price : price;
     state.Low   = state.Low.HasValue ? state.Low < price ? state.Low : price : price;
     state.Close = price;
     return(state);
 }
Esempio n. 18
0
 Task Publish(OHLC ohlc)
 {
     return(Task.Run(() =>
     {
         LastOHLC = ohlc;
         _queueFanout.FanoutPublisher.Send(LastOHLC.ToByteArray());
         //QueueConn?.Send(LastOHLC.SerializeToString_PB());
     }));
 }
Esempio n. 19
0
        public void ATR_TEST_2()
        {
            var res1 = raw.Do(x => ohlc = x).TR().WSMA(14).Select(x => new { OHLC = ohlc, ATR = x }).ToList().Wait();
            var res2 = cnt.Do(x => ohlc = x).TR().WSMA(14).Select(x => new { OHLC = ohlc, ATR = x }).ToList().Wait();

            for (var itr = 0; itr < res1.Count; itr++)
            {
                Trace.WriteLine($"{res1[itr].OHLC.Close.Security}\t{res1[itr].ATR.ToString("0.00")}\t{res2[itr].OHLC.Close.Security}\t{res2[itr].ATR.ToString("0.00")}\t{(res2[itr].ATR - res1[itr].ATR).ToString("0.00")}");
            }
        }
Esempio n. 20
0
        static void UpdateOHLC()
        {
            //If last OHLC date is 1 min older than the latest trade
            //Then fill all the missing OHLC data by reading trades from database and grouping as OHLC
            FreedomContextFactory factory = new FreedomContextFactory();

            var context = factory.Create(ConfigurationManager.ConnectionStrings["marketdata-azure"].ConnectionString);

            var latestOhlc = context.Set <OHLC>().OrderByDescending(x => x.Start).FirstOrDefault();

            if (latestOhlc != null)
            {
                if (DateTime.Now.AddMinutes(-2) > latestOhlc.Start)
                {
                    //Get trades newer than OHLC and convert them to 1m-OHLC
                    var trades = context.Set <DataAccessLayer.Trade>().Where(x => x.Time > latestOhlc.Start).OrderBy(x => x.Time);

                    var oneMinuteOhlcs = trades.ToList().GroupBy(x => x.Time.Minute());

                    //Save max 4 hours trades 240 minutes
                    var minCount = 0;

                    foreach (var oneMinuteOhlc in oneMinuteOhlcs)
                    {
                        if (minCount >= 240)
                        {
                            break;
                        }

                        if (oneMinuteOhlc.Any())
                        {
                            var ohlc = new OHLC()
                            {
                                Low      = oneMinuteOhlc.Select(t => t.Price).Min(),
                                High     = oneMinuteOhlc.Select(t => t.Price).Max(),
                                Open     = oneMinuteOhlc.First().Price,
                                Close    = oneMinuteOhlc.Last().Price,
                                Volume   = oneMinuteOhlc.Sum(t => t.Quantity),
                                Start    = oneMinuteOhlc.First().Time.Minute(),
                                End      = oneMinuteOhlc.First().Time.Minute().AddSeconds(59),
                                Market   = "BTC/EUR",
                                Exchange = "CEX.IO"
                            };

                            context.Set <OHLC>().Add(ohlc);

                            minCount++;
                        }
                    }

                    //Save the OHLC-1m
                    context.SaveChanges();
                }
            }
        }
Esempio n. 21
0
 private void CalculateNewEMA(OHLC currentQuote, int duration)
 {
     //if (EMAs[duration].Count == 0)
     //{
     //    EMAs[duration].Add(TechnicalIndicators.CalculateMovingAverage(Data.Select(x => x.Close), duration, MovingAverage.Exponential).FirstOrDefault());
     //}
     //else
     //{
     //    double previousEMA = EMAs[duration].LastOrDefault();
     //    EMAs[duration].Add(TechnicalIndicators.CalculateExponentialMovingAverage(previousEMA, currentQuote.Close, duration));
     //}
 }
Esempio n. 22
0
File: DMI.cs Progetto: lulzzz/Quant
 /// <summary>
 /// Directional Momentum
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 internal static IObservable <(int hr, int tr, int lr)> DM(this IObservable <OHLC> source)
 {
     return(Observable.Create <(int, int, int)>(obs => {
         OHLC prev = null;
         return source.Subscribe(val => {
             if (prev != null)
             {
                 obs.OnNext(val.DM(prev));
             }
             prev = val;
         }, obs.OnError, obs.OnCompleted);
     }));
 }
Esempio n. 23
0
        private void 从当前点开始播放ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //int x = contextMenuStrip_CandleStick.Left;
            //int y =contextMenuStrip_CandleStick.Top;

            OHLC oc = DrawImageService.Instance.mCandleContext.GetBarFromScreenPoint(RightMouseDownPoint.X, RightMouseDownPoint.Y);

            if (oc != null)
            {
                DrawImageService.Instance.StartDraw();
                DataService.Instance.StartPlayBySpecifyIndex(oc.Index);
            }
        }
Esempio n. 24
0
 /// <summary>
 /// True Range between bars
 /// http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_true_range_atr
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static IObservable <double> TR(this IObservable <OHLC> source)
 {
     return(Observable.Create <double>(obs => {
         OHLC prev = null;
         return source.Subscribe(val => {
             if (prev != null)
             {
                 obs.OnNext(val.TR(prev));
             }
             prev = val;
         }, obs.OnError, obs.OnCompleted);
     }));
 }
Esempio n. 25
0
        private void BollingerBandStrategy(OHLC ohlc, DateTime date, StrategyParameters parameters)
        {
            if (DataPoints.Count < 200)
            {
                return;
            }

            var rsiPeriod     = parameters.RsiPeriod;
            var rsiThreshold  = parameters.RsiThreshold;
            var stopLossRatio = parameters.StopLossRatio;

            //Calculate indicators
            var direction  = CalculateMovingAverage(200);
            var sellSignal = CalculateMovingAverage(5);
            var rsi        = CalculateRelativeStrengthIndex(rsiPeriod);
            var bb         = CalculateBollingerBands(20, 2);
            var percentB   = bb.PercentB;
            var bandwidth  = bb.Bandwidth;

            //Long Entry
            //When the price candle closes or is already above 200 day MA and RSI closes below 5 buy
            //Sell when closes above 5-period moving average
            if (State == TradingState.Initial)
            {
                if (ohlc.High > direction && percentB > 100)
                {
                    CreateOrder(ohlc, date, "Buy", $"<br/> %b {percentB:N0} <br/> bandwidth {bandwidth:N0} <br/> upper {bb.UpperBand:N0} <br/> lower {bb.LowerBand:N0}");
                    State = TradingState.MonitoringDownTrend;
                }
            }
            else if (State == TradingState.MonitoringDownTrend || State == TradingState.WaitingToSell)
            {
                //Stop loss when BUY order loses more than 2% of its value
                var buyOrder = Orders.Last();
                if ((double)((buyOrder.Price - ohlc.Close) / buyOrder.Price) > stopLossRatio)
                {
                    CreateOrder(ohlc, date, "Sell", $"Stop Loss <br/> %b {percentB:N0} <br/> bandwidth {bandwidth:N0} <br/> upper {bb.UpperBand:N0} <br/> lower {bb.LowerBand:N0}");
                    State = TradingState.Initial;
                    return;//Otherwise might sell twice
                }


                //Limit profit on downward swing
                if (percentB < 0)
                {
                    CreateOrder(ohlc, date, "Sell", $"%b hit over 100 <br/> %b {percentB:N0} <br/> bandwidth {bandwidth:N0} <br/> upper {bb.UpperBand:N0} <br/> lower {bb.LowerBand:N0}");
                    State = TradingState.Initial;
                    return;
                }
            }
        }
Esempio n. 26
0
        static OHLC GetTableDataFromDocument(HtmlDocument document, OHLC fillme)
        {
            var tbl = document.GetElementById("historicalquote");

            if (tbl == null)
            {
                return(fillme);
            }
            dynamic myTable = tbl.DomElement;

            fillme.close = myTable.rows[2].cells[1].innerText;
            fillme.open  = myTable.rows[3].cells[1].innerText;
            fillme.high  = myTable.rows[4].cells[1].innerText;
            fillme.low   = myTable.rows[5].cells[1].innerText;
            return(fillme);
        }
Esempio n. 27
0
 public SmoothedBars(OHLC parent, RWT_MA.MAType type, double len)
 {
     input = parent;
     oma   = RWT_MA.MAFactory.create(type, len);
     hma   = RWT_MA.MAFactory.create(type, len);
     lma   = RWT_MA.MAFactory.create(type, len);
     cma   = RWT_MA.MAFactory.create(type, len);
     oma.init(input.Open);
     hma.init(input.High);
     lma.init(input.Low);
     cma.init(input.Close);
     opens  = input.Open;
     highs  = input.High;
     lows   = input.Low;
     closes = input.Close;
 }
        public static OHLC ReadOHLCItems(string[] array, string[] headers)
        {
            OHLC res = new OHLC();

            for (int i = 0; i < headers.Length; i++)
            {
                string item = headers[i];
                switch (item)
                {
                case "Time":
                    res.Time = Convert.ToInt32(Convert.ToDouble(array[i]));
                    break;

                case "Open":
                    res.Open = Convert.ToDecimal(array[i]);
                    break;

                case "High":
                    res.High = Convert.ToDecimal(array[i]);
                    break;

                case "Low":
                    res.Low = Convert.ToDecimal(array[i]);
                    break;

                case "Close":
                    res.Close = Convert.ToDecimal(array[i]);
                    break;

                case "Volume":
                    res.Volume = Convert.ToDecimal(array[i]);
                    break;

                case "Vwap":
                    res.Vwap = Convert.ToDecimal(array[i]);
                    break;

                case "Count":
                    res.Count = Convert.ToInt32(array[i]);
                    break;

                default:
                    break;
                }
            }
            return(res);
        }
        /// <summary>
        /// Create DataTimeSeries, DataTSOHLC, DataTSVolume objects add to DataBuilder collection
        /// </summary>
        /// <param name="tinterval">time interval of timeseries (in minutes)</param>
        /// /// <param name="nrows">number of rows to allocate</param>
        public void NewTimeSeriesOHLCVolume(int tinterval, int nrows = 2880)
        {
            // check if time interval already exist
            foreach (DataTimeSeries ts0 in TimeSeries)
            {
                if (ts0.TimeInterval == tinterval)
                {
                    return;
                }
            }

            DataTimeSeries ts = new DataTimeSeries(tinterval, nrows);

            TimeSeries.Add(ts);
            OHLC.Add(new DataTSOHLC(ts));
            Volume.Add(new DataTSVolume(ts));
        }
Esempio n. 30
0
File: RSI.cs Progetto: lulzzz/Quant
 /// <summary>
 /// TODO: Work in Progress
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static IObservable <int> Delta(this IObservable <OHLC> source)
 {
     return(Observable.Create <int>(obs => {
         OHLC oldVal = null;
         return source.Subscribe((newVal) => {
             if (oldVal != null)
             {
                 // Roll happened  (either in middle or start of new bar.
                 // what to do ?
                 if (newVal.Offset != 0 || oldVal.Close.Security != newVal.Open.Security)
                 {
                 }
                 obs.OnNext((int)(newVal.Close.Price - oldVal.Close.Price));
             }
             oldVal = newVal;
         }, obs.OnError, obs.OnCompleted);
     }));
 }
Esempio n. 31
0
 public override void OnClose(OHLC closing)
 {
     log.DebugFormat("{0} {1} S: {2} O: {3}  H: {4}  L: {5}  C: {6}",
         closing.Date, closing.Time, closing.Symbol, closing.Open, closing.High, closing.Low, closing.Close);
 }