From 8eb8f4054116659ab31bc05fe1aecaff897d3510 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Thu, 16 May 2024 19:06:48 -0700 Subject: [PATCH] Automatically fetch news for the new day after midnight --- indicators/News.cs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/indicators/News.cs b/indicators/News.cs index 677aa2a..560da7b 100644 --- a/indicators/News.cs +++ b/indicators/News.cs @@ -40,10 +40,8 @@ namespace NinjaTrader.NinjaScript.Indicators public class News : Indicator { - // TODO: Date should be determined programatically. - private string newsUrl = "https://www.forexfactory.com/calendar?day=" + DateTime.Now.ToString("MMMdd.yyyy").ToLower(); - private List newsEvents = new List(); + private DateTime currentDate = DateTime.Now.Date; protected override void OnStateChange() { @@ -79,9 +77,12 @@ namespace NinjaTrader.NinjaScript.Indicators { try { + newsEvents.Clear(); + HttpClient client = new HttpClient(); client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); + string newsUrl = "https://www.forexfactory.com/calendar?day=" + DateTime.Now.ToString("MMMdd.yyyy").ToLower(); HttpResponseMessage response = await client.GetAsync(newsUrl); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); @@ -152,14 +153,22 @@ namespace NinjaTrader.NinjaScript.Indicators // Format the time as "hh:mmtt" (e.g., "06:30am") return userTime.ToString("hh:mmtt").ToLower(); } - catch (Exception ex) + catch (Exception) { - Print("Error converting time: " + ex.Message); return time; // Return original time if conversion fails } } - protected override void OnBarUpdate() { } + protected override void OnBarUpdate() { + if (State == State.Realtime) + { + if (DateTime.Now.Date != currentDate) + { + RequestNewsEvents(); + currentDate = DateTime.Now.Date; + } + } + } protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { @@ -183,7 +192,7 @@ namespace NinjaTrader.NinjaScript.Indicators headerSize = MeasureString("Event", headerTextFormat); maxColWidth = Math.Max(maxColWidth, headerSize.Width); - foreach (var newsEvent in newsEvents) + foreach (var newsEvent in new List(newsEvents)) // New list in order to avoid concurrent modification { var timeSize = MeasureString(newsEvent.Time, eventTextFormat); var currencySize = MeasureString(newsEvent.Currency, eventTextFormat);