Let's learn MQL4 online together

Here’s the code snippet for lot optimization:


//Place these declarations before everything
extern double  takeProfit         = 100.0;        // Take Profit (pips)
extern double  stopLoss           = 50.0;        // Stop Loss (pips)
extern int     slippage           = 5; // Maximum Slippage (pips)

//Place the following in OnInit()

if(Digits==5 || Digits==3) // Adjust for 3- or 5-digit Brokers
     {
      takeProfit*=10;
      stopLoss *= 10;
      slippage *= 10;
     }

I asked about other ideas outside of my own. Thanks though for your reply on my own ideas. I really appreciate it!

Also, to make this thread complete for beginner MQL programmers:
Is there any recommendation for a snippet library, or snippet webpage with standard MQL functions? Other recommended websites when a person creates an EA?

As far as I know, you can find them in the mql4 docs. But my advise is to build it based off of your own understanding instead of just copy and paste.

MQL5.com has a codebase that has thousands of snippets but it’s hard to find what you’re looking for. Also I like Qai’s suggestion for DYI when you’re learning.

Here is a more complete description. I haven’t added any graphs/images yet but I will do that later.

[Trend] HALO - Greed is Good

Note this is vesion 2 and I’m already on version 3. I will post more next week in that thread.

I’ve started with another EA that will be 2000-lines. I wrote 1300 lines already. But it’s too big for a solo project I think. And you guys? You learnt MQL these couple of months also like me. Do you know exactly what you are gonna build? Or how are you gonna start building your new Expert Advisor?

My MQL code base contains more than 10000 lines and growing (I’m a programmer). Beside MQL, you’d better learn some architecture technology, such as OOP, if you want to make serious project.

What strategy are you working on to implement?

thank you for your wise input!

Since this subject is about learning mql: which youtube training or ebook course would you recommend for learning OOP in MQL?

I find it a pity that there is almost no tutorials on mql. I did find about 10 mql ebooks covering the basics. [B]Does anyone know where to find advanced MQL courses?[/B]

I did find the following mql teacher covering training on basic and intermediar level: Is there any EA where entry/exit is based on doji, morning star and other candlestick patterns? - Doji Candlestick Patterns - General - MQL5 programming forum

Hate to say it but you boys are putting the cart before the horse here.

Study, read, research all you like but there is only one way to learn, and that’s practice.

But before that you will need a strategy to test. From what I read you haven’t even got that! Go find a strategy and then start practicing to code it. There is a general lack of direction and purpose here to the point it is seemed more desirable to try and con someone-else into doing the hard work for you!

Qia88, I’m working on a breakout strategy with MA100/200, MA crossovers and maybe later some overbought/oversold signals.

I’m now working on this code. Could anyone fix it please?

for (i = 0; i < OrdersTotal(); i++)
{
OrderSelect (i, SELECT_BY_POS, MODE_TRADES);

  if ((OrderMagicNumber() == magic) &&OrderCloseTime==0 && (OrderType()==OP_BUY)) {
  TP_buyorders +=MarketInfo(Symbol(), MODE_TICKVALUE) * OrderLots() * pips;}
  else TP_sellorders += MarketInfo(Symbol(), MODE_TICKVALUE) * OrderLots() * pips;
  Comment("TP buy orders: ", TP_buyorders," euro. ", "And TP sell orders: ", TP_sellorders," euro.");   }
 //The output on the chart should look like this: TP for total buy orders: 120 euro. TP for all sell orders: 80 euro.

Thank you for your input.

The strategies I’ve gathered are worth automating, as you’ve read in my first post. “I don’t need to learn anymore strategy”, because I have enough good ones. I’m now in a phase where I’m trying to automate them step by step.

Forex strategies I learnt:

  • Wyckoff, VSA, elliot, different styles of martingale and hedging, LOB, straddling, PA/grid systems (from: Steve Nison, Chris Lori, Frank Paul, James ****s, Mark MCrae, Agustin Silvani, Andrew Jeken, Alex Wakemann, Ed Ponzi, Martin Cole and Hector)

More of my forex experience:

  • I learnt MQL
  • I"m using tickstory data
  • analysed the news and documented differences, similarities and weaknesses in the fundamental market
  • Optimized/analyzed EA’s regarding out-of-sample testing, cross-validation, high Sharpe ratios
  • tested 25 trading platforms
  • skimmed 1500 ebooks on forex/mql and summerized need-to-knows
  • Researched who the best broker is for me (Dukascopy/Alpari)
  • summerized the popular indicators regarding how-to-use
  • summerized SR/bounce/trend/consolidation signals

Conclusion:
My goal (as many of you traders), is to make profit. But I’m so focussed on other things, like daily reading new strategies and threads/articles. I’m learning forex fulltime. That’s why I need structure (mini goals and deadlines) in my development.

I love to automate my strategies. The only disadvantage is, I would be much faster with a coach that gives me proper deadlines, minigoals and maybe even advanced MQL coaching. At this pace I’m getting there. I’m motivated enough, but I’m not working in a team. Any coder in c++ I know have their own teammates for their projects so it only makes sense for me to form my own team.

1 Like

Sorry bro but all I read there was I don’t have a strategy. Not trying to be nasty or anything but in all honesty… How do you program an EA if you don’t have a strategy first

Here is an update. Enclosed you’ll find basic library functions that I’ve written.
Expert Advisor combining with indicator

  • Moving Average
  • psar
  • cci
    -macd
  • volume
  • accelerator

Important functions:

  • get last order
  • time: return time of candle, startHr, endHr
  • trial version
  • extended error checking

Order management

  • closing or deleting buy, sell, selllimit, buylimit, sellstop, buystop
  • lot increment (martingale style)

extern double lots=0.01;
extern int takeprofit=40;
extern int stoploss=40;
extern int magic=33454;

//checkMA
extern int period_MA=25;

//PSAR
extern double Step=0.02;
extern double Maximum=0.2;
extern double TimeFrame=0;
//cci
extern int period_cci=30;
//rsi
extern int period_rsi=9;
//bb
extern int period_bb=20;
extern int deviation_bb=2;
extern int shift_bb=2;
extern int apply_bb=PRICE_CLOSE;
//timer

extern int startHr=4;
extern int endHr=20;
extern double g=10;
bool check=true;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
//checkMA
   bool check;
   check=checkMA();
   if(check==true) Alert("place buy");
   else if(check==false) Alert("place sell");
//psar
   bool check2;
   check2=psar();
   if(check==true)
     {
      closesell();
      openbuy();
     }
   else if(check==false)
     {
      closebuy();
      opensell();
     }
//CCI

   bool bill=cci();
   if(bill==true && OrdersTotal()<=1)
     {
      closesell();
      openbuy();
     }
   else if(bill==false && OrdersTotal()<=1)
     {
      closebuy();
      opensell();
     }
//macd
   bool check3;
   check=macd();
   if(check==true)
     {
      closesell();
      openbuy();
     }
   else if(check==false)
     {
      closebuy();
      opensell();
     }
//rsi
   bill=rsi();
   if(bill==true)
     {
      closebuy();
      openbuy();
     }
   else if(bill==false)
     {
      closebuy();
      opensell();
     }

//volume
   bool check4=volume();
   if(check4==true)
     {
      openbuy();
     }
   else if(check==false)
     {
      opensell();
     }
//accelator
   bool c=accelator();
   if(c==false && OrdersTotal()<1)
     {
      closesell();
      openbuy();
     }
   else if(c==true && OrdersTotal()<1)
     {
      closebuy();
      opensell();
     }
//getlastorder
   bool b=getlastorder();
   if(b==true)
     {
      double lots=1.2; //if loss, then increase lotSize
                       //openbuy( lot);
     }
   else if(b==false) //previous closed order was in profit
     {
      lots=1;
      //openbuy(lots);
     }
     //check time
   bool t=checktime();
   if(OrdersTotal()==0)
     {
      if(t==true && check==true)
        {
         openbuystop(0,0);
         opensellstop(0,0);
         check=false; //flag check, meaning: next hour_candle this code will execute again.
        }
      else if(t==false)
        {
         closebuy();
         closesell();
         deletepending();
         check=true;
        }
     }
   else if(OrdersTotal()==1)
     {
      deletepending();
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//checkMA
bool checkMA()
  {
   double ma=0;
   ma=iMA(Symbol(),0,period_MA,0,MODE_SMA,PRICE_CLOSE,0);
   if(Ask>ma) return(true);
   else if(Ask<ma) return (false);
   else return (EMPTY_VALUE);
  }
//psar
bool psar()
  {

   double sar=iSAR(NULL,TimeFrame,Step,Maximum,0);
   if(Ask>sar) return(true);
   if(Ask<sar) return(false);
   else return (EMPTY_VALUE);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool cci()
  {
   double point;
   point=iCCI(NULL,0,period_cci,PRICE_TYPICAL,0);
   if(point>0) return(true);
   else if(point<0) return(false);
   else return(EMPTY_VALUE);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool macd()
  {
   double ma;
   ma=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   if(ma>0) return(true);
   else if(ma<0) return(false);
   else return(EMPTY_VALUE);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool rsi()
  {
   double r1,r2;
   r1=iRSI(NULL,0,period_rsi,PRICE_CLOSE,0);
   r2=iRSI(NULL,0,period_rsi,PRICE_CLOSE,1);
   if(r2>70&&r1<70) return(false);
   if(r2<30&&r1>30) return(true);
   else return (EMPTY_VALUE);
  }
//bolinger band
bool bb()
  {
   double b,c;
   b=iBands(NULL, 0,period_bb,deviation_bb,shift_bb,apply_bb,MODE_LOWER,0);
   c=iBands(NULL, 0, period_bb, deviation_bb, shift_bb, apply_bb, MODE_UPPER,0);
   if(Close[0]<b && Open[0]>=b && b>Close[0])
     {
      return(false);
     }
   else if(Close[0]>c && Open[0]<=c && c<=Close[0])
     {
      return (true);
     }
   else return (EMPTY_VALUE);
  }
//volume
bool volume()
  {
   int vol=iVolume(NULL,0,0);
   if(vol>300) return (true);
   else if(vol<300) return (false);
   else return(EMPTY_VALUE);
  }
//accelator
bool accelator()
  {
   double ac,ac1;
   ac=iAC(NULL,0,0);
   ac1=iAC(NULL,0,1);
   if(ac1>0.000&&ac<0.000) return(true);
   else if(ac1<0.000&&ac>0.000) return(false);
   else return(EMPTY_VALUE);
  }
//+------------------------------------------------------------------+
void closebuy()
  {
   for(int i=0; i<OrdersTotal();i++)
      //+------------------------------------------------------------------+
      //|                                                                  |
      //+------------------------------------------------------------------+
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderType()==OP_BUY)
        {
         int j=0;
         while(j!=5)
           {
            OrderClose(OrderTicket(),OrderLots(),Bid,3,Pink);
            j++;
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void closesell()
  {
   for(int i=0; i<OrdersTotal();i++)
      //+------------------------------------------------------------------+
      //|                                                                  |
      //+------------------------------------------------------------------+
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderType()==OP_SELL)
        {
         int j=0;
         while(j!=5)
           {
            OrderClose(OrderTicket(),OrderLots(),Ask,3,Pink);
            j++;
           }
        }
     }
  }
//+------------------------------------------------------------------+
void deletebuy()
  {
   for(int i=0;i<OrdersTotal();i++)
      //+------------------------------------------------------------------+
      //|                                                                  |
      //+------------------------------------------------------------------+
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderType()==OP_BUYSTOP)
        {
         OrderDelete(OrderTicket());
        }
     }
  }
//+------------------------------------------------------------------+
void opensell()
  {
   OrderSend(Symbol(),OP_SELLLIMIT,lots,Bid,3,Bid+stoploss*Point,Bid-takeprofit*Point,NULL,magic,Red);
  }
//+------------------------------------------------------------------+
void openbuy()
  {
   OrderSend(Symbol(),OP_BUY,lots,Ask,3,Ask-stoploss*Point,Ask+takeprofit*Point,NULL,magic,Red);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void openbuystop(double price,double stop)
  {
   if(OrderSend(Symbol(),OP_BUYSTOP,lots,Ask+g*Point,3,Ask+g*Point-stoploss*Point,Ask+g*Point+takeprofit*Point,NULL,magic,Pink)==true)
     {
      Print("Order send");
     }
   else fun_error(GetLastError());
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void opensellstop(double price,double stop)
  {
   OrderSend(Symbol(),OP_SELLSTOP,lots,price,3,stop,price-takeprofit*Point,NULL,magic,Red);
  }
//+------------------------------------------------------------------+
bool deletepending()
  {
   for(int w=0;w<OrdersTotal();w++)
     {
      OrderSelect(w,SELECT_BY_POS,MODE_TRADES);
      if(OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP)
        {
         OrderDelete(OrderTicket());
        }
     }
   return(0);
  }
//getlastorder, for example, if last buy order was a loss, then double lot (martingale)
bool getlastorder()
  {
   for(int i=OrdersTotal();i<0;i--)
      //+------------------------------------------------------------------+
      //|                                                                  |
      //+------------------------------------------------------------------+
     {
      OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
      if(OrderType()==OP_BUY || OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderProfit()<0) return(true);

      else if(OrderType()==OP_BUY || OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderProfit()>0)

         return(false); //if previous closed order made profit, then false.

      else return(EMPTY_VALUE);
     }
   return(0); //should I return 0 or EMPTY_VALUE again?
  }
//+------------------------------------------------------------------+
double lotIncrement()
  {
   double lots=0;
   for(int i=0;i<158800;i++)
     {
      OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
      if(OrderType()==OP_BUY || OrderType()==OP_SELL)
        {
         lots+=OrderLots();
        }
     }
   Comment("total number of lots traded: ",lots);
   return(lots);
  }
//+------------------------------------------------------------------+
double Time() //return time of current candle
  {
   int hour=TimeHour(Time[0]);
   int minute=TimeMinute(Time[0]);
   int second=TimeSeconds(Time[0]);
   Alert("Time of this candle is: ",hour,":",minute,":",second);
   return(0);
  }
//+------------------------------------------------------------------+
bool checktime()
  {
   int i=0;
   int hourtime=TimeHour(Time[i]);
   if(hourtime==startHr)return(true);

   else if(hourtime==endHr) return (false);
   else return (EMPTY_VALUE);
  }
//+------------------------------------------------------------------+
int fun_error(int Error)
  {

   switch(Error)
     {
      case 4: Print("Trade server is busy");
      Sleep(3000);
      return(1);
      default: Print("error",Error);
      return(0);
     }
  }
//+------------------------------------------------------------------+
bool trial_version()
  { //TimeCurrent is the servers time, it cannot be 'hacked' by changing the client's time on his computer
   datetime starts=D'24.02.2014';
   datetime ends=D'5.03.2014';
   if(TimeCurrent()>=starts && TimeCurrent()<=ends)
     {
      Print("EA is still in trial_mode");
     }
   else { Print("Trial mode expired"); }
   return(0);
  }
//+------------------------------------------------------------------+

thank you for your reply Bob. I have a strategy but this thread is not about my strategy. In fact, it’s about learning mql and finding a teammate or forex buddy or mql coach or private forex teacher.
Are you interested to personally share your great vast knowledge with me? Even if you only wanted to support in a way to provide structure, deadlines and mini goals I would be forever thankful and we could learn a lot from each other. I’m looking forward to making friends with you.

Bro, my knowledge not that vast. My commitment is. Problem with speculating is that’s it’s a solo journey. As one of my previous mistakes, any deviation from your own work can and will be disastrous, setting you back months. In my opinion, you are best working alone. Finding a working strategy is going to be easier than finding someone-else who understands it.

But when you get stuck, make this a point of contact with the rest of us. That way you’ll document your development and we’ll all understand a bit better what it is your trying to achieve. End result, our replies can be more tailored to you.

I will add this but into your code. Something I have learnt recently. Learn to use the Print function. During your development phase the only way to check if the bots logic is functioning as desired is to print a log in the journal at each step. Makes debugging real easy.

All the best bro.

1 Like

And read this Loops and Closing or Deleting Orders - Expert Advisor - MQL4 and MetaTrader 4 - MQL4 programming forum

thank you so much for the tips! I truly appreciate it.

thank you. These debugging mql tips are worth gold! It’s truly amazing how informative teaming up can be, although maybe you don’t prefer it this link you provided is actually really informative to me. I appreciate it!

According to your link, this code doesn’t select all orders:

for(PositionIndex = 0; PositionIndex < TotalNumberOfOrders; PositionIndex++)

And this code DOES select all orders:

for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --)

[B]Question[/B]:
Why does it not work when using PositionIndex++?
I read the link, but I still don’t understand. PositionIndex keeps increasing by 1.

0
1
2
3
4
5

So is this causing the bug?

TotalNumberOfOrders
. But why? Because this is a fixed number. For example ‘5 totalOrders’. Even after closing an order, this variable stays fixed: 5. Because it’s inside the loop until all orders have been closed.

The variable is outside the loop:

TotalNumberOfOrders = OrdersTotal();
. So this shouldn’t cause any bug.