stevehopwoodforex.com
https://www.stevehopwoodforex.com/phpBB3/
Print view

Utility Procedures / Code Snippets
https://www.stevehopwoodforex.com/phpBB3/viewtopic.php?t=166
Page 1 of 7
Author:  gaheitman [ Sun Dec 18, 2011 6:55 am ]
Post subject:  Utility Procedures / Code Snippets

Here's a place to publish procedures, code snippets, or especially clever one-liners ( :D ) that you'd like to share with your fellow coders. Some of what goes here will likely make it into the Shell EA code, but even if it doesn't it will make it to all of our individual toolboxes.

One thing to keep in mind, if you post it here, expect to see "Why did you...", "You should have...", "Hey, it's easier if you..." kinds of posts. I expect to get more than my share "But why would you want to do that in the first place?" posts.

On to the code....
Author:  gaheitman [ Sun Dec 18, 2011 7:18 am ]
Post subject:  Dependency Checker

While reading through the Co-integration thread I decided to code a function to check to see if the rterm.exe file was where the user said it was. I did that, let it sit for a while, and then decided to put together a generic dependency checker.

I tell you that, so you know why I decided to implement one of the procedures the way I did.

First, the API imports:

Code: Select all

#import "kernel32.dll"
int GetFileAttributesA (string lpFileNameW);
#import
The Windows API function GetFileAttributes() is an easy way to see if a file exists. It returns -1 if it can't find the file.

Code: Select all

#import "shell32.dll"
int ShellExecuteA(int hWnd,int lpVerb,string lpFile,int lpParameters,int lpDirectory,int nCmdShow);
#import
ShellExecute() allows us to launch applications. Why would we want to do that to check dependencies? This allows us to give the user the opportunity to return to the forum to download the missing file.

Now the functions:

Code: Select all

bool FileExists(string FilePath) {
   return(GetFileAttributesA(FilePath) != -1);
}
FileExists() simply checks the result of GetFileAttributesA() and makes sure they aren't -1.

Code: Select all

bool CheckDependency(string filename,string URL) {
   if (!FileExists("./experts/indicators/"+filename)) {
      if (MessageBox("Indicator "+filename+" not found.  Would you like to return to the forum to download the file?","File Not Found",MB_YESNO|MB_ICONQUESTION) == IDYES)
         ShellExecuteA(0,0,URL,0,0,1);
      return(false);
   }//if (!FileExists("./experts/indicators/"+filename)) 
   return(true);  
}
The function CheckDependency() looks for the specified file in the indicators directory. I suspect I should rewrite it so that you have to pass the full path of what you want to look for, or perhaps the type of file you are looking for so it can look for DLLs as well.

Notice the path starts with "." (period). For those of you who didn't start your life in MS-DOS, the "." stands for the current directory. This saves us from having to know the full install path of Empty4.

If the file check fails, the user will get a popup dialog stating they are missing a file and suggesting they return to the forum to get it. The code works on my machine to open up a browse window to the forum thread, I'm curious if it works for others. Here's the notification dialog:
pic_01 2011-12-18 02.12.gif
Finally, the main procedure. This is the example I plan on adding to the Engulfing reversal bars EA.

Code: Select all

bool CheckAllDependencies() {

   bool dependencies=true;

   if (UseAA)
      dependencies = dependencies && CheckDependency("AllAverages_v2.1 cc.ex4","http://www.stevehopwoodforex.com/phpBB3/viewtopic.php?f=5&t=158");
   
   dependencies = dependencies && CheckDependency("FFCalH.ex4","http://www.stevehopwoodforex.com/phpBB3/viewtopic.php?f=5&t=158");
   return(dependencies);

}
I plan on calling CheckAllDependencies() in Init() and setting a global variable that will keep start() from doing anything if the files aren't there. It's not critical for this EA, but I imagine there are others that might be more dependent on external files.

Thoughts? Questions?

UPDATE: I added a script to test. It will check for ffcalh and a fake file that it won't find. If you choose "Yes" it should bring you to this post.

George
Author:  youcrazykids [ Mon Dec 19, 2011 1:44 am ]
Post subject:  Oscillator in main chart window

Hi all

This'll turn out to be a cracking little thread, methinks.

Here's a little code snippet, which displays an oscillator in the main chart window, instead of a separate window. When adding indicators which usually exist in separate windows, the chart soon becomes compressed, which I don't like. So, had a play around and came up with this. Maybe it's been thought of before, and if so, my apologies!

I've used the Stochastic oscillator as an example. It could easily be edited to display RSI, CCI, or most indicators with definable limits. The routine is far from finished, so if anyone has any suggestions, I'd gladly try to ammend/adapt/improve the code.

untitled.JPG

Code: Select all

int init(){ //This section contains code which executes only on startup

	//This paints level lines on the chart, at a percentage of the chart range. I have chosen 20% and 80%.
	double WindowPriceRange=WindowPriceMax()-WindowPriceMin();
	ObjectCreate("_Level1",OBJ_HLINE,0,Time[0],WindowPriceMin()+WindowPriceRange*0.2); ObjectSet("_Level1",OBJPROP_COLOR,Yellow); ObjectSet("_Level1",OBJPROP_STYLE,STYLE_SOLID);
	ObjectCreate("_Level2",OBJ_HLINE,0,Time[0],WindowPriceMin()+WindowPriceRange*0.8); ObjectSet("_Level2",OBJPROP_COLOR,Yellow); ObjectSet("_Level2",OBJPROP_STYLE,STYLE_SOLID);

} // End of init routine

//-------------------------------------------------------------------------------------------------------------------------------

int start(){

	// This routine paints a 0-100 stochastic oscillator on the main chart, instead of creating a separate chart window.
	
	double WindowPriceRange=WindowPriceMax()-WindowPriceMin(); // Determine the range of the chart window
	double Indicator1PricePos, Indicator1PricePosPrev, Indicator2PricePos, Indicator2PricePosPrev;
	ObjectMove("_Level1",0,Time[0],WindowPriceMin()+WindowPriceRange*0.2); // Move the level lines if the chart is zoomed, etc.
	ObjectMove("_Level2",0,Time[0],WindowPriceMin()+WindowPriceRange*0.8); // Move the level lines if the chart is zoomed, etc.
	
	int c; // define a counting variable for a loop
	while (c<Bars) // define the limits of the loop
	{
	Indicator1PricePos=(WindowPriceMin()+((iStochastic(NULL,0,14,3,7,MODE_SMA,0,MODE_MAIN,c)/100)*WindowPriceRange));
	Indicator1PricePosPrev=(WindowPriceMin()+((iStochastic(NULL,0,14,3,7,MODE_SMA,0,MODE_MAIN,c+1)/100)*WindowPriceRange));
	Indicator2PricePos=(WindowPriceMin()+((iStochastic(NULL,0,14,3,7,MODE_SMA,0,MODE_SIGNAL,c)/100)*WindowPriceRange));
	Indicator2PricePosPrev=(WindowPriceMin()+((iStochastic(NULL,0,14,3,7,MODE_SMA,0,MODE_SIGNAL,c+1)/100)*WindowPriceRange));
	ObjectCreate("_Indicator1"+c,OBJ_TREND,0,Time[c],Low[c]); ObjectSet("_Indicator1"+c,OBJPROP_PRICE1,Indicator1PricePosPrev); ObjectSet("_Indicator1"+c,OBJPROP_PRICE2,Indicator1PricePos); ObjectSet("_Indicator1"+c,OBJPROP_TIME1,Time[c+1]); ObjectSet("_Indicator1"+c,OBJPROP_TIME2,Time[c]); ObjectSet("_Indicator1"+c,OBJPROP_RAY,0); ObjectSet("_Indicator1"+c,OBJPROP_COLOR,DodgerBlue); ObjectSet("_Indicator1"+c,OBJPROP_WIDTH,1); ObjectSet("_Indicator1"+c,OBJPROP_BACK,1);
	ObjectCreate("_Indicator2"+c,OBJ_TREND,0,Time[c],Low[c]); ObjectSet("_Indicator2"+c,OBJPROP_PRICE1,Indicator2PricePosPrev); ObjectSet("_Indicator2"+c,OBJPROP_PRICE2,Indicator2PricePos); ObjectSet("_Indicator2"+c,OBJPROP_TIME1,Time[c+1]); ObjectSet("_Indicator2"+c,OBJPROP_TIME2,Time[c]); ObjectSet("_Indicator2"+c,OBJPROP_RAY,0); ObjectSet("_Indicator2"+c,OBJPROP_COLOR,Blue); ObjectSet("_Indicator2"+c,OBJPROP_WIDTH,1); ObjectSet("_Indicator2"+c,OBJPROP_BACK,1);
	c++;
	} // End of this loop

} // End of start routine

//-------------------------------------------------------------------------------------------------------------------------------

int deinit(){ //This section contains code which executes only on shutdown of the EA. Things like deleting drawing objects, etc.
	ObjectsDeleteAll();
} // End of deinit routine
The code operates as follows:
- On startup, two horizontal lines are painted onto the chart window. These are user-definable limit lines, for visual purposes.
- If the chart moves or is zoomed in/out, these lines will adjust their position relative to the window. So, providing there are sufficient incoming ticks, these lines will rearrange themselves.
- A loop calculates the stochastic main and signal lines for each particular bar, and paints them onto the chart, joining them up with the values for the previous bar.

That's about it, really! I hope someone finds it useful.

Cheers

youcrazykids

[/size]
Author:  gaheitman [ Mon Dec 19, 2011 7:40 am ]
Post subject:  Re: Oscillator in main chart window

youcrazykids wrote: Here's a little code snippet, which displays an oscillator in the main chart window, instead of a separate window. When adding indicators which usually exist in separate windows, the chart soon becomes compressed, which I don't like. So, had a play around and came up with this. Maybe it's been thought of before, and if so, my apologies!

- A loop calculates the stochastic main and signal lines for each particular bar, and paints them onto the chart, joining them up with the values for the previous bar.
Nice! Have you tried to use WindowBarsPerChart() and WindowFirstVisibleBar() to get it to only calculate/draw the current screen? As it is now, I think it recalculates everything on each tick. You might be able to use IndicatorCounted() and just update on new bars and whenever WindowPriceMax/Min changes.

George
Author:  AnotherBrian [ Tue Dec 20, 2011 3:23 pm ]
Post subject:  Prettify / Beautify / format your MQ4 code

After writing some code for what I thought would be a small program, turned out to be many lines of confusion because I didn't pay much attention to formatting. So I consulted Google to find a way to automatically format the code for me. I found jEdit to be very easy, and free.

jEdit DOWNLOAD

After you install it and have it running, go to the menu "Plugins" and turn on the Astsyle plugin.
Copy and rename your MQ4 file to a cpp extension and load it into jEdit. Changing the file extension tells jEdit how to format it and what words to highlight/colour. There's probably a setting in jEdit where you can add the MQ4 extension but I didn't look for it.
Go to the same menu and select the plugin and your code will be formatted.
Save it and change the extension back to MQ4, so Empty4 can read it.

I didn't see a formatter in the Empty4 editor, am I missing something here? :oops:
Is there an easier way to automatically format your code? If so, I'd like to know what it is!! :idea:
Author:  magft [ Tue Dec 20, 2011 5:01 pm ]
Post subject:  Re: Prettify / Beautify / format your MQ4 code

AnotherBrian wrote:After writing some code for what I thought would be a small program, turned out to be many lines of confusion because I didn't pay much attention to formatting. So I consulted Google to find a way to automatically format the code for me. I found jEdit to be very easy, and free.

jEdit DOWNLOAD

After you install it and have it running, go to the menu "Plugins" and turn on the Astsyle plugin.
Copy and rename your MQ4 file to a cpp extension and load it into jEdit. Changing the file extension tells jEdit how to format it and what words to highlight/colour. There's probably a setting in jEdit where you can add the MQ4 extension but I didn't look for it.
Go to the same menu and select the plugin and your code will be formatted.
Save it and change the extension back to MQ4, so Empty4 can read it.

I didn't see a formatter in the Empty4 editor, am I missing something here? :oops:
Is there an easier way to automatically format your code? If so, I'd like to know what it is!! :idea:
gspe from FF sent me settings for jedit to allow proper editing the only thing i couldn't get to work was the compiling part so still have to switch back over to the editor. I'll dig out the settings and post them if you want but if you search FF for jedit you should find the thread.

Mike
Author:  magft [ Tue Dec 20, 2011 5:08 pm ]
Post subject:  Re: Utility Procedures / Code Snippets

Just been playing around with the CoInt EA by Mediator streamling some of the code, as had old code from 7-bit's arb-o-mat, and my version kept hogging 50% cpu. So after doing this editing i found i got it down to 8-16%! Turns out though that my account analyser indicator was causing alot of the cpu usage. It is viusally nice but obviously not useful in the long run as it is so i have extracted the max floating DD bit and put into the EA, as this is the main useful bit i look at!

Anyway, here is the code that creates global variables with the info in if you want to use it in other EAs.

Code: Select all

//Declare Variables
double Drawdown,WorstDrawdown,GDrawdownTime,PercentDD,MaxPercentDD;
string GMaxDrawdown,DrawdownTime,GMaxPercentDD;

int init(){
   //DD GVs
   GMaxDrawdown=AccountNumber()+"_MaxDrawdown";
   if (!GlobalVariableCheck(GMaxDrawdown)) GlobalVariableSet(GMaxDrawdown,0);
   GMaxPercentDD=AccountNumber()+"_GMaxPercentDD";
   if (!GlobalVariableCheck(GMaxPercentDD)) GlobalVariableSet(GMaxPercentDD,0);
   DrawdownTime=AccountNumber()+"_DrawdownTime";
   if (!GlobalVariableCheck(DrawdownTime)) GlobalVariableSet(DrawdownTime,0);
}

int start(){
   //update DD GVs
   WorstDrawdown=GlobalVariableGet(GMaxDrawdown);
   GDrawdownTime=GlobalVariableGet(DrawdownTime);  
   MaxPercentDD=GlobalVariableGet(GMaxPercentDD);
   Drawdown=AccountEquity()-AccountBalance();
   if (Drawdown<WorstDrawdown)
   {
      WorstDrawdown=Drawdown;
      GDrawdownTime=CurTime();
      GlobalVariableSet(GMaxDrawdown,WorstDrawdown);
      GlobalVariableSet(DrawdownTime,GDrawdownTime);
   }
   PercentDD=(MathAbs(WorstDrawdown)/AccountBalance())*100; 
   if (PercentDD>MaxPercentDD)
   {
      MaxPercentDD=PercentDD;
      GlobalVariableSet(GMaxPercentDD,MaxPercentDD);
   }
}

int deinit(){
   //if you want to delete on exit uncomment
   //GlobalVariableDel(GMaxDrawdown);
   //GlobalVariableDel(DrawdownTime);
   //GlobalVariableDel(GMaxPercentDD);
}
Author:  AnotherBrian [ Wed Dec 21, 2011 12:07 am ]
Post subject:  Re: Prettify / Beautify / format your MQ4 code

[/quote]

gspe from FF sent me settings for jedit to allow proper editing the only thing i couldn't get to work was the compiling part so still have to switch back over to the editor. I'll dig out the settings and post them if you want but if you search FF for jedit you should find the thread.

Mike[/quote]

Hi Mike

I found the link, is it as simple as putting the xml file in the same directory as all the other xml files in the jEdit directory? I tried that and doesn't work, no highlights.... Can you save me hours of reading the manual?

http://fx-engineering.blogspot.com/2011/01/jedit.html
Author:  gaheitman [ Wed Dec 21, 2011 11:04 am ]
Post subject:  Re: Prettify / Beautify / format your MQ4 code

AnotherBrian wrote: Hi Mike

I found the link, is it as simple as putting the xml file in the same directory as all the other xml files in the jEdit directory? I tried that and doesn't work, no highlights.... Can you save me hours of reading the manual?

http://fx-engineering.blogspot.com/2011/01/jedit.html
I've just started looking at AStyle. (http://astyle.sourceforge.net/) It's command line only, but seems to work fairly well and has plenty of options. I use the command line options "-A2 -s3 -f --mode=c", though I'm not sure I really need the "-f".

George
Author:  markft [ Sun Dec 25, 2011 4:06 pm ]
Post subject:  Re: Prettify / Beautify / format your MQ4 code

gaheitman wrote: I've just started looking at AStyle. (http://astyle.sourceforge.net/) It's command line only, but seems to work fairly well and has plenty of options. I use the command line options "-A2 -s3 -f --mode=c", though I'm not sure I really need the "-f".
George
I have started using UniversalIndentGUI (http://universalindent.sourceforge.net/). This is a GUI wrapper around a number of command line indenter including astyle. The killer function is it lets you preview the result e.g. similar to eclipse. It can then generate a .astylerc and a .bat file that contains your settings so you can copy the batch file to the experts directory on your Empty4 platforms and run it for each of them. My .astylerc settings are:

-y
--break-elseifs
--pad=oper
--pad=paren-in
--style=ansi
--brackets=break
All times are UTC Page 1 of 7