MQL4 Learning - page 124

 

Please, can any experienced programmer kindly help me take a look at the code below and help me modify the code where the EA opens lots in increasing order to fixed lots. Thanks a million in advance

This is how the EA works:

===================

/*

1. Trader inputs specific price level into the EA (e.g. 1.2550) before activating on the chart.

2. If price closes above that price level with as little as 0.00001 above or below the price level, the EA will increase the lots (e.g. 2, 4, 6, 8, 10...)

Therefore, if price closes above the level, the EA will first close the existing order if any, then increase the lots with a buy order. Same thing when price closes below the specified price level, the advisor will exit the previous open trade before increasing the lot with a sell order.

*/

Below is the code:

==============

//+-----------------------------------+

//| TrendChaser EA.mq4 |

//+-----------------------------------+

extern double Price = 1.255;

extern double Offset = 0.00001;

extern double Lots = 0.1;

extern double TP = 50;

extern double SL = 10;

extern double MagicNumber = 1.0;

extern double Slippage = 2;

extern string comment = "Breakout";

bool InitEA = true;

string Order_Comment = "";

string Sym = "";

double SymPoints = 0.0;

double SymDigits = 0.0;

int PointFactor=1;

int Counter = 1;

int BuyTicket=-1;

int SellTicket=-1;

//+------------------------------------------------------------------+

//| expert initialization function |

//+------------------------------------------------------------------+

int init()

{

//----

Order_Comment = comment;

//----

return(0);

}

//+------------------------------------------------------------------+

//| expert deinitialization function |

//+------------------------------------------------------------------+

int deinit()

{

//----

//----

return(0);

}

//+------------------------------------------------------------------+

//| expert start function |

//+------------------------------------------------------------------+

int start()

{

if (AccountNumber()==0) return (0);

if (InitEA)

{

InitEA = false;

Sym = Symbol();

SymPoints = MarketInfo( Sym, MODE_POINT );

SymDigits = MarketInfo( Sym, MODE_DIGITS );

if( SymPoints == 0.001 ) { SymPoints = 0.01; SymDigits = 3; }

else if( SymPoints == 0.00001 ) { SymPoints = 0.0001; SymDigits = 5; }

if (SymDigits==3 || SymDigits==5)

{

PointFactor = 10;

if (Offset<SymPoints)

{

Offset=Offset*10;

}

}

for (int i=0; i<OrdersTotal(); i++)

{

if (OrderSelect(i,SELECT_BY_POS))

{

if (OrderMagicNumber()==MagicNumber)

{

if (OrderType()==OP_BUY)

{

BuyTicket = OrderTicket();

}

else if (OrderType()==OP_SELL)

{

SellTicket = OrderTicket();

}

}

}

}

}

//----

static bool OpenBuy = false;

static bool OpenSell = false;

static datetime PreviousBarTime=NULL;

datetime barTime = iTime(Symbol(),0,0);

if (barTime!=0 && PreviousBarTime!=barTime)

{

if (PreviousBarTime==NULL)

{

PreviousBarTime=barTime;

return(0);

}

PreviousBarTime=barTime;

double open = Open[0];

double open1 = Open[1];

double buyLevel = Price+Offset;

double sellLevel = Price-Offset;

if (open1=buyLevel)

{

OpenBuy = true;

OpenSell = false;

}

else if (open1>sellLevel && open<=sellLevel)

{

OpenSell = true;

OpenBuy = false;

}

else

{

OpenBuy = false;

OpenSell = false;

}

}

RefreshRates();

double ask = MarketInfo(Sym,MODE_ASK);

double bid = MarketInfo(Sym,MODE_BID);

double digits = MarketInfo(Sym,MODE_DIGITS);

double point = MarketInfo(Sym,MODE_POINT);

if (OpenBuy)

{

if (SellTicket>0)

{

if (OrderSelect(SellTicket,SELECT_BY_TICKET))

{

if (OrderCloseTime()==0)

{

if (OrderClose(OrderTicket(),OrderLots(),ask,Slippage*PointFactor,Teal))

{

SellTicket=-1;

}

}

else SellTicket=-1;

}

}

if (BuyTicket<0 && SellTicket<0)

{

double lotSize = Lots;

if (Counter>0) lotSize = NormalizeLot(Symbol(),Lots*Counter);

int tk = EnterLong(Symbol(), lotSize, 0, Slippage*PointFactor, 0, 0, Order_Comment, MagicNumber, 0, Blue);

if (tk>0)

{

BuyTicket = tk;

Counter++;

}

}

if (BuyTicket>0)

{

OpenBuy = false;

}

}

if (OpenSell)

{

if (BuyTicket>0)

{

if (OrderSelect(BuyTicket,SELECT_BY_TICKET))

{

if (OrderCloseTime()==0)

{

if (OrderClose(OrderTicket(),OrderLots(),bid,Slippage*PointFactor,Teal))

{

BuyTicket=-1;

}

}

else BuyTicket=-1;

}

}

if (BuyTicket<0 && SellTicket<0)

{

lotSize = Lots;

if (Counter>0) lotSize = NormalizeLot(Symbol(),Lots*Counter);

tk = EnterShort(Sym, lotSize, 0, Slippage*PointFactor, 0, 0, Order_Comment, MagicNumber, 0, Red);

if (tk>0)

{

SellTicket = tk;

Counter++;

}

}

if (SellTicket>0)

{

OpenSell = false;

}

}

for (i=0; i<OrdersTotal(); i++)

{

if (OrderSelect(i,SELECT_BY_POS))

{

if (OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)

{

RefreshRates();

ask = MarketInfo(OrderSymbol(),MODE_ASK);

bid = MarketInfo(OrderSymbol(),MODE_BID);

digits = MarketInfo(OrderSymbol(),MODE_DIGITS);

point = MarketInfo(OrderSymbol(),MODE_POINT);

int k=1;

if (OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP) {k=-1;}

double sl=OrderStopLoss();

if (SL>0)//first sl

{

//update stoploss

sl = OrderOpenPrice()-k*SL*point*PointFactor;

}

else

{

}

double tp = OrderTakeProfit();

if (TP>0)

{

tp = OrderOpenPrice()+k*TP*point*PointFactor;

}

if ( (sl>0 && MathAbs(sl-OrderStopLoss())>=1*point) || (tp>0 && MathAbs(tp-OrderTakeProfit())>1*point) )

{

OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(sl,digits),NormalizeDouble(tp,digits),OrderExpiration());

}

}

}

}

//----

return(0);

}

//+------------------------------------------------------------------+

int EnterLong(string sym, double lots, double price, int slippage, double stopLoss, double takeProfit, string comment, int magic, datetime expiry, color cl)

{

int cmd;

double ask, bid, digits;

int tk=-1;

double tp=0, sl=0;

for (int i=0; i<2; i++)

{

RefreshRates();

ask = MarketInfo(sym,MODE_ASK);

bid = MarketInfo(sym,MODE_BID);

digits = MarketInfo(sym,MODE_DIGITS);

price = ask;

tk =OrderSend(sym,OP_BUY,lots, NormalizeDouble(price, digits), slippage, NormalizeDouble(stopLoss,digits), NormalizeDouble(takeProfit,digits),comment,magic, expiry, cl);

if (tk>=0)

{

break;

}

Idle();

}

return (tk);

}

int EnterShort(string sym, double lots, double price, int slippage, double stopLoss, double takeProfit, string comment, int magic, datetime expiry, color cl)

{

double ask,bid,digits;

int cmd;

int tk=-1;

double tp=0, sl=0;

for (int i=0; i<2; i++)

{

RefreshRates();

bid = MarketInfo(sym,MODE_BID);

ask = MarketInfo(sym,MODE_ASK);

digits = MarketInfo(sym,MODE_DIGITS);

price = bid;

tk =OrderSend(sym,OP_SELL,lots, NormalizeDouble(bid, digits), slippage, NormalizeDouble(stopLoss,digits), NormalizeDouble(takeProfit,digits),comment,magic, expiry, cl);

if (tk>=0)

{

break;

}

Idle();

}

return (tk);

}

void Idle()

{

if (IsTradeContextBusy())

{

Sleep(100);

}

else

{

Sleep(2500);

}

}

double NormalizeLot(string curPair, double lots)

{

int digit_lot = 1;

if(MarketInfo(curPair,MODE_MINLOT)>=0.01 && MarketInfo(curPair,MODE_MINLOT)<0.1) digit_lot=2;

if(MarketInfo(curPair,MODE_MINLOT)>=0.1 && MarketInfo(curPair,MODE_MINLOT)<1) digit_lot=1;

if(MarketInfo(curPair,MODE_MINLOT)>=1) digit_lot=0;

lots=NormalizeDouble(lots,digit_lot);

if(lots<MarketInfo(curPair,MODE_MINLOT)) lots=MarketInfo(curPair,MODE_MINLOT);

return (lots);

}

 

Hi,

I want to download a xml-file over SSL. With which dll can I do this?

I tried the curllib. But when I want to import this, there are pointer deklaration in the header files like:

struct curl_httppost {

struct curl_httppost *next; /* next entry in the list */

char *name; /* pointer to allocated name */

long namelength; /* length of name length */

char *contents; /* pointer to allocated data contents */

long contentslength; /* length of contents field */

char *buffer; /* pointer to allocated buffer contents */

long bufferlength; /* length of buffer field */

char *contenttype; /* Content-Type */

struct curl_slist* contentheader; /* list of extra headers for this form */

struct curl_httppost *more; /* if one field name has more than one

file, this link should link to following

files */

long flags; /* as defined below */

#define HTTPPOST_FILENAME (1<<0) /* specified content is a file name */

#define HTTPPOST_READFILE (1<<1) /* specified content is a file name */

#define HTTPPOST_PTRNAME (1<<2) /* name is only stored pointer

do not free in formfree */

#define HTTPPOST_PTRCONTENTS (1<<3) /* contents is only stored pointer

do not free in formfree */

#define HTTPPOST_BUFFER (1<<4) /* upload file from buffer */

#define HTTPPOST_PTRBUFFER (1<<5) /* upload file from pointer contents */

#define HTTPPOST_CALLBACK (1<<6) /* upload file contents by using the

regular read callback to get the data

and pass the given pointer as custom

pointer */

char *showfilename; /* The file name to show. If not set, the

actual file name will be used (if this

is a file part) */

void *userp; /* custom pointer used for

HTTPPOST_CALLBACK posts */

};

How can I do this with metatrader??

Or can anybody give me a tipp how I can open a https-link with my metatrader??

 

script stop code

I need the code to stop a script from working on the strategy tester. I have tried variations of IsTesting() but I cannot get it to work on a live or demo account and not work on the strategy tester. Everything I have tried either stops the scrip working on all three setups or it works on all three. Any help would be much appreciated.

 

MAs and visible bars

Well, so many questions - I wonder who is going to answer all of them...

Mine is basic, I think, - I saw in many indicators a check for a minimum number of bars. It seems to me that now, MT4 draws MAs regardless of the number of visible bars. For example, if I zoom in a chart to a maximum I have about 50 bars but still can plot ma200 and it starts right at the beginning of the chart.

So, what is a point of checking a number of visible bars then? Same with a function iMA. Do we need to make sure that the number of visible bars > than MA period for iMA to work properly?

Thank you.

 

MT4 coding of Time Frames in EA

Hi All,

New to MT4 Programming but learning quickly.

Working on an EA that will run in any time frame. I am having an issue in programming part of the logic.

The logic states that I need to look at the next higher time frame and determine if the current candle is long or short.

Example:

longtf1 = iClose(Symbol(),tf1,1) - iOpen(Symbol(),tf1,1);

Where tf1 is the next higher time frame from the current chart time frame.

How would I return what the current time frame is in the EA and use that in my logic?

I picture something like this:

tf0 = (Gleemed by a call to MT4)

if(tf0 = 60) tf1 = 240;

longtf1 = iClose(Symbol(),tf1,0) - iOpen(Symbol(),tf1,0);

shorttf1 = iOpen(Symbol(),tf1,0) - iClose(Symbol(),tf1,0);

Any help would be greatly appreciated.

Happy trading!

 

The MA starts at the beginning of the chart averaging the existing bars so the MA of leftmost bar= the leftmost bar close. So it is not accurate until "Period" bars have passed.

It would be more accurate to use SetIndexDrawBegin(Index, Period), or what I often do,

limit = Bars - (MathMax (counted_bars, Period). This often cleans up the left end of the chart.

Big Be

 

Use Period() to get the current chart period. Make a function with a table to return the next higher TF. Call it from Init().

You can probably find or adapt one from an existing MTF indicator.

PS I usually skip M30.

Big Be

 

Auto OrderComment

Hi, i my Broker ist Pepperstone and i use the OneClickEA.

And this one set an AutoComment in my Order. I am not able to change it in the Setting, the support cant help me. They say, they have buy it self and they have no option to change the code. Hmm ok.

Now i need your help, is it possible to change over an other way the comment in my orders when i open the order with the EA?

Sorry for my english, its not my native language, i hope you understand what i mean.

Thanks.

 

...

Sissi

I wish that the answer could be longer, but the answer is quite short : no.

Once you place an order with your initial comment the only one that can change that comment field is your broker

Sissi:
Hi, i my Broker ist Pepperstone and i use the OneClickEA.

And this one set an AutoComment in my Order. I am not able to change it in the Setting, the support cant help me. They say, they have buy it self and they have no option to change the code. Hmm ok.

Now i need your help, is it possible to change over an other way the comment in my orders when i open the order with the EA?

Sorry for my english, its not my native language, i hope you understand what i mean.

Thanks.
 

help with my partial close EA

Hi,

would appreciate any help with this as I'm stuck.

This EA is 'supposed' to close half of any trade open on any chart at 10 pips but for the life of me I can't seem to get the code to work right.

Sometimes it will work, on another platform it won't so I wonder if part of my problem is to do with mini accounts or something. Also sometimes it will close half of the first order open, but ignore the rest... and I will be honest I really don't understand why.

The moving the SL works fine on all open trades so it must be breathing and alive, but the partial close part has thrown me.

Can anyone help me figure what i am doing wrong. It is supposed to be able to sit on one chart and monitor all trades open, adjusting SL and/or partially closing as required.

Or have I been flogging a dead horse, is what I am trying to do not possible maybe ?

thanks

PG

Code

//+--------------------------------------------------------+

// *****************

// | Close Half Master |

//+--------------------------------------------------------+

// must be on chart before trades placed

extern bool AllPositions = true; // must be set to true to work on ALL positions

extern bool UsePartClose = true;

extern int LevelProfitSL = -50; // never really figured this but it seems to only work and ensure SL is set on trade if set to -ve value

extern int LevelMovingSL = -200; // initial SL if its not already there

extern int LevelProfit0 = 10;

extern int LevelMoving0 = -170;

extern int LevelProfit1 = 30; //

extern int LevelMoving1 = -150;

// could lose one of the above but it seems to run ok.

extern int LevelProfit2 = 70;

extern int LevelMoving2 = -100;

extern string PCsettings = "Partial settings";

extern string pc_value = "LevelProfit3 = part close value";

extern string info = "preserve_lots protects some and leaves to trail"; // so if LP3 is 10 then part close will happen EVERY 10 pips profit

extern int LevelProfit3 = 100;

extern int LevelMoving3 = 1; //so locked in as a BE trade

extern string how_much = "2 = 50%, 3 = 33% 4=25% of order"; //wish list/to do, make this work on lot amount not %

extern double close_percent = 2.0; // 2 is half each time, 3 is 1/3rd, 4 is 1/4 etc etc

extern double preserve_lots = 0.2; // how much to stop from being closed out

extern string info2 = "trailing starts at step+TS+level3moving";

extern int TrailingStop = 140; //14 + 1 + 10 = 16

extern int TrailingStep = 10;

extern int Slippage = 2;

extern bool ShowComment = true;

extern bool UseSound = true;

string var_132 = "button.wav";

string var_133 = "meep.wav";

bool closedHalf = false;

//+------------------------------------------------------------------+

void deinit() { Comment(""); }

//+------------------------------------------------------------------+

void start()

{

double point; int digits; string msg = "";

if (closedHalf == true && OrdersTotal() == 0) closedHalf = false;

for (int i = 0; i OrdersTotal(); i--)

{ if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

{

if (AllPositions || (OrderSymbol() == Symbol())) // I tried this too: if (AllPositions)

{

ThreeLevelSystemOfOutput(); digits = MarketInfo(OrderSymbol(),MODE_DIGITS);

point = MarketInfo(OrderSymbol(),MODE_POINT);

msg = msg + OrderSymbol() + " Open Price " + DoubleToStr(OrderOpenPrice(),digits) + " SL = " + DoubleToStr(OrderStopLoss(),digits) + " (" + StopLossInPoint() + ")\n";

}

}

}

if (ShowComment) Comment(msg);

}

//+------------------------------------------------------------------+

void ThreeLevelSystemOfOutput()

// actually now 4 :-)

{

int profit = ProfitPosition();

int sl = StopLossInPoint();

int spread = MarketInfo(OrderSymbol(),MODE_SPREAD);

double lots = MathCeil(OrderLots() * 10.0) / 10.0;

// add sl level to make the quirk of setting sl automatically work

//added 0 level to get a extra move like a trailing SL

if (lots < preserve_lots) TrailingPositions();

{

if ((profit > LevelProfitSL) && (profit <= LevelProfit0) && (sl < LevelMovingSL)) ModifyStopLossInPoint(LevelMovingSL);

if ((profit > LevelProfit0) && (profit <= LevelProfit1) && (sl < LevelMoving0)) ModifyStopLossInPoint(LevelMoving0);

if ((profit > LevelProfit1) && (profit <= LevelProfit2) && (sl < LevelMoving1)) ModifyStopLossInPoint(LevelMoving1);

if ((profit > LevelProfit2) && (profit <= LevelProfit3) && (sl < LevelMoving2)) ModifyStopLossInPoint(LevelMoving2);

if ((profit > LevelProfit3) && (sl < LevelMoving3))

{

ModifyStopLossInPoint(LevelMoving3); // updated in v6 from 1 to 3

//changed in v 10 to remove extra condition

//if (UsePartClose && closedHalf == false) PartClose();

if (UsePartClose) PartClose();

}

if (profit > LevelMoving3 + TrailingStop + TrailingStep) TrailingPositions();

}

}

//+------------------------------------------------------------------+

void PartClose()

{

bool result = false;

//2.0 is half, 3.0 is 1/3, 4.0 is a quarter and so on. Should only close out once.

//++++ These are adjusted for 5 digit brokers.

/*int pips2points; // slippage 3 pips 3=points 30=points

double pips2dbl; // Stoploss 15 pips 0.015 0.0150

int Digits.pips; // DoubleToStr(dbl/pips2dbl, Digits.pips)

if (Digits % 2 == 1){ // DE30=1/JPY=3/EURUSD=5 forum.mql4.com/43064#515262

pips2dbl = Point*10; pips2points = 10; Digits.pips = 1;

} else { pips2dbl = Point; pips2points = 1; Digits.pips = 0; }

// OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl

// pips2points multiplier - credit to WHRoeder for correct approach : http://forum.mql4.com/46133

*/

//double lots = MathCeil(OrderLots() / 2.0 * pips2dbl) / 10.0;

double lots = MathCeil(OrderLots() / close_percent * 10.0) / 10.0; // the bit to part close out 1/3, 1/2 of the order etc

if (lots > preserve_lots)

{

if (OrderType() == OP_BUY) { result = OrderClose(OrderTicket(),lots,Bid,Slippage,CLR_NONE); }

if (OrderType() == OP_SELL) { result = OrderClose(OrderTicket(),lots,Ask,Slippage,CLR_NONE); }

if (result) { if (UseSound) PlaySound(var_133);

//closedHalf = true; just testing to see if this is stopping rest of closing of trade, should be uncommented if no difference.

} } }

//+------------------------------------------------------------------+

void TrailingPositions() { double bid; double ask; double point = MarketInfo(OrderSymbol(),MODE_POINT);

if (OrderType() == OP_BUY) { bid = MarketInfo(OrderSymbol(),MODE_BID);

if (bid - OrderOpenPrice() > TrailingStop * point) {

if (OrderStopLoss() < bid - (TrailingStop + TrailingStep - 1) * point)

{ ModifyStopLoss(bid - TrailingStop * point); return; } } }

if (OrderType() == OP_SELL) { ask = MarketInfo(OrderSymbol(),MODE_ASK);

if (OrderOpenPrice() - ask > TrailingStop * point)

{

if ((OrderStopLoss() > ask + (TrailingStop + TrailingStep - 1) * point) || (OrderStopLoss() == 0)) { ModifyStopLoss(ask + TrailingStop * point); } } } }

//+------------------------------------------------------------------+

void ModifyStopLoss(double sl)

{ bool result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);

if (result && UseSound) PlaySound(var_132); }

//+------------------------------------------------------------------+

void ModifyStopLossInPoint(int stoploss)

{

bool result; double sl = 0;

double point = MarketInfo(OrderSymbol(),MODE_POINT);

if (OrderType() == OP_BUY) sl = OrderOpenPrice() + stoploss * point;

if (OrderType() == OP_SELL) sl = OrderOpenPrice() - stoploss * point; result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);

if (result && UseSound) PlaySound(var_132); }

//+------------------------------------------------------------------+

int ProfitPosition() {

double bid;

double ask;

double point = MarketInfo(OrderSymbol(),MODE_POINT);

double profit

= 0;

if (OrderType() == OP_BUY) { bid = MarketInfo(OrderSymbol(),MODE_BID);

profit = (bid - OrderOpenPrice()) / point; }

if (OrderType() == OP_SELL) { ask = MarketInfo(OrderSymbol(),MODE_ASK); profit = (OrderOpenPrice() - ask) / point; } return(MathRound(profit)); }

//+------------------------------------------------------------------+

int StopLossInPoint() {

double point = MarketInfo(OrderSymbol(),MODE_POINT);

double sl = 0;

if (OrderType() == OP_BUY) sl = (OrderStopLoss() - OrderOpenPrice()) / point;

if (OrderType() == OP_SELL) sl = (OrderOpenPrice() - OrderStopLoss()) / point;

if (OrderStopLoss() == 0.0) sl = -OrderOpenPrice() / point; return(MathRound(sl));

}

Reason: