Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

I am working on this Automatic trading script

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

    I am working on this Automatic trading script

    Here is my script but it does not allow me to compile. May someone take a look to assist me? Not sure on why I am getting errors.

    // This namespace holds Strategies in this folder and is required. Do not change it.
    using System;
    using NinjaTrader.Cbi;

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class Auto_Trade_PriceCrossesEMA20_WithRSI_AndDirectiona lFilter_AndATMCallback : Strategy
    {
    private Series<double> ema20, ema4, tma20, rsi20;
    private bool lineDrawnToday = false;
    private DateTime lastDrawnDate;

    private string atmStrategyId = string.Empty;
    private string orderId = string.Empty;

    private int dailyTradeCount = 0;
    private const int maxDailyTrades = 2;

    private const int startTime = 74500;
    private const int endTime = 92000;
    private const string atmTemplateName = "ZB 2 target trade"; // <- make sure this exactly matches your ATM template name in NinjaTrader

    private void LogATMStrategyCallback(string reason, string message)
    {
    Print("ATM Strategy Callback - Reason: " + reason + ", Message: " + message);
    }

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Strategy that trades when price crosses EMA20, RSI confirms, and direction is filtered. Uses ATM template and limits trades.";
    Name = "PriceCrossesEMA20_WithRSI_AndDirectionalFilte r_An dATMCallback";
    Calculate = Calculate.OnBarClose;
    IsOverlay = true;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
    BarsRequiredToTrade = 20;
    }
    else if (State == State.DataLoaded)
    {
    ema20 = EMA(20);
    ema4 = EMA(4);
    tma20 = TMA(20);
    rsi20 = RSI(20, 1);
    }
    }

    protected override void OnBarUpdate()
    {
    if (CurrentBar < 21) return;

    // Filter: Only trade on Mondays and Fridays
    DayOfWeek today = Time[0].DayOfWeek;
    if (today != DayOfWeek.Monday && today != DayOfWeek.Friday)
    return;

    int currentTime = ToTime(Time[0]);
    DateTime currentDate = Time[0].Date;

    // Reset daily counter and line at start of new day
    if (currentDate != lastDrawnDate)
    {
    lineDrawnToday = false;
    lastDrawnDate = currentDate;
    dailyTradeCount = 0;
    }

    // Draw 7:45 EMA line once per day
    if (currentTime == startTime && !lineDrawnToday)
    {
    double emaValue = ema20[0];
    Draw.HorizontalLine(this,
    "EMA20Line_" + currentDate.ToString("yyyyMMdd"), emaValue, Brushes.Blue);
    Draw.Text(this,
    "EMA20Label_" + currentDate.ToString("yyyyMMdd"), "7:45 EMA", 0, emaValue + TickSize * 2);
    lineDrawnToday = true;
    }

    // Display current trade count
    Draw.TextFixed(this, "DailyTradeCount", "Trades Today: " + dailyTradeCount, TextPosition.TopRight, Brushes.Orange, new SimpleFont("Arial", 12), Brushes.Transparent, Brushes.Transparent, 0);

    // Session time window check
    if (currentTime < startTime || currentTime > endTime)
    return;

    // Enforce max trades per day
    if (dailyTradeCount >= maxDailyTrades)
    return;

    // Wait for existing ATM strategy to complete
    if (!string.IsNullOrEmpty(atmStrategyId))
    {
    OrderState entryState = AtmStrategyGetEntryOrderStatus(atmStrategyId);
    MarketPosition pos = Position.MarketPosition;

    if (pos == MarketPosition.Flat && (entryState == OrderState.Filled || entryState == OrderState.Cancelled))
    {
    atmStrategyId = string.Empty;
    orderId = string.Empty;
    }
    else
    {
    return;
    }
    }

    // Directional filter
    bool isBuyDirection = ema4[0] > tma20[0];
    bool isSellDirection = ema4[0] < tma20[0];

    // Entry logic
    if (isBuyDirection && CrossAbove(Close, ema20, 1) && CrossAbove(rsi20, 50, 1))
    {
    LaunchATM(OrderAction.Buy, "FilteredLong");
    }

    if (isSellDirection && CrossBelow(Close, ema20, 1) && CrossBelow(rsi20, 50, 1))
    {
    LaunchATM(OrderAction.SellShort, "FilteredShort");
    }
    }

    private void LaunchATM(OrderAction action, string signalName)
    {
    atmStrategyId = GetAtmStrategyUniqueId();
    orderId = GetAtmStrategyUniqueId();

    AtmStrategyCreate(
    orderId,
    atmStrategyId,
    atmTemplateName,
    action,
    OrderType.Market,
    1, // quantity
    0, // stop price for market order
    TimeInForce.Day,
    null, // parent order
    signalName,
    (atmCallbackReason, atmCallbackOrderId, atmCallbackOrderState, atmCallbackFillPrice, atmCallbackQuantity, atmCallbackId) =>
    {
    LogATMStrategyCallback(atmCallbackReason.ToString( ), action.ToString() + " via ATM: " + signalName);

    if (atmCallbackReason == AtmStrategyCallbackReason.OrderFilled)
    {
    dailyTradeCount++;
    Print("Trade Count Increased: " + dailyTradeCount);
    }
    }
    );
    }
    }
    }

    #2
    Hello Brandynthompson,

    What error are you seeing?

    Just looking at the code this does not appear to be a complete NinjaScript file. Was this something you made yourself or something that was generated?

    Comment


      #3
      Hi, I am new, a few guesses

      When you compile it, do you get errors on the bottom of your screen? When I get errors, I lookup what they are about

      I believe you cannot have spaces in the Strategy name, and you have a space in the word Directional below. I think you also might not be able to use underscore _ which you have a few.

      public class Auto_Trade_PriceCrossesEMA20_WithRSI_AndDirectiona lFilter_AndATMCallback : Strategy

      There might also be an issue with another line

      Name = "PriceCrossesEMA20_WithRSI_AndDirectionalFilte r_An dATMCallback";

      Comment


        #4
        Hello Brandynthompson,

        You can have spaces in the name property:
        Name = "PriceCrossesEMA20_WithRSI_AndDirectionalFilte r_An dATMCallback";

        You cannot have spaces in the class:
        public class Auto_Trade_PriceCrossesEMA20_WithRSI_AndDirectiona lFilter_AndATMCallback : Strategy

        I would still need to know what errors you are seeing.

        Comment


          #5
          Originally posted by NinjaTrader_Jesse View Post
          You can have spaces in the name property:
          Name = "PriceCrossesEMA20_WithRSI_AndDirectionalFilte r_An dATMCallback";

          You cannot have spaces in the class:
          public class Auto_Trade_PriceCrossesEMA20_WithRSI_AndDirectiona lFilter_AndATMCallback : Strategy
          I suspect you are being misled by your own forum software.

          Many times this forum software will forcefully insert spaces
          into long identifiers, or worse, long filenames, esp if supplied
          with the full pathname.

          To wit,
          ThisIsOneLongLineWithNoSpacesI'mJustTypingAnything HereButThereAreAbsoutelyNoSpaceCharactersInThisLin eButTheForumSoftwareWillInsertSpacesItselfBecauseI tThinksItKnowsBest

          Do you see any spaces or line breaks in the above line?
          (I typed it completely as one big long line with no spaces.)
          If so, your forum software did it, not me.

          Comment


            #6
            I generated this code myself and trying to fit it within the ninja trading system.

            These are my current errors

            Click image for larger version

Name:	image.png
Views:	158
Size:	58.4 KB
ID:	1342522

            Comment


              #7
              Yep, the forum software sucks in this regard.

              The line break and the space in 'TypingAnything HereBut'
              and 'BecauseI tThinksItKnowsBest' are due to this forum
              software.

              Bummer.
              Last edited by bltdavid; 05-07-2025, 04:34 PM.

              Comment


                #8
                At first glance ...

                The way these are being used,

                private Series<double> ema20, ema4, tma20, rsi20;

                is wrong. You should use an ISeries, like this,

                private ISeries<double> ema20, ema4, tma20, rsi20;

                Try that.

                Comment


                  #9
                  Hello Brandynthompson,

                  You are missing using statements. I would suggest to use the NinjaScript editor to create a entirely new file. Delete the file you were using and then re code the new file with the changes you want. You need to maintain the initial structure and using statements that are generated with new files to avoid the errors you are seeing.

                  bltdavid, ISeries is used for price input or indicator input specifically and is not how to define a indicator series. The code shown in post 1 should be individual indicators rather than series. For example:

                  private EMAema20 ;
                  You can use the strategy builder to generate the necessary code to use indicators as variables.
                  Last edited by NinjaTrader_Jesse; 05-08-2025, 06:59 AM.

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by NullPointStrategies, Today, 05:17 AM
                  0 responses
                  50 views
                  0 likes
                  Last Post NullPointStrategies  
                  Started by argusthome, 03-08-2026, 10:06 AM
                  0 responses
                  126 views
                  0 likes
                  Last Post argusthome  
                  Started by NabilKhattabi, 03-06-2026, 11:18 AM
                  0 responses
                  69 views
                  0 likes
                  Last Post NabilKhattabi  
                  Started by Deep42, 03-06-2026, 12:28 AM
                  0 responses
                  42 views
                  0 likes
                  Last Post Deep42
                  by Deep42
                   
                  Started by TheRealMorford, 03-05-2026, 06:15 PM
                  0 responses
                  46 views
                  0 likes
                  Last Post TheRealMorford  
                  Working...
                  X