Exemple #1
0
        protected override void OnBarUpdate()
        {
            if (BarsInProgress == 1)
            {
                avg1 = SMA(BarsArray[1], Period)[0];
                return;
            }

            if (SessionIterator == null || CurrentBars[0] < Period || CurrentBars[1] < Period)
            {
                return;
            }

            if (Bars.BarsType.IsIntraday && !SessionIterator.IsInSession(Times[0][0], false, true))
            {
                return;
            }

            avg0 = SMA(BarsArray[0], Period)[0];

            double nominator    = 0;
            double denominator1 = 0;
            double denominator2 = 0;

            for (int i = 0; i < Period; i++)
            {
                nominator    += (avg0 - Inputs[0][i]) * (avg1 - Inputs[1][i]);
                denominator1 += (avg0 - Inputs[0][i]) * (avg0 - Inputs[0][i]);
                denominator2 += (avg1 - Inputs[1][i]) * (avg1 - Inputs[1][i]);
            }

            double denominator = Math.Sqrt(denominator1) * Math.Sqrt(denominator2);

            Value[0] = denominator.ApproxCompare(0) == 0 ? 0 : nominator / denominator;
        }
Exemple #2
0
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description      = NinjaTrader.Custom.Resource.NinjaScriptIndicatorDescriptionBarTimer;
                Name             = NinjaTrader.Custom.Resource.NinjaScriptIndicatorNameBarTimer;
                Calculate        = Calculate.OnEachTick;
                DrawOnPricePanel = false;
                IsChartOnly      = true;
                IsOverlay        = true;
                DisplayInDataBox = false;
            }
            else if (State == State.Realtime)
            {
                if (timer == null)
                {
                    if (Bars.BarsType.IsTimeBased && Bars.BarsType.IsIntraday)
                    {
                        lock (Connection.Connections)
                        {
                            if (Connection.Connections.ToList().FirstOrDefault(c => c.Status == ConnectionStatus.Connected && c.InstrumentTypes.Contains(Instrument.MasterInstrument.InstrumentType)) == null)
                            {
                                Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerDisconnectedError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0);
                            }
                            else
                            {
                                if (!SessionIterator.IsInSession(Now, false, true))
                                {
                                    Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerSessionTimeError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0);
                                }
                                else
                                {
                                    Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerWaitingOnDataError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0);
                                }
                            }
                        }
                    }
                    else
                    {
                        Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerTimeBasedError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0);
                    }
                }
            }
            else if (State == State.Terminated)
            {
                if (timer == null)
                {
                    return;
                }

                timer.IsEnabled = false;
                timer           = null;
            }
        }
Exemple #3
0
        protected override void OnMarketData(MarketDataEventArgs marketDataUpdate)
        {
            // Workaround for market replay backfilling all of replay sessions data(as historical data)
            // Replay should only backfill history up to replay time, so make sure any historical ticks
            // are before the current replay time.
            if ((Connection.PlaybackConnection != null) &&
                (State == State.Historical) &&
                (marketDataUpdate.Time >= Connection.PlaybackConnection.Now))
            {
                if (PrintDebug)
                {
                    Print("Filter Hit - MarketDataEvent Time :" + marketDataUpdate.Time.ToString() +
                          " Playback Time: " + Connection.PlaybackConnection.Now.ToString() +
                          " Event Type: " + marketDataUpdate.MarketDataType +
                          " State: " + State);
                }
                return;
            }

            // Reset for every session
            if (sessionIterator.IsNewSession(marketDataUpdate.Time, false))
            {
                if (PrintDebug)
                {
                    Print("NewSession: " + marketDataUpdate.Time.ToString());
                }
                totalShares  = 0;
                totalDollars = 0;
                sessionIterator.GetNextSession(marketDataUpdate.Time, false);
            }

            // Check session time
            if (!sessionIterator.IsInSession(marketDataUpdate.Time, false, true))
            {
                return;
            }

            // Is this a trade(not bid or ask)
            if (marketDataUpdate.MarketDataType == MarketDataType.Last)
            {
                totalShares  += marketDataUpdate.Volume;
                totalDollars += marketDataUpdate.Volume * marketDataUpdate.Price;
                Vwap[0]       = totalDollars / totalShares;
                if (PrintDebug)
                {
                    Print(marketDataUpdate.Time.ToString() + " Session total shares: " + totalShares.ToString() + " " + State);
                }
            }
        }
Exemple #4
0
        private void OnTimerTick(object sender, EventArgs e)
        {
            ForceRefresh();

            if (DisplayTime())
            {
                if (timer != null && !timer.IsEnabled)
                {
                    timer.IsEnabled = true;
                }

                if (connected)
                {
                    if (SessionIterator.IsInSession(Now, false, true))
                    {
                        if (hasRealtimeData)
                        {
                            TimeSpan barTimeLeft = Bars.GetTime(Bars.Count - 1).Subtract(Now);

                            timeLeft = (barTimeLeft.Ticks < 0
                                                                ? "00:00:00"
                                                                : barTimeLeft.Hours.ToString("00") + ":" + barTimeLeft.Minutes.ToString("00") + ":" + barTimeLeft.Seconds.ToString("00"));

                            Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerTimeRemaining + timeLeft, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0);
                        }
                        else
                        {
                            Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerWaitingOnDataError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0);
                        }
                    }
                    else
                    {
                        Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerSessionTimeError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0);
                    }
                }
                else
                {
                    Draw.TextFixed(this, "NinjaScriptInfo", NinjaTrader.Custom.Resource.BarTimerDisconnectedError, TextPosition.BottomRight, ChartControl.Properties.ChartText, ChartControl.Properties.LabelFont, Brushes.Transparent, Brushes.Transparent, 0);

                    if (timer != null)
                    {
                        timer.IsEnabled = false;
                    }
                }
            }
        }
Exemple #5
0
        protected override void OnMarketData(MarketDataEventArgs e)
        {
            if (Bars.Count <= 0)
            {
                return;
            }

            double         price;
            long           volume;
            VolumeInfoItem volumeInfoItem;
            DateTime       lastBarTimeStamp = GetLastBarSessionDate(Time[0]);

            if (lastBarTimeStamp != currentDate)
            {
                cacheDictionary = new Dictionary <double, VolumeInfoItem>();
                sortedDicList.Add(cacheDictionary);
            }

            currentDate = lastBarTimeStamp;
            if (Bars.IsTickReplay)
            {
                if (e.MarketDataType == MarketDataType.Last)
                {
                    price  = e.Price;
                    volume = e.Volume;

                    if (!cacheDictionary.ContainsKey(price))
                    {
                        cacheDictionary.Add(price, new VolumeInfoItem());
                    }

                    volumeInfoItem = cacheDictionary[price];

                    if (price >= e.Ask)
                    {
                        volumeInfoItem.up += volume;
                    }
                    else if (price <= e.Bid)
                    {
                        volumeInfoItem.down += volume;
                    }
                    else
                    {
                        volumeInfoItem.neutral += volume;
                    }
                }
            }
            else
            {
                if (e.MarketDataType == MarketDataType.Ask)
                {
                    askPrice = e.Price;
                    return;
                }

                if (e.MarketDataType == MarketDataType.Bid)
                {
                    bidPrice = e.Price;
                    return;
                }

                if (e.MarketDataType != MarketDataType.Last || ChartControl == null || askPrice == 0 || bidPrice == 0)
                {
                    return;
                }

                if (Bars != null && !SessionIterator.IsInSession(Core.Globals.Now, true, true))
                {
                    return;
                }

                price  = e.Price;
                volume = e.Volume;

                if (!cacheDictionary.ContainsKey(price))
                {
                    cacheDictionary.Add(price, new VolumeInfoItem());
                }

                volumeInfoItem = cacheDictionary[price];

                if (price >= askPrice)
                {
                    volumeInfoItem.up += volume;
                }
                else if (price <= bidPrice)
                {
                    volumeInfoItem.down += volume;
                }
                else
                {
                    volumeInfoItem.neutral += volume;
                }
            }
        }
Exemple #6
0
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Name                 = "Num Touches";
                Buys                 = new ConcurrentDictionary <double, long>();
                BackColor            = Brushes.Transparent;
                BarColor             = Application.Current.TryFindResource("brushVolumeColumnBackground") as Brush;
                BuyColor             = Brushes.Green;
                DefaultWidth         = 160;
                PreviousWidth        = -1;
                DisplayText          = true;
                ForeColor            = Application.Current.TryFindResource("brushVolumeColumnForeground") as Brush;
                ImmutableBarColor    = Application.Current.TryFindResource("immutableBrushVolumeColumnBackground") as Brush;
                ImmutableForeColor   = Application.Current.TryFindResource("immutableBrushVolumeColumnForeground") as Brush;
                IsDataSeriesRequired = true;
                LastVolumes          = new ConcurrentDictionary <double, long>();
                SellColor            = Brushes.Red;
                Sells                = new ConcurrentDictionary <double, long>();
                Bidask               = VolumeSide.bid;
            }
            else if (State == State.Configure)
            {
                if (UiWrapper != null && PresentationSource.FromVisual(UiWrapper) != null)
                {
                    Matrix m         = PresentationSource.FromVisual(UiWrapper).CompositionTarget.TransformToDevice;
                    double dpiFactor = 1 / m.M11;
                    gridPen      = new Pen(Application.Current.TryFindResource("BorderThinBrush") as Brush, 1 * dpiFactor);
                    halfPenWidth = gridPen.Thickness * 0.5;
                }

                if (SuperDom.Instrument != null && SuperDom.IsConnected)
                {
                    BarsPeriod bp = new BarsPeriod
                    {
                        MarketDataType = MarketDataType.Last,
                        BarsPeriodType = BarsPeriodType.Tick,
                        Value          = 1
                    };

                    SuperDom.Dispatcher.InvokeAsync(() => SuperDom.SetLoadingString());
                    clearLoadingSent = false;

                    if (BarsRequest != null)
                    {
                        BarsRequest.Update -= OnBarsUpdate;
                        BarsRequest         = null;
                    }

                    BarsRequest = new BarsRequest(SuperDom.Instrument,
                                                  Cbi.Connection.PlaybackConnection != null ? Cbi.Connection.PlaybackConnection.Now : Core.Globals.Now,
                                                  Cbi.Connection.PlaybackConnection != null ? Cbi.Connection.PlaybackConnection.Now : Core.Globals.Now);

                    BarsRequest.BarsPeriod   = bp;
                    BarsRequest.TradingHours = (TradingHoursData == TradingHours.UseInstrumentSettings || TradingHours.Get(TradingHoursData) == null) ? SuperDom.Instrument.MasterInstrument.TradingHours : TradingHours.Get(TradingHoursData);
                    BarsRequest.Update      += OnBarsUpdate;

                    BarsRequest.Request((request, errorCode, errorMessage) =>
                    {
                        // Make sure this isn't a bars callback from another column instance
                        if (request != BarsRequest)
                        {
                            return;
                        }

                        lastMaxIndex    = 0;
                        maxVolume       = 0;
                        totalBuyVolume  = 0;
                        totalLastVolume = 0;
                        totalSellVolume = 0;
                        Sells.Clear();
                        Buys.Clear();
                        LastVolumes.Clear();

                        if (State >= NinjaTrader.NinjaScript.State.Terminated)
                        {
                            return;
                        }

                        if (errorCode == Cbi.ErrorCode.UserAbort)
                        {
                            if (State <= NinjaTrader.NinjaScript.State.Terminated)
                            {
                                if (SuperDom != null && !clearLoadingSent)
                                {
                                    SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                                    clearLoadingSent = true;
                                }
                            }

                            request.Update -= OnBarsUpdate;
                            request.Dispose();
                            request = null;
                            return;
                        }

                        if (errorCode != Cbi.ErrorCode.NoError)
                        {
                            request.Update -= OnBarsUpdate;
                            request.Dispose();
                            request = null;
                            if (SuperDom != null && !clearLoadingSent)
                            {
                                SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                                clearLoadingSent = true;
                            }
                        }
                        else if (errorCode == Cbi.ErrorCode.NoError)
                        {
                            SessionIterator superDomSessionIt = new SessionIterator(request.Bars);
                            bool isInclude60 = request.Bars.BarsType.IncludesEndTimeStamp(false);
                            if (superDomSessionIt.IsInSession(Core.Globals.Now, isInclude60, request.Bars.BarsType.IsIntraday))
                            {
                                for (int i = 0; i < request.Bars.Count; i++)
                                {
                                    DateTime time = request.Bars.BarsSeries.GetTime(i);
                                    if ((isInclude60 && time <= superDomSessionIt.ActualSessionBegin) || (!isInclude60 && time < superDomSessionIt.ActualSessionBegin))
                                    {
                                        continue;
                                    }

                                    double ask   = request.Bars.BarsSeries.GetAsk(i);
                                    double bid   = request.Bars.BarsSeries.GetBid(i);
                                    double close = request.Bars.BarsSeries.GetClose(i);
                                    long volume  = request.Bars.BarsSeries.GetVolume(i);

                                    if (ask != double.MinValue && close >= ask)
                                    {
                                        Buys.AddOrUpdate(close, volume, (price, oldVolume) => oldVolume + volume);
                                        totalBuyVolume += volume;
                                    }
                                    else if (bid != double.MinValue && close <= bid)
                                    {
                                        Sells.AddOrUpdate(close, volume, (price, oldVolume) => oldVolume + volume);
                                        totalSellVolume += volume;
                                    }

                                    long newVolume;
                                    LastVolumes.AddOrUpdate(close, newVolume = volume, (price, oldVolume) => newVolume = 0);
                                    totalLastVolume += volume;

                                    if (newVolume > maxVolume)
                                    {
                                        maxVolume = newVolume;
                                    }
                                }

                                lastMaxIndex = request.Bars.Count - 1;

                                // Repaint the column on the SuperDOM
                                OnPropertyChanged();
                            }

                            if (SuperDom != null && !clearLoadingSent)
                            {
                                SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                                clearLoadingSent = true;
                            }
                        }
                    });
                }
            }
            else if (State == State.Active)
            {
                if (!DisplayText)
                {
                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .AddHandler(UiWrapper, "MouseMove", OnMouseMove);

                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .AddHandler(UiWrapper, "MouseEnter", OnMouseEnter);

                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .AddHandler(UiWrapper, "MouseLeave", OnMouseLeave);

                    mouseEventsSubscribed = true;
                }
            }
            else if (State == State.Terminated)
            {
                if (BarsRequest != null)
                {
                    BarsRequest.Update -= OnBarsUpdate;
                    BarsRequest.Dispose();
                }

                BarsRequest = null;

                if (SuperDom != null && !clearLoadingSent)
                {
                    SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                    clearLoadingSent = true;
                }

                if (!DisplayText && mouseEventsSubscribed)
                {
                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .RemoveHandler(UiWrapper, "MouseMove", OnMouseMove);

                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .RemoveHandler(UiWrapper, "MouseEnter", OnMouseEnter);

                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .RemoveHandler(UiWrapper, "MouseLeave", OnMouseLeave);

                    mouseEventsSubscribed = false;
                }

                lastMaxIndex    = 0;
                maxVolume       = 0;
                totalBuyVolume  = 0;
                totalLastVolume = 0;
                totalSellVolume = 0;
                Sells.Clear();
                Buys.Clear();
                LastVolumes.Clear();
            }
        }
        protected override void OnMarketData(MarketDataEventArgs marketDataUpdate)
        {
            // Workaround for market replay sending out all of replay sessions data(as historical data)
            // Replay should only backfill history up to replay time, so make sure any historical ticks
            // are before the current replay time.
            // this code to OnBar and set for on price change notifications for better performance once
            // this bug is resolved
            if ((Connection.PlaybackConnection != null) &&
                (State == State.Historical) &&
                (marketDataUpdate.Time >= Connection.PlaybackConnection.Now))
            {
                return;
            }

            bool redrawHigh = false;
            bool redrawLow  = false;

            // Reset for every session
            if (sessionIterator.IsNewSession(marketDataUpdate.Time, true))
            {
                orHigh = Double.MinValue;
                orLow  = Double.MaxValue;
                sessionIterator.GetNextSession(marketDataUpdate.Time, true);
                renderEndTime = sessionIterator.ActualSessionEnd;
                orCutoffTime  = sessionIterator.ActualSessionBegin.AddSeconds(CutoffSeconds);
                rendered      = false;
                orComplete    = false;
            }

            if (orComplete)
            {
                return;
            }

            // Check session time
            if (!sessionIterator.IsInSession(marketDataUpdate.Time, false, true))
            {
                return;
            }

            // keep track of high low
            if (marketDataUpdate.MarketDataType == MarketDataType.Last)
            {
                if (!orComplete && (marketDataUpdate.Time <= orCutoffTime))
                {
                    redrawHigh = false;
                    if (marketDataUpdate.Price > orHigh)
                    {
                        orHigh         = marketDataUpdate.Price;
                        orHighDateTime = marketDataUpdate.Time;
                        redrawHigh     = true;
                        Values[0][0]   = orHigh;
                    }

                    redrawLow = false;
                    if (marketDataUpdate.Price < orLow)
                    {
                        orLow         = marketDataUpdate.Price;
                        orLowDateTime = marketDataUpdate.Time;
                        redrawLow     = true;
                        Values[1][0]  = orLow;
                    }

                    if (redrawHigh)
                    {
                        RemoveDrawObject(marketDataUpdate.Time.Date.ToString() + "or_high");
                        Draw.Line(this, marketDataUpdate.Time.Date.ToString() + "or_high", true, orHighDateTime, orHigh, renderEndTime, orHigh, HighBrush, DashStyleHelper.Dot, HighBrushWidth);
                    }

                    if (redrawLow)
                    {
                        RemoveDrawObject(marketDataUpdate.Time.Date.ToString() + "or_low");
                        Draw.Line(this, marketDataUpdate.Time.Date.ToString() + "or_low", true, orLowDateTime, orLow, renderEndTime, orLow, LowBrush, DashStyleHelper.Dot, LowBrushWidth);
                    }
                }

                // On first tick past cutoff time mark opening range calc complete and
                // draw the hi and low lines across the entire sesson.
                if ((marketDataUpdate.Time > orCutoffTime) && !orComplete)
                {
                    orComplete = true;
                    RemoveDrawObject(marketDataUpdate.Time.Date.ToString() + "or_high");
                    Draw.Line(this, marketDataUpdate.Time.Date.ToString() + "or_high", true, orHighDateTime, orHigh, renderEndTime, orHigh, HighBrush, DashStyleHelper.Solid, HighBrushWidth);
                    RemoveDrawObject(marketDataUpdate.Time.Date.ToString() + "or_low");
                    Draw.Line(this, marketDataUpdate.Time.Date.ToString() + "or_low", true, orLowDateTime, orLow, renderEndTime, orLow, LowBrush, DashStyleHelper.Solid, LowBrushWidth);

                    // Go back to first bar and Set all the high and low plot
                    // values for the day so databox works for indicator
                    for (int x = 0; x < Bars.BarsSinceNewTradingDay; x++)
                    {
                        Values[0][x] = orHigh;
                        Values[1][x] = orLow;
                    }
                }
            }
        }