Example #1
0
            public OhlcGenerator(IDataFeed dataFeed, PriceSelector selector, TimeSpan duration, TimeSpan? offset = null)
            {
                OhlcBar bar = null;
                selector.PriceTick += price =>
                {
                    if (!price.HasValue)
                    {
                        return;
                    }

                    var priceValue = price.Value;

                    if (bar == null)
                    {
                        bar = new OhlcBar
                        {
                            Open = priceValue,
                            High = priceValue,
                            Low = priceValue,
                            Close = priceValue
                        };
                        if (Open != null) Open(priceValue);
                    }
                    bar.Close = priceValue;
                    bar.High = priceValue > bar.High ? priceValue : bar.High;
                    bar.Low = priceValue < bar.Low ? priceValue : bar.Low;
                };

                Candle lastCandle = null;
                NewCandle += ohlcCandle =>
                {
                    lastCandle = ohlcCandle;
                };

                DateTime? nextPeriodStart = null;
                dataFeed.Second += time =>
                {
                    if (!nextPeriodStart.HasValue)
                    {
                        nextPeriodStart = Misc.GetNextPeriodStart(time, duration, offset);
                    }

                    if (time < nextPeriodStart) return;

                    var thisCandle = bar != null ? bar.GetCandle() : lastCandle;
                    if (NewCandle != null) NewCandle(thisCandle);
                    lastCandle = thisCandle;
                    bar = null;
                    nextPeriodStart += duration;
                };
            }
            public HaGenerator(OhlcBar.OhlcGenerator ohlcGenerator)
            {
                Candle lastHaBar = null;
                ohlcGenerator.NewCandle += candle =>
                {
                    if (candle == null)
                    {
                        if (NewCandle != null) NewCandle(null);
                        return;
                    }

                    var close = (candle.Open + candle.High + candle.Low + candle.Close) / 4;
                    var open = lastHaBar != null
                        ? ((lastHaBar.Open + lastHaBar.Close) / 2)
                        : (candle.Open + candle.Close) / 2;
                    var high = Math.Max(Math.Max(candle.High, open), close);
                    var low = Math.Min(Math.Min(candle.Low, open), close);
                    var newCandle = new Candle(open, high, low, close);

                    if (NewCandle != null) NewCandle(newCandle);

                    lastHaBar = newCandle;
                };
            }