Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Dynamic stop loss not working

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

    Dynamic stop loss not working

    Hi I am a newbie here, and have been stuck on my stop loss code all day. I searched the forums but I am missing something.

    I am trying to update the stop loss when it hits profit target one, two and three but the stop loss does not move up to the stop points. I am getting a message saying
    Set() method to submit an exit order at '9/6/2011 2:30:00 PM' has been ignored. Please search on the term 'Internal Order Handling Rules' in the Help Guide for detailed explanation.
    The stop loss stays at the original stop. Here is the code..

    Code:
           
     #region Variables
            // Wizard generated variables
            private double pivotrange = .002; // Default setting for MyInput0
     		private int x=0;
    		private double adxtrend=48; 
    		private double adxsell=20;
    		private double mfishort=80;
    		private int 	targetMkt1 = 16;
    		private int 	targetMkt2 = 32;		// Number of ticks to Profit Target 2
    		private int 	targetMkt3 = 64;	// Number of ticks to Profit Target 3
    		private int 	cntsMkt1 = 1;		// Number of contracts for Profit Target 1
     private int 	cntsMkt2 = 1;		// Number of contracts for Profit Target 2
     private int 	cntsMkt3 = 1;		// Number of contracts for Profit Target 3
    private int 	cntsMkt4 = 1;		// Number of contracts for Profit Target 3
    private IOrder 	eMkt1Order = null;	// Order data for "Buy/SellMkt2", used to get fill price
    private IOrder 	eMkt2Order = null;	// Order data for "Buy/SellMkt2", used to get fill price
    private IOrder 	eMkt3Order = null;	// Order data for "Buy/SellMkt3", used to get fill price
    private double 	bestMktFill = 0;
    private bool controlOne = true;
    private bool controlTwo = true;
    
    
     protected override void Initialize()
            {
    			Add(PeriodType.Minute, 1); // index 1 on barsinprogress
    			Add(PeriodType.Minute, 15); // index 2 on barinsprogress
    			Add(PeriodType.Minute, 60); // index 3 on barinsprogress
    			Add(PeriodType.Day, 1); // index 4 on barinsprogress
    		 SetProfitTarget("BuyMkt1", CalculationMode.Ticks, targetMkt1);
    		SetProfitTarget("BuyMkt2", CalculationMode.Ticks, targetMkt2);	
    		 SetProfitTarget("BuyMkt3", CalculationMode.Ticks, targetMkt3);
    
    protected override void OnBarUpdate()
            {
    				
    			if (BarsInProgress == 0)   // 5min bars used to show chart
    			{
    //long entry
    			if (ADX(BarsArray[4], 10)[0]>= adxsell && Rising(ADX(BarsArray[2],10)) )
    			{
                           
    				eMkt2Order = null;			eMkt3Order = null;								
    if (cntsMkt1 > 0) eMkt1Order =  EnterLong(1, cntsMkt1, "BuyMkt1");
    if (cntsMkt2 > 0) eMkt2Order = EnterLong(1, cntsMkt2, "BuyMkt2");
    if (cntsMkt3 > 0) eMkt3Order = EnterLong(1, cntsMkt3, "BuyMkt3");				
    	}
    
    ////////////////////////////////////////////////////////////////// stop loss code
    
    if( eMkt2Order != null && eMkt3Order != null )
    				{
    					Print(eMkt2Order.AvgFillPrice + targetMkt1*TickSize);
    			if (High[0] >= (eMkt2Order.AvgFillPrice + targetMkt1*TickSize) && controlOne )
    			{
    				SetStopLoss("", CalculationMode.Price, eMkt2Order.AvgFillPrice + targetMkt1* TickSize, false);
    
    	controlOne = false;
    }
    
    if (High [0] >= (eMkt3Order.AvgFillPrice + targetMkt2* TickSize) && !controlOne)
    {
    	SetStopLoss("", CalculationMode.Price, eMkt3Order.AvgFillPrice + targetMkt2* TickSize, false);
    	controlTwo = false;
    }
    	if (High [0] >= (eMkt3Order.AvgFillPrice + targetMkt3* TickSize) && !controlTwo)
    {
    	SetStopLoss("", CalculationMode.Price, eMkt3Order.AvgFillPrice + targetMkt3* TickSize,false);
    }
    }
    	
    ////////////////////////////////////////////////////////reset
    
    if( eMkt2Order != null)
    				{
    						if (Position.MarketPosition == MarketPosition.Flat)
    		{
    			SetStopLoss("", CalculationMode.Ticks, stoplosstk, false);
    				controlOne = true;
    			controlTwo=true;
    			eMkt2Order = null; 				eMkt3Order = null; 
    			eMkt1Order = null; 	
    			bestMktFill = 0;

    I also tried a different route from which I found searching the forum. Using IOrder's but the script kept running until I got this error
    **NT** Error on calling 'OnOrderUpdate' method for strategy 'PivotsMFIADX/9b2eb699da9244caac77dbe81ec8700d': More than 100 subsequent user events
    .

    The code is shown below

    Code:
    protected override void OnOrderUpdate(IOrder order)
    //		{
    //		if( eMkt3Order.AvgFillPrice != null && eMkt1Order.AvgFillPrice != null && eMkt2Order.AvgFillPrice != null)
    //		{
    //		double bestMktFill = (eMkt1Order.AvgFillPrice + eMkt2Order.AvgFillPrice + eMkt3Order.AvgFillPrice)/3;
    //	
    //
    //	if (bestMktFill <= (High[0]+targetMkt1*TickSize) )
    //{
    //	SetStopLoss("", CalculationMode.Ticks, 0-targetMkt1, false);
    
    //}
    //
    //if (bestMktFill <= (High[0]+targetMkt2*TickSize) )
    //{
    //	SetStopLoss("", CalculationMode.Ticks, 0-targetMkt2, false);
    
    //}
    //
    //if (bestMktFill <= (High[0]+targetMkt3*TickSize) )
    //{
    //	SetStopLoss("", CalculationMode.Ticks, 0-targetMkt3, false);
    
    //}
    //}	
    //}

    Any help would be much appreciated!

    Thanks
    Oliver

    #2
    Welcome to our forums - for checking if the Set Target order got filled, we would recommend working with the concepts shown in this reference sample -



    This means you can then adjust directly in OnExecution() once the fill for the target is seen by NinjaTrader.

    I see you're also working with the TraceOrders debug output, which can be a great help - here it informed you of an ignored order as your order placement ran into NT's internal order handling rules.

    http://www.ninjatrader.com/support/h...d_approach.htm (bottom section here)

    Set() methods that generate orders to exit a position will be ignored if:

    • A position is open and an order submitted by an enter method (EnterLongLimit() for example) is active and the order is used to open a position in the opposite direction
    • A position is open and an order submitted by an exit method (ExitLongLimit() for example) is active

    Comment


      #3
      Update: I got a real simple version partially working. It seems to work most of the time but not all of the time for some reason.. I used the position.quantity to trigger the different stop losses. I did it in OnBarUpdate.. Code is below..

      Code:
      			if (BarsInProgress == 1) //1min bar
      			{
      				if (Close[0] > Position.AvgPrice + 16 * TickSize && Position.Quantity ==2)
      				{
      					SetStopLoss(CalculationMode.Price, Position.AvgPrice);
      					
      				}
      				
      				if (Close[0] > (Position.AvgPrice + 32*TickSize) && Position.Quantity==1)
      				{
      					SetStopLoss(CalculationMode.Price, Position.AvgPrice+16*TickSize);
      					
      				}

      Thank you Bertrand for the information. I am having difficulty with the Position.AvgFillPrice / order.AvgFillPrice command. It doesn't seem to populate with numbers most of the time. I have only had a chance to test it by backtesting thus far. Does it not work with backtesting?

      I am also having trouble with the arraylist in the reference example you linked me too. How do I get the orders out to make a Stoploss at a specific price in the arraylist?
      Also you stated to use OnExecution() , but the example is OnOrderUpdate.. which one should I use?

      I did find some other reference examples that just use OnBarUpdate. But The stoploss and profit target together cancel each other it seems and do not work together. I can get it to almost work if I use stop limits instead of stop losses though. I have a multiple time frame code though, i don't know if that affects anything.

      Anyways here is my attempted new code (first section is the OnOrderUpdate code and second section is OnBarUpdate attempt).. Could you please give me some more pointers so I know where to start. Thanks !!!

      Code:
      			
      		protected override void OnOrderUpdate(IOrder order)
      		{
      			if (order.OrderState == OrderState.PendingSubmit)
      			{
      				// Add the "Stop loss" orders to the Stop Loss collection
      				if (order.Name == "Stop loss")
      					stopLossOrders.Add(order);
      				
      				// Add the "Profit target" orders to the Profit Target collection
      				else if (order.Name == "Profit target")
      					profitTargetOrders.Add(order);			
      
      if (profitTargetOrders.Contains(order))
      			{
      				// Check order for terminal state
      				if (order.OrderState == OrderState.Cancelled || order.OrderState == OrderState.Filled || order.OrderState == OrderState.Rejected)
      				{
      					// Print out information about the order
      					Print(order.ToString());
      				SetStopLoss("", CalculationMode.Price, order.LimitPrice, false);
      					
      					// Remove from collection
      					profitTargetOrders.Remove(order);
      And the OnBarUpdateCode....

      Code:
      				if( eMkt2Order != null && eMkt3Order != null )
      				{
      					Print(eMkt2Order.AvgFillPrice + targetMkt1*TickSize);
      			if (High[0] >= (eMkt2Order.AvgFillPrice + targetMkt1*TickSize) && controlOne )
      			{
      				SetStopLoss("", CalculationMode.Price, eMkt2Order.AvgFillPrice, false);
      
      	controlOne = false;
      }
      
      if (High [0] >= (eMkt3Order.AvgFillPrice + targetMkt2* TickSize) && !controlOne)
      {
      	SetStopLoss("", CalculationMode.Price, eMkt3Order.AvgFillPrice + targetMkt2* TickSize, false);
      	controlTwo = false;
      }
      	if (High [0] >= (eMkt3Order.AvgFillPrice + targetMkt3* TickSize) && !controlTwo)
      {
      	SetStopLoss("", CalculationMode.Price, eMkt3Order.AvgFillPrice + targetMkt3* TickSize,false);
      }
      }
      Last edited by oliver1337; 07-18-2012, 07:01 PM. Reason: Update

      Comment


        #4
        Thanks for the update oliver1337, for backtesting working with the Set() methods you would need to keep in mind the stops are then still executing on the primary series only, as the Set's are 'tied' to this series. If you wish to submit an order explicitly to an added series then please use the more advanced Exit() methods that would allow to spec an BarsInProgress parameter in the overload.

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by sjsj2732, Yesterday, 04:31 AM
        0 responses
        33 views
        0 likes
        Last Post sjsj2732  
        Started by NullPointStrategies, 03-13-2026, 05:17 AM
        0 responses
        286 views
        0 likes
        Last Post NullPointStrategies  
        Started by argusthome, 03-08-2026, 10:06 AM
        0 responses
        286 views
        0 likes
        Last Post argusthome  
        Started by NabilKhattabi, 03-06-2026, 11:18 AM
        0 responses
        133 views
        1 like
        Last Post NabilKhattabi  
        Started by Deep42, 03-06-2026, 12:28 AM
        0 responses
        91 views
        0 likes
        Last Post Deep42
        by Deep42
         
        Working...
        X