Announcement

Collapse
No announcement yet.

Switching from "getCurrentBarIndex()" to "getBarState()"

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

  • Switching from "getCurrentBarIndex()" to "getBarState()"

    My current system bases trades on bar close and uses
    "setComputeOnClose(true);"
    in function preMain with
    "if(getCurrentBarIndex() == -1) {"
    before my order logic. I would like to change my system, however, so that the first trade is triggered based on a bar high or low with subsequent trades to be based on bar close.

    Would the way to achieve this be to use
    "if(getBarState() == BARSTATE_CURRENTBAR) {"
    before my order logic for my first trade and
    "if(getBarState() == BARSTATE_NEWBAR) {"
    before my order logic for my subsequent trades?

    Would I have to make any changes other than eliminating "setComputeOnClose(true);", "if(getCurrentBarIndex() == -1) {", and providing end brackets?

    Thanks.

    Mark

  • #2
    Mark,

    does this mean that the first trade can happen on any tick, and not just at the NEWBAR (really the end of the last bar)?

    Garth
    Garth

    Comment


    • #3
      Here is my understanding of how all these items interact....

      setComputeOnClose(true); forces the efs study to ignore every tick and just focus onthe bars that have already been drawn completly. The main benefit of this is to save cpu power, imho.

      if(getCurrentBarIndex() == -1) checks to see if the efs file is looking at the previous bar to the one currently being drawn. I use this feature to prevent my code from executing on every bar while the efs file is first loading.

      http://share.esignal.com/groupconten...png&groupid=21

      discusses the use of BARSTATE_CURRENTBAR and BARSTATE_NEWBAR.

      I wrote an efs to see what the heck this feature is really doing, located here

      http://share.esignal.com/download.js...=&file=gbs.efs

      Comment


      • #4
        This is a range breakout system set to start at 7:00 PT. The first breakout is often very strong so if I base it on the close there can be quite a bit of slippage. I was thinking that I could base the first trade on the high/low, on any tick, instead of the close. I don't know if this will improve my results but it was the idea I had to address the issue.

        Comment


        • #5
          This is a range breakout system set to start at 7:00 PT. The first breakout is often very strong so if I base it on the close there can be quite a bit of slippage. I was thinking that I could base the first trade on the high/low, on any tick, instead of the close. I don't know if this will improve my results but it was the idea I had to address the issue.
          OK, just wanted to verify.

          Here is what I would do. As you say, take the code for the subsequent trades and insert them between


          PHP Code:
          if(getBarState() == BARSTATE_NEWBAR) { 
          For the first trade, which I assume could happen anytime (though you start scanning at 7:00 PT) I would put some logic as:

          PHP Code:
          if(bFirstTrade == false){
            if (<
          Insert your condition here>){
               <
          Enter Trade>
               
          bFirstTrade true;

          Then of course set a variable outside of main() and PreMain():

          var bFirstTrade == false;


          And yes, you will have to get rid of the setComputeOnClose() and the check for CurrentBarIndex().

          Hope this helps

          Garth
          Garth

          Comment


          • #6
            Developing RT trading code...

            The way I handle this is with "Time Stamping". I find that getbarstate is not functional for RT trading applications. It is only called once per bar - when a new bar is forming.

            I also use a couple of system variables to control the trading system's logic... I use the same naming structure as eSignal to keep things simple (plus you can convert the RT code to a back-testing code my changing these back to esignals "strategy" functions)...

            StrategyisInTrade = false;
            StrategyisShort = false;
            StrategyisLong = false;

            Using a time stamp is a simple piece of code. It operates like this example...

            PHP Code:
            var nlasttradetime 0;
            var 
            StrategyisInTrade false;
            var 
            StrategyisShort false;
            var 
            StrategyisLong false;
            var 
            nstopprice 0;

            function 
            main(){

            if (
            getCurrentBarIndex() == 0) {

              if ((
            getValue("rawtime",0) != nlasttradetime) && (within_time_restrictions) && StrategyisInTrade == false) {
              
            // time is different than last trade time... so execute trades...
                
            if (buy breakout signal) {
                 ....
                 
            StrategyisInTrade true;
                 
            StrategyisShort false;
                 
            StrategyisLong true;
                 
            nstopprice low();
                 
            nlasttradetime getValue("rawtime",0);
                }
                if (
            sell breakout signal) {
                 ....
                 
            StrategyisInTrade true;
                 
            StrategyisShort true;
                 
            StrategyisLong false;
                 
            nstopprice high();
                 
            nlasttradetime getValue("rawtime",0);
                }
              }

              
            // Test for Stops...
              
            if (StrategyisInTrade == true) {
                if ((
            StrategyisShort == true) && (close() >= nstopprice)) {
                   .....
                   
            StrategyisInTrade false;
                   
            StrategyisShort false;
                   
            StrategyisLong false;
                   .....
                }
                if ((
            StrategyisLong == true) && (close() <= nstopprice)) {
                   .....
                   
            StrategyisInTrade false;
                   
            StrategyisShort false;
                   
            StrategyisLong false;
                   .....
                }
              }
              
            //  end if getcurrentbarindex == 0

            //  end of main() 
            This basic structure allows the code to run in RT and execute the stop orders in RT while only allowing one trade per bar.

            Let's say that you only wanted the same code to test once for a BUY or SELL when a new bar is formed on the chart. Then you would simply move the nlasttradetime = getValue('rawtime",0) outside the "IF" statements testing for buy or sell signals.... like this...


            PHP Code:
            var nlasttradetime 0;
            var 
            StrategyisInTrade false;
            var 
            StrategyisShort false;
            var 
            StrategyisLong false;
            var 
            nstopprice 0;

            function 
            main(){

            if (
            getCurrentBarIndex() == 0) {

              if ((
            getValue("rawtime",0) != nlasttradetime) && (within_time_restrictions) && StrategyisInTrade == false) {
              
            // time is different than last trade time... so execute trades...
                
            if (buy breakout signal) {
                 ....
                 
            StrategyisInTrade true;
                 
            StrategyisShort false;
                 
            StrategyisLong true;
                 
            nstopprice low();
                }
                if (
            sell breakout signal) {
                 ....
                 
            StrategyisInTrade true;
                 
            StrategyisShort true;
                 
            StrategyisLong false;
                 
            nstopprice high();
                }
                 
            nlasttradetime getValue("rawtime",0);
              }

              
            // Test for Stops...
              
            if (StrategyisInTrade == true) {
                if ((
            StrategyisShort == true) && (close() >= nstopprice)) {
                   .....
                   
            StrategyisInTrade false;
                   
            StrategyisShort false;
                   
            StrategyisLong false;
                   .....
                }
                if ((
            StrategyisLong == true) && (close() <= nstopprice)) {
                   .....
                   
            StrategyisInTrade false;
                   
            StrategyisShort false;
                   
            StrategyisLong false;
                   .....
                }
              }
              
            //  end if getcurrentbarindex == 0

            //  end of main() 
            This would allow the code to only test for a BUY or SELL signal at the beginning of a new bar.

            Developers can use multiple "time stamps" to control different aspects of their system. Bottom line, I have deployed multiple systems with this logic and IT WORKS FINE.

            Good luck.

            Brad
            Brad Matheny
            eSignal Solution Provider since 2000

            Comment


            • #7
              The way I handle this is with "Time Stamping". I find that getbarstate is not functional for RT trading applications. It is only called once per bar - when a new bar is forming.
              This is provable to be not a true statement. getbarstate() will run just as often as the formula is run (assuming there are no other conditionals around it).
              Garth

              Comment


              • #8
                getbatstate....

                Garth,

                Maybe I did not state it correctly. I find time stamping to be a more universal solution than getbarstate. You are correct, getbarstate will execute on every instance that main() is executed, but getbarstate() = newbar is only true when a new bar is forming.

                Time stamping is a more universal solution as it provides a way of indicating a trading action had been enacted and creates a method of developing a system that is more robust.

                For example... lets say you wanted to allow only one action per bar (entry or exit), but did not want to limit it to the newbar state. Thus you would want to develop code that could execute a single trade anytime during the formation of a bar. getbarstate would not allow you to accomplish this - Timestamping would.

                Plus you can declare multiple timestamp variables to control different actions of your trading system. Where as getbarstate() = newbar is a universal condition that does not depict the type of action taken when the newbar state is true.

                In closing, you are correct that for this example, getbarstate() is an appropriate solution, I was simply trying to add another potential solution that I find works well.

                best regards,

                Brad
                Brad Matheny
                eSignal Solution Provider since 2000

                Comment


                • #9
                  Time, Rawtime etc.

                  Hi: Would one of you folks who understands how these time issues work please explain what event(s) increment time (rawtime). Does it increment with each iteration of Main()? Does it start at Zero or Null? Does it start before or after preMain().
                  When does time begin!!

                  Thanks!!

                  Comment


                  • #10
                    Brad,

                    I agree, and time stamping does provide some nice flexibility, but IMHO, for most purposes time stamping is overkill in the complexity department. KISS is really important when coding in general, and even more so with EFS.

                    Garth
                    Garth

                    Comment


                    • #11
                      rhbishop,

                      rawtime increment on the advancement of time only. rawtime is nothing more than the number of seconds since 1/1/1970.

                      Garth
                      Garth

                      Comment


                      • #12
                        rawtime....

                        Garth is correct. Rawtime does not change with each instance of main(). Rawtime returns the time value of the current bar. So...

                        if the current bar has a time of 8:40 AM, then the rawtime of that bar will be the number of seconds from x till 8:40 am. Thus as that bar continues to form, the rawtime value does not change.

                        when a new bar forms (lets say 8:45), the value of rawtime changes to include the additional seconds.

                        So, for each new bar, rawtime changes to reflect the timestamp fo that bar.

                        This is very handy for developing systems and if you need a better example than those I have posted, please let me know.

                        Brad
                        Brad Matheny
                        eSignal Solution Provider since 2000

                        Comment


                        • #13
                          I must be missing something...

                          Why is rawtime so usefull?

                          Do you compare

                          rawtimeNow to rawtimeOld

                          to see if a new bar is being drawn?

                          Is it "cpu light" or "cpu less filling" vs betBarStatus and/or get.seconds?

                          Comment


                          • #14
                            dloomis.....

                            I find it very functional for trading system applications because it provides a way of "time stamping" a trading action or condition within the trading system....

                            Let's say you only wanted to allow your system to trade once per bar (based on certain conditions). Well, in some cases the conditions could be true more than once per bar, the time stamp variable allows us to code a method of taking only the first instance of the conditional TRUE values and act only once on this bar. The code would look like my example below (in a previous post).

                            Plus you could have the time stamp setup for more than one condition. Lets say you were looking for a RT trading condition (like stochastic cross, higher high, higher close and a MA moving higher). You could code this into a pattern, but it would be messy. The easiest way is to create a series of "if" statements for the conditions and a tracking system for the stochastics cross. The code might look like...

                            PHP Code:
                            var Study = new StochStudy(1473);
                            var 
                            MAStudy = new MAStudy(120"close"MAStudy.SIMPLE);
                            var 
                            nlaststocrosstime 0;
                            var 
                            nstocrosstrend 0// 0 = neutral, 1 = bullish, 2 = bearish
                            var nlasttradetime 0;
                            var 
                            StrategyisInTrade false;
                            var 
                            StrategyisShort false;
                            var 
                            StrategyisLong false;
                            var 
                            nstopprice 0;
                            var 
                            vFast 0;
                            var 
                            vSlow 0;
                            var 
                            vLastFast 0;
                            var 
                            vLastSlow 0;

                            function 
                            main(){

                            //  Get the current values of the Stochastic indicator
                            vFast Study.getValue(StochStudy.FAST);
                            vSlow Study.getValue(StochStudy.SLOW);
                            //  Get the previous values of the Stochastic indicator
                            vLastFast Study.getValue(StochStudy.FAST, -1);
                            vLastSlow Study.getValue(StochStudy.SLOW, -1);
                            //  Get the current and previous values of the Moving Average
                            maNow Study.getValue(MAStudy.MA);
                            lastMA Study.getValue(MAStudy.MA, -1);

                            if (
                            getCurrentBarIndex() == 0) {

                            //  Test for Stochastic Cross.  This function allows for only one completed action per bar using a timestamp.
                            if ((vFast >= vSlow) && (vLastFast vLastSlow) && (nlaststocrosstime != getValue("rawtime"0)) ) {
                               
                            nstocrosstrend 1;  // bullish cross
                               
                            nlaststocrosstime getValue("rawtime",0);
                            }
                            if ((
                            vFast <= vSlow) && (vLastFast vLastSlow) && (nlaststocrosstime != getValue("rawtime"0)) ) {
                               
                            nstocrosstrend = -1;  // bullish cross
                               
                            nlaststocrosstime getValue("rawtime",0);
                            }

                            //  Test for trade entry conditions....
                              
                            if ((getValue("rawtime",0) != nlasttradetime) && (within_time_restrictions) && StrategyisInTrade == false) {
                              
                            // time is different than last trade time... so execute trades...
                                
                            if ((nstocrosstrend == 1) && (high() > high(-1)) && (close() > close(-1)) && (maNow lastMA) ) {
                                 ....
                                 
                            StrategyisInTrade true;
                                 
                            StrategyisShort false;
                                 
                            StrategyisLong true;
                                 
                            nstopprice low();
                                 
                            nlasttradetime getValue("rawtime",0);
                                }
                                if ((
                            nstocrosstrend == -1) && (low() < low(-1)) && (close() < close(-1)) && (maNow lastMA) ) {
                                 ....
                                 
                            StrategyisInTrade true;
                                 
                            StrategyisShort true;
                                 
                            StrategyisLong false;
                                 
                            nstopprice high();
                                 
                            nlasttradetime getValue("rawtime",0);
                                }
                              }

                              
                            // Test for Stops...
                              
                            if (StrategyisInTrade == true) {
                                if ((
                            StrategyisShort == true) && (close() >= nstopprice)) {
                                   .....
                                   
                            StrategyisInTrade false;
                                   
                            StrategyisShort false;
                                   
                            StrategyisLong false;
                                   .....
                                }
                                if ((
                            StrategyisLong == true) && (close() <= nstopprice)) {
                                   .....
                                   
                            StrategyisInTrade false;
                                   
                            StrategyisShort false;
                                   
                            StrategyisLong false;
                                   .....
                                }
                              }
                              
                            //  end if getcurrentbarindex == 0

                            //  end of main() 
                            In this example, if the market was moving lower, the stochastic values would probably be moving lower as well. Using this code, if the market reversed (up), the trading system would wait for the first instance of a stochastics bullish cross, then record that action and prevent it from looking for another cross on that bar. Next, it would test for the conditions to trade. If the trade conditions were true, then it would execute a trade and prevent the system from trading again on that same bar.

                            Now, on the next bar, everything is open again for another trade and for another stochastics cross.

                            As far as CPU usage. I have 4 scripts running on a 2.4 Ghz Pentium machine with 512 MB ram and the CPU usage is normally less than 7% - in most cases 2% to 4%. So this should be a very save way to execute trading actions.

                            The other benefit is that this code will run and execute stop orders, entry orders, and test for conditions in RT. The time stamps provide for a method of preventing the code from "flipping" based on the conditional "if" statements in the code. For example...

                            Lets say the stochastics were hovering at about the same value. Up ticks may cause if to report a bullish cross, then down ticks could cause it to negate this cross. With my code, the cross action would be recorded and action could be taken based on this condition.

                            Another feature that could be added to this code would be a Stochastics Range. Let's say we wanted to only enter a trade if all of the conditions were true and the StoFAST value was above or below the StoSLOW value by more than 2.50 pts. We would simply add the condition to the trade entry conditions - like this...

                            PHP Code:
                            var Study = new StochStudy(1473);
                            var 
                            MAStudy = new MAStudy(120"close"MAStudy.SIMPLE);
                            var 
                            nlaststocrosstime 0;
                            var 
                            nstocrosstrend 0// 0 = neutral, 1 = bullish, 2 = bearish
                            var nlasttradetime 0;
                            var 
                            StrategyisInTrade false;
                            var 
                            StrategyisShort false;
                            var 
                            StrategyisLong false;
                            var 
                            nstopprice 0;
                            var 
                            vFast 0;
                            var 
                            vSlow 0;
                            var 
                            vLastFast 0;
                            var 
                            vLastSlow 0;

                            // user defined StoRange
                            var StoRange 2.50;

                            function 
                            main(){

                            //  Get the current values of the Stochastic indicator
                            vFast Study.getValue(StochStudy.FAST);
                            vSlow Study.getValue(StochStudy.SLOW);
                            //  Get the previous values of the Stochastic indicator
                            vLastFast Study.getValue(StochStudy.FAST, -1);
                            vLastSlow Study.getValue(StochStudy.SLOW, -1);
                            //  Get the current and previous values of the Moving Average
                            maNow Study.getValue(MAStudy.MA);
                            lastMA Study.getValue(MAStudy.MA, -1);

                            if (
                            getCurrentBarIndex() == 0) {

                            //  Test for Stochastic Cross.  This function allows for only one completed action per bar using a timestamp.
                            if ((vFast >= vSlow) && (vLastFast vLastSlow) && (nlaststocrosstime != getValue("rawtime"0)) ) {
                               
                            nstocrosstrend 1;  // bullish cross
                               
                            nlaststocrosstime getValue("rawtime",0);
                            }
                            if ((
                            vFast <= vSlow) && (vLastFast vLastSlow) && (nlaststocrosstime != getValue("rawtime"0)) ) {
                               
                            nstocrosstrend = -1;  // bullish cross
                               
                            nlaststocrosstime getValue("rawtime",0);
                            }

                            //  Test for trade entry conditions....
                              
                            if ((getValue("rawtime",0) != nlasttradetime) && (within_time_restrictions) && StrategyisInTrade == false) {
                              
                            // time is different than last trade time... so execute trades...
                                
                            if ((nstocrosstrend == 1) && (high() > high(-1)) && (close() > close(-1)) && (maNow lastMA) && ((vFast-vSlow) >= StoRange) ) {
                                 ....
                                 
                            StrategyisInTrade true;
                                 
                            StrategyisShort false;
                                 
                            StrategyisLong true;
                                 
                            nstopprice low();
                                 
                            nlasttradetime getValue("rawtime",0);
                                }
                                if ((
                            nstocrosstrend == -1) && (low() < low(-1)) && (close() < close(-1)) && (maNow lastMA) && ((vFast-vSlow) <= (0-StoRange)) ) {
                                 ....
                                 
                            StrategyisInTrade true;
                                 
                            StrategyisShort true;
                                 
                            StrategyisLong false;
                                 
                            nstopprice high();
                                 
                            nlasttradetime getValue("rawtime",0);
                                }
                              }

                              
                            // Test for Stops...
                              
                            if (StrategyisInTrade == true) {
                                if ((
                            StrategyisShort == true) && (close() >= nstopprice)) {
                                   .....
                                   
                            StrategyisInTrade false;
                                   
                            StrategyisShort false;
                                   
                            StrategyisLong false;
                                   .....
                                }
                                if ((
                            StrategyisLong == true) && (close() <= nstopprice)) {
                                   .....
                                   
                            StrategyisInTrade false;
                                   
                            StrategyisShort false;
                                   
                            StrategyisLong false;
                                   .....
                                }
                              }
                              
                            //  end if getcurrentbarindex == 0

                            //  end of main() 
                            This change to the code (one new variable and two additions to our conditional trade entry "if" statements) would wait for the stochastics indicator to cross and move into a positive or negative range of greater than or equal to 2.50 points.

                            I hope these examples have helped some of you to figure out how I use this feature. It is really cool...

                            Brad
                            Brad Matheny
                            eSignal Solution Provider since 2000

                            Comment


                            • #15
                              David,

                              It will let you take a trade for any specific tick, without having to wait for a newbar, but will also make sure that multiple ticks at the same price point don't multi-trigger your conditions (unless they happen within the same second - which is the smallest granularity of a timestamp). So to reall be careful you should still encapsulate any critical code with more protection.

                              They also have a side benefit for some applications of being able to timestamp your trades (say if you are dumping the trade information to a file).

                              Again, for most formula's I think this methods complexity doesn't make it the best choice. But everyone has different styles...
                              Garth

                              Comment

                              Working...
                              X