Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How do I stop the strategy when a profit goal or loss have reached

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

    How do I stop the strategy when a profit goal or loss have reached

    Hello: I have working strategy which places trades based on rules I have programmed but it is always placing an extra trade after reaching the daily goal or loss amount.
    For example, my daily goal is 500$ but I see the last trade has $525 or $510 or $590 as the final cumulative profit, and similarly daily cumulative loss is either -580 or -600.
    My each trade has a profit target of $100 and stop loss of $175.

    I would like to create a logic so that let's say if I am in the trade where I have reached $400 ( 4 x $100 per trade ) and as soon as the last trade is in profit and reaches the $100 profit per trade and cumulative daily goal of $500 reached, that trade should be killed as long a as $500 is reached in that last trade.

    I reset the daily PNL = 0 at the end of daily session at 6PM EST and then start trading at specified time range let's say between 9AM to 11AM EST. and stop trading as soon either profit or loss goal have reached or time range have finished, in this case at 11AM Est.

    Please advise. This is for Ninja version 8. Some how it went into Ninja 7 strategy development section.

    Thank you.




    Last edited by mtamaku; 06-02-2024, 06:53 PM.

    #2
    Hello,

    To implement a daily profit and loss goal in your NinjaTrader strategy, you can use variables to track your cumulative profit and loss. You will need to modify your strategy to:
    1. Track the daily profit and loss.
    2. Check the profit and loss before placing a new trade.
    3. Cancel any active trades if the daily profit or loss goal is reached.
    4. Reset the cumulative PNL at the end of the trading day.

    Here is an example of how you can modify your strategy to include this logic:

    Code:
    #region Using declarations
    using System;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Data;
    #endregion
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class DailyPNLStrategy : Strategy
        {
            private double dailyPNL;
            private double dailyGoal = 500;
            private double dailyLossLimit = -500;
            private double tradeProfitTarget = 100;
            private double tradeStopLoss = 175;
            private DateTime sessionEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 18, 0, 0); // 6 PM EST
            private DateTime tradingStartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 9, 0, 0); // 9 AM EST
            private DateTime tradingEndTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 11, 0, 0); // 11 AM EST
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description = @"Strategy with daily profit and loss goal.";
                    Name = "DailyPNLStrategy";
                    Calculate = Calculate.OnEachTick;
                    IsInstantiatedOnEachOptimizationIteration = false;
                    EntriesPerDirection = 1;
                    EntryHandling = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy = true;
                    ExitOnSessionCloseSeconds = 30;
                    StopTargetHandling = StopTargetHandling.ByStrategyPosition;
                    IsFillLimitOnTouch = false;
                    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                    StartBehavior = StartBehavior.WaitUntilFlat;
                    TimeInForce = TimeInForce.Gtc;
                    TraceOrders = false;
                    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                    BarsRequiredToTrade = 20;
                }
                else if (State == State.Configure)
                {
                    // Configure your strategy here
                }
            }
    
            protected override void OnBarUpdate()
            {
                // Ensure we have enough bars to proceed
                if (CurrentBar < BarsRequiredToTrade)
                    return;
    
                // Reset daily PNL at session end
                if (ToTime(Time[0]) >= ToTime(sessionEnd) && ToTime(Time[0]) < ToTime(sessionEnd).AddMinutes(1))
                {
                    dailyPNL = 0;
                }
    
                // Check trading time range
                if (ToTime(Time[0]) < ToTime(tradingStartTime) || ToTime(Time[0]) > ToTime(tradingEndTime))
                    return;
    
                // Check if daily profit or loss goal has been reached
                if (dailyPNL >= dailyGoal || dailyPNL <= dailyLossLimit)
                {
                    if (Position.MarketPosition != MarketPosition.Flat)
                    {
                        ExitLong();
                    }
                    return;
                }
    
                // Example entry condition (replace with your logic)
                if (CrossAbove(Close, SMA(14), 1))
                {
                    if (dailyPNL + tradeProfitTarget >= dailyGoal)
                    {
                        // Modify profit target for the last trade to ensure it does not exceed the daily goal
                        EnterLong("Entry");
                        SetProfitTarget("Entry", CalculationMode.Currency, dailyGoal - dailyPNL);
                        SetStopLoss("Entry", CalculationMode.Currency, -tradeStopLoss);
                    }
                    else
                    {
                        // Standard trade entry
                        EnterLong("Entry");
                        SetProfitTarget("Entry", CalculationMode.Currency, tradeProfitTarget);
                        SetStopLoss("Entry", CalculationMode.Currency, -tradeStopLoss);
                    }
                }
            }
    
            protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
            {
                // Update daily PNL
                if (execution.Order.OrderState == OrderState.Filled)
                {
                    if (execution.Order.OrderAction == OrderAction.Buy || execution.Order.OrderAction == OrderAction.SellShort)
                    {
                        // Entry order
                        entryPrice = price;
                    }
                    else if (execution.Order.OrderAction == OrderAction.Sell || execution.Order.OrderAction == OrderAction.BuyToCover)
                    {
                        // Exit order
                        double tradeProfit = (price - entryPrice) * quantity;
                        dailyPNL += tradeProfit;
                    }
                }
            }
    
            private double entryPrice;
        }
    }
    ​
    Explanation:
    1. Tracking Daily PNL:
      • The dailyPNL variable tracks the cumulative profit or loss for the day.
      • The dailyGoal and dailyLossLimit variables set the profit and loss thresholds.
    2. Resetting PNL at End of Day:
      • The daily PNL is reset at the end of the session (6 PM EST).
    3. Time Filtering:
      • The strategy only places trades within the specified time range (9 AM to 11 AM EST).
    4. Checking Daily Goals:
      • Before placing a new trade, the strategy checks if the daily profit or loss goal has been reached.
      • If the daily goal is close to being reached, the profit target for the last trade is adjusted to ensure the cumulative daily goal is met without exceeding it.
    5. Handling Executions:
      • The OnExecutionUpdate method updates the dailyPNL whenever an order is filled.

    This should ensure that your strategy stops trading once the daily profit or loss goal is reached and manages the trades to avoid exceeding the goals. Adjust the logic to fit your specific requirements and test thoroughly to ensure it behaves as expected.

    Comment


      #3
      Thank you for the code. Very much appreciated !!

      However, my code id different than yours and when I tried to use this SetStopLoss("Entry", CalculationMode.Currency, -tradeStopLoss); to adjust the last trade stop loss, I am getting the compile error as No Overload for Method 'SetStopLoss' takes 3 arguments.

      Here is my version of variables that I try to copy in your code.


      if (DAILY_PNL + PROFIT_TGT >= DAILY_PROFIT_GOAL)
      {
      EnterLong("Entry");
      SetProfitTarget("Entry", CalculationMode.Currency, DAILY_PROFIT_GOAL - DAILY_PNL);
      SetStopLoss("Entry", CalculationMode.Currency, -STOP_LOSS);
      }​


      Thank you.

      Comment

      Latest Posts

      Collapse

      Topics Statistics Last Post
      Started by Geovanny Suaza, 02-11-2026, 06:32 PM
      0 responses
      572 views
      0 likes
      Last Post Geovanny Suaza  
      Started by Geovanny Suaza, 02-11-2026, 05:51 PM
      0 responses
      331 views
      1 like
      Last Post Geovanny Suaza  
      Started by Mindset, 02-09-2026, 11:44 AM
      0 responses
      101 views
      0 likes
      Last Post Mindset
      by Mindset
       
      Started by Geovanny Suaza, 02-02-2026, 12:30 PM
      0 responses
      549 views
      1 like
      Last Post Geovanny Suaza  
      Started by RFrosty, 01-28-2026, 06:49 PM
      0 responses
      550 views
      1 like
      Last Post RFrosty
      by RFrosty
       
      Working...
      X