Announcement

Collapse
No announcement yet.

Trailing Stop

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

  • Trailing Stop

    The following code gives me a 10 point profit in backtesting every trade. Apparently from the ProfitTarget section. However, the chart seems to print blue bars until the nStopLevel is triggered. I had thought that the
    nStopLevel = low(-1) would be a number that didn't change. It seems like the chart is treating the low(=1) like a trailing stop rather than a fixed stop. But the backtester is only interested in the ProfitTarget exit. Now when I deleted the ProfitTarget section and implemented the Trailing Stop section (between the /* */'s), all the bars are simply grey. Except for one blue bar at the beginning of the bars on the chart (far left). Wow! This gets complicated!
    So here are my questions:
    1) Why doesn't the Trailing Stop section print the blue bars the way the ProfitTarget section does?
    2) Why does the Backtester not pick up on the way the nStopLevel is operating in the same manner that the blue bars do as the code now stands?
    3) How do I get the Trailing Stop section to print blue bars?
    4) How do I get the Backtester to pay attention to the Trailing Stop section? (I just realized I haven't back tested the code with the Trailing Stop section in place.)
    5) Would you appreciate my code as an attachment?
    Again, thanks for your help!
    PHP Code:
    /*------------------
    //PB7 is Longs Only, 
    //2 Bar Breakout and Sound Alert as Preparation for Entry.
    //Trailing Stop at high(-1)
    ------------------*/

    var nNewTrade// New Trade Trigger 0 = OFF / 1 = ON
    var nsignal// returns the direction of the trading signal
    var nTradeEntryPrice;
    var 
    nStopLevel;
    var 
    ProfitTarget1 10.0;
    var 
    ProfitTargetTrigger1;        

     function 
    preMain() {
     
        
    setPriceStudy(true);
        
    setStudyTitle("PB7");
        
    setCursorLabelName("PB7");
        
    setColorPriceBars(true); //ADDED
        
    setDefaultPriceBarColor(Color.grey); //ADDED
    }
     
     function 
    main() {
     
    /*----------------------------------------------------------------
    // If new trade, get entry price - used for our profit target
    ----------------------------------------------------------
    This portion of the code identifies if a new trade has been issued 
    and records the entry price of our trade. If no new trade has been 
    triggered (nNewTrade == 1), then this portion of the code is ignored.
    ----------------------------------------------------------*/
     
        
    if (Strategy.isInTrade() == true && (nNewTrade == 1)) {
            
    // This sets the expected entry price of the current short trade
        
    nTradeEntryPrice open();
            
    // This switches off the nNewTrade variable
        
    nNewTrade 0// Turn off NEW TRADE switch
        
    }
     
    /*-----------------------------------------------
    This portion of the code tests for a stop level breach and 
    executes trades accordingly.
    ----------------------------------------------------------*/
     

        
    if (Strategy.isInTrade() == true && Strategy.isLong() == true) {
            
    // Check if the profit target has been reached/breached
            
    if (low() <= nStopLevel) {
                
    // Stop Breached, Execute Sell order.
                
    Strategy.doSell("Stop Loss Exit"Strategy.STOPStrategy.THISBARStrategy.ALL,nStopLevel);
                
    setPriceBarColor(Color.red);
            }
        }
        
          
    /*----------------------------------------------------------------
         //New Profit exit
        // Test for Profit Target Breach (ProfitTarget1)
        ----------------------------------------------------------
        This portion of the code identifies if our profit target has 
        been reached and exits our trades.
        ----------------------------------------------------------*/

     
    if (Strategy.isInTrade() == true && (Strategy.isLong() == true)) {
            
    // Check if the profit target has been reached/breached
            
    if ((high() >= low(-1)) && ProfitTargetTrigger1 != 1) {
                
    // Profit Target Breached, Execute Sell order.
                
    Strategy.doSell("PT1 Exit"Strategy.STOPStrategy.THISBAR
                    
    Strategy.getDefaultLotSize(), (nTradeEntryPrice ProfitTarget1));
                        
        
            }
        }
     
    /*------------------------------------------------------------------
    This section of code establishes a Trailing Stop and exits at h(-1).
    -------------------------------------------------------------------*/
      /*  if (Strategy.isInTrade() == true && (Strategy.isLong() == true)) {
            //Move nStopLevel to high(=1)
            nStopLevel = high(-1);
                //Establish Exit at breach of nStopLevel
                if (nStopLevel > low() + 0.25) {
                    Strategy.doSell("Stop Loss Exit", Strategy.STOP, Strategy.THISBAR, 
                        Strategy.getDefaultLotSize(), (nStopLevel));
                    setPriceBarColor(Color.yellow);
                }
        }
      */       

     
     
    /*----------------------------------------------------------------
    // Identify new trade signals
    ----------------------------------------------------------------- */
     
        
    if (Strategy.isInTrade() == false) { 
            if (
    close(-1) > high(-2) && close(-2) > high(-3)) {
                    
    //Removed  && close(-3) > high(-4)
                
    nNewTrade 1// New Trade Trigger
                
    nsignal 1// Buy Signal - Trade Type
                
                
            

        }

        
    /*---------------------------------------------------------------
    // Execute Trades ONLY if nNewTrade is triggered ....
    ----------------------------------------------------------------- */
         
        
    if (Strategy.isInTrade() == false) {
            if (
    nNewTrade == 1) { //Execute New Trade        
                //if (nsignal > 0) {
                
    if (nsignal == 1) {
                    
    Strategy.doLong("Go Long"Strategy.MARKETStrategy.THISBAR,Strategy.getDefaultLotSize() ); 
                        
    //Removed *3 at end of .getDefaultLotSize ()
                    
    nStopLevel low(-1) - 5.0;
                    

    /*--------------------------------------------------------------
    //Colors Entry Bar Blue
    ---------------------------------------------------------------*/

        
    if (Strategy.isInTrade() == true) { 
            if (
    Strategy.isLong() == true) {
                
    setPriceBarColor(Color.blue); //ADDED
            
    }
        }



                } 
    // end nSignal
            
    // end if IN TRADE
        
    // END EXECUTE NEW TRADE 
        


  • #2
    Hello pjwinner,


    1) Why doesn't the Trailing Stop section print the blue bars the way the ProfitTarget section does?
    The problem lies with the following line of code from your Profit Target Breach Section.

    if ((high() >= low(-1)) && ProfitTargetTrigger1 != 1) {

    The ProfitTargetTrigger1 variable is not being set to anything so it is always null. Therefore, ProfitTargetTrigger1 != 1 always returns true. The condition, (high() >= low(-1)), is almost always true. The only time it will evaluate to false is if there was a gap to the down side. Your current exit logic is allowing the trade to exit on the bar following the entry for nearly every trade. This is preventing your stop loss section from being executed, which is why you don't see any bars painted red.

    Solution: Add a section that contains your logic for testing the profit target condition that properly sets the ProfitTargetTrigger1 variable. Consider revising the (high() >= low(-1)) condition as well, since that only returns false on gap downs, which is stop loss logic rather than profit target for long positions.

    2) Why does the Backtester not pick up on the way the nStopLevel is operating in the same manner that the blue bars do as the code now stands?
    See #1

    3) How do I get the Trailing Stop section to print blue bars?
    What I usually do for coloring the price bars is create a global variable set to the default price bar color of your choice (vColor). Anywhere in your formula logic that needs to set the color for the price bars, set vColor to that value (ex. vColor = Color.blue). Then at the end of main add a section of code that checks current state of your strategy and call setPriceBarColor(vColor). Since vColor is a global variable it will retain whatever the last value it was set to by your formula logic. You may want to add a line that checks to see if you are not in a trade and set vColor back to grey, or the default price bar color of your choice.

    Aside from that, your trailing stop section seems to have a flaw in the logic as well. The condition, (nStopLevel > low() + 0.25), where nStopLevel is being reset to high(-1) means that your condition will evaluate to true nearly every bar. The only time it will evaluate to false is when you have a gap to the upside or when the low() is within .25 below high(-1).

    5) Would you appreciate my code as an attachment?
    Yes, that is always helpful.


    One last bit of advice on the use of Strategy.STOP or Strategy.LIMIT trades. I notice that you are adding 10 to the price when you make these calls. If the limit price you pass to the Strategy Analyzer is outside the range of the bar, it does not make any adjustments for you automatically. It will simply use the price you pass to it, which may be unrealistic since its outside the bars range. So depending on the symbol and interval you are using this formula on, you may be generating unrealistic back test results. One extra thing I usually do before calling the stop or limit order is to test the price I'm passing to make sure it is within the bar's range. If that test fails, don't allow the call to be made.
    Jason K.
    Project Manager
    eSignal - an Interactive Data company

    EFS KnowledgeBase
    JavaScript for EFS Video Series
    EFS Beginner Tutorial Series
    EFS Glossary
    Custom EFS Development Policy

    New User Orientation

    Comment

    Working...
    X