Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Position.MarketPosition == MarketPosition.Flat - Doesn't work in both directions

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

    Position.MarketPosition == MarketPosition.Flat - Doesn't work in both directions

    Hi, I am not an expert programmer and trying to achieve a simple cross over strategy to work but i wanted to make sure the Market Position is Flat before entering long or short trades.

    I couldn't achieve with short entry but below code works in long entry please help or guide me to also accomplish on short entry.

    /Thanks, SM.

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

    if(CrossAbove(EMA1, EMA2, 1) && Position.MarketPosition == MarketPosition.Flat)
    EnterLong();

    else if (CrossBelow(EMA1, EMA2, 1))
    ExitLong();


    }​



    #2
    Hello smtraders,

    Thanks for your post.

    That would be the correct way to check if the current market position of the strategy is Flat.

    The code you shared would check if a crossabove condition occurs and the strategy position is Flat and places a long entry order with EnterLong();

    If the strategy is not entering short positions, then it is likely that the condition to place a short entry order is not becoming true.

    To understand why the script is behaving as it is, such as placing orders or not placing orders when expected, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

    Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.

    https://ninjatrader.com/support/foru...121#post791121

    Let me know if I may assist further.
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3
      smtraders It would appear that your code, as provided, is not actually entering a short at all.

      It may help if you state your logic in plain language first and then translate that into code.

      For example: if flat and cross above, go long; but if flat and cross below, go short; if not flat, do <whatever you want>;

      Something like this might be similar to what you're intending:
      Code:
      protected override void OnBarUpdate()
      {
          if (CurrentBar < BarsRequiredToTrade)
              return;
      
          if (Position.MarketPosition == MarketPosition.Flat)
          {
              if (CrossAbove(EMA1, EMA2, 1))
                  EnterLong();
              else
              if (CrossBelow(EMA1, EMA2, 1))
                  EnterShort();
          }
          else
          {
              // Do whatever when not flat
          }
      }​
      That code will enter when flat, according to the cross. But after that, you need an exit condition to bring it back to flat if that is your mandatory requirement to enter another position.

      Hope that helps.

      Thanks.​
      Multi-Dimensional Managed Trading
      jeronymite
      NinjaTrader Ecosystem Vendor - Mizpah Software

      Comment


        #4
        Thanks for the replay !

        I tried to modify the code accordingly but now getting strange error not sure what's gone wrong here !


        namespace NinjaTrader.NinjaScript.Strategies
        {
        public class EMACross54 : Strategy
        {
        private EMA EMA1;
        private EMA EMA2;
        private EMA EMA3;
        private double ask;
        private double bid;



        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
        {
        Description = @"EMACross54";
        Name = "EMACross54";
        Calculate = Calculate.OnBarClose;
        EntriesPerDirection = 1;
        EntryHandling = EntryHandling.AllEntries;
        IsExitOnSessionCloseStrategy = true;
        ExitOnSessionCloseSeconds = 30;
        IsFillLimitOnTouch = false;
        MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
        OrderFillResolution = OrderFillResolution.Standard;
        Slippage = 0;
        StartBehavior = StartBehavior.WaitUntilFlat;
        TimeInForce = TimeInForce.Gtc;
        TraceOrders = false;
        RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
        StopTargetHandling = StopTargetHandling.PerEntryExecution;
        BarsRequiredToTrade = 20;
        ask = GetCurrentAsk();
        bid = GetCurrentBid();
        // Disable this property for performance gains in Strategy Analyzer optimizations
        // See the Help Guide for additional information
        IsInstantiatedOnEachOptimizationIteration = false;
        Fast = 10;
        Slow1 = 20;
        Slow2 = 30;

        }
        else if (State == State.Configure)
        {
        }
        else if (State == State.DataLoaded)
        {
        EMA1 = EMA(Close, Convert.ToInt32(Fast));
        EMA2 = EMA(Close, Convert.ToInt32(Slow1));
        EMA3 = EMA(Close, Convert.ToInt32(Slow2));



        EMA1.Plots[0].Brush = Brushes.Goldenrod;
        EMA2.Plots[0].Brush = Brushes.SeaGreen;
        EMA3.Plots[0].Brush = Brushes.Green;

        AddChartIndicator(EMA1);
        AddChartIndicator(EMA2);
        AddChartIndicator(EMA3);


        }
        }



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

        if (Position.MarketPosition == MarketPosition.Flat)
        {
        if(CrossAbove(EMA1, EMA3, 1))
        EnterLongLimit(bid);

        else if (CrossBelow(EMA1, EMA2, 1))
        ExitLongLimit(ask);
        }
        else
        {
        if(CrossBelow(EMA1, EMA3, 1))
        EnterShortLimit(ask);

        else if (CrossAbove(EMA1, EMA2, 1))
        ExitShortLimit(bid);
        }
        }​

        ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        error :
        2022-11-02 21:46:27 Default Strategy 'EMACross54': Error on calling 'OnStateChange' method: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.

        Comment


          #5
          Hello smtraders,

          Thanks for your note.

          I see that you are calling the code below in State.SetDefaults.

          ask = GetCurrentAsk();
          bid = GetCurrentBid();

          The GetCurrentAsk() and GetCurrentBid() methods should be called in the OnBarUpdate() section of your script so that the data being used to access the current Ask and Bid values have been loaded.

          See the help guide documentation below for more information and sample code.

          ​GetCurrentAsk(): https://ninjatrader.com/support/help...currentask.htm
          GetCurrentBid(): https://ninjatrader.com/support/help...currentbid.htm

          Let me know if I may assist further.
          <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by NullPointStrategies, Yesterday, 05:17 AM
          0 responses
          76 views
          0 likes
          Last Post NullPointStrategies  
          Started by argusthome, 03-08-2026, 10:06 AM
          0 responses
          146 views
          0 likes
          Last Post argusthome  
          Started by NabilKhattabi, 03-06-2026, 11:18 AM
          0 responses
          79 views
          0 likes
          Last Post NabilKhattabi  
          Started by Deep42, 03-06-2026, 12:28 AM
          0 responses
          50 views
          0 likes
          Last Post Deep42
          by Deep42
           
          Started by TheRealMorford, 03-05-2026, 06:15 PM
          0 responses
          54 views
          0 likes
          Last Post TheRealMorford  
          Working...
          X