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

reversing strategy

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

    reversing strategy

    Hi, I've been attempting to create a strategy that submits a short entry, and under onexecution, once the short is filled a limit or stop limit order is placed that would reverse the position, and if its reversed, also under onexecution a limit or stop limit order is placed that would reverse that position back to short, and continue reversing until either a target is reached, or a profit threshold of unrealized profit would suffice. I've tried this with the managed approach and the backtester literally freezes. I've tried this using the unmanaged approach and the orders under onexecution are ignored.
    MANAGED
    Code:
    protected override void OnBarUpdate()
            {
    			 if (ToTime(Time[0]) == ToTime(5, 59, 0) 
    			 && Position.MarketPosition == MarketPosition.Flat)
    				//&& entryOrder == null)
               {
                   
    		       EnterShort(1, "short");
    
                  
                   
               }
    		     if (Position.MarketPosition == MarketPosition.Long 
                && Position.GetProfitLoss(Close[0], PerformanceUnit.Currency)>= 180 )
    			 {
    				ExitLong("long");
    		      }
    			 if (Position.MarketPosition == MarketPosition.Short 
                && Position.GetProfitLoss(Close[0], PerformanceUnit.Currency)>= 180 )
    			 {    
    				ExitShort("short");
    		      }
    		
            }
             protected override void OnExecution(IExecution execution)
           {
    	        if(execution.Order != null && execution.Order.OrderState == OrderState.Filled && execution.Order.Name == "short" && execution.Order.OrderAction  == OrderAction.SellShort )
    	        { 
    				
    				EnterLongLimit(1, Position.AvgPrice + 2, "long");
                   
    			
    	        }
    			 if(execution.Order != null && execution.Order.OrderState == OrderState.Filled && execution.Order.Name == "long" && execution.Order.OrderAction  == OrderAction.Buy )
    	       {
    		        
    				EnterShortLimit(1, Position.AvgPrice - 2, "short");
    	       }
    		   if(execution.Order != null && execution.Order.OrderState == OrderState.Filled)
    	       {
    		        Print(execution.Order.ToString());

    UNMANAGED
    [CODE
    protected override void OnExecution(IExecution execution)
    {
    if(execution.Order != null && execution.Order.OrderState == OrderState.Filled && execution.Order.Name == "short" && execution.Order.OrderAction == OrderAction.SellShort )
    {

    shorttarget = SubmitOrder(0, OrderAction.BuyToCover, OrderType.Limit, 1, Position.AvgPrice - 18, 0, "short", "shorttarget");
    shortstop = SubmitOrder(0, OrderAction.BuyToCover, OrderType.StopLimit , 1, Position.AvgPrice + 2, Position.AvgPrice + 2, "short", "shortstop");
    longreverse = SubmitOrder(0, OrderAction.Buy, OrderType.StopLimit , 1, Position.AvgPrice + 2, Position.AvgPrice + 2, "long", "long");

    }
    if(execution.Order != null && execution.Order.OrderState == OrderState.Filled && execution.Order.Name == "long" && execution.Order.OrderAction == OrderAction.Buy )
    {

    longtarget = SubmitOrder(0, OrderAction.Sell, OrderType.Limit, 1, Position.AvgPrice + 18, 0, "long", "longtarget");
    longstop = SubmitOrder(0, OrderAction.Sell, OrderType.StopLimit , 1, Position.AvgPrice - 2, Position.AvgPrice - 2, "long", "longstop");
    shortreverse = SubmitOrder(0, OrderAction.SellShort, OrderType.StopLimit , 1, Position.AvgPrice - 2, Position.AvgPrice - 2, "short", "short");
    }
    if(execution.Order != null && execution.Order.OrderState == OrderState.Filled)
    {
    Print(execution.Order.ToString());
    }

    }][/CODE]

    #2
    Hello sampras010,

    When you mention that running this code causes the Strategy Analyzer to freeze, how many days of historical data are you testing this over?

    If you test over a single day of historical data, does the Strategy Analyzer still freeze without recovering?

    Can you export your script so that I may test this on my end?
    To export a NinjaTrader 7 NinjaScript do the following:
    1. Click File -> Utilities -> Export NinjaScript
    2. Enter a unique name for the file in the value for 'File name:'
    3. Select the strategy from the objects list on the left -> click the right facing arrow ">" to add the strategy to the export
    4. Click the 'Export' button -> click 'yes' to add any referenced indicators to the export -> click OK to clear the export location message


    By default your exported file will be in the following location:
    • (My) Documents\NinjaTrader 7\bin\Custom\ExportNinjaScript\<export_file_name.z ip>


    Below is a link to the help guide on Exporting NinjaScripts.
    http://www.ninjatrader.com/support/h...nt7/export.htm
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Here's the one I tried with the managed approach. I've been testing it over a month and it freezes without recovering. It also froze over a single day.
      Attached Files

      Comment


        #4
        Hello sampras010,

        The logic in this script can cause an endless loop on the very first historical bar.

        The entry order is a short entry. When this order fills immediately a buy limit order is placed on the wrong side of the market and fills immediately (buy limit orders should be placed below the current market price. If you want to place an order above the market price us a stop or stop limit order). Once that buy limit fills immediately a short limit is placed again on the wrong side of the market and it fills instantly. Basically this will go back and forth generating thousands of orders.

        This is an endless unbreakable loop and cannot be exited.

        I wouldn't recommend logic that causes an infinite amount of orders to be placed in an unbroken loop. Either require a new bar before placing a new order or only a certain amount of trades to be allowed until a new bar forms. This would prevent an endless loop when placing orders on the wrong side of the market.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          I tried again with stop limit orders under onexecution. No endless loop, which was good, but theyre still not being submitted, or theyre being ignored.



          if(execution.Order != null && execution.Order.OrderState == OrderState.Filled && execution.Order.Name == "short" && execution.Order.OrderAction == OrderAction.SellShort )
          {

          EnterLongStopLimit(1, Position.AvgPrice + 5, "long");


          }
          if(execution.Order != null && execution.Order.OrderState == OrderState.Filled && execution.Order.Name == "long" && execution.Order.OrderAction == OrderAction.Buy )
          {

          EnterShortStopLimit(1, Position.AvgPrice - 5, "short");
          }

          Comment


            #6
            Hi sampras010,

            Are you certain they are being ignored and are not being placed and then cancelled at the close of the bar because the liveUntilCancelled is not set to true?

            Are you seeing messages in the output window that orders are being ignored?
            If so, please include the message.

            If not, how do you know that orders are being ignored?
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              haha. No I'm not sure theyre being ignored. And I don't see that in the output window. But there's without a doubt no fills where there should be stoplimit fills. How can I set liveuntilcanceled to true? If that's not it, I'm not sure what else would need to be changed or added.

              Comment


                #8
                Hi sampras010,

                EnterLongStopLimit(0, true, DefaultQuantity, (Position.AvgPrice + 5 * TickSize), (Position.AvgPrice + 5 * TickSize), "long") ;

                EnterLongStopLimit(int barsInProgressIndex, bool liveUntilCancelled, int quantity, double limitPrice, double stopPrice, string signalName)

                http://ninjatrader.com/support/helpG...gstoplimit.htm


                Adding TraceOrders = true; to the Initialize part of your script would let you know if orders are being ignored and / or cancelled at the end of a bar.
                http://ninjatrader.com/support/helpG...raceorders.htm
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Thanks Chelsea. Although when backtesting over a month the backtester is still freezing (not sure why), I'm getting functional backtests over a few days. The only other trouble I'm having is stoplimits orders aren't always filled. Is there a way I can change them to stopmarket orders. I don't see stop market in the help guide list of order methods.

                  Comment


                    #10
                    Hello sampras010,

                    If your logic is the same, even using a StopLimit or Stop order can cause an endless loop if both the StopLimit prices are within the bar which causes them to fill.

                    You can use a Stop order with EnterLongStop or EnterShortStop.
                    http://ninjatrader.com/support/helpG...erlongstop.htm
                    http://ninjatrader.com/support/helpG...rshortstop.htm

                    I was able to figure out that there was an endless loop by adding a print to OnOrderUpdate that prints the state of orders and in OnExecution that prints the time of the execution with the execution to string.

                    I was able to see an infinite amount of prints appearing in the output window all with the same execution time. This is what tipped me off to a logic error.

                    I recommend that you add prints to your code and debug so that you can understand why the script is behaving as it is.
                    https://www.youtube.com/watch?v=K8v_...tu.be&t=48m45s
                    Chelsea B.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by ScottWalsh, Today, 06:52 PM
                    1 response
                    6 views
                    0 likes
                    Last Post NinjaTrader_Manfred  
                    Started by ScottW, Today, 06:09 PM
                    1 response
                    4 views
                    0 likes
                    Last Post NinjaTrader_Manfred  
                    Started by ftsc2022, 10-25-2022, 12:03 PM
                    5 responses
                    256 views
                    0 likes
                    Last Post KeyonMatthews  
                    Started by Board game geek, 10-29-2023, 12:00 PM
                    14 responses
                    244 views
                    0 likes
                    Last Post DJ888
                    by DJ888
                     
                    Started by Waxavi, 04-19-2024, 02:10 AM
                    4 responses
                    56 views
                    0 likes
                    Last Post sonia0101  
                    Working...
                    X