Tuesday, 18 September 2012

Membuat EA tanpa Coding, Cross MA

http://indo.mt5.com/showthread.php?7186-Praktek-Membuat-EA-sederhana-tanpa-melakukan-coding.

Salam profit untuk semua trader di forum MT5 tercinta. 

Mohon ijin kepada moderator yang baik untuk membuka thread baru tentang programming Expert Advisor (EA). Saya mengaku sebenarnya saya adalah newbie asli, baik di dunia Forex apalagi di bidang Expert Advisor. Namun karena tahun lalu (2010) newbie ini pernah nekat menulis thread tentang cara membuat EA, akibatnya banyak yang minta diskusi tentang Expert Advisor di email. Dan dari situ saya mengetahui bahwa betapa menggeloranya semangat teman-teman trader untuk bisa tahu dan menguasai cara membuat EA ini.

Bagi mereka yang pernah belajar programming C dan C++, tentu tidak akan mengalami kesulitan untuk memahami bahasa pemrograman MQL yang menjadi bahasanya EA. Tapi bagi yang tidak suka ruwet-ruwet, bagaimana ?. Di luar sana banyak software-software yang memudahkan pembuatan EA seperti Forex EA Generator. Tapi menguasai software ini tidak mudah. Masih banyak kendala yang harus dihadapi mereka yang belum pernah belajar bahasa komputer.

Melalui thread ini, saya mengajak teman-teman yang ingin sekali bisa membuat EA- untuk praktek cara membuat EA sederhana tanpa melakukan coding. Tools yang kita gunakan adalah Expert Advisor Builder online di alamat internet ini :

http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/

Bagaimana teman-teman ? Apakah semangat ingin membuat EA sendiri ?

Jika jawabannya ya, maka anda tidak membutuhkan waktu lama. Cukup simak luangkan waktu menyimak penjelasan singkat di thread ini -- lalu praktekkan !. Lewat ujicoba 2 atau 3 kali biasanya anda sudah bisa menggenerate EA sendiri tanpa kesulitan. Tentu saja EA yang dibuat dengan Builder online ini bukan jenis EA yang ruwet-ruwet. EA yang bisa diciptakan disini adalah jenis EA yang memakai indikator bawaan MT4 sendiri.

Tapi lumayanlah. Setelah mahir menggunakan builder ini, anda sudah bisa membuat EA dengan konsep trading sendiri. Bisa mengujicoba dengan backtesting, dan bisa sharing EA anda di forum MT5 dengan trader lain. Ada kemajuan !. Tidak perlu minta bantuan master EA yang lewat untuk dibuatkan EA lagi. Ke depannya anda bisa memperdalam ilmu coding jika dibutuhkan dengan dasar yang saat ini dimiliki.

Baik, inilah tampilan EA Builder online tsb.

Spoiler Spoiler:



Praktek : Membuat EA Simple MA.

Langsung praktek saja ya ? Kita lewatkan teori-teori yang tidak perlu. Langsung saja ke tujuan.

Katakan kita memiliki sebuah konsep trading dengan Simple MA. Ada 2 MA, masing-masing adalah MA 12 simple close dan MA 32 simple close. Perhatikan gambar di bawah ini :

Spoiler Spoiler:


Kita memiliki rule sebagai berikut :

1. Jika MA12 memotong MA32 dari atas ke bawah, maka SELL dengan TP 10 dan SL 30.
2. Jika MA12 memotong MA32 dari bawah ke atas, maka BUY dengan TP 10 dan SL 30.

Bagaimana membuat EA dari konsep trading di atas ?.

Kita akan langsung memasukkan nilai-nilai tadi di EA Builder kita. Ayo, sekarang kita meluncur ke TKP.

Penggunaan EA Builder Online nanti sangat sederhana. Cuma ada 4 langkah, dan EA kita sudah jadi. Langkah itu tampak di gambar, yaitu :

1. Masukkan parameter Order Option (TP, SL, Slippage, dll).
2. Masukkan logika SELL (Kapan EA harus melakukan SELL).
3. Masukkan logika BUY (Kapan EA harus melakukan BUY).
4. Selesai, tekan tombol "Complete", dan EA telah tersedia untuk anda. 

Kita praktekkan langsung di bawah ya....


Saya biasanya melakukan pengisian parameter seperti dalam coding EA, yaitu mulai dari mengisi nilai TP, nilai SL dan lain-lain. Maka kita masuk ORDER OPTION dulu, dan kita masukkan angka parameter yang kita inginkan.

Spoiler Spoiler:


Dalam praktek ini, saya gunakan Lot sebesar 1 lot setiap OP. StopLoss 30 pip, TakeProfit 10 pip, dan fasilitas Trailing Stop saya matikan (disable). Kapan-kapan jika anda menginginkan adanya fasilitas Trailing Stop di dalam EA anda, cukup anda ubah ke enable.

Berikutnya kita masuk ke tahap 2, yaitu memasukkan logika SELL. Kapan EA harus melakukan SELL ?

Untuk anda-anda yang belum pernah coding, saya coba jabarkan dengan detil -- sehingga pemula sekalipun pasti bisa membuat EA di thread ini.

Perhatikan gambar chart ini.

Spoiler Spoiler:


Katakanlah saat ini candle terakhir yang sedang berjalan adalah candle yang saya beri nomor 2. Tidak usah dilihat candle-candle selanjutnya, anggap tidak ada. Saat ini, candle terakhir dan yang tengah berjalan adalah candle nomor 2.

Pada saat candle 2, si MA 32 (merah) sedang berada di atas MA 12 (kuning). MA 32 saat itu sudah dipotong dari atas oleh MA 12. Bahasa matematika-nya adalah MA32 > MA12. Dan ini terjadi di candle sekarang atau disebut "Shift 0".

Sekarang lihat satu candle sebelumnya. Disini, MA 32 (merah) posisinya di bawah MA 12 (kuning). Atau MA 32 < MA 12 pada Shift 1. Shift 1 maksudnya pada satu candle sebelum candle yang sekarang.

Kalau kita tulis ulang persamaan tadi, menjadi demikian.

MA32 < MA12 Shift 1 AND MA32 > MA12 Shift 0

Persamaan di atas adalah kondisi programming dimana si EA harus melakukan SELL. buat yang masih bingung, silakan dibaca -- diresapi dan dihayati berulang-ulang.

Persamaan tadi segera kita masukkan ke EA Builder Online kita di bawah. Sebagai catatan, saya membuat EA ini untuk pair EURUSD di TF 1H. Ya ini sekedar contoh.

Spoiler Spoiler:


Pada gambar di atas, kita baru memasukkan persamaan ini :

MA32 < MA12 Shift 1

Kita belum memasukkan persamaan yang satu lagi. Yaitu yang Shift 1. Maka kita tekan tombol ADD untuk memasukkan persamaan yang kanan (Shift 0).

Spoiler Spoiler:


Nah, masukkan persamaan MA32 > MA12 Shift 0 di builder ini. Perhatikan bahwa antara persamaan kiri dan kanan menggunakan operator AND (lihat lingkaran pada gambar).

Kalau tahap ini sudah selesai anda lakukan, maka anda baru selesai memasukkan logika SELL ke dalam EA ini. Sekarang EA sudah mengerti kapan dia harus SELL.

Tapi kan dia belum mengerti bagaimana dan kapan harus BUY ? Maka kita akan masuk ke tahap 3 yaitu memasukkan logika BUY.



Sebelum memasukkan logika BUY, baiknya kita mencoret-coret dulu persamaan yang diperlukan. Agar nanti mudah memasukkan ke EA Builder-nya.

Spoiler Spoiler:


Kita sama-sama memperhatikan gambar. Posisi BUY terjadi bila :

Kiri (Shift 1) : MA32 (merah) di atas MA12 (kuning)
Kanan (Shift 0) : MA32 (merah) di bawah MA12 (kuning)

Atau bila ditulis dengan cara lain :

MA32 > MA12 Shift 1 AND MA32 < MA12 Shift 0

Sip. Maknyus !. Kita akan implementasikan formula ini ke dalam EA Builder. Kita klik BUY Strategy

Spoiler Spoiler:


Pada gambar atas, kita masukkan dulu persamaan kiri (yang shift 1). Lalu tekan ADD untuk memasukkan persamaan yang kanan. Operatornya adalahAND, jangan lupa dimasukkan ya.

Spoiler Spoiler:


 Baiklah, EA kita seharusnya sudah selesai !.

Cari tombol COMPLETE, dan tekan. Maka EA kita berupa coding MQL akan terdownload ke laptop kita.


Hasil :


//+------------------------------------------------------------------+
//| This MQL is generated by Expert Advisor Builder                  |
//|                http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/ |
//|                                                                  |
//|  In no event will author be liable for any damages whatsoever.   |
//|                      Use at your own risk.                       |
//|                                                                  |
//+------------------- DO NOT REMOVE THIS HEADER --------------------+

#define SIGNAL_NONE 0
#define SIGNAL_BUY   1
#define SIGNAL_SELL  2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

#property copyright "Expert Advisor Builder"
#property link      "http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/"

extern   int      MagicNumber    = 0;
extern   bool     SignalMail     = False;
extern   bool     EachTickMode   = True;
extern   double   Lots           = 1.0;
extern   int      Slippage       = 3;
extern   bool     UseStopLoss    = True;
extern   int      StopLoss       = 30;
extern   bool     UseTakeProfit  = True;
extern   int      TakeProfit     = 10;
extern   bool     UseTrailingStop = False;
extern   int      TrailingStop   = 30;

int BarCount;
int Current;
bool TickCheck = False;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   BarCount = Bars;
   if (EachTickMode) Current = 0; else Current = 1;
   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {
   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() {
   int Order = SIGNAL_NONE;
   int Total, Ticket;
   double StopLossLevel, TakeProfitLevel;

   if (EachTickMode && Bars != BarCount) TickCheck = False;
   Total = OrdersTotal();
   Order = SIGNAL_NONE;

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+


double Buy1_1 = iMA("EURUSD", PERIOD_H1, 32, 0, MODE_SMA, PRICE_CLOSE, Current + 1);
double Buy1_2 = iMA("EURUSD", PERIOD_H1, 12, 0, MODE_SMA, PRICE_CLOSE, Current + 1);
double Buy2_1 = iMA("EURUSD", PERIOD_H1, 32, 0, MODE_SMA, PRICE_CLOSE, Current + 0);
double Buy2_2 = iMA("EURUSD", PERIOD_H1, 12, 0, MODE_SMA, PRICE_CLOSE, Current + 0);

double Sell1_1 = iMA("EURUSD", PERIOD_H1, 32, 0, MODE_SMA, PRICE_CLOSE, Current + 1);
double Sell1_2 = iMA("EURUSD", PERIOD_H1, 12, 0, MODE_SMA, PRICE_CLOSE, Current + 1);
double Sell2_1 = iMA("EURUSD", PERIOD_H1, 32, 0, MODE_SMA, PRICE_CLOSE, Current + 0);
double Sell2_2 = iMA("EURUSD", PERIOD_H1, 12, 0, MODE_SMA, PRICE_CLOSE, Current + 0);
   
   //+------------------------------------------------------------------+
   //| Variable End                                                     |
   //+------------------------------------------------------------------+

   //Check position
   bool IsTrade = False;

   for (int i = 0; i < Total; i ++) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() <= OP_SELL &&  OrderSymbol() == Symbol()) {
         IsTrade = True;
         if(OrderType() == OP_BUY) {
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Buy)                                           |
            //+------------------------------------------------------------------+

            //+------------------------------------------------------------------+
            //| Signal End(Exit Buy)                                             |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               continue;
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) {                 
               if(Bid - OrderOpenPrice() > Point * TrailingStop) {
                  if(OrderStopLoss() < Bid - Point * TrailingStop) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0, MediumSeaGreen);
                     if (!EachTickMode) BarCount = Bars;
                     continue;
                  }
               }
            }
         } else {
            //Close

            if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Close Sell");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               continue;
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) {                 
               if((OrderOpenPrice() - Ask) > (Point * TrailingStop)) {
                  if((OrderStopLoss() > (Ask + Point * TrailingStop)) || (OrderStopLoss() == 0)) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop, OrderTakeProfit(), 0, DarkOrange);
                     if (!EachTickMode) BarCount = Bars;
                     continue;
                  }
               }
            }
         }
      }
   }
   //+------------------------------------------------------------------+
   //| Signal Begin(Entry)                                              |
   //+------------------------------------------------------------------+

   if (Buy1_1 > Buy1_2 && Buy2_1 < Buy2_2) Order = SIGNAL_BUY;

   if (Sell1_1 < Sell1_2 && Sell2_1 > Sell2_2) Order = SIGNAL_SELL;
   //+------------------------------------------------------------------+
   //| Signal End                                                       |
   //+------------------------------------------------------------------+

   //Buy
   if (Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      if(!IsTrade) {
         //Check free margin
         if (AccountFreeMargin() < (1000 * Lots)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss) StopLossLevel = Ask - StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel = 0.0;

         Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
    Print("BUY order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
   } else {
    Print("Error opening BUY order : ", GetLastError());
   }
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) BarCount = Bars;
         return(0);
      }
   }

   //Sell
   if (Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      if(!IsTrade) {
         //Check free margin
         if (AccountFreeMargin() < (1000 * Lots)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }
         if (UseStopLoss) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel = 0.0;

         Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
    Print("SELL order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Open Sell");
   } else {
    Print("Error opening SELL order : ", GetLastError());
   }
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) BarCount = Bars;
         return(0);
      }
   }

   if (!EachTickMode) BarCount = Bars;
   return(0);
}
//+------------------------------------------------------------------+


Kita akan coba melakukan backtesting di MT4. 

Yah...hasilnya sih tidak terlalu memuaskan secara profit  namanya juga konsep trading asal jadi. Tapi EA ini sudah sanggup trading BUY dan SELL tepat pada cross indikator MA yang kita inginkan.

Spoiler Spoiler:


CATATAN :

om saya mw menanyakan tentang kolom "close(buy) strategy" dan "close(sell) strategy" untuk apa? :

Begini. Dalam contoh yang saya berikan di atas, -- OP-nya kan akan berakhir kalau kena TP atau kena SL.

Nah, bagaimana kalau kita membuat konsep trading dimana OP berakhir jika MA-nya bersilang balik ? - Disinilah kita menggunakan Close (Buy) Strategy dan Close (Sell) Strategy. OP akan ditutup jika MA bersilang kebalikannya. Nanti selama thread ini berjalan kita akan memakai fungsi ini agar newbies bisa belajar banyak membuat EA.


--------------------------------------------------------

biasanya newbie sperti ane msih lom bs invest bnyk gan plingan cm $20 ja n main na di cent pke TF M15 n lot 0.01 
jadi klo qt mau ubah itu gmn cranya ya??

Kalau LOT 0.01 dan TF 15M ingin dimasukkan sebagai coding di dalam EA, maka ini caranya :

Ini untuk memasukkan LOT (di bagian Order Option)
Spoiler Spoiler:


Ini untuk memasukkan parameter TimeFrame 15M ( di bagian Sell Strategy atau Buy Strategy)
Spoiler Spoiler:
---------------------------------------------------

Perubahan di TF H1 menjadi M5



//+------------------------------------------------------------------+
//| This MQL is generated by Expert Advisor Builder |
//| http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/ |
//| |
//| In no event will author be liable for any damages whatsoever. |
//| Use at your own risk. |
//| |
//+------------------- DO NOT REMOVE THIS HEADER --------------------+

#define SIGNAL_NONE 0
#define SIGNAL_BUY 1
#define SIGNAL_SELL 2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

#property copyright "Expert Advisor Builder"
#property link "http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/"

extern int MagicNumber = 0;
extern bool SignalMail = False;
extern bool EachTickMode = True;
extern double Lots = 0.01;
extern int Slippage = 3;
extern bool UseStopLoss = True;
extern int StopLoss = 30;
extern bool UseTakeProfit = True;
extern int TakeProfit = 10;
extern bool UseTrailingStop = False;
extern int TrailingStop = 30;

int BarCount;
int Current;
bool TickCheck = False;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init() {
BarCount = Bars;

if (EachTickMode) Current = 0; else Current = 1;

return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit() {
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start() {
int Order = SIGNAL_NONE;
int Total, Ticket;
double StopLossLevel, TakeProfitLevel;



if (EachTickMode && Bars != BarCount) TickCheck = False;
Total = OrdersTotal();
Order = SIGNAL_NONE;

//+------------------------------------------------------------------+
//| Variable Begin |
//+------------------------------------------------------------------+


double Buy1_1 = iMA("EURUSD", PERIOD_M5, 16, 0, MODE_SMA, PRICE_CLOSE, Current + 1);
double Buy1_2 = iMA("EURUSD", PERIOD_M5, 6, 0, MODE_SMA, PRICE_CLOSE, Current + 1);
double Buy2_1 = iMA("EURUSD", PERIOD_M5, 16, 0, MODE_SMA, PRICE_CLOSE, Current + 0);
double Buy2_2 = iMA("EURUSD", PERIOD_M5, 6, 0, MODE_SMA, PRICE_CLOSE, Current + 0);

double Sell1_1 = iMA("EURUSD", PERIOD_M5, 16, 0, MODE_SMA, PRICE_CLOSE, Current + 1);
double Sell1_2 = iMA("EURUSD", PERIOD_M5, 6, 0, MODE_SMA, PRICE_CLOSE, Current + 1);
double Sell2_1 = iMA("EURUSD", PERIOD_M5, 16, 0, MODE_SMA, PRICE_CLOSE, Current + 0);
double Sell2_2 = iMA("EURUSD", PERIOD_M5, 6, 0, MODE_SMA, PRICE_CLOSE, Current + 0);




//+------------------------------------------------------------------+
//| Variable End |
//+------------------------------------------------------------------+

//Check position
bool IsTrade = False;

for (int i = 0; i < Total; i ++) {
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if(OrderType() <= OP_SELL && OrderSymbol() == Symbol()) {
IsTrade = True;
if(OrderType() == OP_BUY) {
//Close

//+------------------------------------------------------------------+
//| Signal Begin(Exit Buy) |
//+------------------------------------------------------------------+



//+------------------------------------------------------------------+
//| Signal End(Exit Buy) |
//+------------------------------------------------------------------+

if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);
if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
if (!EachTickMode) BarCount = Bars;
IsTrade = False;
continue;
}
//Trailing stop
if(UseTrailingStop && TrailingStop > 0) { 
if(Bid - OrderOpenPrice() > Point * TrailingStop) {
if(OrderStopLoss() < Bid - Point * TrailingStop) {
OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0, MediumSeaGreen);
if (!EachTickMode) BarCount = Bars;
continue;
}
}
}
} else {
//Close

//+------------------------------------------------------------------+
//| Signal Begin(Exit Sell) |
//+------------------------------------------------------------------+



//+------------------------------------------------------------------+
//| Signal End(Exit Sell) |
//+------------------------------------------------------------------+

if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange);
if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Close Sell");
if (!EachTickMode) BarCount = Bars;
IsTrade = False;
continue;
}
//Trailing stop
if(UseTrailingStop && TrailingStop > 0) { 
if((OrderOpenPrice() - Ask) > (Point * TrailingStop)) {
if((OrderStopLoss() > (Ask + Point * TrailingStop)) || (OrderStopLoss() == 0)) {
OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop, OrderTakeProfit(), 0, DarkOrange);
if (!EachTickMode) BarCount = Bars;
continue;
}
}
}
}
}
}

//+------------------------------------------------------------------+
//| Signal Begin(Entry) |
//+------------------------------------------------------------------+

if (Buy1_1 > Buy1_2 && Buy2_1 < Buy2_2) Order = SIGNAL_BUY;

if (Sell1_1 < Sell1_2 && Sell2_1 > Sell2_2) Order = SIGNAL_SELL;


//+------------------------------------------------------------------+
//| Signal End |
//+------------------------------------------------------------------+

//Buy
if (Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
if(!IsTrade) {
//Check free margin
if (AccountFreeMargin() < (1000 * Lots)) {
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}

if (UseStopLoss) StopLossLevel = Ask - StopLoss * Point; else StopLossLevel = 0.0;
if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel = 0.0;

Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);
if(Ticket > 0) {
if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
Print("BUY order opened : ", OrderOpenPrice());
if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
} else {
Print("Error opening BUY order : ", GetLastError());
}
}
if (EachTickMode) TickCheck = True;
if (!EachTickMode) BarCount = Bars;
return(0);
}
}

//Sell
if (Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
if(!IsTrade) {
//Check free margin
if (AccountFreeMargin() < (1000 * Lots)) {
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}

if (UseStopLoss) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;
if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel = 0.0;

Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
if(Ticket > 0) {
if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
Print("SELL order opened : ", OrderOpenPrice());
if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Open Sell");
} else {
Print("Error opening SELL order : ", GetLastError());
}
}
if (EachTickMode) TickCheck = True;
if (!EachTickMode) BarCount = Bars;
return(0);
}
}

if (!EachTickMode) BarCount = Bars;

return(0);
}
//+------------------------------------------------------------------+


HASIL BT nya :

Lihat screen shot di bawah. EA-nya langsung melakukan OP di account demo ini. Tidak ada masalah. Pertanyaannya, apakah ketika memasukkan EA ke chart, kolom "Allow Live Trading" sudah ikut dicentang ?
Spoiler Spoiler:









Logic EA berdasarkan volume candle

EA berdasarkan volume candle

saya masih newbie dalam hal EA.
ada teman2 yang bisa bantu betulin EA yang saya coba buat ini Ngga?

logic BUY:
1.apabila candle pertama di TF 15 M ditutup di atas, dengan range minimal 30 point.
2.lalu buka candle berikutnya, naik 10 point langsung ambil posisi BUY.


logic SELL:
1.apabila candle pertama di TF 15 M ditutup di bawah, dengan range minimal 30 point.
2.lalu buka candle berikutnya, turun 10 point langsung ambil posisi SELL.

mohon bantuan dari master2...!!!!


stop loss : 30 point
taking profit : 100 point
trailing stopnya : 20 point

NB: klo bisa, SL,TP,dan TS ( TrailingStop) nya di hidden.
dan jam tradingnya mulai jam 9.15 wita - 12.00 wita & dilanjutkan lagi trading jam 13.00 wita - 16.15 wita.

mohon bantuan revisi dan edit dari teman2 master yang mengerti MQL4.



//+------------------------------------------------------------------+
//| Belajar2.mq4 |
//| Copyright 2012, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"

extern double Lots = 0.1;
extern bool use_hidden_TakeProfit = true;
extern int hidden_TakeProfit = 100;
extern bool use_hidden_StopLoss = true;
extern int hidden_Stoploss = 30 ;
extern int TrailingStop = 20 ;
extern int Magic = 12345;
extern int Slippage = 5;


//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----

if (iClose(Symbol (),0,1)>iOpen(Symbol(),0,1)&& iClose(Symbol(),0,1)-iOpen(Symbol(),0,1)<=20*Point)
{OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-hidden_Stoploss*Point,Ask+hidden_TakeProfit*Point, "Belajar2",Magic,0,Blue);}

else if (iClose(Symbol (),0,1)<iOpen(Symbol(),0,1)&& iOpen(Symbol(),0,1)-iClose(Symbol(),0,1)<=20*Point)
{OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+ hidden_Stoploss*Point,Bid-hidden_TakeProfit*Point,"Belajar2",Magic,0,Red);}

if( OrderSelect(12345,SELECT_BY_TICKET) && OrderCloseTime()==0 ) {
if( OrderType()==OP_BUY ) {
OrderModify(OrderTicket(),OrderOpenPrice(),Open[0]-Point*TrailingStop,OrderTakeProfit(),0);
}
else if( OrderType()==OP_SELL ) {
OrderModify(OrderTicket(),OrderOpenPrice(),Open[0]+Point*TrailingStop,OrderTakeProfit(),0);
}
}

//----
return(0);
}
//+------------------------------------------------------------------+

Logic Pivot Point

misal mau cari pivot point
contoh rumus pivot yang saya pakai (H+L+C)/3

jika dalam MQ4:

double h = iHigh(symbol(), 1440, 1); <<< mencari nilai high hari kemarin
double l = iLow(symbol(), 1440, 1); <<< mencari nilai low hari kemarin
double c = iClose(symbol(), 1440, 1); <<< mencari nilai close hari kemarin

double pivot = (h + l + c) / 3;

Logic Mengganti Indi RSI menjadi zigzag, caranya...

ganti code ini:





dengan code ini:



jangan lupa meletakkan code:
extern int ExtDepth=12;
extern int ExtDeviation=5;
extern int ExtBackstep=3;

pada bagian user input.

good luck



note :
---------------------
di sini saya sharekan seting zizzag paling simple

double atas = iCustom(0,0,"ZigZag",50,5,3,1,0);
double bawah = iCustom(0,0,"ZigZag",50,5,3,2,0);
if( bawah>atas)return("buy");
if( atas>bawah)return("sell");

sl 100; tp 300; TF30 Pair GU

--------------------------

Salam semua nya.
Saya ingin tanya bagaimana kalo kita pakai 2 time frame berbeda untuk konfirmasinya?
Mis: Zigzag 1h sudah muncul lalu kita tunggu Zigzag 4h muncul. Saat keduanya muncul di waktu yang sama (masih dalam range 4H ) baru EA eksekusi. Bila muncul diatas SELL dan bila muncul di bawah BUY. Bagaimana konfigurasi program EAnya? 

regard,
axadnan

jawab :

coba trik berikut ini




Logic Mencari nilai RSI dari TF H1 atau TF H4

lakukan print saja jadi nilainya bisa dibaca di jurnal
ini codenya:
double nilai_RSI=iRSI(simbol,timeframe,period,applied_pri ce,shift);
Print("nilai RSI = ",nilai_RSI);
dimana:

simbol = nama pair yang diinginkan atau NULL atau Symbol() untuk current chart

timeframe = nilai time frame bisa 1 untuk M1, 5 untuk M5, 15 untuk M15, 30 untuk M30, 60 untuk H1, 240 untuk H4, 1440 untuk D atau 0 untuk current chart

period = periode rsi, bisa diisi berapa saja sesuai dengan keinginan

applied_price = price yang digunakan untuk dasar perhitungan RSI. bisa 0 untuk close price, 1 untuk open price, 2 untuk high price, 3 untuk low price, 4 untuk (high+low)/2, 5 untuk (high+low+close)/3, 6 untuk (high+low+close+close)/4

shift = ofset bar dari current bar



2 logic Cara dibawah ini sama saja, tetapi saya lebih prefer ke kode yang kedua karena ngetiknya cepet dan help shadownya g ilang saat ngetik.

PERIOD_H1 adalah constantnya, sedangkan valuenya 60
PRICE_CLOSE adalah constantnya, sedangkan valuenya 0


kayak gini ...
Code:
double nilai_RSI=iRSI(Symbol(),PERIOD_H1,14,PRICE_CLOSE,0);
Print("nilai RSI = ",nilai_RSI);
Atau kayak gini:

Code:
double nilai_RSI=iRSI(Symbol(),60,14,0,0);
Print("nilai RSI = ",nilai_RSI);

Ayo bikin EA bersama Totom - part 6

Hasil EA .... Another Martingale....


//+------------------------------------------------------------------+
//|                                           Another Martingale.mq4 |
//|                              Copyright © 2009, Totom Sukopratomo |
//|                            mailto : eaforexprogramming@gmail.com |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| be my referall by register in my link and get free managed account 
//| for $50000 deposit in standard or $1000 in micro with 
//| 5% per month profit 
//| here is the link:
//+------------------------------------------------------------------+

#property copyright "Copyright © 2009, Totom Sukopratomo"
#property link      "mailto: eaforexprogramming@gmail.com"

//*------USER INPUT-----*
extern int MagicNumber=1;               // use for identifing order 
extern double StartLot=0.1;             // basic lot
extern int StopLoss=30;                 // stop loss
extern int TakeProfit=30;               // take profit
extern int TrailingStop=0;              // to moving out stoploss into
                                        // profit direction. adding
                                        // number bigger than 0 will
                                        // activated this fuction
extern bool MoveToBreakEvent=false;     // to moving stoploss into
                                        // opening price so there
                                        // a losses can neutralize
                                        // when market moves again us
extern int LockedPips=1;                // small amount of pips profit
                                        // expected to be earn when
                                        // market moves again us after
                                        // move to break event funtion
                                        // is triggered out
extern int RSIPeriod=9;                 // amount of bar to calculate
                                        // rsi price 
extern int UpperLevel=70;               // a level to determine market
                                        // is overbought if price is touch
                                        // it
extern int LowerLevel=30;               // same as above but for 
                                        // oversold comdition
extern bool Martingale=true;            // false to deactivated this feature
extern double Multiplier=2.5;           // previous lotsize will multiplied
                                        // with this value to get lotsize
                                        // of next order if EA getting loss
extern int DeepLevel=10;                // how many continue losses
                                        // will be covered by martingale
                                        // function
extern int StartHour=0;                 // time for EA start trading
extern int EndHour=20;                  // time for EA stop trading 
       double pt,                       // custom point
       stoplevel,                       // stop level
       minlot,                          // minimal lot
       maxlot;                          // maximal lot
//+------------------------------------------------------------------+
//| order counting                                                   |
//+------------------------------------------------------------------+
int ordercount()                        // we counting our order here
{
   int total=0;                         // total of our order 
   int i;                               // pos of our order 
   for(i=0; i<OrdersTotal(); i++)       // looping to count our order 
                                        // from pos 0 until last pos
   {
       OrderSelect(i,SELECT_BY_POS,MODE_TRADES);  // is it right our order?
       if(OrderSymbol()!=Symbol() ||    // if symbol of order didn't match 
       OrderMagicNumber()!=MagicNumber) // with current chart symbol 
       continue;                        // or the magic numb of order 
                                        // didn't match with our magic
                                        // number, don't count it
       total++;                         // count if all criteria matched
   }
   return(total);                       // this function returned total of
                                        // our opened order 
}
//+------------------------------------------------------------------+
//| check for losses                                                 |
//+------------------------------------------------------------------+  
bool checkforlosses()                   // we check our last closed order 
{                                       // from losses here 
   int losses=0;                        // total of losses
   int i;                               // pos of our order 
   for(i=0; i<OrdersHistoryTotal(); i++) // looping to check all of our
   {                                     // order history from pos 0 until
                                        // last pos
       OrderSelect(i,SELECT_BY_POS,MODE_HISTORY); // is it right our order?
       if(OrderSymbol()!=Symbol() ||    // if symbol of order didn't match 
       OrderMagicNumber()!=MagicNumber) // with current chart symbol 
       continue;                        // or the magic numb of order 
                                        // didn't match with our magic
                                        // number, it is not our's, just don't check it
       if(OrderProfit()<0) losses++;    // so we count it as a losses 'cause negative profit
       else                losses=0;    // otherwise we leave it as is 
   }
   if(losses>0)  return(true);          // if last of our order is in losses
                                        // true "value" will returned from this function
   return(false);                       // when there is no losses false will returned
}
//+------------------------------------------------------------------+
//| last lot                                                         |
//+------------------------------------------------------------------+ 
double lastlot()                        // we will find last lot size 
{                                       // order with this function
  double lot=0;                         // lot size
  int i;                                // pos of our order 
  for(i=0; i<OrdersHistoryTotal(); i++) // looping to check all of our
   {                                     // order history from pos 0 until
                                        // last pos
       OrderSelect(i,SELECT_BY_POS,MODE_HISTORY); // is it right our order?
       if(OrderSymbol()!=Symbol() ||    // if symbol of order didn't match 
       OrderMagicNumber()!=MagicNumber) // with current chart symbol 
       continue;                        // or the magic numb of order 
                                        // didn't match with our magic
                                        // number, it is not our's
       lot=OrderLots();                 // last lot
  }
  return(lot);                          // last lot size returned
}
//+------------------------------------------------------------------+
//| my lot                                                           |
//+------------------------------------------------------------------+ 
double mylot()                          // we calculate for next lot here
{                                       // when a loss occured or not 
  int prec=0;                           // precision value 
  double lot,                           // lot size
         minlot,                        // minimal size of lot
         maxlot,                        // maximal size of lot
         maxlotX;                       // maximal size of martingale lot 
  minlot=MarketInfo(Symbol(),MODE_MINLOT); // get brokers minimal lot size
  maxlot=MarketInfo(Symbol(),MODE_MAXLOT); // get brokers maximal lot size
  if(minlot==0.01) prec=2;              // get precision value
  if(minlot==0.1)  prec=1;              // get precision value
  maxlotX=NormalizeDouble(StartLot*MathPow(Multiplier,DeepLevel), prec); //get max.
                                        // martingale lotsize
  if(Martingale)                        // if martingale activated
  {
     if(checkforlosses())               // if last order is in losses
     {
        lot=NormalizeDouble(lastlot()*Multiplier,prec); // martingale lot
     }
     else
     {
        lot=StartLot;                   // normal lot
     }
  }  
  else
  {
     lot=StartLot;                      // normal lot
  }
  
  if(lot>maxlot)  return(StartLot);     // if lot size is bigger than broker rules,
                                        // we change it into StartLot value
  if(lot>maxlotX) return(StartLot);     // if lot size is bigger than martingale level,
                                        // we change it into StartLot value 
  if(lot<minlot)  return(minlot);       // if lot size smaller than minlot, we change
                                        // into monlot value
  return(lot);                          // lot size returned
}
//+------------------------------------------------------------------+
//| get signal                                                       |
//+------------------------------------------------------------------+
string getsignal()                      // we calculate trading signal here
{
   double rsi=iRSI(Symbol(),0,RSIPeriod,0,0);  // we use RSI to get signal
   if(rsi<LowerLevel) return("buy");    // buy signal returned when
                                        // oversold detected
   if(rsi>UpperLevel) return("sell");   // sell signal returned when
                                        // overbought detected
   return("wait and see");              // no signal returned
} 
//+------------------------------------------------------------------+
//| send order                                                       |
//+------------------------------------------------------------------+     
int sendorder(int cmd,double lots,double prc,double sl,double tp,color warna)
{
   return(OrderSend(Symbol(),cmd,lots,prc,2,sl,tp,"",MagicNumber,0,warna));
}  
//+------------------------------------------------------------------+
//| trailing stop                                                    |
//+------------------------------------------------------------------+   
void trailingstop()                     // we check our opened order to see 
{                                       // posibility to move its stoploss 
   double stoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL); // stoplevel 
   for(int i=OrdersTotal()-1; i>=0; i--) // lets scan all order and position
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES); // is this our order?
      if(OrderSymbol()!=Symbol() ||     // if symbol of order didn't match 
      OrderMagicNumber()!=MagicNumber)  // with current chart symbol 
      continue;                         // or the magic numb of order 
                                        // didn't match with our magic
                                        // number, it is not our's
      if(OrderType()==OP_BUY)           // order type need to be identified 
      {                                 // in order price selection (bid or ask)    
         if(
         MathAbs(OrderTakeProfit()-OrderStopLoss())<=2*stoplevel*pt
           )  break;                    // we calculate range between SL & TP
                                        // to avoid posible error
         if(
         Bid>=OrderStopLoss()+(StopLoss+TrailingStop)*pt
           )                            // common price calculation
         {
             OrderModify(               // moving stoploss
             OrderTicket(),
             OrderOpenPrice(),
             OrderStopLoss()+
             TrailingStop*pt,
             OrderTakeProfit(),
             CLR_NONE);
         }
      }
      if(OrderType()==OP_SELL)
      {
         if(
         MathAbs(OrderTakeProfit()-OrderStopLoss())<=2*stoplevel*pt
           )  break;
         if(
         Ask<=OrderStopLoss()-(StopLoss+TrailingStop)*pt
           )                            // common price calculation
         {
             OrderModify(               // moving stoploss
             OrderTicket(),
             OrderOpenPrice(),
             OrderStopLoss()-
             TrailingStop*pt,
             OrderTakeProfit(),
             CLR_NONE);
         }
      }
   }
}
//+------------------------------------------------------------------+
//| move to break event                                              |
//+------------------------------------------------------------------+   
void breakevent()                       // we check our opened order to see 
{                                       // posibility to move its stoploss 
   double stoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL); // stoplevel 
   for(int i=OrdersTotal()-1; i>=0; i--) // lets scan all order and position
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES); // is this our order?
      if(OrderSymbol()!=Symbol() ||     // if symbol of order didn't match 
      OrderMagicNumber()!=MagicNumber)  // with current chart symbol 
      continue;                         // or the magic numb of order 
                                        // didn't match with our magic
                                        // number, it is not our's
      if(OrderType()==OP_BUY)           // order type need to be identified 
      {                                 // in order price selection (bid or ask)    
         if(
         OrderStopLoss()>=OrderOpenPrice()  // common calculation
           )  break;                    
                                        
         if(
         Bid>=OrderOpenPrice()+(stoplevel+LockedPips)*pt
           )                            // common price calculation
         {
             OrderModify(               // moving stoploss
             OrderTicket(),
             OrderOpenPrice(),
             OrderOpenPrice()+
             LockedPips*pt,
             OrderTakeProfit(),
             CLR_NONE);
         }
      }
      if(OrderType()==OP_SELL)
      {
         if(
         OrderStopLoss()<=OrderOpenPrice()  // common calculation
           )  break;
         if(
         Ask<=OrderOpenPrice()-(stoplevel+LockedPips)*pt
           )                            // common price calculation
         {
             OrderModify(               // moving stoploss
             OrderTicket(),
             OrderOpenPrice(),
             OrderOpenPrice()-
             LockedPips*pt,
             OrderTakeProfit(),
             CLR_NONE);
         }
      }
   }
}
//+------------------------------------------------------------------+
//| order management                                                 |
//+------------------------------------------------------------------+
int ordermanagement()                   // we manage our orders here
{
   if(ordercount()==0)                  // when there is no opened orders 
   {
      if(getsignal()=="buy")            // when buy signal is appeared
      {
        if(sendorder(OP_BUY,mylot(),    // we send our buy order into
           Ask,Ask-StopLoss*pt,         // broker's server then we out
           Ask+TakeProfit*pt,           // from this cycle to avoid
           Blue)>0) return(0);          // errors possibility
      }
      if(getsignal()=="sell")           // same procces as buy signal
      {
        if(sendorder(OP_SELL,mylot(),
           Bid,Bid+StopLoss*pt,
           Bid-TakeProfit*pt,
           Red)>0) return(0);
      }
   }
   if(TrailingStop>0) trailingstop(); // we calling trailing stop function
                                      // if TrailingStop value bigger than 0
   if(MoveToBreakEvent) breakevent(); // we calling breakevent function here
   return(0);
}
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
    if(Digits==3 || Digits==5) pt=10*Point;  // when use at broker with 5 digits 
    else                       pt=Point;     // pricing, this function is useful 
    double stoplevel;                        // minimal pips for stop
    stoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);  // get broker's stoplevel
    if(StopLoss<=stoplevel) StopLoss=stoplevel;   // we compare our StopLoss with
                                             // stoplevel and adjust it when error occured
    if(TakeProfit<=stoplevel) TakeProfit=stoplevel;  // we compared our TakeProfit
                                             // as we compared our StopLoss
//----                                        
    return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
    Comment('');
//----
    return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
    if(Hour()<StartHour)              // when time to trade is not coming yet
    {                                 // let user now
       Comment("\nTrade time is not coming yet..");  // and
       return(0);                     // we just stop here
    }
    if(Hour()>EndHour)                // when time to trade is over
    {                                 // let user know
       Comment("\nTrade time is over...");  // and
       return(0);                     // we just stop here
    }
//----
    Comment("");                      // no comment needed
    ordermanagement();                // we calling order management funtion here
//----
    return(0);                        // we out of our cycle when everything done 
  }
//+------------------------------------------------------------------+