Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

OnBarUpdate' method on bar 520: String was not recognized as a valid DateTime

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

    OnBarUpdate' method on bar 520: String was not recognized as a valid DateTime

    Hello,

    I was hoping that someone here can help me with an answer.

    The code below shows my strategy.The problem is when testing it disables itself every few trades. Iam using playback and I tested it on the slow speed as well as fast.

    The error code is:Error on calling 'OnBarUpdate' method on bar 520: String was not recognized as a valid DateTime

    Bar 520 can vary to any bar number. I would like for the code to ignore the error and continue without disabling the strategy.

    region Using declarations
    using System;
    using System.Globalization;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    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.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class BuilderProject_10_18_2023_25_21_111 : Strategy
    {
    region Variables

    // Variables for entry and exit prices
    double EntPrL = 0;
    double EntPrS = 0;

    // Variables for entry and exit conditions
    Series<double> VarL1;
    Series<double> VarL2;
    Series<double> VarL3;
    Series<double> VarL4;
    Series<double> VarL5;
    Series<double> VarL7;
    Series<double> VarS1;
    Series<double> VarS2;
    Series<double> VarS3;
    bool EntCondL = false;
    bool EntCondS = false;
    bool ExCondL = false;
    bool ExCondS = false;
    int SessionEndTime;

    // Variables for position sizing
    int NShares = 0;
    double Equity = 0;

    // Variable for back-test bar reference adjustment
    int BTAdjust = 1;

    // Variables for neural network
    double[] NNInputs = new double[3];
    double[] NNWeights = new double[6];
    double NNOutput;
    #endregion

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = "Adaptrade Builder strategy BuilderProject_10_18_2023_25_21_111";
    Name = "BuilderProject_10_18_2023_25_21_111";

    // Set calculation options
    Calculate = Calculate.OnPriceChange;
    IsUnmanaged = true;
    BarsRequiredToTrade = 111;
    IsExitOnSessionCloseStrategy = false;
    PlaceMMExitOnEntry = false;

    // Default values of strategy inputs
    N1 = 35;
    N2 = 100;
    N3 = 37;
    N4 = 50;
    N5 = 124300;
    N6 = 3;
    X1 = 4.1418;
    Shift1 = 19;
    Shift2 = 10;
    Shift3 = 7;
    Wgt1 = 0.3735;
    Wgt2 = 0.3828;
    Wgt3 = 0.2769;
    Wgt4 = 0.0444;
    Wgt5 = 0.8497;
    Wgt6 = 0.7802;
    NBarEnt1 = 49;
    EntFr = 1.3940;
    NBarEx1 = 7;
    StartEquity = 50000.00;
    PSParam = 23637.45;
    RoundPS = true;
    RoundTo = 1;
    MinSize = 1;
    SizeLimit = 1;
    }
    else if (State == State.Configure)
    {
    // Plot indicators used in strategy logic
    AS_PivotR(N6).Plots[0].Brush = Brushes.Blue;
    AddChartIndicator(AS_PivotR(N6));
    }
    else if (State == State.DataLoaded)
    {
    // Allocate array variables
    VarL1 = new Series<double>(this);
    VarL2 = new Series<double>(this);
    VarL3 = new Series<double>(this);
    VarL4 = new Series<double>(this);
    VarL5 = new Series<double>(this);
    VarL7 = new Series<double>(this);
    VarS1 = new Series<double>(this);
    VarS2 = new Series<double>(this);
    VarS3 = new Series<double>(this);
    }
    else if (State == State.Realtime)
    {
    AS_OnChangeToRealtime();
    }
    else if (State == State.Terminated)
    {
    AS_CancelEntriesOnTerminate();
    }
    }

    // Manage trading orders; called every time an order changes state.
    protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice,
    int quantity, int filled, double averageFillPrice,
    OrderState orderState, DateTime time, ErrorCode error, string comment)
    {
    AS_ManageOrders(order);
    }

    // Main strategy logic; called on the first tick or close of each bar for real-time or historical evaluation.
    protected override void OnBarUpdate()
    {
    if (CurrentBar < BarsRequiredToTrade)
    return;

    // Evaluate strategy logic once per bar
    if (IsFirstTickOfBar)
    {
    // Adjust bar references when switching to real-time data
    BTAdjust = (State == State.Historical ? 0 : 1);

    // Get session times
    if (Bars.BarsSinceNewTradingDay == 0)
    {
    SessionEndTime = Bars.TradingHours.Sessions[0].EndTime;
    }

    LastBarOfSession = ToTime(Time[0]) == SessionEndTime;

    // Entry prices
    EntPrL = WMA(Close, NBarEnt1)[BTAdjust] - EntFr * ATR(1)[BTAdjust];
    EntPrS = WMA(Close, NBarEnt1)[BTAdjust] + EntFr * ATR(1)[BTAdjust];

    // Entry and exit conditions
    VarL1[0] = ATR(1)[Shift1 + BTAdjust];
    VarL2[0] = ATR(1)[Shift2 + BTAdjust];
    VarL3[0] = AS_AdaptZLT(VarL2, N1, N2, X1)[0];
    VarS1[0] = ATR(1)[Shift1 + BTAdjust];
    VarS2[0] = ATR(1)[Shift2 + BTAdjust];
    VarS3[0] = AS_AdaptZLT(VarS2, N1, N2, X1)[0];
    EntCondL = true;
    EntCondS = true;
    ExCondL = VarL1[0] == VarL3[0];
    ExCondS = VarS1[0] == VarS3[0];

    // Neural network inputs
    VarL4[0] = Typical[BTAdjust];
    VarL5[0] = WMA(VarL4, N3)[0];
    VarL7[0] = ToTime(Time[BTAdjust]);

    NNInputs[0] = AS_UlcerIndex(VarL5, N4)[Shift3];
    NNInputs[1] = VarL7[0] - N5;
    NNInputs[2] = AS_PivotR(N6)[BTAdjust];

    // Evaluate neural network function
    NNWeights[0] = Wgt1;
    NNWeights[1] = Wgt2;
    NNWeights[2] = Wgt3;
    NNWeights[3] = Wgt4;
    NNWeights[4] = Wgt5;
    NNWeights[5] = Wgt6;

    NNOutput = AS_NNCompute2(NNInputs, 3, NNWeights, 6, 100);

    // Position sizing calculations
    Equity = StartEquity + SystemPerformance.AllTrades.TradesPerformance.Gros sProfit +
    SystemPerformance.AllTrades.TradesPerformance.Gros sLoss;

    NShares = MinSize;

    if (RoundPS && RoundTo > 0)
    NShares = (int)Math.Floor((double)MinSize/RoundTo);

    if (Math.Abs(PSParam) > 0 && (Equity - StartEquity) > 0)
    NShares = (int)(0.5 * (1 + Math.Sqrt(Math.Pow((2 * NShares - 1), 2.0) + 8 * (Equity - StartEquity)/Math.Abs(PSParam))));

    if (RoundPS && RoundTo > 0)
    NShares = NShares * RoundTo;

    if (RoundPS && RoundTo > 0)
    NShares = (int)Math.Floor((double)NShares/RoundTo) * RoundTo;

    NShares = Math.Max(NShares, MinSize);
    NShares = Math.Min(NShares, SizeLimit);

    // Entry orders
    if (Position.MarketPosition == MarketPosition.Flat && EntCondL && Close[BTAdjust] > EntPrL && NNOutput >= 0.5)
    {
    AS_EnterLongLimit(NShares, EntPrL);
    }
    else
    {
    AS_CancelLongEntry();
    }

    if (Position.MarketPosition == MarketPosition.Flat && EntCondS && Close[BTAdjust] < EntPrS && NNOutput <= -0.5)
    {
    AS_EnterShortLimit(NShares, EntPrS);
    }
    else
    {
    AS_CancelShortEntry();
    }

    // Exit orders, long trades
    if (Position.MarketPosition == MarketPosition.Long)
    {
    if (ExCondL || (BarsSinceEntryExecution() >= NBarEx1 && Close[BTAdjust] > Position.AveragePrice))
    AS_ExitLongMarket();
    }

    // Exit orders, short trades
    if (Position.MarketPosition == MarketPosition.Short)
    {
    if (ExCondS || (BarsSinceEntryExecution() >= NBarEx1 && Close[BTAdjust] < Position.AveragePrice))
    AS_ExitShortMarket();
    }
    }

    // Cancel all orders at end of session
    if (State != State.Historical && LastBarOfSession)
    {
    TimeSpan CancelSeconds = new TimeSpan(0, 0, 30);

    // Cancel any open orders within CancelSeconds of end-of-session
    if (DateTime.Now > (DateTime.ParseExact(SessionEndTime.ToString(), "HHMMss", CultureInfo.InvariantCulture) - CancelSeconds))
    {
    AS_CancelOrders();
    }
    }
    }




    #2
    Hello binarytech,

    Thank you for your post.

    In order to identify the cause of the error, I suggest adding Print() statements throughout OnBarUpdate() or commenting out different lines of code and testing in between each change. If you add a Print() every few lines, then you can review the NinjaScript Output window. Once the error appears, the last print to show in the output will help you to narrow down the potential offending code that caused the error because it will be located somewhere after the last print that appears and before the next print. For more info about using prints to debug your script:


    Strategies do have a RealtimeErrorHandling property that may be modified, though this applies to errors and rejections received by the strategy and the strategy may still be stopped due to runtime errors such as the one you have been receiving:


    Please let us know if we may be of further assistance.

    Comment


      #3
      Originally posted by NinjaTrader_Emily View Post
      Hello binarytech,

      Thank you for your post.

      In order to identify the cause of the error, I suggest adding Print() statements throughout OnBarUpdate() or commenting out different lines of code and testing in between each change. If you add a Print() every few lines, then you can review the NinjaScript Output window. Once the error appears, the last print to show in the output will help you to narrow down the potential offending code that caused the error because it will be located somewhere after the last print that appears and before the next print. For more info about using prints to debug your script:


      Strategies do have a RealtimeErrorHandling property that may be modified, though this applies to errors and rejections received by the strategy and the strategy may still be stopped due to runtime errors such as the one you have been receiving:


      Please let us know if we may be of further assistance.
      Hey Emily,

      Thanks for getting back to me. I tried putting Print statements, but I am getting the same error as in the log tab. I am not very good with code. I also inserted a RealtimeErrorHandling statement, but it did not stop the program execution as you said it might not. The error seems to happen at 12:00 AM, but not every day. I checked the data and it seems to be the same as other days and times. All that I want to do is for the code to keep executing and bypass this specific error. Can you show me a code that can bypass this error? Thanks.

      Comment


        #4
        Hello binarytech,

        Thank you for your reply.

        There is no way to bypass the error until you identify which line of code is causing the error. What was the output after adding print statements? Which print statement appeared last before the error came up?

        It is against our support policy to provide hands-on debugging assistance. If you would prefer hands-on assistance, you can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services. Please let me know if you would like our NinjaTrader Ecosystem team to follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request or provide one-on-one educational services.

        Please let me know if I may be of further assistance.

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by NullPointStrategies, Today, 05:17 AM
        0 responses
        52 views
        0 likes
        Last Post NullPointStrategies  
        Started by argusthome, 03-08-2026, 10:06 AM
        0 responses
        130 views
        0 likes
        Last Post argusthome  
        Started by NabilKhattabi, 03-06-2026, 11:18 AM
        0 responses
        70 views
        0 likes
        Last Post NabilKhattabi  
        Started by Deep42, 03-06-2026, 12:28 AM
        0 responses
        43 views
        0 likes
        Last Post Deep42
        by Deep42
         
        Started by TheRealMorford, 03-05-2026, 06:15 PM
        0 responses
        47 views
        0 likes
        Last Post TheRealMorford  
        Working...
        X