Utility Procedures / Code Snippets

Post Reply
AnotherBrian

OnTimer() or start()

Post by AnotherBrian »

I've started to use the OnTimer() instead of start().

I do this because running my EA only needs to happen once in a while. For example - placing pending orders once a day. I set it to run once every minute. The problem is that OnTimer() doesn't run in Strategy Tester so you cant check code execution. Here is how I solved that.

All comments welcome, trying to improve and understand.

Code: Select all

int TimeBetweenExecutions=60;
int init()
  {
   if(TimeBetweenExecutions<3)TimeBetweenExecutions=3;
   EventSetTimer(TimeBetweenExecutions);//runs EA every x seconds
   return(0);
  }
int deinit()
  {
   EventKillTimer();
   return(0);
  }
int start()//only used when testing
  {
   if(IsTesting())Main();
   return(0);
  }
void OnTimer()
  {
   Main();
  }
void Main()
  {
  //all the code goes here
  }
User avatar
renexxxx
Trader
Posts: 860
Joined: Sat Dec 31, 2011 3:48 am

OnTimer() or start()

Post by renexxxx »

AnotherBrian » Thu Sep 17, 2015 11:28 am wrote: All comments welcome, trying to improve and understand.
Hi Brian,

That code is fine, as long as you understand that in the tester, Main() is called for every tick, whereas, when the EA is run in a normal forward test, Main() is only called every x-seconds.
You could do something like this in start()

Code: Select all

int start()//only used when testing
  {
   static datetime nextRun = -1;   
   if(IsTesting() && (nextRun < TimeCurrent()) ) {
      Main();
      nextRun = TimeCurrent() + TimeBetweenExecutions;
   }
   return(0);
  }
AnotherBrian

Utility Procedures / Code Snippets

Post by AnotherBrian »

Thanks Renexxxx;
Yes, I understand that.
Your mod is interesting, that would make that backtester behave more like a forward test (even though backtesting is crap, the goal is simply to check the execution).
Thanks Renexxxx, once again, your a code god.
Hope this helps other coders.
DigitalCrypto
Trader
Posts: 237
Joined: Tue Feb 24, 2015 4:38 am

Utility Procedures / Code Snippets

Post by DigitalCrypto »

Edit: Didn't include right code or pic. Is now fixed for $1 pip example given.


One thing I almost always forget to do is price the pips correctly when looking to enter a position.
This is a snippet of code you can use to determine what the minimum pip value should be to return 1:1 per pip movement.

$1 Pips is the minimum position size you should use to enter the position for a $1USD (or your base currency) per pip return.

In this example ATC Brokers minimum lot size is 0.05. So in order to see a 1:1 return per dollar we simply double the minlot cost to 0.14 and multiply by the intended dollar return we would like to have per pip.

Maybe someone has better math than I do. I always round up. Nothing like a little freebie here and there! :smile:

Code: Select all


int start()
  {
   //----

   string   Text="";
   
   double PipValue = DoubleToStr(MarketInfo(Symbol(), MODE_TICKVALUE),2);
   double Minlot   = DoubleToStr(MarketInfo(Symbol(), MODE_MINLOT),2);
   double ThisLot  = DoubleToStr(((100/PipValue*Minlot)/100),2);
   
   Text =   "Pip/Tick Value = " + DoubleToStr(PipValue,2) +
    	      "\n"+
 	         "Spread = " + DoubleToStr(MarketInfo(Symbol(), MODE_SPREAD), 0) +
 	         "\n"+
 	         "Min Lot = " + DoubleToString(Minlot,2) +
 	         "\n"+
 	         "Min Lot Cost = " + DoubleToStr(ThisLot,2) +
 	         "\n"+
 	         "$1 Pips = " + DoubleToStr(ThisLot*2,2);

   Comment(Text);

   return(0);
  }
You do not have the required permissions to view the files attached to this post.
DigitalCrypto
Trader
Posts: 237
Joined: Tue Feb 24, 2015 4:38 am

Fix FXCM's Broken Ask Line

Post by DigitalCrypto »

FXCM's Empty4 Terminal still reflects their old pricing models. They said it cannot be fixed for standard accounts because customers around the world are still using the old price models but have worked around the problem by using Market watch Bid/Ask. However when enabling the Ask line on the platform it does not reflect this change. So here's a quick fix for anyone else that may have this issue.

First turn off the Ask line in the console properties then we can add the following code to our experts and indicators

Make it user selectable

Code: Select all

extern string fix99 ="===================================================================";
extern string fxcmask            ="---Fix FXCM's Ask Line---";
extern bool   FixFXCMAsk         =true;
extern color  askcolour          =Purple;  //DXH Whatever color you like best
Next create a new moveable ask line.

Code: Select all

void DrawAskLine() // DXH Added to display correct Ask line on FXCM Empty4
{
   ObjectCreate(ChartID(),"AskLine",OBJ_HLINE,0,iTime(Symbol(),0,0),Ask,askcolour);
   ObjectSetInteger(ChartID(),"AskLine",OBJPROP_COLOR,askcolour);
   ObjectMove(0,"AskLine",0,iTime(Symbol(),0,0),Ask);

}// void DrawAskLine()
Lastly called via OnTick()

Code: Select all

if(FixFXCMAsk)DrawAskLine(); //DXH Fixed FXCMs Broken Ask Line
And the gratuitous screen shot of the fix in action
You do not have the required permissions to view the files attached to this post.
AnotherBrian

Utility Procedures / Code Snippets

Post by AnotherBrian »

If you want the chart set up a certain way when the EA starts, put this code in, and adjust to your needs.

The following give you a blank chart with yellow foreground. No time or price, no grids, no price.
I use this for a multi-pair so I want a blank screen.

I just discovered this a week ago...

Code: Select all

void ChartSetup()
  {
   ChartSetInteger(0,CHART_MODE,CHART_LINE);
   ChartSetInteger(0,CHART_COLOR_BACKGROUND,Black);
   ChartSetInteger(0,CHART_COLOR_FOREGROUND,Yellow);
   ChartSetInteger(0,CHART_SHOW_GRID,0);
   ChartSetInteger(0,CHART_FOREGROUND,0);
   ChartSetInteger(0,CHART_SHOW_BID_LINE,0);
   ChartSetInteger(0,CHART_SHOW_OHLC,0);
   ChartSetInteger(0,CHART_SHOW_PERIOD_SEP,0);
   ChartSetInteger(0,CHART_SHOW_ASK_LINE,0);
   ChartSetInteger(0,CHART_SHOW_VOLUMES,0);
   ChartSetInteger(0,CHART_SHOW_OBJECT_DESCR,0);
   ChartSetInteger(0,CHART_SHOW_TRADE_LEVELS,0);
   ChartSetInteger(0,CHART_SHOW_DATE_SCALE,0);
   ChartSetInteger(0,CHART_SHOW_PRICE_SCALE,0);
   ChartSetInteger(0,CHART_COLOR_GRID,clrNONE);
   ChartSetInteger(0,CHART_COLOR_VOLUME,clrNONE);
   ChartSetInteger(0,CHART_COLOR_CHART_UP,clrNONE);
   ChartSetInteger(0,CHART_COLOR_CHART_DOWN,clrNONE);
   ChartSetInteger(0,CHART_COLOR_CHART_LINE,clrNONE);
   ChartSetInteger(0,CHART_COLOR_CANDLE_BULL,clrNONE);
   ChartSetInteger(0,CHART_COLOR_CANDLE_BEAR,clrNONE);
   ChartSetInteger(0,CHART_COLOR_BID,clrNONE);
   ChartSetInteger(0,CHART_COLOR_ASK,clrNONE);
   ChartSetInteger(0,CHART_COLOR_LAST,clrNONE);
   ChartSetInteger(0,CHART_COLOR_STOP_LEVEL,clrNONE);
   ChartSetInteger(0,CHART_SHOW_LAST_LINE,0);
  }
DigitalCrypto
Trader
Posts: 237
Joined: Tue Feb 24, 2015 4:38 am

Utility Procedures / Code Snippets

Post by DigitalCrypto »

A friend turned me on to a nice coding font called Inconsolata. Give it a try and see what you think.

Since I am bad with remembering names a bit of word association got me to thinking about "in console latte". Yeah it's smooth like that...

It also gives EA HUDs and Indicators a smoother more professional look IMHO.

Main site with GitHub link
http://levien.com/type/myfonts/inconsolata.html
You do not have the required permissions to view the files attached to this post.
DigitalCrypto
Trader
Posts: 237
Joined: Tue Feb 24, 2015 4:38 am

Common function shortcuts to speed up coding

Post by DigitalCrypto »

I think if I type any more long MQL functions I will go nuts. Here's a more efficient way if you want shortcuts.

I started creating small functions to abbreviate all that crap because I don't really want carpal tunnel syndrome again. I may throw it all into an include file for later or just tag it at the bottom of the scripts.

Code: Select all

//NormalizeDouble(Double value,Int digits);
double ND(double Value, int Precision){return(NormalizeDouble(Value,Precision));}

Example:
AverageSpread = ND(SpreadTotal/counter,1);


//DoubleToStr(Double value, Int Digits)
string DTS(double Value, int Precision){return{DoubleToStr(Value,Precision));}

Example:
SM("Calculating the average spread. " + DTS(left,0)+" left to count.");

DigitalCrypto
Trader
Posts: 237
Joined: Tue Feb 24, 2015 4:38 am

Utility Procedures / Code Snippets

Post by DigitalCrypto »

I've grown really accustomed to the onscreen hud display. I use it for everything. Of course when I am running many charts on the same terminal it's hard to put everything I need to see in a small place. I ventured out to see what I could do about it and wanted to contribute a small piece of code that I implemented for Trading Timeframe and Trading Directions so they use only a single line on the screen.

Concept
=======
First test long or short are true to remind me that I may be in operating ID10T mode
If pass then display TradingTimeframe and Trading Direction(s)

Code: Select all

if (!TradeLong && !TradeShort) {SM("TRADELONG & TRADESHORT ARE FALSE!" + NL);}
   else {
      string TradeLongDirection="", TradeShortDirection="", TradeDirection="";
      if (TradeLong) TradeLongDirection = " Longs"; if (TradeShort) TradeShortDirection = " Shorts";
      if (TradeLong && TradeShort) {TradeDirection = "Trading Longs & Shorts";}else{TradeDirection = "Trading: " + TradeLongDirection + TradeShortDirection;}
      SM ("TTF:" + TradingTimeFrameDisplay + " " + TradeDirection); 
   }  
Hope this helps anyone else

- David
DigitalCrypto
Trader
Posts: 237
Joined: Tue Feb 24, 2015 4:38 am

Finding the trend

Post by DigitalCrypto »

Here's a function I wrote to determine a market trend using a higher timeframe without relying on any indicators.

Code: Select all


bool TrendUp = False, TrendDown = False;
ENUM_TIMEFRAMES TRENDTIMEFRAME = PERIOD_H4;

OnInit()
{
    //Don't assume trend direction until it's calculated
    TrendUp = False;
    TrendDown = False;
}

void FindTrend()
{
   //+------------------------------------------------------------------+
   //|   Trends are determined by momentum closes.  Any time price      |
   //|   has closed higher than the previous high or lower than the     |
   //|   previous low on the TRENDTIMEFRAME we want to take trades on   |
   //|   the lower TRADINGTIMEFRAME in that direction ONLY!             |
   //+------------------------------------------------------------------+
   
   //Static types  
   int i, LastUp, LastDown;
   
   //If there is no trend direction we need to find it
   if (!TrendUp && !TrendDown)
      { 
         //Find Highest TRENDTIMEFRAME Close
         i = 0;
         LastUp = 0;
         while(i < 20)
         {
            if(iClose(Symbol(), TRENDTIMEFRAME, i) > iHigh(Symbol(), TRENDTIMEFRAME, i+1))
               {
                  LastUp = i;   
                  break;
               }
            i++;
         }//while(i < 20)
         
         //Find Lowest TRENDTIMEFRAME Close
         i = 0;
         LastDown = 0;
         while(i < 20)
         {
            if(iClose(Symbol(), TRENDTIMEFRAME, i) < iLow(Symbol(), TRENDTIMEFRAME, i+1))
               {
                  LastDown = i;   
                  break;
               }
            i++;
         }//while(i < 20)
         
         //Determine which is more recent and set trend direction
         if (LastUp < LastDown)      TrendUp    = True;
         else if (LastDown < LastUp) TrendDown  = True; 
         
      }//if (!TrendUp && !TrendDown)
      
   //Check if we had a prior trend direction and keep it. Id est "inside bars"
   if (TrendUp)
      if(iClose(Symbol(), TRENDTIMEFRAME, 1) < iHigh(Symbol(), TRENDTIMEFRAME,2))
         if(iClose(Symbol(), TRENDTIMEFRAME, 1) > iLow(Symbol(), TRENDTIMEFRAME, 2))
            TrendUp = True;
   
   if (TrendDown)
      if(iClose(Symbol(), TRENDTIMEFRAME, 1) > iLow(Symbol(), TRENDTIMEFRAME, 2))
         if(iClose(Symbol(), TRENDTIMEFRAME, 1) < iHigh(Symbol(), TRENDTIMEFRAME,2))
            TrendDown = True;

return;
}//void FindTrend()
Post Reply

Return to “Coders Hangout”