Beispiel #1
0
        public static List <TradingHours> GetTradingHours(ContractDetails contractDetails)
        {
            var dateFormat   = "yyyyMMdd:HHmm";
            var output       = new List <TradingHours>();
            var tradingHours = contractDetails.TradingHours.Split(";");

            foreach (var item in tradingHours)
            {
                var tradingHoursItem = item.Trim();
                if (tradingHoursItem.Length > 0)
                {
                    if (ValidTradingHoursItem(tradingHoursItem))
                    {
                        var hours       = tradingHoursItem.Split("-");
                        var tradingHour = new TradingHours
                        {
                            Start = DateTime.ParseExact(hours[0].Trim(), dateFormat, CultureInfo.InvariantCulture),
                            End   = DateTime.ParseExact(hours[1].Trim(), dateFormat, CultureInfo.InvariantCulture)
                        };
                        output.Add(tradingHour);
                    }
                }
            }
            return(output);
        }
Beispiel #2
0
        public ActionResult PostTradingHours(PostEditPageViewModel model)
        {
            var id          = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier).Value;
            var currentUser = _traderStore.GetAll().FirstOrDefault(u => u.TraderId == Guid.Parse(id));

            if (string.IsNullOrWhiteSpace(model.StartTime))
            {
                return(BadRequest(new AuthResponse {
                    Errror = "Error, trading hours not set!"
                }));
            }

            try
            {
                var createTradingHours = new TradingHours
                {
                    StartTime = model.StartTime,
                    EndTime   = model.EndTime,
                    TraderId  = currentUser.TraderId
                };
                _tradeTimeStore.Post(createTradingHours);
            }
            catch (Exception)
            {
                return(BadRequest(new AuthResponse {
                    Errror = " trading hours not set"
                }));
                //throw;
            }

            return(Ok(model));
        }
Beispiel #3
0
        private void requestAndDrawSettlement(DateTime time)
        {
            DateTime previousEnd  = TradingHours.String2TradingHours(RTHTemplate).GetPreviousTradingDayEnd(time);
            DateTime previousEnd2 = TradingHours.String2TradingHours(RTHTemplate).GetPreviousTradingDayEnd(previousEnd.AddMinutes(-1));

            //Print("PREVIOUS END "+time+" = "+previousEnd+" "+previousEnd2);
            BarsRequest barsRequest = new BarsRequest(BarsArray[0].Instrument, previousEnd.AddDays(-2), previousEnd);

            barsRequest.BarsPeriod = new BarsPeriod {
                BarsPeriodType = BarsPeriodType.Day, Value = 1
            };

            DateTime time0 = Times[0][0];
            DateTime time1 = Times[0][1];

            barsRequest.Request(new Action <BarsRequest, ErrorCode, string>((bars, errorCode, errorMessage) =>
            {
                if (errorCode != ErrorCode.NoError)
                {
                    //Print(string.Format("Error on requesting bars: {0}, {1}", errorCode, errorMessage));
                    Log("JBMarketProfileLevels could not load settled bars", LogLevel.Error);
                    return;
                }

                double settlement2 = 0;
                if (bars.Bars.Count > 0)
                {
                    for (int i = bars.Bars.Count - 1; i >= 0; i--)
                    {
                        if (DateTime.Compare(bars.Bars.GetTime(i), previousEnd2) <= 0)
                        {
                            settlement2 = bars.Bars.GetClose(i);
                            break;
                        }
                        else if (DateTime.Compare(bars.Bars.GetTime(i), previousEnd) <= 0)
                        {
                            this.settlement = bars.Bars.GetClose(i);
                        }
                    }
                    if (DateTime.Compare(time0, previousEnd) <= 0)
                    {
                        DrawSettlementRay("SETTLEM " + previousEnd.ToString("MMM dd"), time1, settlement, time, SettlementColor);
                    }
                    else
                    {
                        DrawSettlementRay("SETTLEM " + previousEnd.ToString("MMM dd"), previousEnd, settlement, time, SettlementColor);
                    }
                    if (settlement2 > 0)
                    {
                        DrawSettlementRay("SETTLEM " + previousEnd2.ToString("MMM dd"), previousEnd2, settlement2, time, SettlementColor);
                    }
                }
            }));
        }
Beispiel #4
0
        private TradingHours Xlon()
        {
            var tradingHours = new TradingHours
            {
                OpenOffsetInUtc  = TimeSpan.FromHours(8),
                CloseOffsetInUtc = TimeSpan.FromHours(16),
                Mic = "XLON"
            };

            return(tradingHours);
        }
Beispiel #5
0
        async void DownloadLastPriceYF(Asset[] p_assets, TradingHours p_tradingHoursNow)  // takes ? ms from WinPC
        {
            Utils.Logger.Debug("DownloadLastPriceYF() START");
            m_nYfDownload++;
            try
            {
                // https://query1.finance.yahoo.com/v7/finance/quote?symbols=AAPL,AMZN  returns all the fields.
                // https://query1.finance.yahoo.com/v7/finance/quote?symbols=QQQ%2CSPY%2CGLD%2CTLT%2CVXX%2CUNG%2CUSO&fields=symbol%2CregularMarketPreviousClose%2CregularMarketPrice%2CmarketState%2CpostMarketPrice%2CpreMarketPrice  // returns just the specified fields.
                // "marketState":"PRE" or "marketState":"POST", In PreMarket both "preMarketPrice" and "postMarketPrice" are returned.
                var yfTickers = p_assets.Select(r => (r as Stock) !.YfTicker).ToArray();
                var quotes    = await Yahoo.Symbols(yfTickers).Fields(new Field[] { Field.Symbol, Field.RegularMarketPreviousClose, Field.RegularMarketPrice, Field.MarketState, Field.PostMarketPrice, Field.PreMarketPrice }).QueryAsync();

                foreach (var quote in quotes)
                {
                    Asset?sec = null;
                    foreach (var s in p_assets)
                    {
                        if ((s as Stock) !.YfTicker == quote.Key)
                        {
                            sec = s;
                            break;
                        }
                    }

                    if (sec != null)
                    {
                        dynamic?lastVal  = float.NaN;
                        string  fieldStr = (p_tradingHoursNow == TradingHours.PreMarketTrading) ? "PreMarketPrice" : "PostMarketPrice";
                        // TLT doesn't have premarket data. https://finance.yahoo.com/quote/TLT  "quoteSourceName":"Delayed Quote", while others: "quoteSourceName":"Nasdaq Real Time Price"
                        if (!quote.Value.Fields.TryGetValue(fieldStr, out lastVal))
                        {
                            lastVal = (float)quote.Value.RegularMarketPrice;  // fallback: the last regular-market Close price both in Post and next Pre-market
                        }
                        sec.LastValue = (float)lastVal;
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Logger.Error(e, "DownloadLastPriceYF()");
            }
        }
Beispiel #6
0
        public override int GetInitialLookBackDays(BarsPeriod barsPeriod, TradingHours tradingHours, int barsBack)
        {
            int minutesPerWeek = 0;

            lock (tradingHours.Sessions)
            {
                foreach (Session session in tradingHours.Sessions)
                {
                    int beginDay = (int)session.BeginDay;
                    int endDay   = (int)session.EndDay;
                    if (beginDay > endDay)
                    {
                        endDay += 7;
                    }

                    minutesPerWeek += (endDay - beginDay) * 1440 + ((session.EndTime / 100) * 60 + (session.EndTime % 100)) - ((session.BeginTime / 100) * 60 + (session.BeginTime % 100));
                }
            }

            return((int)Math.Max(1, Math.Ceiling(barsBack / Math.Max(1, minutesPerWeek / 7.0 / barsPeriod.Value) * 1.05)));
        }
Beispiel #7
0
        public override int GetInitialLookBackDays(BarsPeriod barsPeriod, TradingHours tradingHours, int barsBack)
        {
            switch (BarsPeriod.BaseBarsPeriodType)
            {
            case BarsPeriodType.Day:       return((int)Math.Ceiling(barsPeriod.BaseBarsPeriodValue * barsBack * 7.0 / 4.5));

            case BarsPeriodType.Minute:
                int minutesPerWeek = 0;
                lock (tradingHours.Sessions)
                {
                    foreach (Session session in tradingHours.Sessions)
                    {
                        int beginDay = (int)session.BeginDay;
                        int endDay   = (int)session.EndDay;
                        if (beginDay > endDay)
                        {
                            endDay += 7;
                        }

                        minutesPerWeek += (endDay - beginDay) * 1440 + session.EndTime / 100 * 60 + session.EndTime % 100 - (session.BeginTime / 100 * 60 + session.BeginTime % 100);
                    }
                }

                return((int)Math.Max(1, Math.Ceiling(barsBack / Math.Max(1, minutesPerWeek / 7.0 / barsPeriod.BaseBarsPeriodValue) * 1.05)));

            case BarsPeriodType.Month:       return(barsPeriod.BaseBarsPeriodValue * barsBack * 31);

            case BarsPeriodType.Second:       return((int)Math.Max(1, Math.Ceiling(barsBack / Math.Max(1, 8.0 * 60 * 60 / barsPeriod.BaseBarsPeriodValue)) * 7.0 / 5.0));                               // 8 hours

            case BarsPeriodType.Tick:       return(1);

            case BarsPeriodType.Volume:       return(1);

            case BarsPeriodType.Week:       return(barsPeriod.BaseBarsPeriodValue * barsBack * 7);

            case BarsPeriodType.Year:       return(barsPeriod.BaseBarsPeriodValue * barsBack * 365);

            default:       return(1);
            }
        }
Beispiel #8
0
        public override int GetInitialLookBackDays(BarsPeriod barsPeriod, TradingHours tradingHours, int barsBack)
        {
            switch (BarsPeriod.BaseBarsPeriodType)
            {
            case BarsPeriodType.Day: return(new DayBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));

            case BarsPeriodType.Minute: return(new MinuteBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));

            case BarsPeriodType.Month: return(new MonthBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));

            case BarsPeriodType.Second: return(new SecondBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));

            case BarsPeriodType.Tick: return(new TickBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));

            case BarsPeriodType.Volume: return(new VolumeBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));

            case BarsPeriodType.Week: return(new WeekBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));

            case BarsPeriodType.Year: return(new YearBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));

            default: return(new MinuteBarsType().GetInitialLookBackDays(barsPeriod, tradingHours, barsBack));
            }
        }
 public override int GetInitialLookBackDays(BarsPeriod period, TradingHours tradingHours, int barsBack)
 {
     return((int)Math.Max(1, Math.Ceiling(barsBack / Math.Max(1, 8.0 * 60 * 60 / period.Value)) * 7.0 / 5.0));
 }
Beispiel #10
0
 public override int GetInitialLookBackDays(BarsPeriod barsPeriod, TradingHours tradingHours, int barsBack)
 {
     return(barsPeriod.Value * barsBack * 365);
 }
Beispiel #11
0
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description             = @"Enter the description for your new custom Indicator here.";
                Name                    = "JBMarketProfileLevels";
                Calculate               = Calculate.OnEachTick;
                IsOverlay               = true;
                DisplayInDataBox        = true;
                DrawOnPricePanel        = true;
                DrawHorizontalGridLines = true;
                DrawVerticalGridLines   = true;
                PaintPriceMarkers       = true;
                ScaleJustification      = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                //Disable this property if your indicator requires custom values that cumulate with each new market data event.
                //See Help Guide for additional information.
                IsSuspendedWhileInactive = true;

                LineWidth = 2;
                LineStyle = DashStyleHelper.Dot;

                ShowPOC        = true;
                ShowONPOC      = true;
                ShowVA         = false;
                ShowONVA       = false;
                ShowHILO       = true;
                ShowONHILO     = true;
                ShowSettlement = true;

                HILOColor = Brushes.Red;
                VAColor   = Brushes.White;
                POCColor  = Brushes.Magenta;

                ONHILOColor = Brushes.Red;
                ONVAColor   = Brushes.White;
                ONPOCColor  = Brushes.Magenta;

                SettlementColor = Brushes.DarkOrange;

                Opacity       = 100;
                BrokenOpacity = 45;

                LabelFont = new Gui.Tools.SimpleFont("Arial", 8);

                RTHTemplate = "CME US Index Futures RTH";
                ONTemplate  = "Overnight Template";

                tpoProfiles = new List <JBTPOProfile>();

                initDone = false;
            }
            else if (State == State.Configure)
            {
                try {
                    TradingHours.String2TradingHours(RTHTemplate).GetPreviousTradingDayEnd(DateTime.Now);                     // Test if template exists
                    AddDataSeries(BarsArray[0].Instrument.FullName, new BarsPeriod {
                        BarsPeriodType = BarsPeriodType.Minute, Value = 30
                    }, RTHTemplate);
                    try {
                        TradingHours.String2TradingHours(ONTemplate).GetPreviousTradingDayEnd(DateTime.Now);                          // Test if template exists
                        AddDataSeries(BarsArray[0].Instrument.FullName, new BarsPeriod {
                            BarsPeriodType = BarsPeriodType.Minute, Value = 30
                        }, ONTemplate);
                        initDone = true;
                    } catch (Exception e) {
                        Draw.TextFixed(this, "NinjaScriptInfo", "JBMarketProfileLevels error loading trading hours with template name '" + ONTemplate + "', check properties", TextPosition.Center);
                        Log("JBMarketProfileLevels could not load specified trading hours templates", LogLevel.Error);
                    }
                } catch (Exception e) {
                    Draw.TextFixed(this, "NinjaScriptInfo", "JBMarketProfileLevels error loading trading hours with template name '" + RTHTemplate + "', check properties", TextPosition.Center);
                    Log("JBMarketProfileLevels could not load specified trading hours templates", LogLevel.Error);
                }
                AllowRemovalOfDrawObjects = true;

                //test();
            }
            else if (State == State.Historical)
            {
                if (!initDone)
                {
                    return;
                }
                if (!Bars.IsTickReplay)
                {
                    Draw.TextFixed(this, "NinjaScriptInfo", "JBMarketProfileLevels needs tick replay enabled on the data series", TextPosition.Center);
                    Log("JBMarketProfileLevels needs tick replay enabled on the data series", LogLevel.Error);
                    initDone = false;
                }
                else
                {
                    rthSessionIterator = new SessionIterator(BarsArray[RTH]);
                    ethSessionIterator = new SessionIterator(BarsArray[ETH]);

                    SetZOrder(-1);
                }
            }
            else if (State == State.Transition)
            {
                if (!initDone)
                {
                    return;
                }
                if (tpoProfile != null)
                {
                    update(tpoProfile);
                }
                requestAndDrawSettlement(DateTime.Now);
            }
            else if (State == State.Realtime)
            {
                if (Instrument != null && Instrument.MarketData != null && Instrument.MarketData.Settlement != null)
                {
                    settlement = Instrument.MarketData.Settlement.Price;
                    requestAndDrawSettlement(DateTime.Now);
                }
            }
        }
Beispiel #12
0
 public override int GetInitialLookBackDays(BarsPeriod period, TradingHours tradingHours, int barsBack)
 {
     return(3);
 }
Beispiel #13
0
 public override int GetInitialLookBackDays(BarsPeriod barsPeriod, TradingHours tradingHours, int barsBack)
 {
     return((int)Math.Ceiling(barsPeriod.Value * barsBack * 7.0 / 4.5));
 }
Beispiel #14
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();
            }
        }