Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How to get Candles from start to end time

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    How to get Candles from start to end time

    Hi, I was working on some indicator, and wanted to store candles from start to end time if provided by me, but i am not able to capture that
    Code:
    string startTime = timeData["StartTime"];
                        string endTime = timeData["EndTime"];
                        Print($"Received time range : {startTime} {endTime}");
                        
    //                    DateTime start = DateTime.Parse(startTime);
    //                    DateTime end = DateTime.Parse(endTime);
                        DateTime playbackDate = Bars.GetTime(0).Date; // Assuming Bars is accessible here
                        TimeSpan startTimeOfDay = TimeSpan.Parse(startTime);
                        TimeSpan endTimeOfDay = TimeSpan.Parse(endTime);
                        DateTime start = playbackDate.Add(startTimeOfDay);
                        DateTime end = playbackDate.Add(endTimeOfDay);
    
                        Print($"Parsing datetim :{start} :{end}");
                        Print($"time count: {this.Time.Count}");
                        Print($"{this.Time[0]}, {this.Time[1]}");
                        
                        List<Dictionary<string, object>> candles = new List<Dictionary<string, object>>();
                        
                        for(int i = 0; i< this.Time.Count; i++)
                        {
                            if(this.Time[i] >= start && this.Time[i] <= end)
                            {
                                var candle = new Dictionary<string, object>
                                {
                                    {"date", this.Time[i].ToString("yyyy-MM-dd HH:mm:ss.fffffff'Z'")},
                                    {"close", this.Close[i]},
                                    {"open", this.Open[i]},
                                    {"high", this.High[i]},
                                    {"low", this.Low[i]},
                                };
                                candles.Add(candle);
                            }
                        }​
    here i am getting barsAgo error because of this.Time.Count which basically calculates total count of candles which is wrong. What i want is to know if there is easier method to basically capture OCHLV between start and end time provided by me, and can capture in all the modes, live, playback, and simulation.
    Thanks

    #2
    Hello patz1398,

    To use BarsAgo you need to be at least that far into processing inside the OnBarUpdate method. Are you waiting for enough bars to have processed before executing this code? Also the Count is not the same as an Index, you will have Count - 2 to access the last closed bar, using an index greater than that will cause an error.

    Comment


      #3
      "To use BarsAgo you need to be at least that far into processing inside the OnBarUpdate method. Are you waiting for enough bars to have processed before executing this code?"
      So i was testing it in playback and i am only sending endtime >= latest bar that appeared. Also print statement in the code above is giving me not current chart date. I was testing it in playback.

      Comment


        #4
        Hello patz1398,

        You are using a loop so the chart dates you get back depend on the bars ago you used, you would have to use a print to see how many bars ago is being used to know what specific bar that may be during that iteration of the OnBarUpdate.

        Comment


          #5
          so i found out the main problem is that barsAgo is not in sync with current chart. For example, if i have open 1 min chart, with 5 days of historical data. Today is 17th december 2024. I provide the start and end time. When i try to do
          DateTime parsedStartTime = DateTime.Parse($"{Time[0]:yyyy-MM-dd} {startTime}");
          DateTime parsedEndTime = DateTime.Parse($"{Time[0]:yyyy-MM-dd} {endTime}");

          i get ST : 12/11/2024 8:00:00 AM, ET :12/11/2024 10:00:00 AM in output.

          but Bars.GetTime(CurrentBar) is giving correct output. Why is that DateTime.Parse is picking up date which is not even included in loaded historical days? My main aim is to send data from current bar to start of the day but if i am not able to get index properly it would be tough also second thing is to get data between start and end time and plot vertical lines on that start and end time.

          Code:
          '''
          public async Task<object> SenderReceiver()
          {
          HttpClient httpClient = new HttpClient();
          try
          {
          Print($"Requesting start_time and end_time from Flask on {PortNumber}");
          var flaskResponse = await httpClient.GetAsync($"http://127.0.0.1:{PortNumber}/sendTimeToNinja");
          // Print($"flaskResponse : {flaskResponse}");
          flaskResponse.EnsureSuccessStatusCode();

          var responseContent = await flaskResponse.Content.ReadAsStringAsync();
          var timeData = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);

          string startTime = timeData["StartTime"];
          string endTime = timeData["EndTime"];
          Print($"Received time range : {startTime} {endTime}");

          DateTime parsedStartTime = DateTime.Parse($"{Time[0]:yyyy-MM-dd} {startTime}");
          DateTime parsedEndTime = DateTime.Parse($"{Time[0]:yyyy-MM-dd} {endTime}");

          Print($"ST : {parsedStartTime}, ET :{parsedEndTime}");
          Print($"{Bars.GetTime(CurrentBar)}");
          int startBarIndex = -1;
          int endBarIndex = -1;

          for (int i = 0 ; i <CurrentBar; i++)
          {
          if (Time[i] == parsedStartTime)
          startBarIndex = i;
          Print($"Time: {Time[i]}, startBarIndex : {i}");
          if (Time[i] == parsedEndTime)
          endBarIndex = i;
          }
          Print($"startBarindex: {startBarIndex} endBarIndex : {endBarIndex}");

          if(startBarIndex != -1)
          {
          Draw.VerticalLine(this, "StartLine", startBarIndex, Brushes.Red, DashStyleHelper.DashDotDot, 2);
          Print($"Vertical line drawn at start time : {parsedStartTime}");
          }
          else
          {
          Print("Error StartTime not found!!");
          }
          if (endBarIndex != -1)
          {
          Draw.VerticalLine(this, "EndLine", endBarIndex, Brushes.LimeGreen, DashStyleHelper.DashDotDot, 2);
          Print($"Vertical line drawn at end time : {parsedEndTime}");
          }
          else
          {
          Print("Error EndTime not found!!");
          }​
          '''

          Comment


            #6
            Hello patz1398,

            The code you have shown is using an async task which is not supported in NinjaScript, that will put that code out of the correct context so values you get won't be in sync with the scripts actual processing. You need to remove the async portion of this code and execute it directly in the scripts override to avoid it being out of sync. The times you are parsing also may be part of the problem, unfortunately I cannot help with web requests but can suggest using items like the Time series to get the processing bar time.

            Comment


              #7
              hey, i figured out, there out how i can get the same day data, use if(State != State.Historical) this will give correct date time when accessing candles, and works with async too.

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
              0 responses
              556 views
              0 likes
              Last Post Geovanny Suaza  
              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
              0 responses
              324 views
              1 like
              Last Post Geovanny Suaza  
              Started by Mindset, 02-09-2026, 11:44 AM
              0 responses
              101 views
              0 likes
              Last Post Mindset
              by Mindset
               
              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
              0 responses
              545 views
              1 like
              Last Post Geovanny Suaza  
              Started by RFrosty, 01-28-2026, 06:49 PM
              0 responses
              547 views
              1 like
              Last Post RFrosty
              by RFrosty
               
              Working...
              X