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

OnExecution() to manage trades and track losing trades

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

    OnExecution() to manage trades and track losing trades

    Hi,

    I would like to know if this is the right way to manage trades and track losing ones.


    HTML Code:
            protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price,
                                              int quantity, Cbi.MarketPosition marketPosition, string orderId, DateTime time)
                                {
                                    if (execution.Order != null && execution.Order.OrderState == Cbi.OrderState.Filled)
                                    {
                                        // Check if the trade was a loser
                                        if (GetAtmStrategyRealizedProfitLoss(atmStrategyId)< 0)
                                        {
                                            losingTrades++;
                                            if (losingTrades >= 1)
                                            {
                                                canTrade = false; // Prevent further trading in this event
                                            }
                                        }
                                    }
                                }
    ​
    I would like my script to stop placing trades if there is a losing trade within an event. My current script keeps placing trades after losing one.

    This is one of the events

    HTML Code:
       if (orderId.Length == 0 && atmStrategyId.Length == 0 &&  isPreviousBarBullish )
                        {
    
                                        canTrade = true;
                                        hadALosingTrade = false;
                        }
    ​
    and I use a atmstrategy

    HTML Code:
     if (canTrade && ...)
                        {
    
                                        isAtmStrategyCreated = false;  // reset atm strategy created check to false
                                        atmStrategyId = GetAtmStrategyUniqueId();
                                        orderId = GetAtmStrategyUniqueId();
                                        AtmStrategyCreate(OrderAction.Buy, OrderType.Market, 0, 0, TimeInForce.Day, orderId, "3 Posistion BreakEvenCheckNQ", atmStrategyId, (atmCallbackErrorCode, atmCallBackId) => {
                                        //check that the atm strategy create did not result in error, and that the requested atm strategy matches the id in callback
                                        if (atmCallbackErrorCode == ErrorCode.NoError && atmCallBackId == atmStrategyId)
                                            isAtmStrategyCreated = true;
                                            });
    
                                    canTrade =!hadALosingTrade;
    
                        }​
    Am I writing it right? If not does anyone know where I can find a reference script to help me.

    #2
    Hello patdmoney,

    Thank you for your post.

    Since you are using Atm Strategy Methods to submit your orders, OnExecution(), OnOrderUpdate(), and OnPositionUpdate() will not execute.

    From the Help Guide:

    "Executions from ATM Strategies will not have an impact on the hosting NinjaScript strategy position and PnL - the NinjaScript strategy hands off the execution aspects to the ATM, thus no monitoring via the regular NinjaScript strategy methods will take place (also applies to strategy performance tracking)"

    Using Atm Strategies - https://ninjatrader.com/support/help...strategies.htm

    Instead of keeping track of the orders in OnExecutionUpdate(), you can use ATM Strategy Methods. Please see the following page for a list of all the available methods:

    https://ninjatrader.com/support/help...gy_methods.htm

    For an example demonstrating using an Atm Strategy in your script, check out SampleAtmStrategy included in NinjaTrader 8.

    Please let me know if you have any other questions.
    Gaby V.NinjaTrader Customer Service

    Comment


      #3
      Thank you. Can I use this script to manage my losing trades with the ATM strategy?

      HTML Code:
                  // Determine if the last trade was a loss
                  if (SystemPerformance.AllTrades.Count > 0 && Position.MarketPosition == MarketPosition.Flat)
                  {
                       Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
                       Trade firstTrade = SystemPerformance.AllTrades[0];
      
                      if (lastTrade.ProfitCurrency <= 0)
                      {
                          canTrade = false;
                      }
                  }​

      Comment


        #4
        Hello,

        No, you will need to use ATM Strategy Methods to keep track to keep track of the orders. As mentioned in the previous quote, "no monitoring via the regular NinjaScript strategy methods will take place (also applies to strategy performance tracking)".

        Please let us know if you have any other questions.
        Gaby V.NinjaTrader Customer Service

        Comment


          #5
          So, if you are using the atm strategy you basically don’t have an effective way to track your losing trade. Can I use something like this

          private string currentAtmStrategyId = string.Empty;
          private bool canTrade;

          HTML Code:
          protected override void OnBarUpdate()
          {
          // Check if ATM Strategy is active
          if (!string.IsNullOrEmpty(currentAtmStrategyId))
          {
          // Get the realized PnL of the current ATM strategy
          double atmPnL = GetAtmStrategyRealizedProfitLoss(currentAtmStrategyId);
          
          // Check if the last trade was a loss
          if (atmPnL < 0)
          {
          canTrade = false;
          }
          else
          {
          canTrade = true;
          }
          }
          
          // Your trade entry logic
          if (canTrade && /* your entry condition */)
          {
          // Define your ATM strategy
          string atmStrategyTemplate = "YourATMStrategyName";
          
          // Create a new ATM Strategy
          currentAtmStrategyId = GetAtmStrategyUniqueId();
          AtmStrategyCreate(OrderAction.Buy, OrderType.Market, 0, 0, TimeInForce.Day, currentAtmStrategyId, atmStrategyTemplate, "MyAtmStrategy", false);
          }
          
          // Additional logic for managing the ATM strategy
          // ...
          }
          
          // Additional methods and logic
          // ...​​
          Last edited by patdmoney; 12-27-2023, 07:39 AM.

          Comment


            #6
            Hello,

            Yes, you can track it that way, utilizing only Atm Strategy Methods.

            Please let us know if you have any other questions.
            Gaby V.NinjaTrader Customer Service

            Comment


              #7
              Thanks, one last question.

              Can I use this
              protected override void Initialize()
              {
              initialAccountValue = Account.Get(AccountItem.CashValue, Currency.UsDollar);
              }​
              with the ATM strategy to track the PNL and stop the strategy if the PNL falls below a certain percentage.
              Last edited by patdmoney; 12-27-2023, 08:46 AM.

              Comment


                #8
                Hello,

                That line of code will get the account's current cash value. You can also access the PnL using AccountItem.RealizedProfitLoss.

                https://ninjatrader.com/support/help...ccountitem.htm

                Please note using the Account.Get will get total PnL on the account including manual trades, not the PnL from the ATM by itself. To get the ATM PnL you will need to use Atm Strategy Methods.

                https://ninjatrader.com/support/help...edprofitlo.htm
                Gaby V.NinjaTrader Customer Service

                Comment


                  #9
                  Ok, that works for me then. I want to get the total PnL.

                  Thanks

                  Comment


                    #10
                    I have another question. I would like to know the best way to reset GetAmtstrategyRealizedProfitLoss().
                    HTML Code:
                    protected override void OnBarUpdate()
                    {
                        // Check if there is an active ATM Strategy and manage its PnL
                        if (!string.IsNullOrEmpty(currentAtmStrategyId))
                        {
                            double atmPnL = GetAtmStrategyRealizedProfitLoss(currentAtmStrategyId);
                    
                            // If the last trade was a loss, set canTrade to false and reset the ATM strategy
                            if (atmPnL < 0)
                            {
                                canTrade = false;
                    
                                // Close the current ATM strategy to reset the PnL
                                AtmStrategyClose(currentAtmStrategyId);
                                currentAtmStrategyId = string.Empty;
                            }
                            else
                            {
                                canTrade = true;
                            }
                        }
                    
                    ​
                    does this looks right ?

                    Comment


                      #11
                      Hello,

                      Yes, once you close the ATM strategy via AtmStrategyClose() cancels any working orders and closes any open position of a strategy using the default ATM strategy close behavior.

                      https://ninjatrader.com/support/help...r_atm_stra.htm

                      When you recreate the strategy using AtmStrategyCreate(), this new instance will have its own new PnL.
                      Gaby V.NinjaTrader Customer Service

                      Comment


                        #12
                        Hi,

                        I am having some issues with my script and I don't understand what I am doing wrong.

                        it is supposed to stop the strategy when we have a losing trade.

                        HTML Code:
                        if (!string.IsNullOrEmpty(atmStrategyId)) //atmStrategyId.Length > 0)
                        
                                        {  
                                        double atmPnL = GetAtmStrategyRealizedProfitLoss(atmStrategyId);
                                        //atmStrategyId = GetAtmStrategyUniqueId();
                        
                                        if (atmPnL < 0)
                                        {
                                            if (GetAtmStrategyMarketPosition(atmStrategyId) == MarketPosition.Long)
                                                {
                                                    canTradeLong = false;
                                                }
                                                else if (GetAtmStrategyMarketPosition(atmStrategyId) == MarketPosition.Short)
                                                    {
                                                        canTradeShort = false;
                                                    }
                                            Print("OnBarUpdate():Do you see me here too1? " + Time[0]);
                                                // Close the current ATM strategy
                                                AtmStrategyClose(atmStrategyId);
                                                atmStrategyId = string.Empty;
                        
                                         }
                                        }​
                        The script below is supposed to Resume trading logic after a losing trade.

                        HTML Code:
                         if (orderId.Length == 0 && atmStrategyId.Length == 0  && canTradeLong == false && isBearishBar)// && isPreviousBarBearish)
                                        {
                                            Print("OnBarUpdate():Do you see me here too? Long" + Time[0]);
                                            canTradeLong = true; // Resume trading for long positions
                                            //atmStrategyId = string.Empty;
                                        }
                                   if (orderId.Length == 0 && atmStrategyId.Length == 0  && canTradeShort == false && isBullishBar)// && isPreviousBarBullish)
                                            {
                                                Print("OnBarUpdate():Do you see me here too? Short" + Time[0]);
                                                canTradeShort = true; // Resume trading for short positions
                                                //atmStrategyId = string.Empty;
                                            }​
                        When I check the Ouput I can see that it prints the statement that I want during the losing trade but does not stop and the script does not call the resume trading logic.

                        Any feedback?

                        Comment


                          #13
                          Hello,

                          Thank you for your response.

                          Are you setting the resetting the orderID to string.Empty?

                          To understand why the script is behaving as it is, such as placing orders or not placing orders or drawing objects 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.

                          In the strategy add prints (outside of any conditions) that print the date time of the bar and all values compared in every condition that places an order.

                          The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

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

                          Further, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

                          I am happy to assist you with analyzing the output from the output window.

                          Run or backtest the script and when the output from the output window appears save this by right-clicking the output window and selecting Save As... -> give the output file a name and save -> then attach the output text file to your reply.

                          Below is a link to a forum post that demonstrates using informative prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.

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

                          Please let me know if I may further assist with analyzing the output or if you need any assistance creating a print or enabling TraceOrders.
                          Gaby V.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi,

                            It works now. I used Print() to see how the script was behaving. It looks like by removing the { } from the if Statement was the solution.

                            Now, I am using AtmStrategyChangeStopTarget to modify my stop loss.

                            HTML Code:
                            if (atmStrategyId.Length > 0)
                                        {
                                            Print("OnBarUpdate():Are you ON for Long"   +atmStrategyId.Length + Time[0]);
                                            if (GetAtmStrategyMarketPosition(atmStrategyId) == MarketPosition.Long && isCurrentBarsBullish &&
                                                currentSlongPrice > lastStopLossPriceLong && currentSlongPrice < GetAtmStrategyPositionAveragePrice(atmStrategyId))
                                            {
                            
                                                Print("OnBarUpdate():Dynamic StopLong" + Time[0]);
                                                    lastStopLossPriceLong = currentSlongPrice;
                                                    AtmStrategyChangeStopTarget(0, currentSlongPrice, "STOP1", atmStrategyId);
                                                    AtmStrategyChangeStopTarget(0, currentSlongPrice, "STOP2", atmStrategyId);
                            
                            
                            
                                                // Print some information about the strategy to the output window, please note you access the ATM strategy-specific position object here
                                                Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
                                                Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
                                                Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId));
                                            }
                            }
                            
                            ​
                            It works like I want both for Long and Short but I notice that sometimes when
                            if (atmStrategyId.Length > 0)
                            the AtmStrategyChangeStopTarge does not always trigger.
                            However, if I remove the {...} for after
                            if (GetAtmStrategyMarketPosition(atmStrategyId) == MarketPosition.Long && isCurrentBarsBullish &&
                            currentSlongPrice > lastStopLossPriceLong && currentSlongPrice < GetAtmStrategyPositionAveragePrice(atmStrategyId)) ​
                            It will always work when
                            if (atmStrategyId.Length > 0)
                            but it will move the stop loss back when the current bar is bearish and the system will give me a bunch of errors about moving the stop loss above the market price.

                            I like using the {...} because its behavior is more predictable but the fact that it does not trigger every time is an issue. Is there anything that I need to do to avoid that behavior? I have tried to empty atmStrategyId

                            HTML Code:
                                        if (atmStrategyId.Length > 0)
                                        {
                                            Print("OnBarUpdate():Are you ON for Long"   +atmStrategyId.Length + Time[0]);
                                            if (GetAtmStrategyMarketPosition(atmStrategyId) == MarketPosition.Long && isCurrentBarsBullish &&
                                                currentSlongPrice > lastStopLossPriceLong && currentSlongPrice < GetAtmStrategyPositionAveragePrice(atmStrategyId))
                                            {
                            
                            
                                            }
                                            atmStrategyId = string.Empty;
                                    }​
                            But it does not work

                            Thanks
                            Last edited by patdmoney; 01-01-2024, 10:42 AM.

                            Comment


                              #15
                              Hello patdmoney,

                              Use prints to confirm all of the conditions in the condition set are evaluating as true.
                              Print the time of the bar, print all values used in the condition set, include labels for each value and comparison operator.


                              Use GetAtmStrategyStopTargetOrderStatus() to confirm the price the orders are working at.
                              Chelsea B.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by AaronKoRn, Today, 09:49 PM
                              0 responses
                              11 views
                              0 likes
                              Last Post AaronKoRn  
                              Started by carnitron, Today, 08:42 PM
                              0 responses
                              10 views
                              0 likes
                              Last Post carnitron  
                              Started by strategist007, Today, 07:51 PM
                              0 responses
                              11 views
                              0 likes
                              Last Post strategist007  
                              Started by StockTrader88, 03-06-2021, 08:58 AM
                              44 responses
                              3,980 views
                              3 likes
                              Last Post jhudas88  
                              Started by rbeckmann05, Today, 06:48 PM
                              0 responses
                              9 views
                              0 likes
                              Last Post rbeckmann05  
                              Working...
                              X