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

Hedge position an Multi chart strategy not acting correctly

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

    Hedge position an Multi chart strategy not acting correctly

    what im trying to accomplish is setting a limit order on another chart separate from the main chart .


    example im in a short position on NQ. as the trade open i want to place a limit order on the ES $400 below the close of the last bar with a trailing stop and no profit target.


    running the current code the hedge positions are not being trigger properly and are being executed when they should not have been hit?


    anyone that could help me do this the right way. i would be appreciated , im new to coding


    here is the code:




    // enter long position based on the trend confirmation

    if (isPivotConfirmTrend1)

    {

    EnterLong();

    SetStopLoss(CalculationMode.Currency, atrStop);

    SetProfitTarget(CalculationMode.Currency, profitTarget);




    // add a limit order with a trailing stop and no profit target in the opposite direction to hedge the position

    double limitPrice = Close[0] - HedgeOffset;

    EnterShortLimit(1, true, DefaultQuantity, limitPrice, "HedgeOrder");

    SetTrailStop("HedgeOrder", CalculationMode.Currency, TrailStopSize, false);

    }

    // enter short position based on the trend confirmation

    else if (isPivotConfirmTrend2)

    {

    EnterShort();

    SetStopLoss(CalculationMode.Currency, atrStop);

    SetProfitTarget(CalculationMode.Currency, profitTarget);




    // add a limit order with a trailing stop and no profit target in the opposite direction to hedge the position

    double limitPrice = Close[0] + HedgeOffset;

    EnterLongLimit(1, true, DefaultQuantity, limitPrice, "HedgeOrder");

    SetTrailStop("HedgeOrder", CalculationMode.Currency, TrailStopSize, false);

    }


    #2
    Hello thehammer,

    Thanks for your post.

    I am researching this matter and will follow-up with you as soon as I have finished looking into the inquiry that you have reported.

    Thanks for your patience; I look forward to assisting further.
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Much Thanks !

      Comment


        #4
        Also meant to say if I'm in a short position on NQ
        I want to place long limit order $400 above the close of the last bar

        Comment


          #5
          Hello thehammer,

          Thanks for your patience.

          To submit Entry orders to two separate instruments, you would need to add one of the instruments, such as ES 03-23, to the script as a secondary series by calling AddDataSeries(). You could then submit your Entry orders to the primary series instrument or submit them added secondary series by specifying the barsInProgressIndex of the instrument.

          EnterLongLimit(int barsInProgressIndex, bool isLiveUntilCancelled, int quantity, double limitPrice, string signalName)

          To submit an order to the first added series in a script, you would set the barsInProgressIndex parameter to 1.

          When submitting Entry orders to two separate instruments, Exit methods, such as ExitLongLimit()/ExitLongStopMarket(), must be used for your stop loss and profit target orders. Set methods will only submit to the primary data series the script is running on, not the secondary series.

          Note that Set methods and Exit methods should not both be used in the same script as this would go against the Managed Approach Internal Order Handling Rules linked here: https://ninjatrader.com/support/help...antedPositions

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

          Managed Approach Order Methods: https://ninjatrader.com/support/help...d_approach.htm

          Working with Multi-TimeFrame/Multi-Instrument NinjaScripts (this page is very important to review to gain an understanding of working with multiple instruments in a NinjaScript): https://ninjatrader.com/support/help...nstruments.htm


          When using Set methods in a script, please note that since Set methods prep NinjaTrader to submit protective orders for an Entry order, you should call Set methods before your Entry order method.

          From the Set method help guide pages: "Since they are submitted upon receiving an execution, the Set method should be called prior to submitting the associated entry order to ensure an initial level is set."

          Example:

          SetProfitTarget();
          SetStopLoss();
          EnterLong();

          See the help guide documentation below.
          SetStopLoss(): https://ninjatrader.com/support/help...etstoploss.htm
          SetProfitTarget(): https://ninjatrader.com/support/help...ofittarget.htm
          SetTrailStop(): https://ninjatrader.com/support/help...ttrailstop.htm

          Please let me know if I may assist further.
          Brandon H.NinjaTrader Customer Service

          Comment


            #6
            got it. seems like to do what i would like i can only use advanced order handling. thanks

            Comment


              #7
              ok i adjusted to the enter exit strategy instead of the set method.

              but still having problems now the profit and targets are not engaging on the main chart and the hedge only engaged a few trades



              here is the current code


              // Set 1

              // enter long position based on the trend confirmation

              if (isPivotConfirmTrend1)



              {

              EnterLong(2, @"myEntry");

              OkToTrade = true;



              // add a limit order with a trailing stop and no profit target in the opposite direction to hedge the position

              double limitPrice = Close[0] - HedgeOffset;

              EnterShortLimit(1, true, DefaultQuantity, limitPrice, "HedgeOrder");

              CurrentTriggerPrice2 = (Close[0] - limitPrice - (TrailFrequency * TickSize)) ;

              CurrentStopPrice2 = (Close[0] - limitPrice - (TrailStopDistance * TickSize)) ;



              }



              // Set 2

              if ((Position.MarketPosition == MarketPosition.Long)

              && (OkToTrade == true))

              {

              ExitLongLimit(1, (Position.AveragePrice + (profitTarget )) , @"myTarget1", @"myEntry");

              ExitLongStopLimit(2, 0, (Position.AveragePrice + (-atrStop)) , @"myStop", @"myEntry");

              OkToTrade = false;

              }

              // Set 3

              if ((Position.MarketPosition == MarketPosition.Short)

              && (Close[0] < CurrentTriggerPrice2))

              {

              CurrentTriggerPrice2 = (Close[0] - (TrailFrequency * TickSize)) ;

              CurrentStopPrice2 = (Close[0] - (TrailStopDistance * TickSize)) ;

              }



              // Set 4

              if (CurrentStopPrice != 0)

              {

              ExitShortStopLimit(1, false, Convert.ToInt32(DefaultQuantity), 0, CurrentStopPrice, "HedgeOrder", "myEntry");

              }










              // set 1

              // enter short position based on the trend confirmation

              else if (isPivotConfirmTrend2)

              {

              EnterShort(2, @"myEntry");

              OkToTrade = true;



              // add a limit order with a trailing stop and no profit target in the opposite direction to hedge the position

              double limitPrice = Close[0] + HedgeOffset;

              EnterLongLimit(1, true, DefaultQuantity, limitPrice, "HedgeOrder");

              CurrentTriggerPrice = (Close[0] + limitPrice + (TrailFrequency * TickSize)) ;

              CurrentStopPrice = (Close[0] + limitPrice + (TrailStopDistance * TickSize)) ;



              }



              // Set 2

              if ((Position.MarketPosition == MarketPosition.Short)

              && (OkToTrade == true))

              {

              ExitShortLimit(1, (Position.AveragePrice - (profitTarget )) , @"myTarget1", @"myEntry");

              ExitShortStopLimit(2, 0, (Position.AveragePrice - (+atrStop)) , @"myStop", @"myEntry");

              OkToTrade = false;

              }



              // Set 3

              if ((Position.MarketPosition == MarketPosition.Long)

              && (Close[0] > CurrentTriggerPrice))

              {

              CurrentTriggerPrice = (Close[0] + (TrailFrequency * TickSize)) ;

              CurrentStopPrice = (Close[0] + (TrailStopDistance * TickSize)) ;

              }



              // Set 4

              if (CurrentStopPrice != 0)



              {

              ExitLongStopLimit(1, false, Convert.ToInt32(DefaultQuantity), 0, CurrentStopPrice, "HedgeOrder", "myEntry");

              }













              }

              }

              }


              Comment


                #8
                i meant profit and stop are not engaging

                Comment


                  #9
                  Hello thehammer,

                  Thanks for your note.

                  Position.MarketPosition would only check what the market position is on the primary instrument the script is running on.

                  You would need to add a BarsInProgress == 1 check and place your Position.MarketPosition condition within that BarsInProgress condition to see what the Position.MarketPosition is on the added data series in the script. For example:

                  Code:
                  if (BarsInProgress == 1)
                  {
                      if (Position.MarketPosition == MarketPosition.Short)
                      {
                          //do something here.
                      }
                  }
                  Please review this help guide page to gain a full understanding of how to work with multi-instrument/multi-timeframe NinjaScripts: https://ninjatrader.com/support/help...nstruments.htm

                  Also, to understand how the script is behaving and placing orders, debugging prints should be added to the script. Below is a link to a forum post that demonstrates using prints to understand behavior.
                  https://ninjatrader.com/support/foru...121#post791121

                  Let me know if I may assist further.
                  Brandon H.NinjaTrader Customer Service

                  Comment


                    #10
                    how do i cancel the hedge position on the secondary chart once the main chart target has been hit ?


                    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)

                    {

                    // Check if the execution is related to your main chart position exit orders

                    if (execution.Name == "myTarget1" || execution.Name == "myStop")

                    {

                    // Cancel the hedge position order

                    if (OrderState("HedgeOrder") != null)

                    {

                    CancelOrder(OrderState("HedgeOrder"));

                    }

                    }

                    }
                    ​i tried this but getting error

                    Comment


                      #11
                      so now i have the primary positions working but the hedge positions won't close when the primary positions hit the targets :


                      here is the code :



                      // enter long position based on the trend confirmation

                      if (isPivotConfirmTrend1)



                      {

                      EnterLong(3,@"myEntrylong");

                      Print("Entered Long position"); // Added debug message

                      OkToTrade = true;



                      // add a limit order with a trailing stop and no profit target in the opposite direction to hedge the position

                      double limitPrice = Close[0] + (HedgeOffset * TickSize);

                      hedgeShortLimitOrder = EnterShortLimit(1, true, DefaultQuantity, limitPrice, "HedgeOrder");

                      Print(string.Format("Created HedgeShortLimitOrder: {0}", hedgeShortLimitOrder));

                      CurrentTriggerPrice2 = ( limitPrice + (TrailFrequency * TickSize)) ;

                      CurrentStopPrice2 = ( limitPrice + (TrailStopDistance * TickSize)) ;



                      }



                      // enter short position based on the trend confirmation

                      else if (isPivotConfirmTrend2)

                      {

                      EnterShort(3,@"myEntryshort");

                      Print("Entered Short position"); // Added debug message

                      OkToTrade = true;



                      // add a limit order with a trailing stop and no profit target in the opposite direction to hedge the position

                      double limitPrice = Close[0] - (HedgeOffset * TickSize);

                      hedgeLongLimitOrder = EnterLongLimit(1, true, DefaultQuantity, limitPrice, @"HedgeOrder");

                      Print(string.Format("Created HedgeLongLimitOrder: {0}", hedgeLongLimitOrder));

                      CurrentTriggerPrice = ( limitPrice - (TrailFrequency * TickSize)) ;

                      CurrentStopPrice = ( limitPrice - (TrailStopDistance * TickSize)) ;



                      }



                      }

                      }



                      private void ManageExit()

                      {

                      // declare a variable to hold the ATR value

                      double atrValue = atr[0];




                      // multiply the ATR value by to get the stop loss value

                      double atrStop = atrValue * StopMultiplier;




                      // declare a variable to hold the profit target value

                      double profitTarget = atrValue * ProfitMultiplier;



                      if (atrValue > 12 )

                      return;




                      if (Position.MarketPosition == MarketPosition.Long)

                      {

                      // Add the debug message here

                      Print(string.Format("Stop Price in ManageExit (Long): {0}", Position.AveragePrice + (-atrStop * TickSize)));








                      primaryLongTargetOrder = ExitLongLimit(3, Position.AveragePrice + (profitTarget * TickSize), @"myTarget", "myEntrylong");

                      ExitLongStopLimit(3, 0, (Position.AveragePrice - (-atrStop * TickSize)), @"myStop", @"myEntrylong");

                      OkToTrade = false;

                      }

                      else if (Position.MarketPosition == MarketPosition.Short)

                      {

                      // Add the debug message here

                      Print(string.Format("Stop Price in ManageExit (Short): {0}", Position.AveragePrice - (+atrStop * TickSize)));








                      primaryShortTargetOrder = ExitShortLimit(3, Position.AveragePrice - (profitTarget * TickSize), @"myTarget", @"myEntryshort");

                      ExitShortStopLimit(3, 0, (Position.AveragePrice + (atrStop * TickSize)), @"myStop", @"myEntryshort");

                      OkToTrade = false;

                      }

                      }






                      private void ManageTrailingStop()

                      {

                      Print("Position: " + Position.MarketPosition); // Added debug print for the current market position



                      if ((Position.MarketPosition == MarketPosition.Short) && (Close[0] < CurrentTriggerPrice2))

                      {

                      Print("Short position update triggered"); // Added debug print for when the short position update is triggered

                      CurrentTriggerPrice2 = Math.Min(Close[0] - (TrailFrequency * TickSize), Low[0]);

                      CurrentStopPrice2 = Math.Min(Close[0] - (TrailStopDistance * TickSize), Low[0]);

                      Print("CurrentTriggerPrice2: " + CurrentTriggerPrice2); // Added debug print for the updated CurrentTriggerPrice2 value

                      Print("CurrentStopPrice2: " + CurrentStopPrice2); // Added debug print for the updated CurrentStopPrice2 value

                      }

                      else if ((Position.MarketPosition == MarketPosition.Long) && (Close[0] > CurrentTriggerPrice))

                      {

                      Print("Long position update triggered"); // Added debug print for when the long position update is triggered

                      CurrentTriggerPrice = Math.Max(Close[0] + (TrailFrequency * TickSize), High[0]);

                      CurrentStopPrice = Math.Max(Close[0] + (TrailStopDistance * TickSize), High[0]);

                      Print("CurrentTriggerPrice: " + CurrentTriggerPrice); // Added debug print for the updated CurrentTriggerPrice value

                      Print("CurrentStopPrice: " + CurrentStopPrice); // Added debug print for the updated CurrentStopPrice value

                      }




                      if (CurrentStopPrice != 0 || CurrentStopPrice2 != 0)

                      {

                      // Add the debug message here for short position

                      if (Position.MarketPosition == MarketPosition.Short)

                      {

                      Print(string.Format("Stop Price in ManageTrailingStop (Short): {0}", CurrentStopPrice2));

                      }



                      if (hedgeShortStopOrder == null && Position.MarketPosition == MarketPosition.Short)

                      {

                      hedgeShortStopOrder = ExitShortStopLimit(1, false, Convert.ToInt32(DefaultQuantity), 0, CurrentStopPrice2, @"HedgeOrder", @"myEntryshort");

                      }



                      // Add the debug message here for long position

                      else if (Position.MarketPosition == MarketPosition.Long)

                      {

                      Print(string.Format("Stop Price in ManageTrailingStop (Long): {0}", CurrentStopPrice));

                      }



                      else if (hedgeLongStopOrder == null && Position.MarketPosition == MarketPosition.Long)

                      {

                      hedgeLongStopOrder = ExitLongStopLimit(1, false, Convert.ToInt32(DefaultQuantity), 0, CurrentStopPrice, @"HedgeOrder", @"myEntrylong");

                      }

                      else

                      {

                      if (Position.MarketPosition == MarketPosition.Short)

                      {

                      ChangeOrder(hedgeShortStopOrder, Convert.ToInt32(DefaultQuantity), 0, CurrentStopPrice);

                      }

                      else if (Position.MarketPosition == MarketPosition.Long)

                      {

                      ChangeOrder(hedgeLongStopOrder, Convert.ToInt32(DefaultQuantity), 0, CurrentStopPrice);

                      }

                      }

                      }



                      }



                      protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)

                      {

                      // Close hedge position if primary position is closed

                      if (primaryPositionClosed && hedgeLongLimitOrder != null && Position.MarketPosition == MarketPosition.Flat)

                      {

                      if (marketPosition == MarketPosition.Long)

                      {

                      ExitLong(HedgeInstrument);

                      hedgeLongLimitOrder = null;

                      }

                      else if (marketPosition == MarketPosition.Short)

                      {

                      ExitShort(HedgeInstrument);

                      hedgeShortLimitOrder = null;

                      }

                      }




                      if (execution.Order == primaryLongTargetOrder || execution.Order == primaryLongStopOrder || execution.Order == primaryShortTargetOrder || execution.Order == primaryShortStopOrder)




                      {

                      primaryPositionClosed = true;

                      }




                      if (execution.Order == hedgeLongLimitOrder)

                      {

                      Print("HedgeLongLimitOrder filled");

                      }

                      else if (execution.Order == hedgeShortLimitOrder)

                      {

                      Print("HedgeShortLimitOrder filled");

                      }

                      }







                      private void CloseHedgePositionsOnSessionEnd()

                      {








                      TimeSpan currentTime = Time[0].TimeOfDay;

                      int sessionEndTimeInSeconds = Bars.TradingHours.Sessions[Bars.TradingHours.Sessions.Count - 1].EndTime;

                      TimeSpan sessionEndTime = TimeSpan.FromSeconds(sessionEndTimeInSeconds);



                      Print(string.Format("TimeUntilSessionClose: {0}, Position: {1}", sessionEndTime - currentTime, Position.MarketPosition));




                      if (sessionEndTime - currentTime <= TimeSpan.FromMinutes(5)) // Close positions when 5 minutes or less remain until the session closes

                      {

                      if (Position.MarketPosition == MarketPosition.Flat)

                      {

                      if (hedgeLongStopOrder != null)

                      {

                      CancelOrder(hedgeLongStopOrder);

                      ExitLong("HedgeExit");

                      hedgeLongStopOrder = null;

                      }

                      if (hedgeShortStopOrder != null)

                      {

                      CancelOrder(hedgeShortStopOrder);

                      ExitShort("HedgeExit");

                      hedgeShortStopOrder = null;

                      }

                      }

                      }

                      }



                      }



                      }

                      Comment


                        #12
                        here is the ninja script output
                        Attached Files

                        Comment


                          #13
                          Hello thehammer,

                          Thanks for your note.

                          I see you are calling the code below which is using incorrect syntax.

                          if (OrderState("HedgeOrder") != null)
                          {
                          CancelOrder(OrderState("HedgeOrder"));
                          }


                          "HedgeOrder" is not an OrderState and OrderState("HedgeOrder") cannot be used for the CancelOrder() method parameters.

                          ​See this help guide page about OrderState values: https://ninjatrader.com/support/help...rderupdate.htm

                          To use the CancelOrder(), you should track the order object within OnOrderUpdate and and call CancelOrder() using the order object as seen in the SampleCancelOrder reference sample linked below.



                          I have also attached a modified version of the SampleCancelOrder reference sample, called ModSampleCancelOrder, that you may view. This modified sample demonstrates submitting orders to a secondary data series and canceling the order once three bars have passed since the limit order was submitted. You could test this script by opening a 15-Second ES 06-23 chart window and a 15-Second NQ 06-23 chart window and enabling the strategy on the NQ chart.

                          When the strategy places a buy limit order to the secondary ES 06-23 data series and more than three bars have passed by since the buy limit order was placed and the order was not filled, the buy limit order is canceled.

                          Please let me know if I may assist further.
                          Attached Files
                          Brandon H.NinjaTrader Customer Service

                          Comment


                            #14
                            thanks for the help

                            Comment


                              #15
                              Originally posted by thehammer View Post
                              thanks for the help
                              Hi Hammer
                              did this script work? and did you accomplish the hedge you had planned. it is an interesting idea. Wanted to see if you tested and found this profitable?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by StockTrader88, 03-06-2021, 08:58 AM
                              45 responses
                              3,992 views
                              3 likes
                              Last Post johntraderuser2  
                              Started by TAJTrades, Today, 09:46 AM
                              0 responses
                              7 views
                              0 likes
                              Last Post TAJTrades  
                              Started by rhyminkevin, Yesterday, 04:58 PM
                              5 responses
                              62 views
                              0 likes
                              Last Post dp8282
                              by dp8282
                               
                              Started by realblubb, Today, 09:28 AM
                              0 responses
                              8 views
                              0 likes
                              Last Post realblubb  
                              Started by AaronKoRn, Yesterday, 09:49 PM
                              1 response
                              19 views
                              0 likes
                              Last Post Rikazkhan007  
                              Working...
                              X