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

Scale Out of a Position

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

    Scale Out of a Position

    Hi
    I have utilised Josh's Sample Strategy for Scaling Out of Position which works well for two contracts - I am having problems with > 2 contracts.
    My want is as follows:

    1/ Kick off with 4x contracts with stop loss at -20 points.
    2/ Profit Target for first 2x contracts is +5 at which point stop loss moved to -5.
    3/ Profit target for third contract is +10 at which point stop loss moved to breakeven (this is where I am having the problem).

    Points 1/ & 2/ work fine during backtest.
    For point 3/, sometimes the stop loss works OK (i.e. exit at breakeven, but sometimes it exits at -5 ?!?!?).

    Attached is a sample of the strategy that has been deployed:

    protectedoverridevoid Initialize()
    {
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.UniqueEntries;

    SetProfitTarget("Long 1a", CalculationMode.Ticks, 5);
    SetProfitTarget("Long 1b", CalculationMode.Ticks, 5);
    SetProfitTarget("Long 1c", CalculationMode.Ticks, 10);
    SetProfitTarget("Long 1d", CalculationMode.Ticks, 20);

    SetStopLoss("", CalculationMode.Ticks, 20, false);
    CalculateOnBarClose = false;
    }
    ///<summary>
    /// Called on each bar update event (incoming tick)
    ///</summary>
    protectedoverridevoid OnBarUpdate()
    {
    // Condition set 1

    if (Position.MarketPosition == MarketPosition.Flat)
    {
    SetStopLoss(CalculationMode.Ticks, 20);
    }

    // If a long position is open, allow for stop loss modification to breakeven
    elseif (Position.MarketPosition == MarketPosition.Long)
    {
    // Once the price is greater than entry price+5 ticks, set stop loss to breakeven - 5
    if (Close[0] > Position.AvgPrice + 5 * TickSize)
    {
    SetStopLoss(CalculationMode.Price, Position.AvgPrice - 5);
    }

    if (Close[0] > Position.AvgPrice + 10 * TickSize)
    {
    SetStopLoss(CalculationMode.Price, Position.AvgPrice);
    }
    }

    if (Conditions x, y & z comply.............
    {
    if (Position.MarketPosition == MarketPosition.Flat)

    {
    EnterLong("Long 1a");
    EnterLong("Long 1b");
    EnterLong("Long 1c");
    EnterLong("Long 1d");
    }


    is there anything I wrong here that is causing this issue with the stop loss on the 4th contract.

    many thx
    David

    #2
    It looks like you have a typo in the following line:

    Code:
    SetStopLoss(CalculationMode.Price, Position.AvgPrice - 5);
    Try this instead...

    Code:
    SetStopLoss(CalculationMode.Price, Position.AvgPrice - 5 * TickSize);

    Comment


      #3
      KBJ
      Thx for the note. I am using the YM so am assuming this will not make a difference (although have now coded as you kindly suggested).

      I think I have found the issue - & I should point out that I have found this during backtesting not realtime (Where I have CalculateOnBarClose=False).

      The issue is that the code states if Close[0] > PositionAveragePrice (+ x) then modify stop loss. Now in backtest mode this will only be calculated at the end of the bar & it would appear that even if price does exceed PositionAveragePrice some time during the bar & then retraces below it at the end of the bar the StopLoss is not modified. In realtime this would not be an issues with CalculateOnBarClose=False ?

      Josh / NinjaTrader:
      Your sample price modification strategy that you posted would do exactly the same I presume. Is there any way of coding this differently to overcome this. I presume there is since ProfitTargets & StopLosses can be hit when specific prices are hit intra-bar during backtest.

      many thx in advance
      David

      Comment


        #4
        When you place it within the confines of the OnBarUpdate() method it does become an issue of CalculateOnBarClose.

        In NT6.5 you can place it within the confines of OnMarketData() and that should address it.
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          Thx Josh for the clarification.
          David

          Comment


            #6
            Josh.
            I have the StopLoss in OnBarUpdate & now am testing in realtime with CalculateOnBarClose=False & I am still seeing the same issue. This surprises me since I would expect the stop loss to be modified immediately the 'targets' were hit. this does not appear to be the case. any ideas without resorting to OnMarketData ???

            thx
            David

            Comment


              #7
              Hard to say without actually seeing code and the resulting behavior of the code.
              Josh P.NinjaTrader Customer Service

              Comment


                #8
                Josh - do you want me to sent it along with some screen shots ?

                thx
                DG

                Comment


                  #9
                  Josh - I sent the strategy & a screenshot to Support via email. Hope you are able to review. thx. David

                  Comment


                    #10
                    Josh

                    After inserting the Print Command, it definitely reads that line of text when price is at breakeven + 10 (see below).

                    if (Close[0] > Position.AvgPrice + 10 * TickSize)
                    {
                    SetStopLoss(CalculationMode.Price, Position.AvgPrice);
                    Print ("Breakeven");
                    }

                    The stop loss is not modified, however, using the TraceOrder() I get the following:

                    ********************
                    Amended stop order: order “” Name ‘Stop Loss’ State = PendingChange Instrument YM ##-## Action =Sell Limit price=0 Stop Price = OLD STOP LOSS.
                    Amended stop order: order “” Name ‘Stop Loss’ State = PendingChange Instrument YM ##-## Action =Sell Limit price=0 Stop Price = NEW STOP LOSS.

                    And then I get continual lines stating that the StopLoss = OLD value.

                    I am puzzled……………..any advice?



                    Thx
                    David


                    Josh's Note ----

                    "Hmm. Your code looks correct, but I can’t really test it since I don’t have Jurik indicators. In either case I suggest you use Print to determine that your if statement is actually triggered to bring your stop loss to break even. Also, use TraceOrders = true; to see when your orders are submitted/modified and such".

                    Comment


                      #11
                      David,

                      I've tried your code, but I can't reproduce what you are seeing. These are the print logs I am receiving.

                      Code:
                      1/14/2008 12:26:00 PM Entered internal PlaceOrder() method at 1/14/2008 12:26:00 PM: Action=Buy OrderType=Market Quantity=100 LimitPrice=0 StopPrice=0 SignalName='Long 1a' FromEntrySignal=''
                      1/14/2008 12:26:00 PM Entered internal PlaceOrder() method at 1/14/2008 12:26:00 PM: Action=Buy OrderType=Market Quantity=100 LimitPrice=0 StopPrice=0 SignalName='Long 1b' FromEntrySignal=''
                      1/14/2008 12:26:00 PM Entered internal PlaceOrder() method at 1/14/2008 12:26:00 PM: Action=Buy OrderType=Market Quantity=100 LimitPrice=0 StopPrice=0 SignalName='Long 1c' FromEntrySignal=''
                      1/14/2008 12:26:00 PM Entered internal PlaceOrder() method at 1/14/2008 12:26:00 PM: Action=Buy OrderType=Market Quantity=100 LimitPrice=0 StopPrice=0 SignalName='Long 1d' FromEntrySignal=''
                      1/14/2008 12:26:00 PM Cancelled pending exit order, since associated position is closed: Order='NT-00836/Back101' Name='Stop loss' State=Working Instrument='AAPL' Action=Sell Limit price=0 Stop price=[COLOR=black]178.38[/COLOR] Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00552' Filled=0 Fill price=0 Token='bcfb6f2560a84e8aaf6b3844807d3bec' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:26:00 PM Cancelled OCO paired order: BarsInProgress=0: Order='NT-00836/Back101' Name='Stop loss' State=Cancelled Instrument='AAPL' Action=Sell Limit price=0 Stop price=[COLOR=Red]178.38[/COLOR] Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00552' Filled=0 Fill price=0 Token='bcfb6f2560a84e8aaf6b3844807d3bec' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:26:00 PM Cancelled pending exit order, since associated position is closed: Order='NT-00838/Back101' Name='Stop loss' State=Working Instrument='AAPL' Action=Sell Limit price=0 Stop price=[COLOR=black]178.38[/COLOR] Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00553' Filled=0 Fill price=0 Token='cf5986ff097f452e8424c0d0ff3a56d8' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:26:00 PM Cancelled OCO paired order: BarsInProgress=0: Order='NT-00838/Back101' Name='Stop loss' State=Cancelled Instrument='AAPL' Action=Sell Limit price=0 Stop price=[COLOR=Red]178.38[/COLOR] Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00553' Filled=0 Fill price=0 Token='cf5986ff097f452e8424c0d0ff3a56d8' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:26:00 PM Cancelled pending exit order, since associated position is closed: Order='NT-00840/Back101' Name='Stop loss' State=Working Instrument='AAPL' Action=Sell Limit price=0 Stop price=[COLOR=black]178.38[/COLOR] Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00554' Filled=0 Fill price=0 Token='f04a546d1ba245968badae470189439c' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:26:00 PM Cancelled OCO paired order: BarsInProgress=0: Order='NT-00840/Back101' Name='Stop loss' State=Cancelled Instrument='AAPL' Action=Sell Limit price=0 Stop price=[COLOR=Red]178.38[/COLOR] Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00554' Filled=0 Fill price=0 Token='f04a546d1ba245968badae470189439c' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:27:00 PM Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='' Mode=Price Value=[COLOR=Red]178.53[/COLOR] Currency=0 Simulated=False
                      1/14/2008 12:27:00 PM Amended stop order: Order='NT-00842/Back101' Name='Stop loss' State=Working Instrument='AAPL' Action=Sell Limit price=0 Stop price=178.53 Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00555' Filled=0 Fill price=0 Token='68fa87aec6fa4c3194d9d7cd425582f1' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:27:00 PM Raise: [COLOR=Red]178.53[/COLOR]
                      1/14/2008 12:27:00 PM Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='' Mode=Price Value=[COLOR=Red]178.58[/COLOR] Currency=0 Simulated=False
                      1/14/2008 12:27:00 PM Amended stop order: Order='NT-00842/Back101' Name='Stop loss' State=Working Instrument='AAPL' Action=Sell Limit price=0 Stop price=[COLOR=Red]178.58[/COLOR] Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00555' Filled=0 Fill price=0 Token='68fa87aec6fa4c3194d9d7cd425582f1' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:27:00 PM Breakeven: [COLOR=Red]178.58[/COLOR]
                      1/14/2008 12:27:00 PM Cancelled expired order: BarsInProgress=0: Order='NT-00836/Back101' Name='Stop loss' State=Cancelled Instrument='AAPL' Action=Sell Limit price=0 Stop price=178.38 Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00552' Filled=0 Fill price=0 Token='bcfb6f2560a84e8aaf6b3844807d3bec' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:27:00 PM Cancelled expired order: BarsInProgress=0: Order='NT-00838/Back101' Name='Stop loss' State=Cancelled Instrument='AAPL' Action=Sell Limit price=0 Stop price=178.38 Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00553' Filled=0 Fill price=0 Token='cf5986ff097f452e8424c0d0ff3a56d8' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:27:00 PM Cancelled expired order: BarsInProgress=0: Order='NT-00840/Back101' Name='Stop loss' State=Cancelled Instrument='AAPL' Action=Sell Limit price=0 Stop price=178.38 Quantity=100 Strategy='JMACrossContinuation' Type=Stop Tif=Gtc Oco='NT-00554' Filled=0 Fill price=0 Token='f04a546d1ba245968badae470189439c' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:27:00 PM Cancelled pending exit order, since associated position is closed: Order='NT-00843/Back101' Name='Profit target' State=Working Instrument='AAPL' Action=Sell Limit price=178.78 Stop price=0 Quantity=100 Strategy='JMACrossContinuation' Type=Limit Tif=Gtc Oco='NT-00555' Filled=0 Fill price=0 Token='7c4ea4975e2f4df9a20744bba3233f66' Gtd='12/1/2099 12:00:00 AM'
                      1/14/2008 12:27:00 PM Cancelled OCO paired order: BarsInProgress=0: Order='NT-00843/Back101' Name='Profit target' State=Cancelled Instrument='AAPL' Action=Sell Limit price=178.78 Stop price=0 Quantity=100 Strategy='JMACrossContinuation' Type=Limit Tif=Gtc Oco='NT-00555' Filled=0 Fill price=0 Token='7c4ea4975e2f4df9a20744bba3233f66' Gtd='12/1/2099 12:00:00 AM'
                      Notice the first three stop orders that are cancelled. They are cancelled because their profit targets were filled. This is expected behavior. Notice the correct raise of the stop loss when 5 ticks in profit were made. The new stop loss because Position.AvgPrice - 5*TickSize so (178.38 + 0.20 - 0.05). At 10 ticks in profit we are then raised to breakeven which is (178.38 + 0.20). The stop loss is modified to 178.58 accurately.

                      P.S. In your code you did this: Position.AvgPrice - 5. You may want to multiply that 5 by TickSize if your instrument's ticks are not equal to 1.

                      Also, it is best to test your code with the Simulator in real-time since backtesting these complex scale out conditions is not realistic or effective at all. (Limitations from not being able to "peak" inside the bar)
                      Last edited by NinjaTrader_JoshP; 01-18-2008, 03:31 AM.
                      Josh P.NinjaTrader Customer Service

                      Comment


                        #12
                        you are seeing what i expect to see.
                        however, for some reason, it does not appear to accept my revision to the stop loss.
                        every time the price goes above Position.AvgPrice + 10 it tries to change the stop, but repeatedly says Pending Change

                        Amended stop order: order “” Name ‘Stop Loss’ State = PendingChange Instrument YM ##-## Action =Sell Limit price=0 Stop Price = OLD STOP LOSS.
                        Amended stop order: order “” Name ‘Stop Loss’ State = PendingChange Instrument YM ##-## Action =Sell Limit price=0 Stop Price = NEW STOP LOSS.


                        And then I get continual lines stating that the StopLoss = OLD value.

                        is there something wrong with the way I am placing the orders?
                        P.S. my tick size is 1 (YM) but have modified code as you suggested.

                        any further thoughts.....??
                        I don't think it is the code per se, there is something wrong with the order I think....

                        thx
                        David

                        Comment


                          #13
                          If you could post a full count of the trace logs we could see what is happening more easily. Starting from the four entry orders till all four positions have been closed out.

                          I've also attached a stripped down modded version of your strategy. See if that works on your end.
                          Attached Files
                          Last edited by NinjaTrader_JoshP; 01-18-2008, 04:01 AM.
                          Josh P.NinjaTrader Customer Service

                          Comment


                            #14
                            Josh - your stripped down version gives exactly the same issue that I was seeing on the original code.
                            I have sent the trace log to your private email address.

                            thx
                            David

                            Comment


                              #15
                              Josh - how do i insert the text from the output window into the Support Forum - it does not allow one to copy.

                              thx
                              DG

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by CortexZenUSA, Today, 12:53 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post CortexZenUSA  
                              Started by CortexZenUSA, Today, 12:46 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post CortexZenUSA  
                              Started by usazencortex, Today, 12:43 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post usazencortex  
                              Started by sidlercom80, 10-28-2023, 08:49 AM
                              168 responses
                              2,264 views
                              0 likes
                              Last Post sidlercom80  
                              Started by Barry Milan, Yesterday, 10:35 PM
                              3 responses
                              11 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Working...
                              X