How to design an Average Directional Movement Index Expert Advisor in MQL4/5? - mql4

I have a trading strategy based on ADX, in a simplest way I enter when ADX is above 30 both on the 30 minutes and hourly chart.
I need to create an EA in MQL5 just to give me a sound alert, when ADX has hit level 30 both on 30 minutes and hourly timeframe.
I would really appreciate if someone can help me with that.

So,
let's move on:
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
if ( iADX( _Symbol, PERIOD_H1, anAvgPERIOD, PRICE_HIGH, MODE_MAIN, 0 ) > 30.
&& iADX( _Symbol, PERIOD_M30, anAvgPERIOD, PRICE_HIGH, MODE_MAIN, 0 ) > 30.
){
PlaySound( "aFileWithDesiredSOUND.wav" );
}
}
One ought not be surprised, that this does not work for obvious reasons in the MT4 Strategy Tester.

Related

MQL4 Expert Advisor Error #134 'Not Enough Money' When executing Only Sell Trade

I am coding a bot to execute trades for me when I receive them on my email. I have achieved this however, I have run into a small problem I can't seem to solve. When a buy trade is placed by the EA, it runs smoothly and places the trade. However, when a sell trade is placed, it throws an error #134.
MQL4 Website
ERR_NOT_ENOUGH_MONEY 134 : Not enough money.
Here is my code:
int placeOrder = OrderSend(
trade,
type,
MarketInfo(getResult(trade, " "), MODE_MINLOT),
buy ? Ask : Bid, // for the market price
3, // do this if it doesnt move more than slippage
buy ? Ask-100*_Point : Bid+100*_Point, // Stop loss 100 points
buy ? Ask+200*_Point : Bid-200*_Point, // Take profit 200 points
"ANBai trade", // comment
0, // no id number
0, // no expiration date
Green // draw green arrow
);
if(placeOrder<0){
return raw + " OrderSend failed with error #"+ error(GetLastError()) +"\n\n";
}else{
return raw + " Trade executed!\n\n";
}
As you know, we buy at ask and sell at bid. This error does not happen on BUY, as much as I place many trades.

OrderSend mq4 ea

I'm projecting a EA for SELL LIMIT adn BUY LIMIT operation. It's quite simple. The MT4 must open the order (or more than one) at a specific price. Here is my code with 2 pending orders
void OnTick(){
if (OrdersTotal()==0)
int sellticket_0 = OrderSend
(Symbol(),OP_BUYLIMIT,0.12,"0.73870",0,"0.73552","0.73893",NULL,0,
TimeCurrent()+167552,clrGreen);
if (OrdersTotal()==1)
int sellticket_1=OrderSend
(Symbol(),OP_BUYLIMIT,0.12,"0.73683",0,"0.73552","0.73813",NULL,0,
TimeCurrent()+167552,clrGreen);
}
Unfortunately it doesn't work.

How to get OHLC prices for a historic bar in MQL4?

I'm getting a bit stuck with a piece of mql4 code. Esentially, I need to access and store the OHLC prices of a historic bar back in time maximum 30 days back from current date. This is how I am currently doing it.
input int referenceDay=1;
static double reference;
if ( Day() == referenceDay ) reference = Open[0];
This is working fine until the point I either add to the code which, it then resets the reference back to 0. I am looking for a way to be able to access the history on each new candle and store the price for the referenceDay.
The objective is that whenever the EA is loaded to the chart, it automatically goes into the history and updates the reference price to be used on this trading day without having to wait for the entire month's iteration in real time.
The objective is that whenever the EA is loaded to the chart, it automatically goes into the history and updates the reference price
So far so good.
Once EA gets loaded,
the definition of static double reference; sets the initial value of reference == 0.;
next, the call to Day() sets the rules:
int Day(); returns the current day of the month, which is not the "today"'s-day, but the day of month of the so called last known server time. Given the EA was loaded on Sunday afternoon, or Monday morning, before the Market was opened, the "last known server time" is still Friday ... remember, the Server-side datetime rules ( so, if trading on APAC or Australia / New Zealand TimeZone servers, additional gymnastics are in place ).
So, as the code continues - in all such cases, when the input int referenceDay value will accidentally != the last known server time Day(), your ( just ) initialised variable reference will remain == 0.
Surprised?
May test it:
static double reference = EMPTY; // .SET EXPLICIT INITIALISER
if ( Day() == referenceDay )
{ reference = Open[0];
print( reference,
"AFTER Day() MATCHED referenceDay" // THIS NEED NOT HAPPEN
);
}
else
{ print( reference,
"ON( ",Day(), " ) ",
"AFTER Day() DID NOT MATCH referenceDay = ",
referenceDay
}
May redefine the assignment strategy, using:
input int referenceDAYinput = 1;
int referenceDAYnDaysBACK = max( 0, // FUSED
Day() - referenceDAYinput
);
static double referenceLEVEL = iOpen( _Symbol,
PERIOD_D1,
referenceDAYnDaysBACK
);
This code snippet certainly does not strive to be the complete solution, but shows the mechanics for achieving the desired objective.
Your actual code will have to solve how many Trading days - which is needed to address the TimeSeries-indexing logic of MetaTrader Terminal 4 platofrm -- ( not just the Calendar days ) -- there were in between the referenceDAYinput and the "last known server time"-Day(), but your are this close to have this done.

FreeRTOS Posix GCC Simulator vTaskDelay doesn't delay properly

I am playing with FreeRTOS Posix GCC Simulator and creating simple task and delaying 1 sec and printing just doesn't give right results.
Creating task like this should show text being printed every 1 sec but it seems that it is more like 8-9 sec between prints.
What could be the issue?
void prvTask1( void *pvParameters )
{
for ( ;; )
{
printf( "Task 1 ...%d\n", xTaskGetTickCount());
vTaskDelay( 1000 / portTICK_RATE_MS );
}
}
Config:
#define configTICK_RATE_HZ ( ( portTickType ) 1000 )
#define portTICK_RATE_MS ( ( portTickType ) 1000 / configTICK_RATE_HZ )
I've tested with values:
#define configTICK_RATE_HZ ( ( portTickType ) 250)
#define portTICK_RATE_MS ( ( portTickType ) 1000 / configTICK_RATE_HZ )
It looks like it is ~1 sec per printf. Somehow it seems raising values from ~500 > 1000 gives worser results on 1 sec delay (becomes much more then 1 sec).
FreeRtos demo FreeRtosConfig.h says:
#define configTICK_RATE_HZ ( 1000 )
// In this non-real time simulated environment
// the tick frequency has to be at least a multiple
// of the Win32 tick frequency, and therefore very slow.
Maybe you should try to build and run the original example of FreeRtos.
I did try to run the example of FreeRtos8.2.1 and vTaskDelay works just fine

getTickCount time unit confusion

At the answer to the question on Stack and in the book at here on page 52 I found the normal getTickCount getTickFrequency combination to measure time of execution gives time in milliseconds . However the OpenCV website says its time in seconds. I am confused. Please help...
There is no room for confusion, all the references you have given point to the same thing.
getTickCount gives you the number of clock cycles after a certain event, eg, after machine is switched on.
A = getTickCount() // A = no. of clock cycles from beginning, say 100
process(image) // do whatever process you want
B = getTickCount() // B = no. of clock cycles from beginning, say 150
C = B - A // C = no. of clock cycles for processing, 150-100 = 50,
// it is obvious, right?
Now you want to know how many seconds are these clock cycles. For that, you want to know how many seconds a single clock takes, ie clock_time_period. If you find that, simply multiply by 50 to get total time taken.
For that, OpenCV gives second function, getTickFrequency(). It gives you frequency, ie how many clock cycles per second. You take its reciprocal to get time period of clock.
time_period = 1/frequency.
Now you have time_period of one clock cycle, multiply it with 50 to get total time taken in seconds.
Now read all those references you have given once again, you will get it.
dwStartTimer=GetTickCount();
dwEndTimer=GetTickCount();
while((dwEndTimer-dwStartTimer)<wDelay)//delay is 5000 milli seconds
{
Sleep(200);
dwEndTimer=GetTickCount();
if (PeekMessage (&uMsg, NULL, 0, 0, PM_REMOVE) > 0)
{
TranslateMessage (&uMsg);
DispatchMessage (&uMsg);
}
}

Resources