Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Strategy Builder profit target exit quantity

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

    Strategy Builder profit target exit quantity

    Hello,

    I'm a complete novice at coding and have had some success with a strategy in the builder. Is there a simple way to set a profit target but only sell half the position (of 2 contracts) to leave a runner?

    Thanks in advance!

    #2
    Code:
    [COLOR=#2ecc71]if [/COLOR](High[[COLOR=#2ecc71]0[/COLOR]] > High[[COLOR=#2ecc71]1[/COLOR]])         [COLOR=#16a085]// <- whatever your condition is to exit[/COLOR]
    {
    ExitLong(Convert.ToInt32(Position.Quantity/2), [COLOR=#2980b9]@"halfcover"[/COLOR], [COLOR=#2980b9]@"entry[/COLOR]"); [COLOR=#16a085]//assumes a long trade for this example
    // the  @"halfcover" is name I gave the this signal, you can make up your own.
    // @"entry" has to be replaced with whatever signal name you gave your entry[/COLOR]
    }
    Last edited by _WELD_; 07-25-2022, 09:04 PM.

    Comment


      #3
      Thank you WELD!

      Comment


        #4
        Hi Paypachaysa,

        You could as well do this:

        Code:
        namespace NinjaTrader.NinjaScript.Strategies
        {
            public class MyCustomStrategy : Strategy
            {
                private int qty = 6;
        
                protected override void OnStateChange()
                {   
                    if (State == State.SetDefaults)
                    {   
                        Description = @"Enter the description for your new custom Strategy here.";
                        Name = "MyCustomStrategy";
                        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;
        
                        // Disable this property for performance gains in Strategy Analyzer optimizations
                        // See the Help Guide for additional information
                        IsInstantiatedOnEachOptimizationIteration = true;
                    }   
                    else if (State == State.Configure)
                    {
                    }
                    else if (State == State.DataLoaded)
                    {
                    }
                }   
        
                protected override void OnBarUpdate()
                {   
                    // Get current profit
                    double netProfit = SystemPerformance.AllTrades.TradesPerformance.NetProfit;
        
                    // Always make sure that number of bars that have passed are greater than BarsRequiredToTrade
                    if (CurrentBar >= BarsRequiredToTrade)
                    {
                        // Enter a position
                        EnterLong(qty);
        
                        // Check if net profit is greater than 200
                        if (netProfit > 200);
                        {
                            // Exit position in half quantity
                            ExitLong(qty / 2);
                        }
                    }   
                }   
            }   
        }
        Coding it this way, you're able to set a profit target then exit a position in half quantity.

        I hope this helpful.
        I build useful software systems for financial markets
        Generate automated strategies in NinjaTrader : www.stratgen.io

        Comment


          #5
          woltah231,

          This is very helpful thank you. I managed to get this to compile without errors but it is not working as expected. It buys 2 and sells one $.25 apart. I must be doing something wrong with the check profit.. Can you see my error here. This is the first thing I've ever tried to work with code. Sorry!


          Code:
          protected override void OnBarUpdate()
          {
          double netProfit = SystemPerformance.AllTrades.TradesPerformance.NetP rofit;
          
          if (BarsInProgress != 0)
          return;
          
          if (CurrentBars[0] < 0)
          return;
          
          // Set 1
          if (ninZaSolarWind1.Signal_Trade[0] == 1)
          
          {
          EnterLong(2, "");
          
          }
          
          
          if (netProfit > 200);
          
          {
          ExitLong(2 / 2);
          
          }
          
          
          // Set 2
          if (ninZaSolarWind1.Signal_Trade[0] == -1)
          {
          EnterShort(2, "");
          
          }
          
          if (netProfit > 200);
          
          {
          
          ExitShort(2 / 2);
          }
          
          }
          }

          Comment


            #6
            Hello Paypachaysa,

            I gave you the wrong solution. netProfit is an overall profit so we shouldn't be using it to check if we made profit for the current position. Here's the actual solution:

            Code:
            public class MyCustomStrategy : Strategy
            {
                private int qty = 1;
                private double enteredPrice = 0;
            
                protected override void OnStateChange()
                {   
                    if (State == State.SetDefaults)
                    {   
                        Description = @"Enter the description for your new custom Strategy here.";
                        Name = "MyCustomStrategy";
                        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;
            
                        // Disable this property for performance gains in Strategy Analyzer optimizations
                        // See the Help Guide for additional information
                        IsInstantiatedOnEachOptimizationIteration = true;
                    }   
                    else if (State == State.Configure)
                    {
                    }
                    else if (State == State.DataLoaded)
                    {
                    }
                }
            
                protected override void OnBarUpdate()
                {   
                    double LossLimitPerDay = 2000;
                    double bigPointValue = Bars.Instrument.MasterInstrument.PointValue;
            
                    // Always make sure that number of bars that have passed are greater than BarsRequiredToTrade
                    if (CurrentBar >= BarsRequiredToTrade)
                    {   
                        // NOTE: I'm using CL 1 Day data series that's why I'm using $2000 stop loss and profit.
                        // NOTE: Feel free to change Stop Loss and Profit price
                        EnterLong(qty, "Entered Long");
            
                        int barsSinceEntry = BarsSinceEntryExecution();
            
                        // Get entered price
                        if (barsSinceEntry == 0) {
                            // Get actual price of instrument using big point value
                            enteredPrice = Position.AveragePrice * bigPointValue;
                        }
            
                        // Make sure we're in long position
                        if (Position.MarketPosition == MarketPosition.Long)
                        {
                            // If profit is greater than 2000, exit long.
                            if (((Close[0] * bigPointValue) - 2000) > enteredPrice)
                            {   
                                ExitLong(qty, "Exit with Profit", "Entered Long");
                            }   
            
                            // If loss is lesser than 2000, exit long
                            if (((Close[0] * bigPointValue) + LossLimitPerDay) < enteredPrice)
                            {   
                                ExitLong(qty, "Stop Loss", "Entered Long");
                            }
                        }   
                    }
                }
            }
            In this code, I used CL 1 Day data series so the LossLimitPerDay and Profit Target is big. if (((Close[0] * bigPointValue) - 2000) > enteredPrice), this validation basically checks if the gap of current Close and Entered Price is greater than $2000. The same logic is used for Stop Loss.

            Let me know if this works for you.
            I build useful software systems for financial markets
            Generate automated strategies in NinjaTrader : www.stratgen.io

            Comment


              #7
              Thank you, would it be the same code and smaller dollar value if I am looking for $50 intraday?

              Comment


                #8
                Hello Paypachaysa,

                Yes, you can use the same code.
                I build useful software systems for financial markets
                Generate automated strategies in NinjaTrader : www.stratgen.io

                Comment

                Latest Posts

                Collapse

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