Announcement

Collapse
No announcement yet.

Strategy.isShort() returning erroneous value?

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

  • Strategy.isShort() returning erroneous value?

    I have a somewhat complicated efs strategy that I use for backtesting. I've been having some problems with it behaving erratically (totally skipping some trading days).

    I finally chased down the issue to what appears to be the function call to Strategy.isShort() returning "true" when, in fact, there is no open trade. This is causing my logic to go haywire.

    I've done extensive debugging and am 99% sure this is an erroneous return value (leaving that 1% chance that somehow I'm missing something). I come to this conclusion because the strategy analysis report reports clean trades before and after this time in the script. If I really did have a position hanging out there the next entry/exit would reflect it by either closing the erroneous position (if the next entry were opposite) or reporting an increased size upon closing of the next position (if the next entry were in the same direction.

    Has anyone else encountered a bug where these funtions (isShort or isLong) will return incorrect values? Its wreaking all kinds of havoc with my backtesting attempts and making it pretty much impossible for me to trust anything I'm getting from the strategy analyzer. I've searched out here and haven't found any reference to this.

    Thanks anyone who can help.

  • #2
    ebr
    If you are not already doing this you may want to try setting the conditions as for example
    if(Strategy.isShort()==true) rather than just if(Strategy.isShort())
    Just an idea
    Alex

    Comment


    • #3
      yes, I have had similar problems however, it turned out to be a problem of my own creation. If I were to bet, I think you may have the same problem. post some code and I will look at.

      Here is some of mine, note that each time there is a trace statement, it is writing to a buffer which is flushed to a file every bar

      PHP Code:
      function ShortTrade(){trace("316:     in ShortTrade");

          if (
      ok2Trade == false){trace("318:");return;}

          if (
      Strategy.isLong() == true) {trace("320:"+Strategy.getPositionSize()+" sTs:"+sTradeStatus);// we are in a long
              
      sAction "Long Rev";sType "Sell";
              
      sExit close()- nSlippage;trace("322:"+sExit);
              
      Strategy.doSell(sAction,Strategy.CLOSEStrategy.THISBAR,Strategy.ALL);trace("323:"+Strategy.getPositionSize()+" sTs:"+sTradeStatus);
              
      sTradeStatus 0;trace("324:sTs:"+sTradeStatus);
              
      sTradeProfit = ( sExit-sEntry )-.1 ;
              if ( 
      sTradeProfit>)
                  
      sTotalWins++;
              else
                  
      sTotalLosses++;
              
      sTotalProfit += sTradeProfit;trace("330:");
              
      blockText(sAction,sTradeProfit,sTotalProfit);trace("331:");
              
      PerformanceReport("close trade");trace("332:");
          }
          
          if (!(
      Strategy.isInTrade())) {trace("335:"+Strategy.getPositionSize()+" sTs:"+sTradeStatus);
              
      sAction "Short Entry";sType "Short";
              
      sEntry close()- nSlippage;trace("337:"+sEntry);
              
      Strategy.doShort(sActionStrategy.CLOSEStrategy.THISBAR,nPOS);trace("338:"+Strategy.getPositionSize()+" sTs:"+sTradeStatus);
              
      sTradeStatus = -1;trace("339:sTs:"+sTradeStatus);
              
      sTotalTrades++;trace("340:");
              
      PerformanceReport("open trade");trace("341:"); 
              var 
      tAction "Reverse";trace("342:");
              
      sDrawShape(-1tAction);trace("343:");
          }

      FWIW, I also track trade status with sTradeStatus variable flag. this allows me to insure I am always in sync (as I had the same problem as you) Are you using limit or stop buys? That was my problem.
      PHP Code:
      function Cleanup(){//checks trade signals for being out of sync, colors bars and colors background

        
      if (Strategy.isInTrade() == false){
              if ((
      sTradeStatus)){
                  
      debugPrintln("Problem !!! ~~Strategy.isInTrade() == false~~ however @ "+sTime()+" sTradeStatus = "+sTradeStatus);
              }
          }
          if (
      Strategy.isLong() == true){
              if ((
      sTradeStatus != 1)){
                  
      debugPrintln("Problem !!! ~~ Strategy.isLong() == true ~~ however @ "+sTime()+" sTradeStatus = "+sTradeStatus+" and Strategy.isLong() is "+Strategy.isLong());
              }
          }            
          if (
      Strategy.isShort() == true){
              if ((
      sTradeStatus != -1)){
                  
      debugPrintln("Problem !!! ~~ Strategy.isShort() == true ~~ however @ "+sTime()+" sTradeStatus = "+sTradeStatus+" and Strategy.isShort() is "+Strategy.isShort());
              }
          } 

      Comment


      • #4
        By the way, the strategy analyzer reflects only what you have told it to do. To find all the errors in my code I ended up duplicating the strategy analyzer output to a file.

        Every time, I found a mistake, it was mine and the strategy analyzer was only reflecting what I was telling it to do

        FWIW

        Comment


        • #5
          Alex - I changed my code to use my own variable to track if I'm in a trade or not and it now works flawlessly.

          This is further proof to me that there is some sort of bug in the Strategy.is... functions.

          If "if (Strategy.isLong())" does not evaluate the same as "if (Strategy.isLong() == true)" then, I'd also say something is wrong. How can those two statements ever yield different results (and the language be operating properly)?

          Steve - Thanks for confirming my madness . I don't quite understand how this problem was "of your own making" though. Please explain. And what did it have to do with the order type? All of my executions are done with "Limit" orders because they are executed at a specific price within a given bar (once I know that price has been breached).

          I also write my statistics to a file now but found the opposite of you. My file output was correct while the strategy analyzer was missing entire days (due to the error we're talking about here).

          Thanks both of you for your help.

          Comment


          • #6
            Well, here is how I exit on limit/stop

            PHP Code:
            if (Strategy.isShort() == true){trace("167:in short-------"+Strategy.getPositionSize()+" sTs:"+sTradeStatus);//we are in a short
                    
            trace("168:high-sEntry:"+(high()-sEntry));
                    if((
            high() - sEntry) >= STOffset){//stopped out
                        
            sAction "Short Stop Exit";sType "Cover";
                        
            sExit sEntry+STOffset;trace("170:"+sExit);
                        
            Strategy.doCover(sAction,Strategy.STOPStrategy.THISBAR,Strategy.ALL,sExit);
                        
            trace("171:"+Strategy.getPositionSize()+" sTs:"+sTradeStatus);
                        
            sTradeStatus 0;trace("172:sTs:"+sTradeStatus); 
            I had been adding slippage to my exit price, and found when the price met my stop price but did not meet my stop plus slippage, I skipped trades. Please post some code and we may be able to help you further. This may be related to the boolean issue which was discussed earlier today on the BB too.

            Comment


            • #7
              note that in this case, my internal tracking of my logic indicated my code was flawless, however, I was preventing the strategy analyzer from working correctly

              Comment


              • #8
                Here's the same relative segment of my code. Looks very similar of course (except note that I've scrapped the Strategy.is... functions for my own variables).

                PHP Code:
                                if (areLong) { // look for stop and target
                            
                if (low() <= stopPrice) { // stop hit
                                
                Strategy.doSell("Long Stopped",Strategy.LIMIT,Strategy.THISBAR,null,stopPrice);
                                
                areLong false;
                                if (
                fileOut) { // if we're writing to a file - keep stats
                                    
                profit profit - (((entryPrice stopPrice) * posSize) / Strategy.getDefaultLotSize());
                                    
                comm comm + (0.25 * (posSize Strategy.getDefaultLotSize()));
                                } 
                I don't account for slippage directly because I rarely encounter it in real life with stop orders (futures) and I make sure that I check the price was traded through for my limit orders.

                Also, I haven't seen the boolean discussion, so I'll look that up. Thanks again.

                Comment


                • #9
                  I have a couple thoughts,

                  The boolean thing is very likely. The phenomin occurs when you open up the edit studies menu. All booleans are changed to strings. I am not sure exactly what the strategy analyzer does when it runs and loads the efs, but it could be similar. It is probably worhtwhile checking for variable type. during backtesting.

                  The other thing is that you have a null there where you are selling Strategy.THISBAR,null I have all the shares sold Strategy.THISBAR,Strategy.ALL It probably does not matter however, something to check

                  Comment


                  • #10
                    ebr et al,

                    It is not just the Strategy.isShort() function, but Strategy.isLong() function as well. In tracing what wasn't working correctly in my code, I created this simple code (I've removed the entry & exit routines):

                    var vDummy;

                    function preMain() {
                    setStudyTitle("codeTest");
                    }

                    function main() {
                    if (Strategy.isShort() == true); {
                    vDummy = Strategy.isShort();
                    debugPrint(vDummy, "Short Strategy =", "\n");
                    vDummy = (high() >= nStopHard);
                    debugPrint(vDummy, "Short Stop hit =", "\n");
                    }
                    if (Strategy.isLong() == true); {
                    vDummy = Strategy.isLong();
                    debugPrint(vDummy, "Long Strategy =", "\n");
                    vDummy = (low() >= nStopHard);
                    debugPrint(vDummy, "Long Stop hit =", "\n");
                    }
                    }

                    Every time I run it, I ALWAYS get values for long & short strategies, as well as Short & Long Stops being true or false. Obviously I can't be long & short at the same time.

                    I also have to place the variable first for the print order to be correct, but that is another problem...

                    I was hoping I didn't have to create my own code to deal with this, so thank you for starting the thread.

                    Comment


                    • #11
                      Hello gpfx19,

                      As far as I can tell Strategy.isShort() and Strategy.isLong() are returning their proper true/false values depending on whether or not your current possition is long, short or no position. I'm not entirely sure I understand the problem you're describing, however. Can you try describing the issue in greater detail. Try giving a description of a specific scenario with some details about the timing and order of process of your code. Or attach your formula so I can test it.
                      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


                      • #12
                        The new posts reminded me that I never updated my progress on this issue.

                        It was definitely "the boolean bug" -- at least, I hope this is classified as a bug with the eSignal folks. Changing my tests from If (Strategy.isShort()) to If (Strategy.isShort() == true) fixed the problem for me.

                        Thanks all who helped.

                        Comment


                        • #13
                          Jason,

                          Here is the code. I have chopped out about half of what I am normally running. Most of those lines are debugPrint, to verify & learn. If you would like the full coding, please ask. When I run this code, I get the same results. Though I am having problems in other areas also, the Stop section pertains to this thread.
                          Thanks -
                          --------------------
                          var bInitiateNewTrade = false;
                          var sDirection = "None";
                          var nEntryPrice = 0;
                          var vTemp;
                          var nContracts = 1;

                          function preMain() {
                          setStudyTitle("codeTest");
                          }

                          function main() {

                          var vStudy1 = new MAStudy(5, -1, "OHLC/4", MAStudy.SIMPLE);
                          var vStudy2 = new MAStudy(5, 0, "OHLC/4", MAStudy.SIMPLE);
                          var vMALastBar = vStudy1.getValue(MAStudy.MA);
                          var vMAThisBar = vStudy2.getValue(MAStudy.MA);

                          // STOP section
                          if (Strategy.isInTrade() == true) {
                          if (Strategy.isShort() == true); {
                          vTemp = Strategy.isShort();
                          debugPrint(vTemp, "Short Strategy =", "\n");
                          }
                          if (Strategy.isLong() == true); {
                          vTemp = Strategy.isLong();
                          debugPrint(vTemp, "Long Strategy =", "\n");
                          }
                          }

                          if (vMALastBar >= vMAThisBar) {
                          bInitiateNewTrade = true;
                          sDirection = "GoLong";
                          setBarBgColor(Color.lime);
                          } else if (vMALastBar < vMAThisBar) {
                          bInitiateNewTrade = true;
                          sDirection = "GoShort";
                          setBarBgColor(Color.red);
                          }

                          if(bInitiateNewTrade == true) { // execute trade only if trigger has been hit
                          if(Strategy.isInTrade() == true) { // exiting present position
                          if ((sDirection == "GoLong") && (Strategy.isShort() == true)) {
                          Strategy.doCover("Exit Short", Strategy.MARKET, Strategy.THISBAR);
                          Strategy.doLong("Reverse to long", Strategy.MARKET, Strategy.THISBAR, nContracts);
                          }
                          if ((sDirection == "GoShort") && (Strategy.isLong() == true)) {
                          Strategy.doSell("Exit Long", Strategy.MARKET, Strategy.THISBAR);
                          Strategy.doShort("Reverse to short", Strategy.MARKET, Strategy.THISBAR, nContracts);
                          }
                          } else { // Logic: reverse position or enter new, but do not add.
                          if (sDirection == "GoLong") {
                          Strategy.doLong("Go Long", Strategy.MARKET, Strategy.THISBAR, nContracts);
                          }
                          if (sDirection == "GoShort") {
                          Strategy.doShort("Go Short", Strategy.MARKET, Strategy.THISBAR, nContracts);
                          }
                          }
                          bInitiateNewTrade = false;
                          }
                          }

                          Comment


                          • #14
                            Looks to me...

                            Like this is a CODE PROBLEM..

                            Your code...

                            if (Strategy.isShort() == true); {
                            vTemp = Strategy.isShort();
                            debugPrint(vTemp, "Short Strategy =", "\n");
                            }
                            if (Strategy.isLong() == true); {
                            vTemp = Strategy.isLong();
                            debugPrint(vTemp, "Long Strategy =", "\n");
                            }

                            should not include the ";" at the end of the "if" statements. It should look like

                            if (Strategy.isShort() == true) {
                            vTemp = Strategy.isShort();
                            debugPrint(vTemp, "Short Strategy =", "\n");
                            }
                            if (Strategy.isLong() == true) {
                            vTemp = Strategy.isLong();
                            debugPrint(vTemp, "Long Strategy =", "\n");
                            }

                            this is the cause of your problem.

                            B
                            Brad Matheny
                            eSignal Solution Provider since 2000

                            Comment


                            • #15
                              Another thing...

                              You should be cautious of using...

                              Strategy.MARKET, Strategy.THISBAR, nContracts

                              for your entries... You are essentially saying that you are going to enter your trade at the OPENING PRICE of the current bar (potentially many minutes after the open of this bar). Thus, you are skewing your backtest results because of this..

                              It's like waiting for this bar to finish forming, then trying to back time up and buy at the open of the finished bar - not logical.

                              B
                              Brad Matheny
                              eSignal Solution Provider since 2000

                              Comment

                              Working...
                              X