From 515f444254cc18185533bb8f0c53d77c4d208936 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Mon, 11 Mar 2024 12:44:31 -0700 Subject: [PATCH] Add an indicator for viewing the performance of the top n components of the index --- indicators/IndexTopN.cs | 192 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 indicators/IndexTopN.cs diff --git a/indicators/IndexTopN.cs b/indicators/IndexTopN.cs new file mode 100644 index 0000000..1e63214 --- /dev/null +++ b/indicators/IndexTopN.cs @@ -0,0 +1,192 @@ +#region Using declarations +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; +using System.Windows.Media; +using System.Xml.Serialization; +using NinjaTrader.Cbi; +using NinjaTrader.Gui; +using NinjaTrader.Gui.Chart; +using NinjaTrader.Gui.SuperDom; +using NinjaTrader.Gui.Tools; +using NinjaTrader.Data; +using NinjaTrader.NinjaScript; +using NinjaTrader.Core.FloatingPoint; +using NinjaTrader.NinjaScript.DrawingTools; +#endregion + +//This namespace holds Indicators in this folder and is required. Do not change it. +namespace NinjaTrader.NinjaScript.Indicators +{ + [CategoryOrder("Index Top N", 1)] + [CategoryOrder("Plots", 2)] + public class IndexTopN : Indicator + { + private const int PrimaryBars = 0; + + private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"; + + // Regular expression to match the Slickcharts table row containing the components' symbols and index weightings. + private const string ComponentRegex = @"\s*\d+\s*(.+?)\s*([A-Z.]+?)\s*(.+?)%"; + + private List Components = new List(); + private Dictionary ComponentPrices = new Dictionary(); + private Dictionary ComponentWeightings = new Dictionary(); + + protected override void OnStateChange() + { + if (State == State.SetDefaults) + { + Description = @"Plots the top N components (weighted by market cap) of the specified index."; + Name = "Index Top N"; + Calculate = Calculate.OnPriceChange; + IsOverlay = false; + DisplayInDataBox = true; + DrawOnPricePanel = true; + ScaleJustification = ScaleJustification.Overlay; + IsSuspendedWhileInactive = false; + + NumComponents = 10; + + AddPlot(new Stroke(Brushes.Yellow, DashStyleHelper.Solid, 3), PlotStyle.Line, "Top N Index"); + } + else if (State == State.Configure) + { + RetrieveComponentData(); + + foreach (var component in Components) + { + //Replace "." with "_" in component name to avoid issues with NinjaTrader's naming conventions and "BRK.B". + AddDataSeries(component.Replace(".", "_")); + } + } + } + + protected override void OnBarUpdate() + { + if (BarsInProgress == PrimaryBars) + { + double indexValue = 0; + foreach (var component in Components) + { + if (ComponentPrices.ContainsKey(component) && ComponentWeightings.ContainsKey(component)) + indexValue += ComponentPrices[component] * ComponentWeightings[component]; + } + + if (indexValue > 0) + Index[0] = indexValue; + } + else + { + string component = Components[BarsInProgress - 1]; + ComponentPrices[component] = Closes[BarsInProgress][0]; + } + } + + private void RetrieveComponentData() + { + const string url = "https://www.slickcharts.com/sp500"; + var httpClient = new HttpClient(); + httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent); + var htmlContent = httpClient.GetStringAsync(url).Result; + + int count = 0; + var matches = Regex.Matches(htmlContent, ComponentRegex); + foreach (Match match in matches) + { + if (count++ >= NumComponents) break; + + var symbol = match.Groups[2].Value; + var percentage = match.Groups[3].Value; + + Components.Add(symbol); + ComponentWeightings.Add(symbol, double.Parse(percentage)); + } + } + + public override string DisplayName + { + get { return "Index Top " + NumComponents; } + } + + #region Plots + [Browsable(false)] + [XmlIgnore] + public Series Index + { + get { return Values[0]; } + } + #endregion + + #region Properties + [Range(1, int.MaxValue), NinjaScriptProperty] + [Display(Name = "Number of Components", GroupName = "Index Top N", Order = 1)] + public int NumComponents { get; set; } + #endregion + } +} + +#region NinjaScript generated code. Neither change nor remove. + +namespace NinjaTrader.NinjaScript.Indicators +{ + public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase + { + private IndexTopN[] cacheIndexTopN; + public IndexTopN IndexTopN(int numComponents) + { + return IndexTopN(Input, numComponents); + } + + public IndexTopN IndexTopN(ISeries input, int numComponents) + { + if (cacheIndexTopN != null) + for (int idx = 0; idx < cacheIndexTopN.Length; idx++) + if (cacheIndexTopN[idx] != null && cacheIndexTopN[idx].NumComponents == numComponents && cacheIndexTopN[idx].EqualsInput(input)) + return cacheIndexTopN[idx]; + return CacheIndicator(new IndexTopN(){ NumComponents = numComponents }, input, ref cacheIndexTopN); + } + } +} + +namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns +{ + public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase + { + public Indicators.IndexTopN IndexTopN(int numComponents) + { + return indicator.IndexTopN(Input, numComponents); + } + + public Indicators.IndexTopN IndexTopN(ISeries input , int numComponents) + { + return indicator.IndexTopN(input, numComponents); + } + } +} + +namespace NinjaTrader.NinjaScript.Strategies +{ + public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase + { + public Indicators.IndexTopN IndexTopN(int numComponents) + { + return indicator.IndexTopN(Input, numComponents); + } + + public Indicators.IndexTopN IndexTopN(ISeries input , int numComponents) + { + return indicator.IndexTopN(input, numComponents); + } + } +} + +#endregion