Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Get the type of the last closed position

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

    Get the type of the last closed position

    Hello NT,

    I am trying to figure out how can I check the type of the last closed position. I have a list of order types and their Names eg "Long Entry" or "Short Entry".

    For example, I want to say that:
    if MyLastClosedPosition is "ShortEntry" or "LongEntry" then do something...

    Is there any method to get this in Ninjascript?

    Thanks for the help!

    #2
    Hello yannistsoupakis,

    Thank you for your post.

    You could use TradeCollection to get the last trade by using the following.

    Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];

    Then, you would use the Entry.MarketPosition property to determine if the trade was long or short. This is seen in example #2 in the help guide documentation below.

    TradeCollection - https://ninjatrader.com/support/help...collection.htm

    Let us know if we may assist further.
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Thanks for the response!

      I am ok with your example and it is working fine.

      I also need to code the following:
      if some criteria are true e.g. close[0]>EMA(200) then don't accept Short Orders and process only Long Orders.

      Is there a way to do this??

      Comment


        #4
        You just can this condition to your entry logic or make it more complicated like this:

        make bools and use em within entry.

        private bool LongOnly;
        private bool ShortOnly;


        if(close[0]>EMA(200))
        {
        LongOnly = true;
        }

        if(close[0]<EMA(200))
        {
        ShortOnly = true;
        }

        if(....) // your entry conditions for short here
        {
        if (LongOnly) return;
        EnterShort();
        }

        if(....) // your entry conditions for long here
        {
        if (ShortOnly) return;
        EnterLong();
        }

        Don't forget to make logic for reseting ShortOnly and LongOnly to false.

        Comment


          #5
          Hello yannistsoupakis,

          Thank you for your note.

          As Leeroy_Jenkins stated, you could use a bool called something like LongOnly that is flipped to true when the Close[0] > EMA(200) for long entry orders. Then, you would check if that bool is true in your entry order condition. This means that for your long entry order to be placed, the LongOnly bool must be true. After you call EnterLong, you flip the bool to false so that the bool is reset. Please see the code shared by Leeroy_Jenkins in the post above for how this could be accomplished.

          Please let us know if we may assist further.
          Brandon H.NinjaTrader Customer Service

          Comment


            #6
            Hello,

            I am using the following code I see in the example to access the last trade and check whether it is long or short

            Trade MyLastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
            (MyLastTrade.Entry.MarketPosition == MarketPosition.Short or Long

            When enabling the strategy, it does not start and gives the following error in the log: Error on calling 'OnBarUpdate' method on bar 10: 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.

            Could you help how to solve this?

            Thank you!

            Comment


              #7
              Hello yannistsoupakis,

              Thank you for your note.

              This error message indicates that you are trying to access an invalid index in your script.

              As one example, calling Close[1] when CurrentBar is 0 (the very first bar) will cause this error. The reason for this is because there will not be a bar ago; essentially there is not enough data at bar 0 to look back one bar. The script will start from the far left of the chart at the very beginning where the CurrentBar will equal 0 and then start working to the right, calling OnBarUpdate() for each bar.

              In this specific example, it would be needed to wait for the second bar to be built (from all series if there are multiple series added), to ensure that you have enough data to call an index 1 bar ago.

              A CurrentBar or CurrentBars check would need to be used in your script to ensure that there are enough bars processed when running your strategy. See the help guide documentation below for more information.

              Make sure you have enough bars - https://ninjatrader.com/support/helpGuides/nt8/make_sure_you_have_enough_bars.htm
              CurrentBar - https://ninjatrader.com/support/help...currentbar.htm
              CurrentBars - https://ninjatrader.com/support/help...urrentbars.htm

              Let us know if we may assist further.
              Brandon H.NinjaTrader Customer Service

              Comment


                #8
                Hello, I am using BarsRequiredToTrade, which I have set it to 20 and I then call my entrysignals.

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

                {
                SetEntrySignalState();
                }

                private void SetEntrySignalState()
                {
                Trade MyLastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
                if (MyLastTrade.Entry.MarketPosition == MarketPosition.Short)
                {
                entry coding....
                }


                else if (MyLastTrade.Entry.MarketPosition == MarketPosition.Long)
                {
                entry coding...
                }

                }

                As I mentioned in my previous post, the error seems to be on the checking of the type of the last trade, since when I comment these lines, the strategy works normally.

                I did a try catch for the entire OnBarUpdate block and it gives me the following output:

                Parameter name: index
                at System.ThrowHelper.ThrowArgumentOutOfRangeExceptio n(ExceptionArgument argument, ExceptionResource resource)
                at System.Collections.Generic.List`1.get_Item(Int32 index)
                at NinjaTrader.NinjaScript.Strategies.BollingerBreako utWithTrailReverse.SetEntrySignalState()
                at NinjaTrader.NinjaScript.Strategies.BollingerBreako utWithTrailReverse.OnBarUpdate()
                System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

                I cannot understand why Index is out of range and negative. Could you assist on that?

                Comment


                  #9
                  Hello yannistsoupakis,

                  Thank you for that information.

                  When working with any issue, it is important to take steps to isolate the issue so that the exact line causing the behavior can be found. This is a process of elimination and a process of debugging by adding prints.

                  First, it is great to create a copy of the script so that the original work is kept safe. Once the copy is created, the copy can be modified in any way without losing the original work. Below is a link to a video that demonstrates making a copy of a script.
                  https://www.youtube.com/watch?v=BA0W...utu.be&t=8m15s

                  The next step is to start commenting out code. It is helpful to think about when the error is occurring to target areas, and comment code from everywhere else quickly. If at any point after removing some code, the error stops, add the last removed item back.

                  If the error is occurring while the script is loading, the issue is likely somewhere in OnStateChange(). In this situation, it is best to remove any logic in OnBarUpdate, remove any custom methods and classes, and remove as many properties as possible, while still being able to reproduce the error.

                  If you still require assistance after reducing the strategy to locate the line of code causing the error, please send us a reduced copy of your strategy that demonstrates the behavior you are reporting so that we may investigate this further.

                  Let us know if we may assist further.

                  Brandon H.NinjaTrader Customer Service

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by AnnBarnes, Today, 12:17 PM
                  0 responses
                  1 view
                  0 likes
                  Last Post AnnBarnes  
                  Started by Lopat, 03-05-2023, 01:19 PM
                  4 responses
                  166 views
                  0 likes
                  Last Post Sam2515
                  by Sam2515
                   
                  Started by f.saeidi, Today, 12:14 PM
                  0 responses
                  2 views
                  0 likes
                  Last Post f.saeidi  
                  Started by giulyko00, Today, 12:03 PM
                  0 responses
                  4 views
                  0 likes
                  Last Post giulyko00  
                  Started by AttiM, 02-14-2024, 05:20 PM
                  12 responses
                  213 views
                  0 likes
                  Last Post DrakeiJosh  
                  Working...
                  X