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

Utility Procedures / Code Snippets
https://www.stevehopwoodforex.com/phpBB3/viewtopic.php?t=166
Page 5 of 7
Author:  snailbeard [ Fri Jul 26, 2013 12:44 pm ]
Post subject:  Re: Utility Procedures / Code Snippets

IKVM.NET
http://www.ikvm.net/

Came a cross a tool for creating a DLL from Java jar.

The plan is to write all (well 90%) of future code in say Java and or perhaps C# and then produce a DLL.

I have not tried this tool yet but it looks interesting and the Java versus c#/.Net depends on what exists in C# and Java already to avoid reinventing the wheel.
Author:  snailbeard [ Wed Aug 28, 2013 3:27 pm ]
Post subject:  Re: Utility Procedures / Code Snippets

Pesky Alerts

Don't want to use the once only option?

Some simple functions for having more control over the frequency of some Alerts (if running on a faster time frame such as M1) or if your loop is processed on every tick:

(the code is running and nolonger producing an alert every tick - but can't be sure that Alerts will come back again until... )

Code: Select all

#define GAPBETWEENENTRYALERTS 3600
datetime  aPairEntryAlertGiven[MAXPAIRS] = {0};

//-----------------------------------
// getSecondsSinceEntryAlert
//-----------------------------------
int getSecondsSinceEntryAlert(int iPairIndex)
{
	datetime dtNow = TimeCurrent();

	return(dtNow - aPairEntryAlertGiven[iPairIndex]);
}
//-----------------------------------
// setEntryAlertTimeNow
//-----------------------------------
void setEntryAlertTimeNow(int iPairIndex)
{
	aPairEntryAlertGiven[iPairIndex] = TimeCurrent();
}
//-----------------------------------
// clearEntryAlertTimeNow
//-----------------------------------
void clearEntryAlertTime(int iPairIndex)
{
	aPairEntryAlertGiven[iPairIndex] = 0;
}

//-----------------------------------
// doTimedEntryAlert
//-----------------------------------
void doTimedEntryAlert (int iPairIndex, string& strAlert )
{
	datetime dtNow = TimeCurrent();
	if( (dtNow - aPairEntryAlertGiven[iPairIndex]) < GAPBETWEENENTRYALERTS )
		return;
		
	setEntryAlertTimeNow(iPairIndex);
	Alert(strAlert);
}

Author:  AnotherBrian [ Wed Aug 28, 2013 5:16 pm ]
Post subject:  Re: Utility Procedures / Code Snippets

KevinT wrote:
Durante wrote:

Code: Select all

//#property show_inputs
Not exactly sure what you mean but if you have something like this near the top of your script you could delete it
Thanks Durante,

Commenting out #property show_inputs, nailed it for the scripts :D

As for the EAs (at least some SH eas ;)) other method of calling the dialog box must have been used! :cry:
For an EA, look at the top and remove the words "extern" - extern means external input from the user.
looks like this
extern int risk;
extern bool useMA;

You can set up the values right inside the code and remove the extern - this is called "hard coding"
I use it for my EA's that I run so I don't occidentally change anything. I don't like to use set files.
Author:  atharmian [ Sun Oct 13, 2013 5:15 am ]
Post subject:  Re: Utility Procedures / Code Snippets

babalu4u,

Looks very cool for a newbie like me.

1. Will this create additional n buffers if put in a loop , for j= 1...n ?

2. So is #1 then useful in writing MTF indis, where my problem is that if I modify a single TF indi so it creates multiple TF instances in same window, the buffer overwrite causes only the last chart TF to be displayed?

The alternative solution I am trying is to use, say, buffer arrUSD modified to arrUSD [i +j*maxBars] where maxBars is the number of displayed bars in any TF. j will be the loop defining TFs.

Regards,
Athar.

babalu4u wrote:Function to add extra buffer in indicator....

Code: Select all

double tableau1[];
double tableau2[];
:
int start()
  {
     if (!ResizeBuffer(tableau1, Bars)) return;
     if (!ResizeBuffer(tableau2, Bars)) return;
:
///////////////////////////////////////////////////////////////////////////////
bool    ResizeBuffer(double& buffer[], int size){
    if (ArraySize(buffer) != size){
        ArraySetAsSeries(buffer, false);    // Shift values B[2]=B[1]; B[1]=B[0]
        if (ArrayResize(buffer, size) <= 0){
            Alert("ArrayResize [1] failed: ", GetLastError());
            return(false);  }
        ArraySetAsSeries(buffer, true);
    }
    return(true);
}
Author:  snailbeard [ Tue Nov 12, 2013 10:23 am ]
Post subject:  Monitoring spread

Monitoring spread

Several members expressed an interest in the code for monitoring spread. However, it depends on some of my other headers, but here is the core of it.

Limitations:
It only takes one sample per minute not per tick and at the begiinning of a new minute so there is the possibility of skewed results.

It could be improved by having a similar approach for collecting ticks and passing that data along to the minute monitor.

Please let other members know how you are approaching your spread monitoring. I am thinking of writing some independent code to record spread and slippage so that we know what the crims are upto when we enter and exit trades.

Code: Select all

//+------------------------------------------------------------------+
//| Monitoring spread
//|
//| This code has been extracted from several headers and is incomplete
//| Copyright Brian Abram 2013
//| Licence: GPL (open source)
//+------------------------------------------------------------------+


double arrSpreadInPips[];
double arrSpreadInPipsFor1Hour[MAXPAIRS][60] = {0};
double arrAvgSpreadInPips[MAXPAIRS] = {0};
double arrHighSpreads[];
double arrLowSpreads[];


void init_PairPointsAndSpreads() {
	int pairCount = ArraySize(Pairs);

	ArrayResize(arrAskPrice, pairCount);
	ArrayResize(arrBidPrice, pairCount);
	ArrayResize(arrSpreadInPips, pairCount);
	ArrayResize(arrHighSpreads, pairCount);
	ArrayResize(arrLowSpreads, pairCount);

}


//+------------------------------------------------------------------+
//| updateAverageSpread
//+------------------------------------------------------------------+
void updateAverageSpread(int iPairIndex) {
	int iCurrMinute = Minute();
	int iLastMinute = -1;
	int iCount = 0;
	double dSpread;
	double dSum;
	// rolling numbers

	if( iLastMinute == iCurrMinute )
		return;
	iLastMinute = iCurrMinute;

	arrSpreadInPipsFor1Hour[iPairIndex][iCurrMinute] = arrSpreadInPips[iPairIndex];

	dSum = 0;
	for( int index = 0; index < 60; index++ ) {
		dSpread = arrSpreadInPipsFor1Hour[iPairIndex][index];
		if( dSpread > EPSILON ) {
			iCount ++;
			dSum = dSum + dSpread;
		}
	}
	if( iCount == 0 ) {
		Print("updateAverageSpread() ERROR  ERROR  ERROR : array is empty!");
		return;
	}
	double dAverage = dSum / iCount;
	arrAvgSpreadInPips[iPairIndex] = dAverage;

}

//+------------------------------------------------------------------+
//| getAverageSpreadInPips
//+------------------------------------------------------------------+
double getAverageSpreadInPips(int iPairIndex) { return(arrAvgSpreadInPips[iPairIndex] ); }


//+------------------------------------------------------------------+
//| getAverageSpreadInPips
//+------------------------------------------------------------------+
double getAverageSpreadInPoints(int iPairIndex) {

	double dAvgSpreadInPoints = bwaConvPipsToPoints(iPairIndex, arrAvgSpreadInPips[iPairIndex] );

	return(dAvgSpreadInPoints );
}

//+------------------------------------------------------------------+
//| updateSpread
//+------------------------------------------------------------------+
double updateSpread( int iPairIndex,  double& dAsk, double& dBid ) {
	dAsk = MarketInfo(Pairs[iPairIndex], MODE_ASK );
	dBid = MarketInfo(Pairs[iPairIndex], MODE_BID );
	double dRawSpread = dAsk - dBid;

	arrSpreadInPips[iPairIndex] = bwaConvPointsToPips( iPairIndex, dRawSpread);
	arrHighSpreads[iPairIndex] = MathMax( arrSpreadInPips[iPairIndex], arrHighSpreads[iPairIndex] ) ;
	arrLowSpreads[iPairIndex] = MathMin( arrSpreadInPips[iPairIndex], arrLowSpreads[iPairIndex] );

	updateAverageSpread(iPairIndex);
	double dAvgSpread = getAverageSpreadInPips(iPairIndex);

	bool bDebugTrace = false;
	if( bDebugTrace && IsTesting() ) {
		string strPart1 = "";
		string strPart2 = "";
		string strPart3 = "";
		string strPart4 = "";
		strPart1 = Pairs[iPairIndex]+ ": Spread: Ask, Bid, Diff, DiffInPips : ";
		strPart2 = DoubleToStr(dAsk,5)+ ",  "+ DoubleToStr(dBid,5)+",  "+DoubleToStr( dRawSpread,5) +"  " ;
		strPart3 = "SpInPips: " + DoubleToStr( arrSpreadInPips[iPairIndex],2) + "  ";
		strPart4 = "Avg Sp in Pips: "+ DoubleToStr( arrAvgSpreadInPips[iPairIndex], 2) + "  ";

		gSpreadDetail =  strPart1 + strPart2 + strPart3 + strPart4;
		Print( gSpreadDetail );
	}

	return(arrSpreadInPips[iPairIndex]);
}
Author:  snailbeard [ Sat Nov 16, 2013 7:36 am ]
Post subject:  Re: Utility Procedures / Code Snippets

More on spread monitoring:

I should have mentioned that I found and downloaded several indicators for monitoring/logging spread. They are probably a lot more 'fit for purpose' than my quick hack and at some stage I'll see what I can learn from their source code.

Here is a short list spread indicators that I download but only briefly looked at:

IND_Monitoring-Spread.mq4
Spreadtrack_v2.mq4
Author:  4EverMaAT [ Mon Jun 23, 2014 12:19 pm ]
Post subject:  Re: Utility Procedures / Code Snippets

snailbeard ยป Sat Nov 16, 2013 2:36 pm wrote:More on spread monitoring:

I should have mentioned that I found and downloaded several indicators for monitoring/logging spread. They are probably a lot more 'fit for purpose' than my quick hack and at some stage I'll see what I can learn from their source code.

Here is a short list spread indicators that I download but only briefly looked at:

IND_Monitoring-Spread.mq4
Spreadtrack_v2.mq4
Can you link to where you downloaded these two from?
Author:  Radar [ Tue Aug 26, 2014 4:44 am ]
Post subject:  Utility Procedures / Code Snippets

Here's some lazy typists' helpers...

If you've read all this thread, you would have come across dietcoke's GlobalVariable shortcut functions here... http://www.stevehopwoodforex.com/phpBB3 ... t=20#p8373

If you're using GV's in an indicator or EA, you have to ensure that multiple instances don't stomp all over each other's GV's. To do this, add the following #defines...

Code: Select all

#define ean "Your_EA's_Name_"
#define indie "Your_Indicator's_Name_"
// For EA's...
#define etp cat(ean, TradePair[cc], "_", string(Period()), "_") // Used in Multi-Symbol functions.
#define esp cat(ean, symbol, "_", string(Period()) "_") // Used in Single Symbol functions.
// For indicators
#define itp cat(indie, TradePair[cc], "_", string(Period()), "_") // Used in Multi-Symbol functions.
#define isp cat(indie, symbol, "_", string(Period()) "_") // Used in Single Symbol functions.
What's "TradePair[cc]" you ask? Well, TradePair is an Array that holds the names symbols that a multi-symbol EA or indicator is working on... Steve, (and now I) use that, and we use the following loop to iterate through that array...

Code: Select all

   for (int cc = 0; cc < NoOfPairs; cc++)
   {
		fnerk = TradePair[cc];
		do something with fnerk;
   }
So, if you use a different method to select individual symbols in a multi-symbol EA or indicator, adjust the defines to suit.

As for "cat"...

Code: Select all

//======== Lazy Typists' String Concatenation Functions========
string cat(string part1, string part2)
{
   string line = StringConcatenate(part1 + part2);
   return(line);
}

string cat(string part1, string part2, string part3)
{
   string line = StringConcatenate(part1 + part2 + part3);
   return(line);
}

string cat(string part1, string part2, string part3, string part4)
{
   string line = StringConcatenate(part1 + part2 + part3 + part4);
   return(line);
}
So now, when you want to play with GV's, all you need to do is...

Code: Select all

// For EA's
//GlobalVariableCheck
      gvc(cat(etp, "My_Variable_Name"))

//GlobalVariableSet
      gvs(cat(esp, "My_Variable_Name"), NormalizeDouble(0, 0));

//GlobalVariableGet
      gvg(cat(etp, "My_Variable_Name"))

//GlobalVariableDel
      gvd(cat(etp, "My_Variable_Name"))
Just change where it says etp/esp to use the appropriate #define...

If you plan to run multiple instances on the same symbol and timeframe, just add an underscore to "My_Variable_Name" and add string(MagicNumber) (or any other unique identifier) after that, like so...

Code: Select all

      gvg(cat(etp, "My_Variable_Name_", string(UniqueIdentifier)))
This has saved me a lot of typing, (and a lot of headaches) with the multi-timeframe basketcase EA that I"m currently working on ;)

Have fun!

Radar =8^)
Author:  DigitalCrypto [ Tue Mar 24, 2015 10:42 pm ]
Post subject:  Utility Procedures / Code Snippets

EDIT: I apologize but I didn't know WindowHandle() had a shitty deinit bug that could cause hangups and freezes. I've tried storing MagicNumber as a Global but it still doesn't fix the problem. Just be aware that it is a known bug and could cause a terminal hang. I do apologize for this.

If you know a work around to get rid of the hangs when switching charts with the EA loaded, by all means please let me know. Thanks.

==========

Newbie to coding for Meta Traitor. Here is a function I hacked together to generate and store magic numbers on disk so I don't have to manually input them all of the time when I restart or move machines.

Critiques, rewrites and deletes are welcome.


Code: Select all


//---- Constants
#define  FILENAME          "Experts\files\/"+Symbol()+"-MagicNumber.txt"  // Change this to your file location

//---- Externals
extern string MN_Ex="------- Magic Number Settings (0 for automatic)";
extern int MagicNumber=0; // For 0 we generate MagicNumber automagically and store it in a file on disk

Get the magic first thing

Code: Select all

int init()

   ... Other stuff

   // Get Magic Number
   if(MagicNumber==0) MagicNumber=GetMagicNumber();

return(0);
Hit the disk and check it out.

Code: Select all

//+------------------------------------------------------------------+
//| Generate or Retrieve Existing Magic Number                       |
//+------------------------------------------------------------------+

int GetMagicNumber()
  {
   if(MagicNumber==0)
     {
      //Open Symbol file and read contents
      int handle,space,i,pos[];
      string str,word;
      handle=FileOpen(FILENAME,FILE_TXT|FILE_READ|FILE_WRITE);    // Try to open the file
      if(handle==-1) {FileWrite(handle,""); FileClose(handle);}   // If it doesn't exist then we need to create it

      if(FileSize(handle)==0)                                     // If the file exists but its contents are zero
        {
         Print("File "+FILENAME+" Wasn't Found! That's ok. We'll create it!"); 
         MagicNumber=WindowHandle(Symbol(),0);// MagicNumber = 37338;
         FileWrite(handle,MagicNumber);
         FileClose(handle);
         Print("File: "+FILENAME+" was created!");
         return(MagicNumber);
        }

      if(FileSize(handle)>0)                                      // If the file exists and the size of the file is greater than 0.
        {
         str=FileReadString(handle);                              // Read one paragraph to the str variable
         if(str!="")                                              // If the string isn't empty
           {
            space=0;
            for(i=0;i<StringLen(str);i++)
              {
               if(StringGetChar(str,i)==32)// Look for 32 spaces only
                 {
                  space++;
                  ArrayResize(pos,space); // Increase the array size
                  pos[space-1]=i;         // Write the number of the space position to array
                 }
              }                           // Now we have array with numbers of positions of all spaces
            for(i=0;i<=space;i++)         // Read the elements of the string
              {
               if(i==0) word=StringSubstr(str,0,pos[0]);                   // The first element of the string (in this case it is the magic number)
               else word=StringSubstr(str,pos[i-1]+1,pos[i]-pos[i-1]-1);   // The rest of the elements
                                                                           // Perform analysis, calculate StrToInteger or whatever StrToDouble here.
               FileClose(handle);         // Close the file
               MagicNumber=StringToInteger(word);

              }
           }
        }
     }
   return(MagicNumber);
  }
Author:  DigitalCrypto [ Sat Apr 18, 2015 11:15 am ]
Post subject:  Solarized Color Scheme for Metaeditor

EDIT: I got the compiler working for Scite editor but I still need to test it in Empty4 when I get to the office. So this post would not be applicable. I will leave it for now until I get the compiler tested. Then I will consolidate the posting. UPDATE: Compiler works for latest builds now. I will write up a post on it.

Most coders look at the screen for long periods of time. To reduce eyestrain I applied Ethan Schoonover's Solarized Color palette to Metaeditor.

http://ethanschoonover.com/solarized

Enjoy!
MetaEditor Solarized.png
http://i.imgur.com/PXpk6bO.png //--Link to external pic on imgur.com

Simply edit c:\Empty4\config\metaeditor.ini or where ever you have it and modify the color section.

[Colors]
Color0=4339207
Color1=10592659
Color2=16777215
Color3=7695960
Color4=15790320
Color5=13798182
Color8=39301
Color9=10002730
Color10=3093212
Color11=1461195

Note: The font I prefer is DejaVu Sans on sourceforge.
http://sourceforge.net/projects/dejavu/
All times are UTC Page 5 of 7