Announcement

Collapse
No announcement yet.

Profit Target exit appears to be getting out well below profit target level.

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

  • Profit Target exit appears to be getting out well below profit target level.

    I've been using code from a forum thread on profit targets which seems to be getting out quite a distance from the actual profit target level. For example I set a profit target of .0020 in cash currencies and when I view the strategy report when my profit target exit occurs is it usually well below the actual .0020 points, usually .0005 to .0015 and I ca't figure out why.

    I noticed the techniques for testing for profit targets and trailing stops/stops has evolved over time, here is the code I've been using. Is this still the recommended way for testing such breeches?

    Also I noticed that there was some mention of a "Real Time EFS Strategies" document, Does such a document exist and/or are there any consideration that need to be programmed in relative to simpley backtesting that I should know aout. I do this for a living and really need to know anything that will alter the results of my tested systems as my job depends on it.

    Thanks very much.

    PROFIT TARGET BREECH CODE:

    /*----------------------------------------------------------------
    // 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.isShort() == true)) {
    // Check if the profit target has been reached/breached
    if (low() <= (nTradeEntryPrice - ProfitTarget1)) {
    // Profit Target Breached, Execute Cover order.
    Strategy.doCover("Short PT1 Exit", Strategy.STOP, Strategy.THISBAR,
    Strategy.getDefaultLotSize(), (nTradeEntryPrice - ProfitTarget1));
    }
    }

    if (Strategy.isInTrade() == true && (Strategy.isLong() == true)) {
    // Check if the profit target has been reached/breached
    if (high() >= (nTradeEntryPrice + ProfitTarget1)) {
    // Profit Target Breached, Execute Sell order.
    Strategy.doSell("Long PT1 Exit", Strategy.STOP, Strategy.THISBAR,
    Strategy.getDefaultLotSize(), (nTradeEntryPrice + ProfitTarget1));


    STOP TARGET BREECH CODE:

    if (Strategy.isInTrade() == true && (Strategy.isShort() == true)) {
    // Check if the profit target has been reached/breached
    if (high() >= nStopLevel) {
    // Stop Breached, Execute Cover order.
    Strategy.doCover("Short T-Stop Exit", Strategy.STOP, Strategy.THISBAR,
    Strategy.getDefaultLotSize(), nStopLevel);
    }
    }

    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("Long T-Stop Exit", Strategy.STOP, Strategy.THISBAR,
    Strategy.getDefaultLotSize(),nStopLevel);
    Glen Demarco
    [email protected]

  • #2
    demarcog
    The portion of code you posted whilst correct in general does not provide enough information as to why you are seeing values that are different from what you are expecting. The problem for example could be caused by how you define the variable nTradeEntryPrice.
    Also missing from the tests for profit targets and stops is a check to make sure that the bar that triggers them actually breaches those values and does not gap over/under them which could return unrealistic results in your backtests.
    Alex

    Comment


    • #3
      Alex thanks for the response. I see what you are saying about gaps. All my sysetms are basically intraday data so I don't think it has been major factor in the profitability testing but you are correct has to be addressed and coded for thanks for the heads up I definately need to add code to eliminate that possibility. I recall seeing an example in one of the early EFS documents that I will try to dig up.

      Here is the code I'm using which I'm sure you will recognize from a thread or document. Again I really appreciate your help as it's very important for me to get this as accurate as possible and appreciate any suggestions/examples of the correct way to do this. I saw a few posts where the Math.max function was used and just looking for code which will most accurately reflect real market trades.

      Thanks Again.var


      nNewTrade; // New Trade Trigger 0 = OFF / 1 = ON
      var nsignal; // returns the direction of the trading signal
      var nTradeEntryPrice;
      var ProfitTarget1 ;
      var nStopLevel;
      var nStartHour = 0; // Start time to allow trades
      var nStartMin = 0;
      var nEndHour = 24; // Ending time to allow trades
      var nEndMin = 00;
      var nEODHour = 24; // End of Day trade close out time
      var nEODMin = 00;
      var nStarttime = 0;
      var nEndtime = 24;

      function preMain() {
      setPriceStudy(true);
      setStudyTitle("Trend-Shortterm");
      //setCursorLabelName("PT CODE");
      setCursorLabelName("Profit Target", 0); //ADDED
      setCursorLabelName("Stop Target", 1); //ADDED
      setCursorLabelName("Trade Price", 2); //ADDED
      setDefaultBarFgColor(Color.yellow, 0); //ADDED
      setDefaultBarFgColor(Color.lime, 1);
      setDefaultBarFgColor(Color.grey, 2);
      setPlotType(PLOTTYPE_FLATLINES, 0); //ADDED
      setPlotType(PLOTTYPE_FLATLINES, 1); //ADDED


      var fp1 = new FunctionParameter("nProfitAmt", FunctionParameter.NUMBER); //ADDED
      fp1.setName("Profit Target Amount"); //ADDED
      fp1.setLowerLimit(0.0010); //ADDED
      fp1.setDefault(.0025); //ADDED

      var fp2 = new FunctionParameter("nStopAmt", FunctionParameter.NUMBER); //ADDED
      fp2.setName("Trailing Stop Amount"); //ADDED
      fp2.setLowerLimit(0.0005); //ADDED
      fp2.setDefault(0.0020); //ADDED

      var fp3 = new FunctionParameter("nIntStopAmt", FunctionParameter.NUMBER); //ADDED
      fp3.setName("Initial Stop Amount"); //ADDED
      fp3.setLowerLimit(0.0005); //ADDED
      fp3.setDefault(0.0030); //ADDED



      var fp6 = new FunctionParameter("nStartHour", FunctionParameter.NUMBER);
      fp6.setName("Start Hour");
      fp6.setLowerLimit(0);
      fp6.setDefault(0);

      var fp7 = new FunctionParameter("nStartMin", FunctionParameter.NUMBER);
      fp7.setName("Start Min");
      fp7.setLowerLimit(0);
      fp7.setDefault(0);

      var fp8 = new FunctionParameter("nEndHour", FunctionParameter.NUMBER);
      fp8.setName("End Hour");
      fp8.setLowerLimit(0);
      fp8.setDefault(24);

      var fp9 = new FunctionParameter("nEndMin", FunctionParameter.NUMBER);
      fp9.setName("End Min");
      fp9.setLowerLimit(0);
      fp9.setDefault(00);

      var fp10 = new FunctionParameter("nEODHour", FunctionParameter.NUMBER);
      fp10.setName("EOD Hour");
      fp10.setLowerLimit(0);
      fp10.setDefault(24);

      var fp11 = new FunctionParameter("nEODMin", FunctionParameter.NUMBER);
      fp11.setName("End Min");
      fp11.setLowerLimit(0);
      fp11.setDefault(00);





      //ADDED formula parameters nProfitAmt and nStopAmt to allow
      // user defined amounts for various symbols.

      function main(nProfitAmt, nStopAmt, nIntStopAmt, nStartHour, nStartMin, nEndHour, nEndMin, nEODHour,
      nEODMin )
      {
      ProfitTarget1 = nProfitAmt;

      // Get Time Variables
      vTime = getValue("Time", 0);
      vHour = vTime.getHours();
      vMin = vTime.getMinutes();



      /*----------------------------------------------------------------
      // 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
      }

      var nDisplayStop = null; //ADDED
      var bPosition = false; //ADDED
      if (Strategy.isInTrade() == true) { //ADDED
      var nDisplayStop = nStopLevel; //ADDED
      var bPosition = true;
      if (Strategy.isLong() == true) setBarBgColor(Color.green); //ADDED
      if (Strategy.isShort() == true) setBarBgColor(Color.red); //ADDED
      } else { //ADDED
      nStopLevel = null; //ADDED
      } //ADDED

      /*----------------------------------------------------------------
      // 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.isShort() == true)) {
      // Check if the profit target has been reached/breached
      if (low() <= (nTradeEntryPrice - ProfitTarget1)) {
      // Profit Target Breached, Execute Cover order.
      Strategy.doCover("Short PT1 Exit", Strategy.STOP, Strategy.THISBAR,
      Strategy.getDefaultLotSize(), (nTradeEntryPrice - ProfitTarget1));
      }
      }

      if (Strategy.isInTrade() == true && (Strategy.isLong() == true)) {
      // Check if the profit target has been reached/breached
      if (high() >= (nTradeEntryPrice + ProfitTarget1)) {
      // Profit Target Breached, Execute Sell order.
      Strategy.doSell("Long PT1 Exit", Strategy.STOP, Strategy.THISBAR,
      Strategy.getDefaultLotSize(), (nTradeEntryPrice + ProfitTarget1));
      }
      }


      if (Strategy.isInTrade() == true && (Strategy.isShort() == true)) {
      // Check if the profit target has been reached/breached
      if (high() >= nStopLevel) {
      // Stop Breached, Execute Cover order.
      Strategy.doCover("Short T-Stop Exit", Strategy.STOP, Strategy.THISBAR,
      Strategy.getDefaultLotSize(), nStopLevel);
      }
      }

      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("Long T-Stop Exit", Strategy.STOP, Strategy.THISBAR,
      Strategy.getDefaultLotSize(),nStopLevel);
      }
      }


      /*----------------------------------------------------------
      This portion of the code calculates and sets the new stop levels.
      ----------------------------------------------------------*/

      if (Strategy.isInTrade() == true && (Strategy.isShort() == true)) {
      nStopLevel = high(-1) + nStopAmt; //ADDED - replace 0.25 with nStopAmt
      }

      if (Strategy.isInTrade() == true && (Strategy.isLong() == true)) {
      nStopLevel = low(-1) - nStopAmt; //ADDED - replace 0.25 with nStopAmt
      }


      /*----------------------------------------------------------------
      // Identify new trade signals
      ----------------------------------------------------------------- */

      //ADDED - bPostion logic to the following line to prevent new entry
      // on the same bar that an exit trade occured.
      // (Strategy.isInTrade() == false && bPosition == false) {
      // if ( bPosition == false) {
      //if (/*Buy Condition*/)) {

      if (((vHour > nStartHour) && (vHour < nEndHour)) ||
      ((vHour == nStartHour) && (vMin >= nStartMin))) {
      if (
      vStoch20_3.getValue(StochStudy.SLOW) > vStoch20_3.getValue(StochStudy.SLOW, -1) &&


      { //ADDED
      nNewTrade = 1; // New Trade Trigger
      nsignal = 1; // Buy Signal - Trade Type
      }
      //if (/*Sell Condition*/) {
      if (
      vPriceOsc5_20.getValue(OscStudy.OSC) < vPriceOsc5_20.getValue(OscStudy.OSC, -1) &&

      {
      nNewTrade = 1; // New Trade Trigger
      nsignal = -1; // Sell Signal - Trade Type
      }
      }


      /*----------------------------------------------------------------
      // Execute Trades ONLY if nNewTrade is triggered ....
      ----------------------------------------------------------------- */

      if (nNewTrade == 1) { //Execute New Trade
      // new or reversed trade position
      if (Strategy.isInTrade() == true) {
      if ((nsignal > 0) && (Strategy.isShort() == true)) {
      Strategy.doCover("Exit Short", Strategy.MARKET, Strategy.NEXTBAR);
      Strategy.doLong("Rev To Long", Strategy.MARKET, Strategy.NEXTBAR);
      Alert.email("Go Long ", getSymbol()+" "+getInterval()) ;
      Strategy.setStop(low()- nIntStopAmt)
      nStopLevel = low(-1) - nStopAmt;
      nTradeEntryPrice = open();
      }
      if ((nsignal < 0) && (Strategy.isLong() == true)) {
      Strategy.doSell("Exit Long", Strategy.MARKET, Strategy.NEXTBAR);
      Strategy.doShort("Rev To Short", Strategy.MARKET, Strategy.NEXTBAR);
      Alert.email("Go Short ", getSymbol()+" "+getInterval());
      Strategy.setStop(high()+ nIntStopAmt);
      nStopLevel = high(-1) + nStopAmt;
      nTradeEntryPrice = open();
      }
      } else {
      if ((nsignal > 0)) {
      Strategy.doLong("Go Long", Strategy.MARKET, Strategy.NEXTBAR);
      Alert.email("Go Long ", getSymbol()+" "+getInterval());
      Strategy.setStop(low()- nIntStopAmt);
      nStopLevel = low(-1) - nStopAmt;
      nTradeEntryPrice = open();
      }
      if ((nsignal < 0)) {
      Strategy.doShort("Go Short", Strategy.MARKET, Strategy.NEXTBAR);
      Alert.email("Go Short ", getSymbol()+" "+getInterval());
      Strategy.setStop(high()+ nIntStopAmt);
      nStopLevel = high(-1) + nStopAmt;
      nTradeEntryPrice = open();
      }
      } // end if IN TRADE
      } // END EXECUTE NEW TRADE

      var nDisplayProfit = null;
      var nTradePnl = null;

      if (Strategy.isLong() == true && nNewTrade == 0) nDisplayProfit = (nTradeEntryPrice + ProfitTarget1);
      if (Strategy.isLong() == true && nNewTrade == 0) nTradePnl = (nTradeEntryPrice + close(0));
      if (Strategy.isShort() == true && nNewTrade == 0) nDisplayProfit = (nTradeEntryPrice - ProfitTarget1);
      if (Strategy.isShort() == true && nNewTrade == 0) nTradePnl = (nTradeEntryPrice - close(0));
      if ( ((vHour > nEODHour)) || ((vHour == nEODHour) && (vMin >= nEndMin)) ) { //Close all OPEN Trades
      if (Strategy.isInTrade() == true) {
      if ((Strategy.isShort() == true)) {
      Strategy.doCover("Close Short EOD", Strategy.MARKET, Strategy.NEXTBAR, Strategy.getDefaultLotSize(),0);
      }
      if ((Strategy.isLong() == true)) {
      Strategy.doSell("Close Long EOD", Strategy.MARKET, Strategy.NEXTBAR, Strategy.getDefaultLotSize(),0);
      }
      }
      }
      return new Array( nDisplayProfit, nDisplayStop, nTradeEntryPrice); // ADDED
      }
      Glen Demarco
      [email protected]

      Comment


      • #4
        demarcog
        I would suggest you review the code you posted as it contains several errors (incomplete if() statements, studies not declared, etc).
        Also when posting code please format it using either the PHP or CODE tags as suggested in the Posting Guidleines for EFS Studies forum.
        Alex

        Comment


        • #5
          Alex,

          Sorry about that I made an error copying. Here is the EFS, I'll read the document about formatting strategies. I am really having a difficult coming up with a coding technique for stops and profit targets that is accurate and appreciate very much your help.

          Thanks Glen
          PHP Code:
          var nNewTrade// New Trade Trigger 0 = OFF / 1 = ON
          var nsignal// returns the direction of the trading signal
          var nTradeEntryPrice
          var 
          ProfitTarget1 ;
          var 
          nStopLevel;
          var 
          nStartHour 0// Start time to allow trades
          var nStartMin 0;
          var 
          nEndHour 24// Ending time to allow trades
          var nEndMin 00
          var 
          nEODHour 24// End of Day trade close out time
          var nEODMin 00;
          var 
          nStarttime 0;
          var 
          nEndtime 24;

          var 
          vStoch20_3 = new StochStudy(140,5,5);


          function 
          preMain() {
              
          setPriceStudy(true);
              
          setStudyTitle("Trend-Shortterm");
              
          //setCursorLabelName("PT CODE");
              
          setCursorLabelName("Profit Target"0); //ADDED
              
          setCursorLabelName("Stop Target"1); //ADDED
              
          setCursorLabelName("Trade Price"2); //ADDED
              
          setDefaultBarFgColor(Color.yellow0); //ADDED
              
          setDefaultBarFgColor(Color.lime1);
              
          setDefaultBarFgColor(Color.grey2);
              
          setPlotType(PLOTTYPE_FLATLINES0); //ADDED
              
          setPlotType(PLOTTYPE_FLATLINES1); //ADDED
             
              
              
          var fp1 = new FunctionParameter("nProfitAmt"FunctionParameter.NUMBER); //ADDED
              
          fp1.setName("Profit Target Amount"); //ADDED
              
          fp1.setLowerLimit(0.0001); //ADDED
              
          fp1.setDefault(.0025); //ADDED

              
          var fp2 = new FunctionParameter("nStopAmt"FunctionParameter.NUMBER); //ADDED
              
          fp2.setName("Trailing Stop  Amount"); //ADDED
              
          fp2.setLowerLimit(0.0001); //ADDED
              
          fp2.setDefault(0.0020); //ADDED
              
              
          var fp3 = new FunctionParameter("nIntStopAmt"FunctionParameter.NUMBER); //ADDED
              
          fp3.setName("Initial Stop  Amount"); //ADDED
              
          fp3.setLowerLimit(0.0001); //ADDED
              
          fp3.setDefault(0.0030); //ADDED
              
              
          var fp4 = new FunctionParameter("nAlevel1"FunctionParameter.NUMBER); //ADDED
              
          fp4.setName("A Level1  Amount"); //ADDED
              
          fp4.setLowerLimit(0); //ADDED
              
          fp4.setDefault(15); //ADDED
              
               
          var fp5 = new FunctionParameter("nAlevel2"FunctionParameter.NUMBER); //ADDED
              
          fp5.setName("A Level2  Amount"); //ADDED
              
          fp5.setLowerLimit(0); //ADDED
              
          fp5.setDefault(40); //ADDED
              
              
          var fp6 = new FunctionParameter("nStartHour"FunctionParameter.NUMBER); 
              
          fp6.setName("Start Hour"); 
              
          fp6.setLowerLimit(0); 
              
          fp6.setDefault(0);  
              
              var 
          fp7 = new FunctionParameter("nStartMin"FunctionParameter.NUMBER); 
              
          fp7.setName("Start Min"); 
              
          fp7.setLowerLimit(0); 
              
          fp7.setDefault(0);
              
              var 
          fp8 = new FunctionParameter("nEndHour"FunctionParameter.NUMBER); 
              
          fp8.setName("End Hour"); 
              
          fp8.setLowerLimit(0); 
              
          fp8.setDefault(24);  
              
              var 
          fp9 = new FunctionParameter("nEndMin"FunctionParameter.NUMBER); 
              
          fp9.setName("End Min"); 
              
          fp9.setLowerLimit(0); 
              
          fp9.setDefault(00); 
              
              var 
          fp10 = new FunctionParameter("nEODHour"FunctionParameter.NUMBER); 
              
          fp10.setName("EOD Hour"); 
              
          fp10.setLowerLimit(0); 
              
          fp10.setDefault(24);  
              
              var 
          fp11 = new FunctionParameter("nEODMin"FunctionParameter.NUMBER); 
              
          fp11.setName("End Min"); 
              
          fp11.setLowerLimit(0); 
              
          fp11.setDefault(00); 
              
              var 
          fp12 = new FunctionParameter("nRevel1"FunctionParameter.NUMBER); 
              
          fp12.setName("R Level1"); 
              
          fp12.setLowerLimit(0.0001); 
              
          fp12.setDefault(0.0016);
              
              var 
          fp13 = new FunctionParameter("nRevel2"FunctionParameter.NUMBER); 
              
          fp13.setName("R Level2"); 
              
          fp13.setLowerLimit(0.0001); 
              
          fp13.setDefault(0.0050);
          }



          //ADDED formula parameters nProfitAmt and nStopAmt to allow
          // user defined amounts for various symbols.

          function main(nProfitAmtnStopAmtnIntStopAmtnAlevel1nAlevel2nStartHournStartMinnEndHournEndMinnEODHour
                        
          nEODMinnRlevel1nRlevel2 
          {
              
          ProfitTarget1 nProfitAmt
              
              
          //  Get Time Variables 
            
          vTime getValue("Time"0);
            
          vHour vTime.getHours();
            
          vMin vTime.getMinutes();
           
            
              
          /*----------------------------------------------------------------
          // 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
              
          }

              var 
          nDisplayStop null//ADDED
              
          var bPosition false;  //ADDED
              
          if (Strategy.isInTrade() == true) {  //ADDED
                  
          var nDisplayStop nStopLevel;  //ADDED
                  
          var bPosition true;
                  if (
          Strategy.isLong() == truesetBarBgColor(Color.green);  //ADDED
                  
          if (Strategy.isShort() == truesetBarBgColor(Color.red);  //ADDED
              
          } else {  //ADDED
                  
          nStopLevel null;  //ADDED
              
          }  //ADDED

              /*----------------------------------------------------------------
              // 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.isShort() == true)) {
                  
          // Check if the profit target has been reached/breached
                  
          if (low() <= (nTradeEntryPrice ProfitTarget1)) {
                      
          // Profit Target Breached, Execute Cover order.
                      
          Strategy.doCover("Short PT1 Exit"Strategy.STOPStrategy.THISBAR
                          
          Strategy.getDefaultLotSize(), (nTradeEntryPrice ProfitTarget1));
                  }
              }

              if (
          Strategy.isInTrade() == true && (Strategy.isLong() == true)) {
                  
          // Check if the profit target has been reached/breached
                  
          if (high() >= (nTradeEntryPrice ProfitTarget1)) {
                      
          // Profit Target Breached, Execute Sell order.
                      
          Strategy.doSell("Long PT1 Exit"Strategy.STOPStrategy.THISBAR
                          
          Strategy.getDefaultLotSize(), (nTradeEntryPrice ProfitTarget1));
                  }
              }


              if (
          Strategy.isInTrade() == true && (Strategy.isShort() == true)) {
                  
          // Check if the profit target has been reached/breached
                  
          if (high() >= nStopLevel) {
                      
          // Stop Breached, Execute Cover order.
                      
          Strategy.doCover("Short T-Stop Exit"Strategy.STOPStrategy.THISBAR
                          
          Strategy.getDefaultLotSize(), nStopLevel);
                  }
              }

              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("Long T-Stop Exit"Strategy.STOPStrategy.THISBAR
                          
          Strategy.getDefaultLotSize(),nStopLevel);
                  }
              }


              
          /*----------------------------------------------------------
              This portion of the code calculates and sets the new stop levels.
              ----------------------------------------------------------*/

              
          if (Strategy.isInTrade() == true && (Strategy.isShort() == true)) {
                  
          nStopLevel high(-1) + nStopAmt;  //ADDED - replace 0.25 with nStopAmt
              
          }

              if (
          Strategy.isInTrade() == true && (Strategy.isLong() == true)) {
                  
          nStopLevel low(-1) - nStopAmt//ADDED - replace 0.25 with nStopAmt
              
          }


              
          /*----------------------------------------------------------------
              // Identify new trade signals
              ----------------------------------------------------------------- */

              //ADDED - bPostion logic to the following line to prevent new entry
              //        on the same bar that an exit trade occured.
            // (Strategy.isInTrade() == false && bPosition == false) {
           //  if ( bPosition == false) {
                  //if (/*Buy Condition*/)) {
                  
                   
          if (((vHour nStartHour) && (vHour nEndHour)) ||
               ((
          vHour == nStartHour) && (vMin >= nStartMin))) {    
                  if (          
                     
          vStoch20_3.getValue(StochStudy.SLOW) > vStoch20_3.getValue(StochStudy.SLOW, -1) ) 

                     {  
          //ADDED
                      
          nNewTrade 1// New Trade Trigger
                      
          nsignal 1// Buy Signal - Trade Type
                  
          }
                  
          //if (/*Sell Condition*/) {
                  
          if (
                      
          vStoch20_3.getValue(StochStudy.SLOW) < vStoch20_3.getValue(StochStudy.SLOW, -1)  ) 
                   {
                      
          nNewTrade 1// New Trade Trigger
                      
          nsignal = -1// Sell Signal - Trade Type
                  
          }
             }


              
          /*----------------------------------------------------------------
              // Execute Trades ONLY if nNewTrade is triggered ....
              ----------------------------------------------------------------- */

              
          if (nNewTrade == 1) { //Execute New Trade
                  // new or reversed trade position
                  
          if (Strategy.isInTrade() == true) {
                      if ((
          nsignal 0) && (Strategy.isShort() == true)) {
                          
          Strategy.doCover("Exit Short"Strategy.MARKETStrategy.NEXTBAR);
                          
          Strategy.doLong("Rev To Long"Strategy.MARKETStrategy.NEXTBAR);
                           
          Alert.email("Go Long "getSymbol()+" "+getInterval()) ;
                          
          Strategy.setStop(low()- nIntStopAmt)
                          
          nStopLevel low(-1) - nStopAmt;
                           
          nTradeEntryPrice open();
                      }
                      if ((
          nsignal 0) && (Strategy.isLong() == true)) {
                          
          Strategy.doSell("Exit Long"Strategy.MARKETStrategy.NEXTBAR);
                          
          Strategy.doShort("Rev To Short"Strategy.MARKETStrategy.NEXTBAR);
                           
          Alert.email("Go Short "getSymbol()+" "+getInterval());
                          
          Strategy.setStop(high()+ nIntStopAmt);
                          
          nStopLevel high(-1) + nStopAmt;
                           
          nTradeEntryPrice open();
                      }
                  } else {
                      if ((
          nsignal 0)) {
                          
          Strategy.doLong("Go Long"Strategy.MARKETStrategy.NEXTBAR);
                          
          Alert.email("Go Long "getSymbol()+" "+getInterval());
                          
          Strategy.setStop(low()- nIntStopAmt);
                          
          nStopLevel low(-1) - nStopAmt;
                           
          nTradeEntryPrice open();
                      }
                      if ((
          nsignal 0)) {
                          
          Strategy.doShort("Go Short"Strategy.MARKETStrategy.NEXTBAR);
                          
          Alert.email("Go Short "getSymbol()+" "+getInterval());
                          
          Strategy.setStop(high()+ nIntStopAmt);
                          
          nStopLevel high(-1) + nStopAmt;
                           
          nTradeEntryPrice open();
                      }
                  } 
          // end if IN TRADE
              
          // END EXECUTE NEW TRADE
              
              
          var nDisplayProfit null
               var 
          nTradePnl null;
               
              if (
          Strategy.isLong() == true && nNewTrade == 0nDisplayProfit = (nTradeEntryPrice ProfitTarget1); 
               if (
          Strategy.isLong() == true && nNewTrade == 0nTradePnl = (nTradeEntryPrice close(0));
              if (
          Strategy.isShort() == true && nNewTrade == 0nDisplayProfit = (nTradeEntryPrice ProfitTarget1);
              if (
          Strategy.isShort() == true && nNewTrade == 0nTradePnl = (nTradeEntryPrice close(0));  
          if ( ((
          vHour nEODHour)) || ((vHour == nEODHour) && (vMin >= nEndMin)) ) {  //Close all OPEN Trades
                  
          if (Strategy.isInTrade() == true) {
                  if ((
          Strategy.isShort() == true)) {
                    
          Strategy.doCover("Close Short EOD"Strategy.MARKETStrategy.NEXTBARStrategy.getDefaultLotSize(),0);
                  } 
                  if ((
          Strategy.isLong() == true)) {
                    
          Strategy.doSell("Close Long EOD"Strategy.MARKETStrategy.NEXTBARStrategy.getDefaultLotSize(),0);    
                  }
                }
          }
             return new Array( 
          nDisplayProfitnDisplayStopnTradeEntryPrice); // ADDED

          Glen Demarco
          [email protected]

          Comment


          • #6
            demarcog
            The first thing you will want to do is fix the problem with the display of the profit target as that will help you understand why you are seeing the discrepancies you mentioned.
            Note that at this time the profit target ie nDisplayProfit in your return statement is not displaying on the chart. To resolve this problem remove && nNewTrade == 0 in lines 272 and 274.
            Once you plot the profit target you will also see that it is related to the Open of the bar that triggers the trade. nTradeEntryPrice in fact is set to open() in lines 241, 249, 257 and 264. However in your strategy commands you are using Strategy.MARKET and Strategy.NEXTBAR in lines 236, 237, 244, 245, 253, 260 hence the Open of the following bar which is the price that the back tester will instead use as the entry price. This will inevitably result in a discrepancy.
            To resolve this issue replace open() with open(1).
            Lastly remember that this script should be used only for backtesting and not in real time
            Alex

            PS. If you go into Edit mode of your message you can see how the PHP tags are used to format the code in a message.

            Comment


            • #7
              Alex,

              Thanks very much for the help in resolving the programming errors.

              You comment about these scripts being for backtesting only concens me. The systems I'm working on are backtested to determine whether they will be eventuially traded real time which is what I'm doing now for a firm and (we actually have several hundred Esignal users).

              Your comment seems to suggest that the results derived through backtesting and in real time will not be the same. If this is true that is a real problem for me as my job depends on the validity of my backtested resuilts.

              I very much need to know what specifically has to be changed in order to have the backtesting results match the realtime results using intraday data. I'm preplexed by the implication that backtesting will yield one set of results, but "real" time actual trading yields another. What would be the point of backtesting. I realize that Esignal cannot determine whether an order will be filled at a given price, but that aside the only tested results that matter are realtime as that's when trading occurs, in realtime.

              Please help me out here as my scripts need to relect realtime results only.

              Thanks Again for all your help.

              PS. I tried to go into edit more as you suggested but denied permission?
              Glen Demarco
              [email protected]

              Comment


              • #8
                demarcog
                You have misunderstood what I said. I said that the script as it is currently written should be used only for backtesting.
                The Strategy Object is only intended for use with the Strategy Analyzer, not for real time use of a trading strategy. If you want to run the same strategy in real time you will have to modify the script for that condition.
                For example in real time you cannot use Strategy.NEXTBAR when a condition is true. This is because the price of the next bar is unknown in real time (I believe I already showed you this very same issue in another thread). So the code for real time would have to be something like the following example

                PHP Code:
                if(getBarState()==BARSTATE_NEWBAR){
                     if(
                your_condition_at_prior_bar == true){
                          
                doLong(open_of_this_bar)
                //etc etc 
                As you can see the end result is the same (ie buy at the Open of the bar that follows the signal) except that is accomplished in a different way.

                Having said that I believe that expecting any strategy to yield the same results in back testing and in real time is unrealistic.
                In real time there is no guarantee that any of your orders will be filled or filled at the price and/or for the same amount of contracts/shares that you use in back testing.
                So, what is the point of back testing? Back testing is used to test whether or not the basic hypothesis for a trading strategy is valid. But that does not mean that in real life you will be getting the same exact results.
                Lastly, as important as this code is to you, it may be in your best interest to hire an EFS Consultant.
                Alex

                Comment


                • #9
                  I think I may have read too much and did misunderstand. Thanks for clarifying that for me and providing me with the code example.

                  I agree that there is an assumption in backtesting that because a price exists in the price data a successful trade can and will be executed at that price in realtime.

                  This is what you are referring to and couldn't agree with you more (that where slippage comes in). I guess for that reason backtesting results will always vary somewhat from real results.

                  The assumption I'm refering to is that if a price point exists a trade was executed (minus slippage), which is great. Esignal's java script is the most awesome tool available that provides a facility to test an infinate number of trading ideas.


                  I'm just trying to find the correct code to as closely as possible approximate the most realistic results, realizing there will be variation.

                  Can I have one script for both backtesting and realtime that uses for example BARSTATE_NEWBAR?




                  BTW, all the code that I am using came from recomendations in a variety of threads by other users with questions about stops and profits targets and the excellent esignal documents. Do you have an updated example of profit target and stop logic as the techniques have evolved over time and I may have missed the latest and mos effective of accomplishing this.

                  Thanks again for all you very helpful and valuable assistance.
                  Glen Demarco
                  [email protected]

                  Comment


                  • #10
                    demarcog

                    Can I have one script for both backtesting and realtime that uses for example BARSTATE_NEWBAR?

                    It is possible but not recommended IMHO. While using a logic based on completed bars makes the two sets of code much more interchangable (and minimizes possible differences) there are still functions that are specific to either set that would only add an unnecessary layer of complexity when used in the same script.
                    I still think you are better off writing one set for back testing using the strategy object and the other for use in real time with the broker functions or whatever other functions you may require under those conditions.
                    Alex

                    Comment

                    Working...
                    X