mql5 pick orders based on calculation - mql4

bool D1GTPrevD1()
{
// if(iClose(NULL,PERIOD_D1,1) < iClose(NULL,PERIOD_D1,0))
If(iClose(NULL,PERIOD_D1,1))
{
double
low = iLow( _Symbol, PERIOD_D1, 1 ),
close = iClose( _Symbol, PERIOD_D1, 1 ),
ov = close-low,
nv = close+ov;
return !( close==nv );
};
return(true);
return(false);
}
bool D1LTPrevD1()
{
// if(iClose(NULL,PERIOD_D1,1) > iClose(NULL,PERIOD_D1,0))
If(iClose(NULL,PERIOD_D1,1))
{
double
high = iHigh( _Symbol, PERIOD_D1, 1 ),
close = iClose( _Symbol, PERIOD_D1, 1 ),
ov = high-close,
nv = close-ov;
return !( close==nv );
};
return(true);
return(false);
}
as in the above compile, like to have calculations to the current candle. As there is no effect while running EA, help me to imply this calculation in mql5

Related

How can I use iOpen(), iClose(), iLow() and iHigh() to find these pinbars?

I want to find the pinbars circled in the attached image below. For the one on the right, the body is about 1/5th of the candle size and for the one on the left, let's say the body is 1/7th the size candle size and it also has a wick of 1/7th the candle size at the bottom. How can I use the iOpen(), iLow() and other similar functions to find these two types of pinbars?
Q : How can I use the iOpen(), iLow() and other similar functions to find these two types of pinbars?
May use a working template like this WasThisTheUserDefinedBearishPATTERN() function and having defined all your user-specific conditions and constants, just call if ( WasThisTheUserDefinedBearishPATTERN( aShift, 4.5, 0.1, 2000 ) ) { do_something(); } when using it for trading:
bool WasThisTheUserDefinedBearishPATTERN( const int aBarNUMBER,
const double aBody2uWICK_MUL,
const double min_FRACTION,
const double MAX_FRACTION
) {
// BAR-UPPER-wick:
double aBarUpWK = ( iHigh( _Symbol, PERIOD_CURRENT, aBarNUMBER )
- iClose( _Symbol, PERIOD_CURRENT, aBarNUMBER )
);
// BAR-body:
double aBarBODY = ( iClose( _Symbol, PERIOD_CURRENT, aBarNUMBER )
- iOpen( _Symbol, PERIOD_CURRENT, aBarNUMBER )
);
// BAR-LOWER-wick:
double aBarLoWK = ( iLow( _Symbol, PERIOD_CURRENT, aBarNUMBER )
- iClose( _Symbol, PERIOD_CURRENT, aBarNUMBER )
);
// FLAG:
bool aBearishFLAG = FALSE;
// -----------------------------------------------------------------
// USER-DEFINE-ABLE SET OF SHAPE-CONDITIONS ..... = add all that apply
// BEARISH BODY:
// has body
// has body BEARISH
// has body not more than about a lo-wick size * < min_FRACTION, MAX_FRACTION >
// has body not less than about a hi-wick size * _MUL
// -------------
if ( aBarBODY >= 0 // not BEARISH
|| aBarUpWK < aBarBODY * aBody2uWICK_MUL // not long enough UpperWICK
){
aBearishFLAG = FALSE; // (NO)
}
else { if ( aBarBODY < 0 // has BEARISH CANDLE
&& ( aBarLoWK == 0 // and may LO-WICK ZERO
|| ( aBarLoWk / aBarBODY > min_FRACTION // .GT. min-WICK-2-BODY-FRACTION
&& aBarLoWk / aBarBODY < MAX_FRACTION // .LT. MAX-WICK-2-BODY-FRACTION
)
)
){ aBearishFLAG = TRUE; } // (YES)
else { aBearishFLAG = FALSE; } // ( NO) OTHERWISE
}
return( aBearishFLAG );
}
Ex-post :
I did WasThisTheUserDefinedBearishPATTERN( aShift, 1, 1/6, 2/6 ) and was expecting it to result in something...
Besides the comment below, kindly also respect The Rules of the World of MQL4 language:
Print( "DIV( 1 / 7 ) == ", 1 / 7 ); // will show you The Rules
Print( "DIV( 1. / 7. ) == ", 1. / 7. ); // will show you The Rules
So the way I would approach this is as follows:
1) What are the characteristics of each candle I am trying to define?
a) Down or up (I prefer 1 or -1)
b) Large rejection tail relative to the body
c) Large rejection tail relative to the non-rejection tail
d) Small body relative to the rejection tail
2) How do we code this in MQL4 using predefined functions?
Let's first make a few assumptions...
First, you are wanting to define these candles in real-time so you can execute when they form.
Second, let's go off the M30 for any given Symbol().
The below function (not tested) will return a 1 when there is a buy signal, and a -1 for a sell signal, and 0 if no signal. You will need to adjust the extern variables accordingly as this is more of a science than a "one-size-fits-all". Also, you might need to use IsNewBar.
//the values below should sum to 100
extern int RTail_To_Range_Ratio = 80; //rejection tail ratio to range of candle
extern int Body_To_Range_Ratio = 10; //body size ratio to range of candle
extern int NRTail_To_Range_Ratio = 10; //non-rejection tail ratio to range of candle
int Signal()
{
//candle information
double dOpen = iOpen(Symbol(),PERIOD_M30,0);
double dHigh = iHigh(Symbol(),PERIOD_M30,0);
double dLow = iLow(Symbol(),PERIOD_M30,0);
double dClose = iClose(Symbol(),PERIOD_M30,0);
double dBody = MathAbs(dOpen - dClose);
double dRange = dHigh - dLow;
double dRTail = 0, dTail = 0;
//green candle
if(dClose > dOPen){
dRTail = dOPen - dLow;
dTail = dHigh - dClose;
//now check ratios
if((dTail / dRange) <= (NRTail_To_Range_Ratio / 100) && (dBody / dRange) <= (Body_To_Range_Ratio / 100) && (dRTail / dRange) >= (RTail_To_Range_Ratio / 100)){
return 1;
}
}
//red candle
else{
dRTail = dHigh - dOpen;
dTail = dClose - dLow;
//now check ratios
if((dTail / dRange) <= (NRTail_To_Range_Ratio / 100) && (dBody / dRange) <= (Body_To_Range_Ratio / 100) && (dRTail / dRange) >= (RTail_To_Range_Ratio / 100)){
return -1;
}
}
return 0;
}
Let me know if this solves your problem #SuperHueman.

While there are no MQL4 errors, why there was no GUI drawing produced?

For a learning purpose, I am trying to code a simple MA indicator that changes color when price crosses. Though there are no errors, it draws nothing. Could you review the attached code to show me my mistake?
#property indicator_chart_window
#property indicator_buffers 2
extern int maperiod = 20;
extern int maprice = PRICE_CLOSE;
extern int mamethod = MODE_SMA;
extern color colorup = Green;
extern color colordn = Red;
double mamain[];
double bufferup[];
double bufferdn[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init(){
//--- indicator buffers mapping
SetIndexBuffer( 0, bufferup );
SetIndexStyle( 0, DRAW_LINE, 0, 2, colorup );
SetIndexBuffer( 1, bufferdn );
SetIndexStyle( 1, DRAW_LINE, 0, 2, colordn );
//---
return( 0 );
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start(){
//---
int counted_bars = IndicatorCounted();
if ( counted_bars < 0 ) return( -1 );
if ( counted_bars > 0 ) counted_bars--;
int limit = Bars - counted_bars;
for ( int i = limit; i >= 0 ; i-- )
{ mamain[i] = iMA( NULL, 0, maperiod, 0, 0, 0, i );
if ( mamain[i] >= iClose( NULL, 0, i ) ) bufferup[i] = mamain[i];
if ( mamain[i] <= iClose( NULL, 0, i ) ) bufferdn[i] = mamain[i];
}
//--- return value of prev_calculated for next call
return( 0 );
}
//+------------------------------------------------------------------+
"Old"-MQL4 may work for some time, but still, get used to new features:
extern ENUM_APPLIED_PRICE MAprice = PRICE_CLOSE; // AVOIDS incompatible values
extern ENUM_MA_METHOD MAmethod = MODE_SMA; // AVOIDS incompatible values
#define MAshift 0 // ADDS code == intent match-robustness
extern int MAperiod = 20;
extern color colorUP = clrGreen;
extern color colorDN = clrRed;
double bufferUP[];
double bufferDN[];
int init(){
ArrayInitialize bufferUP, EMPTY_VALUE );
SetIndexBuffer( 0, bufferUP );
SetIndexStyle( 0, DRAW_LINE, EMPTY, 2, colorUP );
SetIndexLabel( 0, "MA_ABOVE_Close" );
ArrayInitialize bufferDN, EMPTY_VALUE );
SetIndexBuffer( 1, bufferDN );
SetIndexStyle( 1, DRAW_LINE, EMPTY, 2, colorDN );
SetIndexLabel( 1, "MA_UNDER_Close" );
return( 0 );
}
int start(){
int counted_bars = IndicatorCounted();
if ( counted_bars < 0 ) return( -1 );
if ( counted_bars > 0 ) counted_bars--;
for ( int i = Bars - counted_bars; i >= 0 ; i-- ){
double C = iClose( _Symbol, PERIOD_CURRENT, i ),
A = iMA( _Symbol, PERIOD_CURRENT,
MAperiod,
MAshift,
MAmethod,
MAprice,
i
);
if ( A >= C ) bufferUP[i] = A;
if ( A <= C ) bufferDN[i] = A;
}
return( 0 );
}
New-MQL4.56789 uses another call-signature if #property strict:
int OnCalculate( const int rates_total,
const int prev_calculated,
const datetime &time_______ARR[],
const double &open_______ARR[],
const double &high_______ARR[],
const double &low________ARR[],
const double &close______ARR[],
const long &tick_volumeARR[],
const long &volume_____ARR[],
const int &spread_____ARR[]
){
//--- the main loop of calculations
for( int i = prev_calculated - 1;
( i < rates_total
&& !IsStopped() ); // AVOID SHARED (!) solo-THREAD BLOCKING
i++
){
// -----------------------------------------------------------------
double A = iMA( _Symbol, PERIOD_CURRENT,
MAperiod,
MAshift,
MAmethod,
MAprice,
i
);
if ( A >= close______ARR[i] ) bufferUP[i] = A;
if ( A <= close______ARR[i] ) bufferDN[i] = A;
// -----------------------------------------------------------------
}
return( rates_total );
}
your buffer mamain[] is not initialized.
int init(){
IndicatorBuffers(3);
SetIndexBuffer(2,mamain);
}
rates_total and prev_calculated seems preferred but of course you can use IndicatorCounted() but keep in mind the corner situation with the first bar: when you first attach the indicator to the chart, your counted_bars = 0 and limit = Bars, but mamain[] and other indicator buffers have Bars elements only, from 0 to Bars-1. so better to use
int limit = Bars - counted_bars - 1;
About resolving issues - in addition to asking here you can always try to attach your indicator to a chart and see it there's no error (terminal window - Experts folder), that will make delevopment faster

My First MQL4 EA does not generate any Orders. Why?

I'm trying to build a first EA, code below, but it doesn't execute any trades.
I know it is very simple, but logically, I think this should Buy and Sell.
I'm trying to only use a code that I understand.
I'd appreciate it if anyone had any feedback!
//
extern int sma_short = 10;
extern int sma_long = 20;
extern double fakeout = 0.0005 ;
extern double stoploss = 150;
extern double risk = 1;
extern int slippage = 5;
extern int magicnumber = 12345;
extern bool SignalMail = false;
extern bool UseTrailingStop = true;
extern int TrailingStop = 150;
double sma_short_t3;
double sma_short_t0;
double sma_long_t3;
double sma_long_t0;
double sma_diff_t3;
double sma_diff_t0;
double lots;
double stoplosslevel;
int P = 1;
int ticket, ticket2;
int total = OrdersTotal();
bool OpenLong = false;
bool OpenShort = false;
bool CloseLong = false;
bool CloseShort = false;
bool isYenPair = false;
bool OpenOrder = false;
int OnInit()
{
if ( Digits == 5 || Digits == 3 || Digits == 1 ) P = 10; else P = 1; // To account for 5 digit brokers
if ( Digits == 3 || Digits == 2 ) isYenPair = true; // Adjust for YenPair
return( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit( const int reason )
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void Start()
{
sma_short_t3 = iMA( NULL, 0, sma_short, 0, MODE_SMA, PRICE_CLOSE, 3 );
sma_short_t0 = iMA( NULL, 0, sma_short, 0, MODE_SMA, PRICE_CLOSE, 0 );
sma_long_t3 = iMA( NULL, 0, sma_long, 0, MODE_SMA, PRICE_CLOSE, 3 );
sma_long_t0 = iMA( NULL, 0, sma_long, 0, MODE_SMA, PRICE_CLOSE, 0 );
sma_diff_t3 = sma_long_t3 - sma_short_t3;
sma_diff_t0 = sma_long_t0 - sma_short_t0;
if ( OpenOrder )
{
if ( CloseLong || CloseShort )
{
OrderClose( OrderTicket(), OrderLots(), Bid, slippage, MediumSeaGreen );
OpenOrder = False;
CloseLong = False;
CloseShort = False;
}
}
if ( sma_diff_t3 < 0 && sma_diff_t0 > fakeout )
{
OpenLong = True ;
CloseShort = True;
}
if ( sma_diff_t3 > 0 && sma_diff_t0 < -fakeout )
{
OpenShort = True;
CloseLong = True;
}
lots = risk * 0.01 * AccountBalance() / ( MarketInfo( Symbol(), MODE_LOTSIZE ) * stoploss * P * Point ); // Sizing Algo based on account size
if ( isYenPair == true ) lots = lots * 100; // Adjust for Yen Pairs
lots = NormalizeDouble( lots, 2 );
if ( OpenLong )
{
stoplosslevel = Ask - stoploss * Point * P;
OrderSend( Symbol(), OP_BUY, lots, Ask, slippage, stoplosslevel, 0, "Buy(#" + magicnumber + ")", magicnumber, 0, DodgerBlue );
OpenOrder = True;
}
if ( OpenShort )
{
stoplosslevel = Bid + stoploss * Point * P;
OrderSend( Symbol(), OP_SELL, lots, Ask, slippage, stoplosslevel, 0, "Buy(#" + magicnumber + ")", magicnumber, 0, DodgerBlue );
OpenOrder = True ;
}
}
//+------------------------------------------------------------------+
and why do you use (MarketInfo(Symbol(),MODE_LOTSIZE)? what is the idea of that? first try with double lots = 1.00; and if problem still exists - please add a line telling about the reason why ea failed to send. sth like int ticket = OrderSend(***); if(ticket<0)Print("error=",GetLastError()); or more complex telling about the actual prices, lots, stoploss etc.
Few things in MQL4 to rather get used to:
All PriceDOMAIN data has to be NormalizeDouble() before sending to MetaTrader 4 Server.
All EquityDOMAIN data has to follow a set of discrete values,having MathMin( aMinLOT_SIZE + N * aMinLOT_STEP, aMaxLOT_SIZE ). Normalisation of EquityDOMAIN data is broker-specificand instrument-specific, so need not be always 2.
For XTO, OrderSend(), OrderMOdify(), OrderClose(), one ought follow something like this:
if ( OpenLong )
{ stoplosslevel = NormalizeDouble( Ask - stoploss * Point * P, _Digits ); // ALWAYS NormalizeDouble()
int RetCODE = OrderSend( _Symbol,
OP_BUY,
lots,
Ask,
slippage,
stoplosslevel,
0,
"Buy(#" + magicnumber + ")",
magicnumber,
0,
DodgerBlue
);
if ( RetCODE < 0 )
{ Print( "EXC: Tried to go LONG, OrderSend() failed to get confirmed ( Errno: ", GetLastError(), " )" );
}
else
{ OpenOrder = True;
...
}
...
}

Can't make iteration with #property strict

I have this code working without error. Basically, this code is to show value of Moving Averages on five previous bars per 5 minutes. MA's current value is omitted.
int TrendMinDurationBar = 5,
SlowPeriod = 14,
FastPeriod = 7;
void OnTick()
{
if ( NewBar( PERIOD_M5 ) == true ) MA( PERIOD_M5 );
}
void MA( int TF )
{
double Slow[], Fast[];
ArrayResize( Slow, TrendMinDurationBar + 1 );
ArrayResize( Fast, TrendMinDurationBar + 1 );
for ( int i = 1; i <= TrendMinDurationBar; i++ )
{ Slow[i] = NormalizeDouble( iMA( Symbol(), TF, SlowPeriod, 0, MODE_EMA, PRICE_OPEN, i ), Digits );
Fast[i] = NormalizeDouble( iMA( Symbol(), TF, FastPeriod, 0, MODE_EMA, PRICE_OPEN, i ), Digits );
Alert( "DataSlow" + ( string )i + ": " + DoubleToStr( Slow[i], Digits ) );
}
}
bool NewBar( int TF )
{
static datetime lastbar = 0;
datetime curbar = iTime( Symbol(), TF, 0 );
if ( lastbar != curbar )
{ lastbar = curbar; return( true );
}
else return( false );
}
When #property strict is included, the code is only working once after compiled. After new bar on M5 chart exist, it doesn't make any iteration.
What's the solution if I insist to use #property strict?
Works perfectly well with #property strict as an EA in MT4 Build 950.
Are you sure you are running it as EA and not as Script or Indicator?
Welcome to another New-MQL4.56789 Catch-22
My candidate from Help > MQL4 Reference > Updated MQL4
is
this one ( column [New MQL4 with #property strict] )
Functions of any type should return a value
and
one more to be reviewed,
code simply loses the logic even for static double alternative it would be extremely inefficient under these circumstances:
Local arrays are released when exiting {} block

PlotText result is overlapped in amibroker

I use below code
![priceatbuy=0;
for( i = 0; i < BarCount; i++ )
{
if( priceatbuy == 0 && Buy\[ i \] )
priceatbuy = BuyPrice\[ i \];
PlotText("P" + priceatbuy, SelectedValue(BarIndex()), L\[SelectedValue(BarIndex())\] - ist\[SelectedValue(BarIndex())\], colorWhite);
if( priceatbuy > 0 && SellPrice\[ i \] < (priceatbuy - (0.027 * priceatbuy/100)) )
{
Sell\[ i \] = 1;
SellPrice\[ i \] = (priceatbuy - (0.027 * priceatbuy/100)) ;
plotShapes(shapeDownArrow*sell, colorpink );
priceatbuy = 0;
}
else
Sell\[ i \] = 0;
}][1]
With above plotText, when i print the variable "priceatBuy", i see the text is overlapped and I am not able to see the value correctly. Is it because that SellPrice[i] and BuyPrice[i] returning some other value that Plottext doesnt understand? If I print Sell[i] or Buy[i], it prints correctly. May I know how to get this value correctly.
PFA image
Your code is wrong.
Below is a correct code sample (The loop contains SL exit only! So you need to add some profit exit condition too otherwise you always exit at loss.)
percent = 2.0; // percent SL
delay = 1; // buy entry bar delay
Buycond = Cross( MACD(), Signal() ); // buy when macd crosses above of signal line
Buy = Ref( Buycond, -delay );
BuyPrice = Open;
Sell = 0;
SLlong = Null;
SLLineLong = Null; // array
for( i = delay; i < BarCount; i++ ) {
// setting long SL line
if( IsNull( SLlong ) && Buy[ i ] )
SLlong = BuyPrice[ i ] * ( 1 - percent / 100 );
else {
Buy[ i ] = 0;
}
// no shape buy signal if SL not hit
if( NOT IsNull( SLlong ) && BuyCond[ i ] )
Buycond[ i ] = 0;
// if SL is reached exit and reset
Sellsignal = L[ i ] < SLlong;
if( NOT IsNull( SLlong ) && Sellsignal ) {
Sell[ i ] = 1;
SellPrice[ i ] = Min( O[ i ], SLlong );
SLlong = Null;
} else
Sell[ i ] = 0;
//
// for plotting SL line array is required
SLLineLong[i] = SLlong;
}
// Chart pane section
if( Status( "action" ) == actionIndicator ) {
SetBarsRequired( 10000, 10000 );
SetChartOptions( 0, chartShowDates | chartShowArrows | chartWrapTitle );
// Plot price
Plot( C, "", colorDefault, GetPriceStyle() );
// Plot SL line
Plot( SLLineLong, "\nSL long", colorRed, styleLine | styleNoRescale );
//
// Plot Shapes
dist = -12;
PlotShapes( shapeUpArrow * Buycond, colorGreen, 0, L, dist );
PlotShapes( shapeSmallCircle * Buy, colorGreen, 0, BuyPrice, 0 );
PlotShapes( shapeDownArrow * Sell, colorPink, 0, H, dist );
PlotShapes( shapeSmallCircle * Sell, colorPink, 0, SellPrice, 0 );
//
// Plot signal text
fnt = "Arial";
fntsize = 8;
txtdist = 25 - dist;
bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );
PlotTextSetFont( "", fnt, fntsize, 0, 0, -1 );
for( i = fvb; i <= lvb; i++ ) { // iterate through visible chart area only
if( Buy[i] ) // plot text at signal occurences only
PlotText( StrFormat( "BP#\n%g", BuyPrice[ i ] ), i, L[ i ], colorGreen, colorDefault, -txtdist + fntsize );
if( Sell[i] )
PlotText( StrFormat( "SP#\n%g", SellPrice[ i ] ), i, H[ i ], colorPink, colorDefault, txtdist );
}
//
_N( Title = StrFormat( "{{NAME}} - {{INTERVAL}} - {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%), Vol %g {{VALUES}}",
O, H, L, C, SelectedValue( ROC( C, 1 ) ), V ) );
}

Resources