Saturday 19 January 2013

Mendapatkan nilai yang ada dalam indikator tanpa decompiler


Kadang kita mendapatkan indikator berupa *.ex4 tanpa mendapatkan *.mq4 nya. Apakah itu dengan tujuan untuk dioprek atau diporting ke dalam EA. Disini saya ajarkan cara mendapatkan nilai2/signal dll yang ada dalam indikator tanpa melakukan decompiler. Loh, ngapain susah2, kan ada decompiler.. beres. Hehehehe.. tujuan utama artikel ini adalah mempelajari bagaimana suatu nilai dalam indikator itu disimpan, sehingga kita dapat menggunakan indikator tersebut ke dalam EA tanpa melakukan porting (coding ulang).

Sewaktu membuat indikator suatu nilai akan disimpan dalam:
- buffer (ini yang sering)
- object (bisa diliat dengan Ctrl+O
- global variable (bisa diliat dengan F3)

Sering saya liat pertanyaan/permintaan disini, "Tolong buatkan EA untuk indikator XX". Terlepas dari si penanya bisa coding atau gak, tapi di Metaeditor sebenarnya sudah menyediakannya. Artinya kita dapat membuat EA berdasarkan indikator XX, walaupun kita tidak mempunyai .mq4 nya.

Buffer
Seperti sudah saya jelaskan diatas, tempat penyimpanan suatu nilai dalam indikator adalah buffer. Dalam MT4 dijelaskan bahwa buffer ini jumlah maksimalnya adalah 8, yang dimulai dengan index dari 0 s.d 7. Jadi kita dapat mengambil nilai2 tersebut dengan melakukan looping. Apalagi kalau ada .mq4 nya, bisa langsung tembak alamat buffernya untuk mendapatkan nilai yang disimpan.

Object
Walapun jarang, Ada kalanya nilai tersebut disimpan dalam object (misal karena buffer sudah terisi semua). Nilai yg dalam object ini bisa kita dapatkan, asalkan kita tau nama object tersebut. Caranya pasti sudah tau. Dengan melakukan double klik object tsb > klik kanan > properti. Atau tekan F3.

Global Variable
Karena sifatnya global, anda harus tau global variable apa saja yang dipakai oleh indikator tsb. Lain dengan buffer yang sekopnya hanya dalam indikator, atau object yg hanya ada di chart. Global Variable ini akan ada terus walaupun kita berpindah2 chart.

Dibawah ini saya buatkan EA IndicatorReading. Dengan mempelajari cara kerja EA ini, anda dapat memasukan indikator (.mq4 atau .ex4) ke dalam EA tanpa melakukang porting.
 Attached Files

Create your own MetaTrader extension (dll)


Create your own MetaTrader extension (dll) - Part 1

Hi folks!
Today we are going to go step by step creating our first MetaTrader extension (dll) in C++, let's don't waste the time and start by defining what's the MetaTrader extension (dll)?

What's the MetaTrader extension (dll)?


MQL4 language give you a limited things to do with it and there are a lot of things you can not do in MQL4. To get the full control of your Windows operating system (For example, accessing the window registry or file handling APIs) you have to choices:
 
1- To call/use the windows common dlls and import the functions you want, and this is an example:
#import "user32.dll"
int MessageBoxA(int hWnd, string lpText, string lpCaption, int uType);
In the line above we used the #import keyword to import one of the "user32.dll" function; MessageBoxA function. Then we can use this function in our code like any normal function.
 
2- The second choice is creating our own dll in c++ and use it in our code the same as the common windows dlls. And that's what are we going to learn today.
 

The Tools you need:


I tried Visual Basic to create the MetaTrader dll but it failed, the truth is I didn't give it a lot of time and trials because the fact that the Visual Basic is not a real dll (activex) creator.
Note: If you find here any new terms that you don't understand them (like activex), if you can't ignore them you can ask me to explain them to you. But you don't need to know these terms to understand how to create your own dll.
So, the best choice was to use Visual c++, I used Microsoft Visual c++ 6 which you can download free express version of it from here:http://msdn.microsoft.com/vstudio/express/visualc/download/
Note:  The version of Visual C++ used in this tutorial is Microsoft Visual c++ 6 not the express version.
Now let's create our first dll that says "hello world!"

Hello world!


1- The first step you have to run Visual C++ (Figure 1).
Figure 1 - Visual C++ 6 
2- Now from File menu choose New and a dialog like that (Figure 2) will appear.
 
Figure 2 - New project dialog 
3- From this dialog choose "MFC AppWizard (dll)" and write a name for the project in the "Project Name" field (Figure 3) and click "OK".
 
Figure 3 - MFC dll 
Note: You can choose "Win32 Dynamic-Link Library" instead of "MFC AppWizard (dll)" but this means you will not able to use "CString" string type, CString is a string type in MFC that makes the world easier.
4- Another dialog (Figure 4) will appear to you asking you for some option. leave the default options and click "Finish" button. And when the information dialog appear click "OK".
 
Figure 4 - Project options 
5- Congratulation! You have a new project now "demo" project which you can start to write your dll in. Please open the file "demo.cpp" and give it a look.
Now, we are going to write some code in this file:
#define MT4_EXPFUNC __declspec(dllexport)
you put this line after the lines:
#include "stdafx.h"
#include "demo.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
6- Add the end of the file "demo.cpp" and after this line:
CDemoApp theApp;
We are going to write our "Hello" function like that:
MT4_EXPFUNC void __stdcall Hello(char* say)
{
MessageBox(NULL,say,"demo",NULL);
}

 
7- Now we have the function "Hello" which takes a string to say it and returns no thing (void). 
But the world want to know our function and in c++ to make the function availabe to the world we have to add the function name in a file called the .def file. 
Now open the demo.def file and add this line (the bold line) at the end of the file:
; demo.def : Declares the module parameters for the DLL.
LIBRARY "demo"
DESCRIPTION 'demo Windows Dynamic Link Library'
EXPORTS
; Explicit exports can go here
Hello
8- Compile the dll by pressing F7, if you are a lucky man like me you will not get any errors or warnings. Search for the demo.dll in Debug folder in the Demo project folder.
In the coming article we are going to test our dll and we are going to know more about the data type passed and received to and from the dll that we can use to write more advanced dlls.
Hope you find it a useful article!
Coders' Guru

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

Create your own MetaTrader extension (dll) - Part 2

Hi folks!
In the previous part of this article we created step-by-step our first MetaTrader extension (dll) in C++ and in this article we are going to give it a test.
Also we are going to study in this article and the coming article some of the advanced topics briefly (like how to use arrays and structure in your dll).
Hope you are ready for this hard journey which deserves the effort.

Let's test our demo.dll

We are going to write some code to test our demo.dll. These are the steps we have to take before saying "Hello World!"
1- We have the demo.dll in the debug folder in your Visual C++ projects folder. Copy the demo.dll to the library folder ("MetaTrader 4\experts\libraries").
2- Open MetaEditor to create the include file which will hold the declaration of our "Hello" function. This is the code of demo.mqh
 
#import "demo.dll"
   void Hello(string say);
#import
Note how we have imported the dll and how we have declared the "Hello" function with the same parameters (string say) and return value (void) as the function in the dll.
This file will be saved at the Include folder (MetaTrader 4\experts\include).
3- Now, let's create the script to test the demo.dll. We are going to name it "Hello.mq4" and it must be saved at the Scripts folder (MetaTrader 4\experts\scripts).
#include <demo.mqh>

int start()
  {
   Hello ("Hello World!");
   return(0);
  }
Note how we have started the code by including the demo.mqh file to make it a part of our code.
4- Compile the script (F5) and load it now (double click it in the Navigator window in the Terminal). What did you get? a nice dialog like the one showed in figure 1, if not please check everything or email me!
 
Note: You have to enable the option "Allow DLL imports" in MetaTrader before using any code that import external functions (from the common windows dlls or you custom dlls like our demo.dll) that's by going to Tools -> Options -> Expert Advisors tab then checking "Allow DLL imports" (Figure 2).
 

Advanced Sample (ExpertSample)!

Our demo.dll was a simple one yet it was a completed dll. There's an advanced sample that shipped with MetaTrader program which include advanced programming topics. We are going to study it and thank MetaQuotes for its ideal sample.
You will find the sample of the dll in "MetaTrader 4\EXPERTS\SAMPLES"; the dll (ExpertSample.dll) in the folder "MetaTrader 4\EXPERTS\SAMPLES\ExpertSample", the include file (sampledll.mqh) in "MetaTrader 4\EXPERTS\SAMPLES\INCLUDE" and the script (ExportFunctions.mq4) in "MetaTrader 4\EXPERTS\SAMPLES".
You have to open the source code of the dll (To open the source code double click ExpertSample.dsw file) and give the code a look. You will find it more advanced and to some degree a complex one compared to the demo.dll, but don't be afraid we are going to know everything in the next article.



Coding asli :



#property copyright "Copyright © 2009, ChandraWG" 
#property link "www.chandrawiharja.com"

//tambahan filter ordercoment , magicnumber dan suport 5 digit broker(by Gathot007)
extern string continu="::>Bila false berhenti Op baru";
extern bool Continu_trade=true;
extern string Seting_time="::>Sesuai Jam broker";
extern int  StartHour =0;
extern int  StopHour =24;
extern int SL=35,TP=120;
extern double Lots=0.1;
extern int MaxReverse=5;
extern int Pereode_MA=10;
extern int Magic=7;
extern string Coment_EA="Gath_007";
double dpt;

int init()
{
   if(Digits==3 || Digits==5) dpt=10*Point;
   else                          dpt=Point;
}
int start()
{
label();
double tp2=(SL+TP)*dpt;
int ticket;
if (tot()==0 && Continu_trade && dTime()==1)
      {
         if (iClose(Symbol(),0,1) > iMA(Symbol(),0,Pereode_MA,0,MODE_EMA,PRICE_CLOSE,1))
         {
            OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,0,Coment_EA,Magic,0,Blue);
         }
         else if (iClose(Symbol(),0,1) < iMA(Symbol(),0,Pereode_MA,0,MODE_EMA,PRICE_CLOSE,1))
         {
            OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,0,Coment_EA,Magic,0,Red);
         }
         
      } 
if(tot()>0)
   {
      if(OrderSelect(OrdersTotal()-1,SELECT_BY_POS,MODE_TRADES))
      {
      if((OrderStopLoss()==0)&&(OrderSymbol()==Symbol()&& OrderComment()==Coment_EA))
         {
            if(OrderType()==0) 
               {
               ticket=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-SL*dpt,OrderOpenPrice()+TP*dpt,0);
               if (ticket<1) Print("Error Modify Buy order : ",GetLastError()); 
               return (0);
               }
            else if(OrderType()==1) 
               {
               ticket=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+SL*dpt,OrderOpenPrice()-TP*dpt,0);
               if (ticket<1) Print("Error Modify Sell order : ",GetLastError()); 
               return (0);
               }
            else return (0);
         }
      else if((dMagic()<Magic+MaxReverse)&&(OrderSymbol()==Symbol()&& OrderComment()==Coment_EA))
         {         
         if(OrderType()==0) 
            {
            ticket=OrderSend(Symbol(),OP_SELLSTOP,OrderLots()*2,OrderOpenPrice()-SL*dpt,0,OrderOpenPrice(),OrderOpenPrice()-tp2,Coment_EA,dMagic()+1,0,White);
            if (ticket<1) Print("Error opening SELLSTOP order : ",GetLastError()); 
            return (0);
            }
         else if(OrderType()==1) 
            {
            ticket=OrderSend(Symbol(),OP_BUYSTOP,OrderLots()*2,OrderOpenPrice()+SL*dpt,0,OrderOpenPrice(),OrderOpenPrice()+tp2,Coment_EA,dMagic()+1,0,Yellow);
            if (ticket<1) Print("Error opening BUYSTOP order : ",GetLastError()); 
            return (0);
            }
         else if((OrderType()>1)&&(tot()==1)) 
            {
            ticket=OrderDelete(OrderTicket(),0);
            if (ticket<1) Print("Error Deleted order : ",GetLastError()); 
            return (0);
            }
         else return (0);
         }
      else if((OrderType()>1)&&(tot()==1)) 
         {
         ticket=OrderDelete(OrderTicket(),0);
         if (ticket<1) Print("Error Deleted order : ",GetLastError()); 
         return (0);
         }
      else return (0);         
      }
      else Print("Error Select Order : ",GetLastError());
   }
return (0);
}
int tot()
{
  int too=0;
  for(int i=0; i<OrdersTotal(); i++)
  {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol() || OrderComment()!=Coment_EA) continue;
      too++;
  }
  return(too);
}
int dMagic()
{
  int too=0;
  for(int i=0; i<OrdersTotal(); i++)
  {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol()&& OrderComment()==Coment_EA ) continue;
       too=OrderMagicNumber();
  }
  return(too);
}
void label()
{
             Comment(" ::::::::::::::::::::::::::::::::::::::::::::::::::", 
              "\n + Jam Broker             :",Hour(),":",Minute(), 
              "\n + Spread                 : ", MarketInfo(Symbol(), MODE_SPREAD), 
              "\n + Leverage               : 1 : ", AccountLeverage(), 
              "\n + Balance                : ", AccountBalance(), 
              "\n + Equity                 : ", AccountEquity(), 
              "\n + Lots                   :",Lots,
              "\n + SL                     :",SL,
              "\n + TP                     :",TP,
              "\n + MaxReverse             :",MaxReverse,
              "\n + Level saat ini         :",dMagic()-Magic,
              "\n + Waktu Trade Jam        : ", StartHour,": s/d :", StopHour, 
              "\n ::::::::::::::::::::::::::::::::::::::::::::::::::");
}
 int dTime() {
   bool trade = FALSE;
   if(StartHour>StopHour){
     if (TimeHour(TimeCurrent()) >= StartHour || TimeHour(TimeCurrent()) < StopHour) trade = TRUE;
   } else
     if (TimeHour(TimeCurrent()) >= StartHour && TimeHour(TimeCurrent()) < StopHour) trade = TRUE;
   return (trade);
}


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


modiv menjadi :

#property copyright "Copyright © 2009, ChandraWG"
#property link "www.chandrawiharja.com"


//tambahan filter ordercoment , magicnumber dan suport 5 digit broker(by Gathot007) 

extern string continu="::>Bila false berhenti Op baru"

extern bool Continu_trade=true

extern string Seting_time="::>Sesuai Jam broker"

extern int  StartHour =0

extern int  StopHour =24

extern int SL=35,TP=120

extern double Lots=0.1

extern int MaxReverse=5

extern int Pereode_MA=10

extern int Magic=7

extern string Coment_EA="Gath_007"

double dpt

extern int dailymax=1;  // penambahan di sini 

int day=-1,daily=0

int init() 



{
   if(
Digits==|| Digits==5dpt=10*Point;
   else                          
dpt=Point;
 
 
int start()
label(); double tp2=(SL+TP)*dptint ticket;
if  (
day!=Day())  {daily=0;}

if (
tot()==&& Continu_trade && dTime()==1&&  daily dailymax )
      {
         if (
iClose(Symbol(),0,1) > iMA(Symbol(),0,Pereode_MA,0,MODE_EMA,PRICE_CLOSE,1))
         {
            
OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,0,Coment_EA,Magic,0,Blue);
            
day=Day(); daily++;
         }
         else if (
iClose(Symbol(),0,1) < iMA(Symbol(),0,Pereode_MA,0,MODE_EMA,PRICE_CLOSE,1))
         {
            
OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,0,Coment_EA,Magic,0,Red);
             
day=Day(); daily++;
         }
       
      }
if(
tot()>0)
   {
      if(
OrderSelect(OrdersTotal()-1,SELECT_BY_POS,MODE_TRADES))
      {
      if((
OrderStopLoss()==0)&&(OrderSymbol()==Symbol()&& OrderComment()==Coment_EA))
         {
            if(
OrderType()==0)
               {
               
ticket=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-SL*dpt,OrderOpenPrice()+TP*dpt,0);
               if (
ticket<1) Print("Error Modify Buy order : ",GetLastError());
               return (
0);
               }
            else if(
OrderType()==1)
               {
               
ticket=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+SL*dpt,OrderOpenPrice()-TP*dpt,0);
               if (
ticket<1) Print("Error Modify Sell order : ",GetLastError());
               return (
0);
               }
            else return (
0);
         }
      else if((
dMagic()<Magic+MaxReverse)&&(OrderSymbol()==Symbol()&& OrderComment()==Coment_EA))
         {       
         if(
OrderType()==0)
            {
            
ticket=OrderSend(Symbol(),OP_SELLSTOP,OrderLots()*2,OrderOpenPrice()-SL*dpt,0,OrderOpenPrice(),OrderOpenPrice()-tp2,Coment_EA,dMagic()+1,0,White);
            if (
ticket<1) Print("Error opening SELLSTOP order : ",GetLastError());
            return (
0);
            }
         else if(
OrderType()==1)
            {
            
ticket=OrderSend(Symbol(),OP_BUYSTOP,OrderLots()*2,OrderOpenPrice()+SL*dpt,0,OrderOpenPrice(),OrderOpenPrice()+tp2,Coment_EA,dMagic()+1,0,Yellow);
            if (
ticket<1) Print("Error opening BUYSTOP order : ",GetLastError());
            return (
0);
            }
         else if((
OrderType()>1)&&(tot()==1))
            {
            
ticket=OrderDelete(OrderTicket(),0);
            if (
ticket<1) Print("Error Deleted order : ",GetLastError());
            return (
0);
            }
         else return (
0);
         }
      else if((
OrderType()>1)&&(tot()==1))
         {
         
ticket=OrderDelete(OrderTicket(),0);
         if (
ticket<1) Print("Error Deleted order : ",GetLastError());
         return (
0);
         }
      else return (
0);       
      }
      else Print(
"Error Select Order : ",GetLastError());
   }
return (
0);
int tot()
{
  
int too=0;
  for(
int i=0i<OrdersTotal(); i++)
  {
      
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(
OrderSymbol()!=Symbol() || OrderComment()!=Coment_EA) continue;
      
too++;
  }
  return(
too);
int dMagic()
{
  
int too=0;
  for(
int i=0i<OrdersTotal(); i++)
  {
      
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(
OrderSymbol()!=Symbol()&& OrderComment()==Coment_EA ) continue;
       
too=OrderMagicNumber();
  }
  return(
too);
void label()
{
             
Comment(" ::::::::::::::::::::::::::::::::::::::::::::::::::",
              
"\n + Jam Broker             :",Hour(),":",Minute(),
              
"\n + Spread                 : "MarketInfo(Symbol(), MODE_SPREAD),
              
"\n + Leverage               : 1 : "AccountLeverage(),
              
"\n + Balance                : "AccountBalance(),
              
"\n + Equity                 : "AccountEquity(),
              
"\n + Lots                   :",Lots,
              
"\n + SL                     :",SL,
              
"\n + TP                     :",TP,
              
"\n + MaxReverse             :",MaxReverse,
              
"\n + Level saat ini         :",dMagic()-Magic,
              
"\n + Waktu Trade Jam        : "StartHour,": s/d :"StopHour,
              
"\n ::::::::::::::::::::::::::::::::::::::::::::::::::");
}
 
int dTime() {
   
bool trade FALSE;
   if(
StartHour>StopHour){
     if (
TimeHour(TimeCurrent()) >= StartHour || TimeHour(TimeCurrent()) < StopHourtrade TRUE;
   } else
     if (
TimeHour(TimeCurrent()) >= StartHour && TimeHour(TimeCurrent()) < StopHourtrade TRUE;
   return (
trade);
}