
Migrando do MQL4 para o MQL5
Introdução
Muitos desenvolvedores acumularam muitos indicadores e estratégias de negócios escritas no MQL4. Para usá-las no Metatrader 5, elas devem ser convertidas para o MQL5. Não é fácil reescrever todos os programas no MQL5. Seria muito mais fácil convertê-los se houvesse uma tradução referência e melhor com exemplos.
Nesse artigo eu gostaria de sugerir minha versão de um guia para migrar do MQL4 para o MQL5.
1. Períodos do gráfico
No MQL5 as constantes de período mudaram, e alguns novos períodos de tempo (M2, M3, M4, M6, M10, M12, H2, H3, H6, H8, H12) foram adicionados. Para converter os períodos de tempo do MQL4 você pode utilizar a seguinte função:
ENUM_TIMEFRAMES TFMigrate(int tf) { switch(tf) { case 0: return(PERIOD_CURRENT); case 1: return(PERIOD_M1); case 5: return(PERIOD_M5); case 15: return(PERIOD_M15); case 30: return(PERIOD_M30); case 60: return(PERIOD_H1); case 240: return(PERIOD_H4); case 1440: return(PERIOD_D1); case 10080: return(PERIOD_W1); case 43200: return(PERIOD_MN1); case 2: return(PERIOD_M2); case 3: return(PERIOD_M3); case 4: return(PERIOD_M4); case 6: return(PERIOD_M6); case 10: return(PERIOD_M10); case 12: return(PERIOD_M12); case 16385: return(PERIOD_H1); case 16386: return(PERIOD_H2); case 16387: return(PERIOD_H3); case 16388: return(PERIOD_H4); case 16390: return(PERIOD_H6); case 16392: return(PERIOD_H8); case 16396: return(PERIOD_H12); case 16408: return(PERIOD_D1); case 32769: return(PERIOD_W1); case 49153: return(PERIOD_MN1); default: return(PERIOD_CURRENT); } }
Deve-se notar que no MQL5 os valores numéricos das constantes de período de tempo do gráfico (desde H1) não são iguais ao número de minutos de uma barra (por exemplo, no MQL5, o valor numérico da constante PERIOD_H1=16385, mas no MQL4 é PERIOD_H1=60). Você deve levar em conta ao converter para o MQL5, se valores numéricos das constantes do MQL4 são usados nos programas do MQL4.
Para determinar o número de minutos de um período de tempo especifico do gráfico, divida o valor, devolvido pela função PeriodSeconds, por 60.
2. Declarando constantes
Algumas das constantes padrão do MQL4 estão ausente do MQL5, portanto elas devem ser declaradas:
//+------------------------------------------------------------------+ //| InitMQL4.mqh | //| Copyright DC2008 | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "keiji" #property copyright "DC2008" #property link "https://www.mql5.com" //--- Declaration of constants #define OP_BUY 0 //Buy #define OP_SELL 1 //Sell #define OP_BUYLIMIT 2 //Pending order of BUY LIMIT type #define OP_SELLLIMIT 3 //Pending order of SELL LIMIT type #define OP_BUYSTOP 4 //Pending order of BUY STOP type #define OP_SELLSTOP 5 //Pending order of SELL STOP type //--- #define MODE_OPEN 0 #define MODE_CLOSE 3 #define MODE_VOLUME 4 #define MODE_REAL_VOLUME 5 #define MODE_TRADES 0 #define MODE_HISTORY 1 #define SELECT_BY_POS 0 #define SELECT_BY_TICKET 1 //--- #define DOUBLE_VALUE 0 #define FLOAT_VALUE 1 #define LONG_VALUE INT_VALUE //--- #define CHART_BAR 0 #define CHART_CANDLE 1 //--- #define MODE_ASCEND 0 #define MODE_DESCEND 1 //--- #define MODE_LOW 1 #define MODE_HIGH 2 #define MODE_TIME 5 #define MODE_BID 9 #define MODE_ASK 10 #define MODE_POINT 11 #define MODE_DIGITS 12 #define MODE_SPREAD 13 #define MODE_STOPLEVEL 14 #define MODE_LOTSIZE 15 #define MODE_TICKVALUE 16 #define MODE_TICKSIZE 17 #define MODE_SWAPLONG 18 #define MODE_SWAPSHORT 19 #define MODE_STARTING 20 #define MODE_EXPIRATION 21 #define MODE_TRADEALLOWED 22 #define MODE_MINLOT 23 #define MODE_LOTSTEP 24 #define MODE_MAXLOT 25 #define MODE_SWAPTYPE 26 #define MODE_PROFITCALCMODE 27 #define MODE_MARGINCALCMODE 28 #define MODE_MARGININIT 29 #define MODE_MARGINMAINTENANCE 30 #define MODE_MARGINHEDGED 31 #define MODE_MARGINREQUIRED 32 #define MODE_FREEZELEVEL 33 //--- #define EMPTY -1Nota: Constantes no MQL4 e no MQL5 diferem, portanto é melhor declará-las em um arquivo separado para uso posterior.
3. Variáveis pré-definidas
MQL4 | MQL5 | Descrição |
---|---|---|
double Ask | MqlTick last_tick; SymbolInfoTick(_Symbol,last_tick); double Ask=last_tick.ask; | Ask O último preço de venda conhecido para o símbolo atual. SymbolInfoTick |
int Bars | int Bars=Bars(_Symbol,_Period); | Bars Número de barras no gráfico atual. Bars |
double Bid | MqlTick last_tick; SymbolInfoTick(_Symbol,last_tick); double Bid=last_tick.bid; | Bid O último preço de compra conhecido do símbolo atual. SymbolInfoTick |
double Close[] | double Close[]; int count; // number of elements to copy ArraySetAsSeries(Close,true); CopyClose(_Symbol,_Period,0,count,Close); | Close Arranjo de séries que contêm preços próximos para cada barra do gráfico atual. CopyClose, ArraySetAsSeries |
int Digits | int Digits=_Digits; | Digits Número de dígitos após o ponto decimal para os preços do símbolo atual. _Digits |
double High[] | double High[]; int count; // number of elements to copy ArraySetAsSeries(High,true); CopyHigh(_Symbol,_Period,0,count,High); | High Arranjo de séries que contêm os preços mais altos de cada barra do gráfico atual. CopyHigh, ArraySetAsSeries |
double Low[] | double Low[]; int count; // number of elements to copy ArraySetAsSeries(Low,true); CopyLow(_Symbol,_Period,0,count,Low); | Low Arranjo de séries que contêm os preços mais baixos de cada barra do gráfico atual. CopyLow, ArraySetAsSeries |
double Open[] | double Open[]; int count; // number of elements to copy ArraySetAsSeries(Open,true); CopyOpen(_Symbol,_Period,0,count,Open); | Open Arranjo de séries que contêm preços abertos de cada barra do gráfico atual. CopyOpen, ArraySetAsSeries |
double Point | double Point=_Point; | Point O valor do ponto do símbolo atual na moeda da cotação. _Point |
datetime Time[] | datetime Time[]; int count; // number of elements to copy ArraySetAsSeries(Time,true); CopyTime(_Symbol,_Period,0,count,Time); | Time Arranjo de séries que contêm o tempo aberto de cada barra do gráfico atual. Dados como datetime representam o tempo, em segundos, que passaram desde de 0:00 de 1 de janeiro de 1970. CopyTime, ArraySetAsSeries |
double Volume[] | long Volume[]; int count; // number of elements to copy ArraySetAsSeries(Volume,true); CopyTickVolume(_Symbol,_Period,0,count,Volume); | Volume Arranjo de séries que contêm volumes de ponto de cada barra do gráfico atual. CopyTickVolume, ArraySetAsSeries |
4. Informações da conta
MQL4 | MQL5 | Descrição |
---|---|---|
double AccountBalance() | double AccountInfoDouble(ACCOUNT_BALANCE) | AccountBalance Retorna com o valor de saldo da conta atual (a quantidade de dinheiro na conta). AccountInfoDouble |
double AccountCredit() | double AccountInfoDouble(ACCOUNT_CREDIT) | AccountCredit Retorna com o valor de crédito da conta atual. AccountInfoDouble |
string AccountCompany() | string AccountInfoString(ACCOUNT_COMPANY) | AccountCompany Retorna com o nome da companha de corretagem onde a conta atual foi registrada. AccountInfoString |
string AccountCurrency() | string AccountInfoString(ACCOUNT_CURRENCY) | AccountCurrency Retorna com o nome da moeda da conta atual. AccountInfoString |
double AccountEquity() | double AccountInfoDouble(ACCOUNT_EQUITY) | AccountCredit Retorna com o valor de igualdade da conta atual. O cálculo da igualdade depende das configurações do servidor de negócios. AccountInfoDouble |
double AccountFreeMargin() | double AccountInfoDouble(ACCOUNT_FREEMARGIN) | AccountFreeMargin Retorna com o valor de margem livre da conta atual. AccountInfoDouble |
double AccountFreeMarginCheck(string symbol, int cmd, double volume) | - | AccountFreeMarginCheck Retorna com a margem livre que restar após a posição específica ter sido aberta no preço atual na conta atual. |
double AccountFreeMarginMode() | - | AccountFreeMarginMode Modo de cálculo da margem livre autorizado a abrir posições na conta atual. |
int AccountLeverage() | int AccountInfoInteger(ACCOUNT_LEVERAGE) | AccountLeverage Retorna com a alavancagem da conta atual. AccountInfoInteger |
double AccountMargin() | double AccountInfoDouble(ACCOUNT_MARGIN) | AccountMargin Retorna com o valor da margem da conta atual. AccountInfoDouble |
string AccountName() | string AccountInfoString(ACCOUNT_NAME) | AccountName Retorna com o nome da conta atual. AccountInfoString |
int AccountNumber() | int AccountInfoInteger(ACCOUNT_LOGIN) | AccountNumber Retorna com o número da conta atual. AccountInfoInteger |
double AccountProfit() | double AccountInfoDouble(ACCOUNT_PROFIT) | AccountProfit Retorna com o valor do lucro da conta atual. AccountInfoDouble |
string AccountServer() | string AccountInfoString(ACCOUNT_SERVER) | AccountServer Retorna com o nome do servidor conectado. AccountInfoString |
int AccountStopoutLevel() | double AccountInfoDouble(ACCOUNT_MARGIN_SO_SO) | AccountStopoutLevel Retorna com o valor do nível de Stop Out. AccountInfoDouble |
int AccountStopoutMode() | int AccountInfoInteger(ACCOUNT_MARGIN_SO_MODE) | AccountStopoutMode Retorna com o modo de cálculo para o nível de Stop Out. AccountInfoInteger |
5. Funções do arranjo (array)
MQL4 | MQL5 | Descrição |
---|---|---|
int ArrayBsearch(double array[], double value, int count=WHOLE_ARRAY, int start=0, int direction=MODE_ASCEND) | int ArrayBsearch(double array[], double searched_value ) | ArrayBsearch A função busca um valor especificado em um arranjo numérico unidimensional. ArrayBsearch |
int ArrayCopy(object&dest[], object source[], int start_dest=0, int start_source=0, int count=WHOLE_ARRAY) | int ArrayCopy(void dst_array[], void src_array[], int dst_start=0, int src_start=0, int cnt=WHOLE_ARRAY ) | ArrayCopy Copia um arranjo para outro. Arranjos devem ser do mesmo tipo, mas arranjos do tipo double[], int[], datetime[], color[], e bool[] podem ser copiados como arranjos de mesmo tipo. Retorna com a quantidade de elementos copiados. ArrayCopy |
int ArrayCopyRates(double&dest_array[], string symbol=NULL, int timeframe=0) | - | ArrayCopyRates Copia dados das barras do gráfico atual para o arranjo bidimensional do tipo RateInfo[][6] e Retorna com a quantidade de barras copiadas, ou -1 se falhou. |
int ArrayCopySeries(double&array[], int series_index, string symbol=NULL, int timeframe=0) | int ArrayCopySeriesMQL4(double &array[], int series_index, string symbol=NULL, int tf=0) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int count=Bars(symbol,timeframe); switch(series_index) { case MODE_OPEN: return(CopyOpen(symbol,timeframe,0,count,array)); case MODE_LOW: return(CopyLow(symbol,timeframe,0,count,array)); case MODE_HIGH: return(CopyHigh(symbol,timeframe,0,count,array)); case MODE_CLOSE: return(CopyClose(symbol,timeframe,0,count,array)); default: return(0); } return(0); } | ArrayCopySeries Copia um arranjo de série temporal para um arranjo personalizado e Retorna com a contagem dos elementos copiados. CopyOpen, CopyLow, CopyHigh, CopyClose, Bars |
int ArrayDimension( object array[]) | - | ArrayDimension Retorna com a posição do arranjo multidimensional. |
bool ArrayGetAsSeries( object array[]) | bool ArrayGetAsSeries(void array) | ArrayGetAsSeries Retorna como TRUE se um arranjo for organizado como um arranjo de série temporal (os elementos do arranjo são classificados do último para o primeiro), senão retorna como FALSE. ArrayGetAsSeries |
int ArrayInitialize(double &array[], double value) | int ArrayInitializeMQL4(double &array[], double value) { ArrayInitialize(array,value); return(ArraySize(array)); } | ArrayInitialize Ajusta todos os elementos de um arranjo numérico para o mesmo valor. Retorna com a contagem de elementos inicializados. ArrayInitialize, ArraySize |
bool ArrayIsSeries( object array[]) | bool ArrayIsSeries(void array[]) | ArrayIsSeries Retorna como TRUE se a verificação de variante do arranjo for um arranjo de série temporal (Time[],Open[],Close[],High[],Low[], ou Volume[]), senão retorna como FALSE. ArrayIsSeries |
int ArrayMaximum(double array[], int count=WHOLE_ARRAY, int start=0) | int ArrayMaximumMQL4(double &array[], int count=WHOLE_ARRAY, int start=0) { return(ArrayMaximum(array,start,count)); } | ArrayMaximum Busca o elemento com o valor máximo. A função Retorna com a posição desse elemento máximo no arranjo. ArrayMaximum |
int ArrayMinimum(double array[], int count=WHOLE_ARRAY, int start=0) | int ArrayMinimumMQL4(double &array[], int count=WHOLE_ARRAY, int start=0) { return(ArrayMinimum(array,start,count)); } | ArrayMinimum Busca o elemento com o valor mínimo. A função Retorna com a posição desse elemento mínimo no arranjo. ArrayMinimum |
int ArrayRange(object array[], int range_index) | int ArrayRange(void array[], int rank_index ) | ArrayRange Retorna com a contagem de elementos na dimensão fornecida do arranjo. ArrayRange |
int ArrayResize(object &array[], int new_size) | int ArrayResize(void array[], int new_size, int allocated_size=0 ) | ArrayResize Ajusta a contagem de elementos para a primeira dimensão. ArrayResize |
bool ArraySetAsSeries(double &array[], bool set) | bool ArraySetAsSeries(void array[], bool set ) | ArraySetAsSeries Retorna com a contagem de elementos na dimensão fornecida do arranjo. Já que os índices são de base zero, o tamanho da dimensão é 1 maior que o maior índice. ArraySetAsSeries |
int ArraySize( object array[]) | int ArraySize(void array[]) | ArraySize Retorna com a contagem dos elementos contida no arranjo. ArraySize |
int ArraySort(double &array[], int count=WHOLE_ARRAY, int start=0, int sort_dir=MODE_ASCEND) | int ArraySortMQL4(double &array[], int count=WHOLE_ARRAY, int start=0, int sort_dir=MODE_ASCEND) { switch(sort_dir) { case MODE_ASCEND: ArraySetAsSeries(array,true); case MODE_DESCEND: ArraySetAsSeries(array,false); default: ArraySetAsSeries(array,true); } ArraySort(array); return(0); } | ArraySort Ordena arranjos numéricos pela primeira dimensão. Arranjos de séries não podem ser ordenados pelo ArraySort(). ArraySort, ArraySetAsSeries |
6. Verificação
MQL4 | MQL5 | Descrição |
---|---|---|
int GetLastError() | int GetLastError() | GetLastError A função retorna ao último erro ocorrido, então o valor da variável especial last_error onde o último código de erro está armazenado será zerado. GetLastError |
bool IsConnected() | bool TerminalInfoInteger(TERMINAL_CONNECTED) | IsConnected A função retorna com com o status da conexão principal entre o terminal cliente e o servidos que realiza o envio de dados. Ele retorna como TRUE se a conexão ao servidor foi estabelecida com sucesso, senão, ele retorna como FALSE. TerminalInfoInteger |
bool IsDemo() | bool IsDemoMQL4() { if(AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_DEMO) return(true); else return(false); } | IsDemo Retorna como TRUE se o especialista rodar em uma conta demo, senão retorna como FALSE. AccountInfoInteger |
bool IsDllsAllowed() | bool TerminalInfoInteger(TERMINAL_DLLS_ALLOWED) | IsDllsAllowed Retorna como TRUE se o acionamento da função DLL for autorizado pelo Consultor Especialista, senão retorna como FALSE. TerminalInfoInteger |
bool IsExpertEnabled() | bool AccountInfoInteger(ACCOUNT_TRADE_EXPERT) | IsExpertEnabled Retorna como TRUE se o uso do Consultor Especialista estiver habilitado no terminal do cliente, senão retorna como FALSE. AccountInfoInteger |
bool IsLibrariesAllowed() | bool MQLInfoInteger(MQL5_DLLS_ALLOWED) | IsLibrariesAllowed Retorna como TRUE se um Consultor Especialista puder acionar a função da biblioteca, senão retorna como FALSE. MQLInfoInteger |
bool IsOptimization() | bool MQLInfoInteger(MQL5_OPTIMIZATION) | IsOptimization Retorna como TRUE se um Consultor Especialista estiver rodando no modo de otimização de analista de estratégia, senão retorna como FALSE. MQLInfoInteger |
bool IsStopped() | bool IsStopped() | IsStopped Retorna como TRUE se o programa (um Consultor Especialista ou um script) foi comandado para interromper sua operação, senão retorna como FALSE. IsStopped |
bool IsTesting() | bool MQLInfoInteger(MQL5_TESTING) | IsTesting Retorna como TRUE se um Consultor Especialista estiver rodando no modo de teste, senão retorna como FALSE. MQLInfoInteger |
bool IsTradeAllowed() | bool MQLInfoInteger(MQL5_TRADE_ALLOWED) | IsTradeAllowed Retorna como TRUE se negócios pelo Consultor Especialista estiverem autorizados e uma linha para negócios não estiver ocupada, senão retorna como FALSE. MQLInfoInteger |
bool IsTradeContextBusy() | - | IsTradeContextBusy Retorna como TRUE se uma linha estiver ocupada por outro Consultor Especialista, senão retorna como FALSE. |
bool IsVisualMode() | bool MQLInfoInteger(MQL5_VISUAL_MODE) | IsVisualMode Retorna como TRUE se o Consultor Especialista for testado com o botão "Modo Visual" marcado, senão retorna como FALSE. MQLInfoInteger |
int UninitializeReason() | int UninitializeReason() | UninitializeReason Retorna com o código do motivo de desinicialização para Consultor Especialistas, indicadores personalizados, e scripts. UninitializeReason |
7. Terminal de cliente
MQL4 | MQL5 | Descrição |
---|---|---|
string TerminalCompany() | string TerminalInfoString(TERMINAL_COMPANY) | TerminalCompany Retorna com o nome da companhia proprietária do terminal de cliente. TerminalInfoString |
string TerminalName() | string TerminalInfoString(TERMINAL_NAME) | TerminalName Retorna com o nome do terminal do cliente. TerminalInfoString |
string TerminalPath() | string TerminalInfoString(TERMINAL_PATH) | TerminalPath Retorna com o diretório, do qual o terminal de cliente foi inicializado. TerminalInfoString |
8. Funções comuns
MQL4 | MQL5 | Descrição |
---|---|---|
void Alert(...) | void Alert(argument,...) | Alert Exibe uma caixa de diálogo contendo a data definida pelo usuário. Os parâmetros podem ser de qualquer tipo. Alert |
void Comment(...) | void Comment(argument,...) | Comment A função resulta no comentário definido pelo usuário no canto superior esquerdo do gráfico. Comment |
int GetTickCount() | uint GetTickCount() | GetTickCount A função GetTickCount() recupera o número de milissegundos que se passaram desde que o sistema foi iniciado. GetTickCount |
double MarketInfo(string symbol, int type) | double MarketInfoMQL4(string symbol, int type) { switch(type) { case MODE_LOW: return(SymbolInfoDouble(symbol,SYMBOL_LASTLOW)); case MODE_HIGH: return(SymbolInfoDouble(symbol,SYMBOL_LASTHIGH)); case MODE_TIME: return(SymbolInfoInteger(symbol,SYMBOL_TIME)); case MODE_BID: return(Bid); case MODE_ASK: return(Ask); case MODE_POINT: return(SymbolInfoDouble(symbol,SYMBOL_POINT)); case MODE_DIGITS: return(SymbolInfoInteger(symbol,SYMBOL_DIGITS)); case MODE_SPREAD: return(SymbolInfoInteger(symbol,SYMBOL_SPREAD)); case MODE_STOPLEVEL: return(SymbolInfoInteger(symbol,SYMBOL_TRADE_STOPS_LEVEL)); case MODE_LOTSIZE: return(SymbolInfoDouble(symbol,SYMBOL_TRADE_CONTRACT_SIZE)); case MODE_TICKVALUE: return(SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_VALUE)); case MODE_TICKSIZE: return(SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_SIZE)); case MODE_SWAPLONG: return(SymbolInfoDouble(symbol,SYMBOL_SWAP_LONG)); case MODE_SWAPSHORT: return(SymbolInfoDouble(symbol,SYMBOL_SWAP_SHORT)); case MODE_STARTING: return(0); case MODE_EXPIRATION: return(0); case MODE_TRADEALLOWED: return(0); case MODE_MINLOT: return(SymbolInfoDouble(symbol,SYMBOL_VOLUME_MIN)); case MODE_LOTSTEP: return(SymbolInfoDouble(symbol,SYMBOL_VOLUME_STEP)); case MODE_MAXLOT: return(SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX)); case MODE_SWAPTYPE: return(SymbolInfoInteger(symbol,SYMBOL_SWAP_MODE)); case MODE_PROFITCALCMODE: return(SymbolInfoInteger(symbol,SYMBOL_TRADE_CALC_MODE)); case MODE_MARGINCALCMODE: return(0); case MODE_MARGININIT: return(0); case MODE_MARGINMAINTENANCE: return(0); case MODE_MARGINHEDGED: return(0); case MODE_MARGINREQUIRED: return(0); case MODE_FREEZELEVEL: return(SymbolInfoInteger(symbol,SYMBOL_TRADE_FREEZE_LEVEL)); default: return(0); } return(0); } | MarketInfo Retorna com vários dados sobre ações listadas na janela Market Watch. SymbolInfoInteger, SymbolInfoDouble, Bid, Ask |
int MessageBox(string text=NULL, string caption=NULL, int flags=EMPTY) | int MessageBox(string text, string caption=NULL, int flags=0) | MessageBox A caixa de mensagem cria, exibe e comanda a caixa de mensagem. MessageBox |
void PlaySound(string filename) | bool PlaySound(string filename) | PlaySound A função reproduz um arquivo de som. PlaySound |
void Print(...) | void Print(argument,...) | Print Imprime uma mensagem no registro do especialista. |
bool SendFTP(string filename, string ftp_path=NULL) | bool SendFTP(string filename, string ftp_path=NULL) | SendFTP Envia o arquivo para o conjunto do servidor FTP em ferramentas->opções->aba editor. Se a tentativa falhar, retorna como FALSE. SendFTP |
void SendMail(string subject, string some_text) | bool SendMail(string subject, string some_text) | SendMail Envia uma mensagem para o e-mail determinado em ferramentas->opções->aba email. SendMail |
void Sleep(int milliseconds) | void Sleep(int milliseconds) | Sleep A função Sleep() suspende a execução do especialista atual dentro do intervalo especificado. Sleep |
9. Funções de conversão
MQL4 | MQL5 | Descrição |
---|---|---|
string CharToStr(int char_code) | string CharToString(int char_code) | CharToStr Conversão do código do símbolo em uma cadeia de um caractere. CharToString |
string DoubleToStr(double value, int digits) | string DoubleToString(double value, int digits=8) | DoubleToStr Retorna com uma cadeia de texto com o valor numérico especificado convertido em um formato de precisão especificado. DoubleToString |
double NormalizeDouble(double value, int digits) | double NormalizeDouble(double value, int digits) | NormalizeDouble Envolve o valor do ponto flutuante para a precisão fornecida. Retorna com o valor normalizado do tipo duplo. NormalizeDouble |
double StrToDouble(string value) | double StringToDouble(string value) | StrToDouble Converte a representação da cadeia do número para um tipo duplo (formato de precisão dupla com ponto flutuante). StringToDouble |
int StrToInteger(string value) | long StringToInteger(string value) | StrToInteger Converte uma cadeia contendo a representação do valor do caractere em um valor do tipo int (inteiro). StringToInteger |
datetime StrToTime(string value) | datetime StringToTime(string value) | StrToTime Converte uma cadeia em um formato "aaaa.mm.dd hh:mi" para o tipo datetime (a quantidade de segundos que se passaram desde 1 de janeiro de 1970). StringToTime |
string TimeToStr(datetime value, int mode=TIME_DATE|TIME_MINUTES) | string TimeToString(datetime value, int mode=TIME_DATE|TIME_MINUTES) | TimeToStr Converte o valor contendo o tempo em segundos que se passou desde 1 de janeiro de 1970 em uma cadeia do formato "aaaa.mm.dd hh:mi". TimeToString |
10. Indicadores Personalizados
MQL4 | MQL5 | Descrição |
---|---|---|
void IndicatorBuffers(int count) | - | IndicatorBuffers Distribui memória para os buffers utilizada para os cálculos do indicador personalizado. |
int IndicatorCounted() | int IndicatorCountedMQL4() { if(prev_calculated>0) return(prev_calculated-1); if(prev_calculated==0) return(0); return(0); } | IndicatorCounted A função retorna com a quantidade de barras não alteradas após o indicador ter sido inicializado pela última vez. OnCalculate |
void IndicatorDigits(int digits) | bool IndicatorSetInteger(INDICATOR_DIGITS,digits) | IndicatorDigits Estabelece um formato de precisão (a contagem de dígitos após o ponto decimal) para visualizar os valores do indicador. IndicatorSetInteger |
void IndicatorShortName(string name) | bool IndicatorSetString(INDICATOR_SHORTNAME,name) | IndicatorShortName Estabelece o nome "curto" de um indicador personalizado para ser mostrado na DataWindow (janela de dados) e na subjanela do gráfico. IndicatorSetString |
void SetIndexArrow(int index, int code) | bool PlotIndexSetInteger(index,PLOT_ARROW,code) | SetIndexArrow Estabelece um símbolo de seta para a linha de indicadores do tipo DRAW_ARROW. PlotIndexSetInteger |
bool SetIndexBuffer(int index, double array[]) | bool SetIndexBuffer(index,array,INDICATOR_DATA) | SetIndexBuffer Liga a variável do arranjo declarada em um nível global para o buffer pré-definido do indicador personalizado. SetIndexBuffer |
void SetIndexDrawBegin(int index, int begin) | bool PlotIndexSetInteger(index,PLOT_DRAW_BEGIN,begin) | SetIndexDrawBegin Estabelece o número da barra (do inicio dos dados) do qual o desenho da linha do indicador fornecido deve começar. PlotIndexSetInteger |
void SetIndexEmptyValue(int index, double value) | bool PlotIndexSetDouble(index,PLOT_EMPTY_VALUE,value) | SetIndexEmptyValue Estabelece o valor vazio da linha de desenho. PlotIndexSetDouble |
void SetIndexLabel(int index, string text) | bool PlotIndexSetString(index,PLOT_LABEL,text) | SetIndexLabel Estabelece a descrição da linha de desenho para mostrar na DataWindow e na dica de ferramenta. PlotIndexSetString |
void SetIndexShift(int index, int shift) | bool PlotIndexSetInteger(index,PLOT_SHIFT,shift) | SetIndexShift Estabelece o deslocamento para a linha de desenho. PlotIndexSetInteger |
void SetIndexStyle(int index, int type, int style=EMPTY, int width=EMPTY, color clr=CLR_NONE) | void SetIndexStyleMQL4(int index, int type, int style=EMPTY, int width=EMPTY, color clr=CLR_NONE) { if(width>-1) PlotIndexSetInteger(index,PLOT_LINE_WIDTH,width); if(clr!=CLR_NONE) PlotIndexSetInteger(index,PLOT_LINE_COLOR,clr); switch(type) { case 0: PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_LINE); case 1: PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_SECTION); case 2: PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_HISTOGRAM); case 3: PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_ARROW); case 4: PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_ZIGZAG); case 12: PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_NONE); default: PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_LINE); } switch(style) { case 0: PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_SOLID); case 1: PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_DASH); case 2: PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_DOT); case 3: PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_DASHDOT); case 4: PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_DASHDOTDOT); default: return; } | SetIndexStyle Estabelece o novo tipo, estilo, largura e cor para uma linha de indicador fornecida. PlotIndexSetInteger |
void SetLevelStyle(int draw_style, int line_width, color clr=CLR_NONE) | void SetLevelStyleMQL4(int draw_style, int line_width, color clr=CLR_NONE) { IndicatorSetInteger(INDICATOR_LEVELWIDTH,line_width); if(clr!=CLR_NONE) IndicatorSetInteger(INDICATOR_LEVELCOLOR,clr); switch(draw_style) { case 0: IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_SOLID); case 1: IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_DASH); case 2: IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_DOT); case 3: IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_DASHDOT); case 4: IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_DASHDOTDOT); default: return; } } | SetLevelStyle A função estabelece um novo estilo, largura e cor dos níveis horizontais do indicador para ser lançado em uma janela separada. IndicatorSetInteger |
void SetLevelValue(int level, double value) | bool IndicatorSetDouble(INDICATOR_LEVELVALUE,level,value) | SetLevelValue A função estabelece um valor para um nível horizontal fornecido do indicador para ser lançado em uma janela separada. IndicatorSetDouble |
11. Funções de data e horário
MQL4 | MQL5 | Descrição |
---|---|---|
int Day() | int DayMQL4() { MqlDateTime tm; TimeCurrent(tm); return(tm.day); } | Day Retorna com o dia do mês atual, por exemplo, o dia do mês do último horário conhecido do servidor. TimeCurrent, MqlDateTime |
int DayOfWeek() | int DayOfWeekMQL4() { MqlDateTime tm; TimeCurrent(tm); return(tm.day_of_week); } | DayOfWeek Retorna com o dia atual de base zero da semana (0-domingo,1,2,3,4,5,6) do último horário conhecido do servidor. TimeCurrent, MqlDateTime |
int DayOfYear() | int DayOfYearMQL4() { MqlDateTime tm; TimeCurrent(tm); return(tm.day_of_year); } | DayOfYear Retorna com o dia atual do ano (1 quer dizer 1 de janeiro,..,365(6) significa 31 de dezembro), por exemplo, o dia do ano do último horário conhecido do servidor. TimeCurrent, MqlDateTime |
int Hour() | int HourMQL4() { MqlDateTime tm; TimeCurrent(tm); return(tm.hour); } | Hour Retorna com a hora (0,1,2..23) do último horário conhecido do servidor no momento por volta do momento do início do programa (esse valor não mudará dentro do período da execução do programa). TimeCurrent, MqlDateTime |
int Minute() | int MinuteMQL4() { MqlDateTime tm; TimeCurrent(tm); return(tm.min); } | Minute Retorna com o minuto atual (0,1,2,..59) do último horário conhecido do servidor por volta do momento do início do programa. TimeCurrent, MqlDateTime |
int Month() | int MonthMQL4() { MqlDateTime tm; TimeCurrent(tm); return(tm.mon); } | Month Retorna com o mês atual como um número (1 - janeiro,2,3,4,5,6,7,8,9,10,11,12), por exemplo, o número do mês do último horário conhecido do servidor. TimeCurrent, MqlDateTime |
int Seconds() | int SecondsMQL4() { MqlDateTime tm; TimeCurrent(tm); return(tm.sec); } | Seconds Retorna com a quantidade de segundos que se passaram do começo do minuto atual do último horário conhecido do servidor por volta do momento do início do programa (este valor não mudará dentro do período da execução do programa). TimeCurrent, MqlDateTime |
datetime TimeCurrent() | datetime TimeCurrent() | TimeCurrent Retorna com o último horário conhecido do servidor (horário da última cotação recebida) na forma do número de segundos que se passaram desde 0:00 de 1 de janeiro de 1970. TimeCurrent |
int TimeDay(datetime date) | int TimeDayMQL4(datetime date) { MqlDateTime tm; TimeToStruct(date,tm); return(tm.day); } | TimeDay Retorna com o dia do mês (1 - 31) para a data especificada. TimeToStruct, MqlDateTime |
int TimeDayOfWeek(datetime date) | int TimeDayOfWeekMQL4(datetime date) { MqlDateTime tm; TimeToStruct(date,tm); return(tm.day_of_week); } | TimeDayOfWeek Retorna com o dia de base zero da semana (0 equivale a domingo,1,2,3,4,5,6) para a data especificada. TimeToStruct, MqlDateTime |
int TimeDayOfYear(datetime date) | int TimeDayOfYearMQL4(datetime date) { MqlDateTime tm; TimeToStruct(date,tm); return(tm.day_of_year); } | TimeDayOfYear Retorna com o dia (1 equivale a 1 de janeiro,..,365(6) equivale a 31 de Dezembro) do ano para a data especificada. TimeToStruct, MqlDateTime |
int TimeHour(datetime time) | int TimeHourMQL4(datetime date) { MqlDateTime tm; TimeToStruct(date,tm); return(tm.hour); } | TimeHour Retorna com a hora para o horário especificado. TimeToStruct, MqlDateTime |
datetime TimeLocal() | datetime TimeLocal() | TimeLocal Retorna com o horário do computador local na forma do número de segundos que se passaram desde 0:00 de 1 de janeiro de 1970. TimeLocal |
int TimeMinute(datetime time) | int TimeMinuteMQL4(datetime date) { MqlDateTime tm; TimeToStruct(date,tm); return(tm.min); } | TimeMinute Retorna com o minuto do horário especificado. TimeToStruct, MqlDateTime |
int TimeMonth(datetime time) | int TimeMonthMQL4(datetime date) { MqlDateTime tm; TimeToStruct(date,tm); return(tm.mon); } | TimeMonth Retorna com o número do mês para o tempo especificada. TimeToStruct, MqlDateTime |
int TimeSeconds(datetime time) | int TimeSecondsMQL4(datetime date) { MqlDateTime tm; TimeToStruct(date,tm); return(tm.sec); } | TimeSeconds Retorna com a quantidade de segundos que passaram desde o início do minuto para o horário especificado. TimeToStruct, MqlDateTime |
int TimeYear(datetime time) | int TimeYearMQL4(datetime date) { MqlDateTime tm; TimeToStruct(date,tm); return(tm.year); } | TimeYear Retorna com o ano da data especificada. O valor retornado pode estar dentro do intervalo de 1970 a 2037. TimeToStruct, MqlDateTime |
int Year() | int YearMQL4() { MqlDateTime tm; TimeCurrent(tm); return(tm.year); } | Year Retorna com o ano atual, por exemplo, o ano do último horário conhecido do servidor. TimeCurrent, MqlDateTime |
12. Funções de arquivo
MQL4 | MQL5 | Descrição |
---|---|---|
void FileClose(int handle) | void FileClose(int file_handle) | FileClose Fecha o arquivo anteriormente aberto pela função FileOpen(). FileClose |
void FileDelete(string filename) | bool FileDelete(string file_name int common_flag=0) | FileDelete Exclui o nome do arquivo especificado. FileDelete |
void FileFlush(int handle) | void FileFlush(int file_handle) | FileFlush Libera todos os dados armazenados no buffer de arquivo para o disco. FileFlush |
bool FileIsEnding(int handle) | bool FileIsEnding(int file_handle) | FileIsEnding Retorna como um verdadeiro lógico se o ponteiro do arquivo estiver no fim do arquivo, senão retorna como false. FileIsEnding |
bool FileIsLineEnding(int handle) | bool FileIsLineEnding(int file_handle) | FileIsLineEnding Para arquivo CSV retorna como um verdadeiro lógico se o ponteiro do arquivo estiver no fim da linha, senão retorna como false. FileIsLineEnding |
int FileOpen(string filename, int mode, int delimiter=';') | int FileOpen(string ile_name, int pen_flags, short delimiter='\t' uint codepage=CP_ACP) | FileOpen Abre o arquivo para entrada e/ou para saída. Retorna para um identificador de arquivo para o arquivo aberto ou -1 (se a função falhar). FileOpen |
int FileOpenHistory(string filename, int mode, int delimiter=';') | - | FileOpenHistory Abre o arquivo no diretório do histórico atual (terminal_directory\history\server_name) ou em seus subdiretórios. Retorna o identificador de arquivo para o arquivo aberto. Se a função falhar, o valor de retorno é -1. |
int FileReadArray(int handle, object &array[], int start, int count) | uint FileReadArray(int file_handle, void array[], int start_item=0, int items_count=WHOLE_ARRAY) | FileReadArray Lê a quantidade especificada de elementos do arquivo binário dentro do arranjo. FileReadArray |
double FileReadDouble(int handle, int size=DOUBLE_VALUE) | double FileReadDoubleMQL4(int handle, int size=DOUBLE_VALUE) { return(FileReadDouble(handle)); } | FileReadDouble Lê o número de precisão dupla com ponto flutuante da posição do arquivo binário atual. FileReadDouble |
int FileReadInteger(int handle, int size=LONG_VALUE) | int FileReadInteger(int file_handle, int size=INT_VALUE) | FileReadInteger A função lê o inteiro da posição do arquivo binário atual. FileReadInteger |
double FileReadNumber(int handle) | double FileReadNumber(int file_handle) | FileReadNumber Lê o número da posição do arquivo atual antes do delimitador. Somente para arquivos CSV. FileReadNumber |
string FileReadString(int handle, int length=0) | string FileReadString(int file_handle, int size=-1) | FileReadString A função lê uma linha a partir da posição atual do arquivo. FileReadString |
bool FileSeek(int handle, int offset, int origin) | bool FileSeekMQL4(long handle, int offset, ENUM_FILE_POSITION origin) { FileSeek(handle,offset,origin); return(true); } | FileSeek A função move o ponteiro do arquivo para uma nova posição que é um deslocamento, em bytes, desde o início, do fim da posição do arquivo atual. FileSeek |
int FileSize(int handle) | ulong FileSize(int file_handle) | FileSize A função retorna como o tamanho do arquivo em bytes. FileSize |
int FileTell(int handle) | ulong FileTell(int file_handle) | FileTell Retorna como a posição atual do ponteiro do arquivo. FileTell |
int FileWrite(int handle,...) | uint FileWrite(int file_handle,...) | FileWrite A função é destinada a gravação de dados no arquivo CSV, estando o delimitador inserido automaticamente. FileWrite |
int FileWriteArray(int handle, object array[], int start, int count) | int FileWriteArray(int file_handle, void array[], int start_item=0, int items_count=WHOLE_ARRAY) | FileWriteArray A função grava um arranjo em um arquivo binário. FileWriteArray |
int FileWriteDouble(int handle, double value, int size=DOUBLE_VALUE) | uint FileWriteDouble(int file_handle, double dvalue) | FileWriteDouble A função grava um valor duplo com um ponto flutuante em um arquivo binário. FileWriteDouble |
int FileWriteInteger(int handle, int value, int size=LONG_VALUE) | uint FileWriteInteger(int file_handle, int ivalue, int size=INT_VALUE) | FileWriteInteger A função grava o valor inteiro em um arquivo binário. FileWriteInteger |
int FileWriteString(int handle, string value, int size) | uint FileWriteString(int file_handle, string svalue, int size=-1) | FileWriteString A função grava o arranjo em um arquivo binário da posição atual do arquivo. FileWriteString |
13. Variáveis globais
MQL4 | MQL5 | Descrição |
---|---|---|
bool GlobalVariableCheck(string name) | bool GlobalVariableCheck(string name) | GlobalVariableCheck Retorna como TRUE (verdadeiro) se a variável global existir, senão, retorna como FALSE (falso). GlobalVariableCheck |
bool GlobalVariableDel(string name) | bool GlobalVariableDel(string name) | GlobalVariableDel Exclui a variável global. GlobalVariableDel |
double GlobalVariableGet(string name) | double GlobalVariableGet(string name) | GlobalVariableGet Retorna o valor de uma variável global existente ou 0 se um erro ocorrer. GlobalVariableGet |
string GlobalVariableName(int index) | string GlobalVariableName(int index) | GlobalVariableName A função retorna o nome de uma variável global por seu índice na lista de variáveis globais. GlobalVariableName |
datetime GlobalVariableSet(string name, double value) | datetime GlobalVariableSet(string name, double value) | GlobalVariableSet Estabelece um novo valor das variáveis globais. Se ele não existir, o sistema cria uma nova variável global. GlobalVariableSet |
bool GlobalVariableSetOnCondition(string name, double value, double check_value) | bool GlobalVariableSetOnCondition(string name, double value, double check_value) | GlobalVariableSetOnCondition Estabelece o novo valor da variável global existente se o valor atual for igual ao terceiro parâmetro check_value. GlobalVariableSetOnCondition |
int GlobalVariablesDeleteAll(string prefix_name=NULL) | int GlobalVariablesDeleteAll(string prefix_name=NULL datetime limit_data=0) | GlobalVariablesDeleteAll Exclui variáveis globais. GlobalVariablesDeleteAll |
int GlobalVariablesTotal() | int GlobalVariablesTotal() | GlobalVariablesTotal A função retorna a contagem total das variáveis globais. GlobalVariablesTotal |
14. Funções matemáticas
MQL4 | MQL5 | Descrição |
---|---|---|
double MathAbs(double value) | double MathAbs(double value) | MathAbs Retorna o valor absoluto (módulo) do valor numérico especificado. MathAbs |
double MathArccos(double x) | double MathArccos(double val) | MathArccos A função MathArccos retorna o arco coseno de x dentro do intervalo de 0 a Pi (em radianos). MathArccos |
double MathArcsin(double x) | double MathArcsin(double val) | MathArcsin A função MathArcsin resulta no arco seno de x no intervalo de -Pi/2 a Pi/2 radianos. MathArcsin |
double MathArctan(double x) | double MathArctan(double value) | MathArctan O MathArctan resulta no arco tangente de x. MathArctan |
double MathCeil(double x) | double MathCeil(double val) | MathCeil A função MathCeil resulta um valor numérico que representa o menor inteiro que é maior ou igual a x. MathCeil |
double MathCos(double value) | double MathCos(double value) | MathCos Resulta no cosseno do ângulo especificado. MathCos |
double MathExp(double d) | double MathExp(double value) | MathExp Resulta no valor de e elevado a potência de d. MathExp |
double MathFloor(double x) | double MathFloor(double val) | MathFloor A função MathFloor resulta um valor numérico que representa o maior inteiro que é menor ou igual a x. MathFloor |
double MathLog(double x) | double MathLog(double val) | MathLog A função MathLog resulta o logaritmo natural de x se bem sucedido. MathLog |
double MathMax(double value1, double value2) | double MathMax(double value1, double value2) | MathMax Resulta o valor máximo de dois valores numéricos. MathMax |
double MathMin(double value1, double value2) | double MathMin(double value1, double value2) | MathMin Resulta o valor mínimo de dois valores numéricos. MathMin |
double MathMod(double value1, double value2) | double MathMod(double value1, double value2) | MathMod A função resulta no resto de pontos flutuantes da divisão de dois números. MathMod |
double MathPow(double base, double exponent) | double MathPow(double base, double exponent) | MathPow Resulta no valor da expressão da base elevada à potência especificada (valor do expoente). MathPow |
int MathRand() | int MathRand() | MathRand A função MathRand resulta em um inteiro pseudo-aleatório dentro do intervalo de 0 a 32767. MathRand |
double MathRound(double value) | double MathRound(double value) | MathRound Resulta no valor arredondado para o inteiro mais próximo do valor numérico especifico. MathRound |
double MathSin(double value) | double MathSin(double value) | MathSin Resulta no seno do ângulo especificado. MathSin |
double MathSqrt(double x) | double MathSqrt(double value) | MathSqrt A função MathSqrt resulta na raiz quadrada de x. MathSqrt |
void MathSrand(int seed) | void MathSrand(int seed) | MathSrand A função MathSrand() estabelece o ponto de partida para gerar uma série de inteiros pseudo-aleatórios. MathSrand |
double MathTan(double x) | double MathTan(double rad) | MathTan O MathTan resulta na tangente de x. MathTan |
15. Funções dos objetos
MQL4 | MQL5 | Descrição |
---|---|---|
bool ObjectCreate(string name, int type, int window, datetime time1, double price1, datetime time2=0, double price2=0, datetime time3=0, double price3=0) | bool ObjectCreateMQL4(string name, ENUM_OBJECT type, int window, datetime time1, double price1, datetime time2=0, double price2=0, datetime time3=0, double price3=0) { return(ObjectCreate(0,name,type,window, time1,price1,time2,price2,time3,price3)); } | ObjectCreate A criação de um objeto com o nome especificado, tipo e coordenadas iniciais na janela especificada. ObjectCreate |
bool ObjectDelete(string name) | bool ObjectDeleteMQL4(string name) { return(ObjectDelete(0,name)); } | ObjectDelete Exclui um objeto que tem o nome especificado. ObjectDelete |
string ObjectDescription(string name) | string ObjectDescriptionMQL4(string name) { return(ObjectGetString(0,name,OBJPROP_TEXT)); } | ObjectDescription Resulta na descrição do objeto. ObjectGetString |
int ObjectFind(string name) | int ObjectFindMQL4(string name) { return(ObjectFind(0,name)); } | ObjectFind Busca um objeto que tem o nome especificado. ObjectFind |
double ObjectGet(string name, int prop_id) | double ObjectGetMQL4(string name, int index) { switch(index) { case OBJPROP_TIME1: return(ObjectGetInteger(0,name,OBJPROP_TIME)); case OBJPROP_PRICE1: return(ObjectGetDouble(0,name,OBJPROP_PRICE)); case OBJPROP_TIME2: return(ObjectGetInteger(0,name,OBJPROP_TIME,1)); case OBJPROP_PRICE2: return(ObjectGetDouble(0,name,OBJPROP_PRICE,1)); case OBJPROP_TIME3: return(ObjectGetInteger(0,name,OBJPROP_TIME,2)); case OBJPROP_PRICE3: return(ObjectGetDouble(0,name,OBJPROP_PRICE,2)); case OBJPROP_COLOR: return(ObjectGetInteger(0,name,OBJPROP_COLOR)); case OBJPROP_STYLE: return(ObjectGetInteger(0,name,OBJPROP_STYLE)); case OBJPROP_WIDTH: return(ObjectGetInteger(0,name,OBJPROP_WIDTH)); case OBJPROP_BACK: return(ObjectGetInteger(0,name,OBJPROP_WIDTH)); case OBJPROP_RAY: return(ObjectGetInteger(0,name,OBJPROP_RAY_RIGHT)); case OBJPROP_ELLIPSE: return(ObjectGetInteger(0,name,OBJPROP_ELLIPSE)); case OBJPROP_SCALE: return(ObjectGetDouble(0,name,OBJPROP_SCALE)); case OBJPROP_ANGLE: return(ObjectGetDouble(0,name,OBJPROP_ANGLE)); case OBJPROP_ARROWCODE: return(ObjectGetInteger(0,name,OBJPROP_ARROWCODE)); case OBJPROP_TIMEFRAMES: return(ObjectGetInteger(0,name,OBJPROP_TIMEFRAMES)); case OBJPROP_DEVIATION: return(ObjectGetDouble(0,name,OBJPROP_DEVIATION)); case OBJPROP_FONTSIZE: return(ObjectGetInteger(0,name,OBJPROP_FONTSIZE)); case OBJPROP_CORNER: return(ObjectGetInteger(0,name,OBJPROP_CORNER)); case OBJPROP_XDISTANCE: return(ObjectGetInteger(0,name,OBJPROP_XDISTANCE)); case OBJPROP_YDISTANCE: return(ObjectGetInteger(0,name,OBJPROP_YDISTANCE)); case OBJPROP_FIBOLEVELS: return(ObjectGetInteger(0,name,OBJPROP_LEVELS)); case OBJPROP_LEVELCOLOR: return(ObjectGetInteger(0,name,OBJPROP_LEVELCOLOR)); case OBJPROP_LEVELSTYLE: return(ObjectGetInteger(0,name,OBJPROP_LEVELSTYLE)); case OBJPROP_LEVELWIDTH: return(ObjectGetInteger(0,name,OBJPROP_LEVELWIDTH)); } } | ObjectGet A função resulta no valor da propriedade do objeto especificado. ObjectGetInteger, ObjectGetDouble |
string ObjectGetFiboDescription(string name, int index) | string ObjectGetFiboDescriptionMQL4(string name, int index) { return(ObjectGetString(0,name,OBJPROP_LEVELTEXT,index)); } | ObjectGetFiboDescription A função resulta na descrição do nível de um objeto Fibonacci. ObjectGetString |
int ObjectGetShiftByValue(string name, double value) | int ObjectGetShiftByValueMQL4(string name, double value) { ENUM_TIMEFRAMES timeframe=TFMigrate(PERIOD_CURRENT); datetime Arr[]; int shift; MqlRates mql4[]; if(ObjectGetTimeByValue(0,name,value)<0) return(-1); CopyRates(NULL,timeframe,0,1,mql4); if(CopyTime(NULL,timeframe,mql4[0].time, ObjectGetTimeByValue(0,name,value),Arr)>0) return(ArraySize(Arr)-1); else return(-1); } | ObjectGetShiftByValue A função calcula e resulta no índice da barra (relacionada ao deslocamento para a barra atual) para o preço fornecido. MqlRates, ObjectGetTimeByValue, CopyRates, CopyTime, ArraySize |
double ObjectGetValueByShift(string name, int shift) | double ObjectGetValueByShiftMQL4(string name, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(PERIOD_CURRENT); MqlRates mql4[]; CopyRates(NULL,timeframe,shift,1,mql4); return(ObjectGetValueByTime(0,name,mql4[0].time,0)); } | ObjectGetValueByShift A função calcula e resulta no valor do preço para a barra especificada (relacionada ao deslocamento para a barra atual). MqlRates, CopyRates, ObjectGetValueByTime |
bool ObjectMove(string name, int point, datetime time1, double price1) | bool ObjectMoveMQL4(string name, int point, datetime time1, double price1) { return(ObjectMove(0,name,point,time1,price1)); } | ObjectMove A função desloca uma coordenada de objeto no gráfico. Os objetos podem ter de um a três coordenadas dependendo de seus tipos. ObjectMove |
string ObjectName(int index) | string ObjectNameMQL4(int index) { return(ObjectName(0,index)); } | ObjectName A função resulta no nome do objeto pelo seu índice na lista de objetos. ObjectName |
int ObjectsDeleteAll(int window=EMPTY, int type=EMPTY) | int ObjectsDeleteAllMQL4(int window=EMPTY, int type=EMPTY) { return(ObjectsDeleteAll(0,window,type)); } | ObjectsDeleteAll Exclui todos os objetos do tipo especificado e na subjanela especificada do gráfico. ObjectsDeleteAll |
bool ObjectSet(string name, int prop_id, double value) | bool ObjectSetMQL4(string name, int index, double value) { switch(index) { case OBJPROP_TIME1: ObjectSetInteger(0,name,OBJPROP_TIME,(int)value);return(true); case OBJPROP_PRICE1: ObjectSetDouble(0,name,OBJPROP_PRICE,value);return(true); case OBJPROP_TIME2: ObjectSetInteger(0,name,OBJPROP_TIME,1,(int)value);return(true); case OBJPROP_PRICE2: ObjectSetDouble(0,name,OBJPROP_PRICE,1,value);return(true); case OBJPROP_TIME3: ObjectSetInteger(0,name,OBJPROP_TIME,2,(int)value);return(true); case OBJPROP_PRICE3: ObjectSetDouble(0,name,OBJPROP_PRICE,2,value);return(true); case OBJPROP_COLOR: ObjectSetInteger(0,name,OBJPROP_COLOR,(int)value);return(true); case OBJPROP_STYLE: ObjectSetInteger(0,name,OBJPROP_STYLE,(int)value);return(true); case OBJPROP_WIDTH: ObjectSetInteger(0,name,OBJPROP_WIDTH,(int)value);return(true); case OBJPROP_BACK: ObjectSetInteger(0,name,OBJPROP_BACK,(int)value);return(true); case OBJPROP_RAY: ObjectSetInteger(0,name,OBJPROP_RAY_RIGHT,(int)value);return(true); case OBJPROP_ELLIPSE: ObjectSetInteger(0,name,OBJPROP_ELLIPSE,(int)value);return(true); case OBJPROP_SCALE: ObjectSetDouble(0,name,OBJPROP_SCALE,value);return(true); case OBJPROP_ANGLE: ObjectSetDouble(0,name,OBJPROP_ANGLE,value);return(true); case OBJPROP_ARROWCODE: ObjectSetInteger(0,name,OBJPROP_ARROWCODE,(int)value);return(true); case OBJPROP_TIMEFRAMES: ObjectSetInteger(0,name,OBJPROP_TIMEFRAMES,(int)value);return(true); case OBJPROP_DEVIATION: ObjectSetDouble(0,name,OBJPROP_DEVIATION,value);return(true); case OBJPROP_FONTSIZE: ObjectSetInteger(0,name,OBJPROP_FONTSIZE,(int)value);return(true); case OBJPROP_CORNER: ObjectSetInteger(0,name,OBJPROP_CORNER,(int)value);return(true); case OBJPROP_XDISTANCE: ObjectSetInteger(0,name,OBJPROP_XDISTANCE,(int)value);return(true); case OBJPROP_YDISTANCE: ObjectSetInteger(0,name,OBJPROP_YDISTANCE,(int)value);return(true); case OBJPROP_FIBOLEVELS: ObjectSetInteger(0,name,OBJPROP_LEVELS,(int)value);return(true); case OBJPROP_LEVELCOLOR: ObjectSetInteger(0,name,OBJPROP_LEVELCOLOR,(int)value);return(true); case OBJPROP_LEVELSTYLE: ObjectSetInteger(0,name,OBJPROP_LEVELSTYLE,(int)value);return(true); case OBJPROP_LEVELWIDTH: ObjectSetInteger(0,name,OBJPROP_LEVELWIDTH,(int)value);return(true); default: return(false); } return(false); } | ObjectSet Altera o valor da propriedade do objeto especificado. ObjectSetInteger, ObjectSetDouble |
bool ObjectSetFiboDescription(string name, int index, string text) | bool ObjectSetFiboDescriptionMQL4(string name, int index, string text) { return(ObjectSetString(0,name,OBJPROP_LEVELTEXT,index,text)); } | ObjectSetFiboDescription A função atribui uma nova descrição a um nível de um objeto Fibonacci. ObjectSetString |
bool ObjectSetText(string name, string text, int font_size, string font_name=NULL, color text_color=CLR_NONE) | bool ObjectSetTextMQL4(string name, string text, int font_size, string font="", color text_color=CLR_NONE) { int tmpObjType=(int)ObjectGetInteger(0,name,OBJPROP_TYPE); if(tmpObjType!=OBJ_LABEL && tmpObjType!=OBJ_TEXT) return(false); if(StringLen(text)>0 && font_size>0) { if(ObjectSetString(0,name,OBJPROP_TEXT,text)==true && ObjectSetInteger(0,name,OBJPROP_FONTSIZE,font_size)==true) { if((StringLen(font)>0) && ObjectSetString(0,name,OBJPROP_FONT,font)==false) return(false); if(text_color>-1 && ObjectSetInteger(0,name,OBJPROP_COLOR,text_color)==false) return(false); return(true); } return(false); } return(false); } | ObjectSetText Altera a descrição do objeto. ObjectGetInteger, ObjectSetString, ObjectSetInteger StringLen |
int ObjectsTotal(int type=EMPTY) | int ObjectsTotalMQL4(int type=EMPTY, int window=-1) { return(ObjectsTotal(0,window,type)); } | ObjectsTotal Retorna com a quantidade total do tipo especificado no gráfico. ObjectsTotal |
int ObjectType(string name) | int ObjectTypeMQL4(string name) { return((int)ObjectGetInteger(0,name,OBJPROP_TYPE)); } | ObjectType A função retorna com o valor do tipo de objeto. ObjectGetInteger |
16. Funções da cadeia
MQL4 | MQL5 | Descrição |
---|---|---|
string StringConcatenate(...) | int StringConcatenate(string &string_var, void argument1 void argument2 ...) | StringConcatenate Forma uma cadeia dos dados passados e os devolve. StringConcatenate |
int StringFind(string text, string matched_text, int start=0) | int StringFind(string string_value, string match_substring, int start_pos=0) | StringFind Busca uma sub cadeia Retorna com a posição na cadeia da qual a sub cadeia procurada se inicia, ou tem valor -1 se a sub cadeia não tiver sido encontrada. StringFind |
int StringGetChar(string text, int pos) | ushort StringGetCharacter(string string_value, int pos) | StringGetChar Retorna com o caractere (código) de uma posição especificada na cadeia. StringGetCharacter |
int StringLen(string text) | int StringLen(string string_value) | StringLen Retorna com a contagem de caracteres em uma cadeia. StringLen |
string StringSetChar(string text, int pos, int value) | bool StringSetCharacter(string &string_var, int pos, ushort character) | StringSetChar Retorna com a cópia da cadeia com um caractere alterado na posição especificada. StringSetCharacter |
string StringSubstr(string text, int start, int length=0) | string StringSubstr(string string_value, int start_pos, int length=-1) | StringSubstr Extrai uma sub cadeia de uma cadeia de texto iniciando da posição fornecida. StringSubstr |
string StringTrimLeft(string text) | int StringTrimLeft(string& string_var) | StringTrimLeft A função corta os espaços dos avanços de linha e abas na parte esquerda da cadeia. StringTrimLeft |
string StringTrimRight(string text) | int StringTrimRight(string& string_var) | StringTrimLeft A função corta os espaços dos avanços de linha e abas na parte direita da cadeia. StringTrimRight |
17. Indicadores técnicos
Os princípios da utilização dos indicadores técnicos no Consultor Especialistas são considerados no artigoMQL5 para iniciantes: Guia para usar indicadores técnicos em Consultores Especialistas. O método, utilizado nesta referência é suficiente para obter os resultados de cálculo do indicador para o preço especificado. Para fazer isso, precisamos da função auxiliar:
double CopyBufferMQL4(int handle,int index,int shift) { double buf[]; switch(index) { case 0: if(CopyBuffer(handle,0,shift,1,buf)>0) return(buf[0]); break; case 1: if(CopyBuffer(handle,1,shift,1,buf)>0) return(buf[0]); break; case 2: if(CopyBuffer(handle,2,shift,1,buf)>0) return(buf[0]); break; case 3: if(CopyBuffer(handle,3,shift,1,buf)>0) return(buf[0]); break; case 4: if(CopyBuffer(handle,4,shift,1,buf)>0) return(buf[0]); break; default: break; } return(EMPTY_VALUE); }Vamos declarar as seguintes constantes:
ENUM_MA_METHOD MethodMigrate(int method) { switch(method) { case 0: return(MODE_SMA); case 1: return(MODE_EMA); case 2: return(MODE_SMMA); case 3: return(MODE_LWMA); default: return(MODE_SMA); } } ENUM_APPLIED_PRICE PriceMigrate(int price) { switch(price) { case 1: return(PRICE_CLOSE); case 2: return(PRICE_OPEN); case 3: return(PRICE_HIGH); case 4: return(PRICE_LOW); case 5: return(PRICE_MEDIAN); case 6: return(PRICE_TYPICAL); case 7: return(PRICE_WEIGHTED); default: return(PRICE_CLOSE); } } ENUM_STO_PRICE StoFieldMigrate(int field) { switch(field) { case 0: return(STO_LOWHIGH); case 1: return(STO_CLOSECLOSE); default: return(STO_LOWHIGH); } } //+------------------------------------------------------------------+ enum ALLIGATOR_MODE { MODE_GATORJAW=1, MODE_GATORTEETH, MODE_GATORLIPS }; enum ADX_MODE { MODE_MAIN, MODE_PLUSDI, MODE_MINUSDI }; enum UP_LOW_MODE { MODE_BASE, MODE_UPPER, MODE_LOWER }; enum ICHIMOKU_MODE { MODE_TENKANSEN=1, MODE_KIJUNSEN, MODE_SENKOUSPANA, MODE_SENKOUSPANB, MODE_CHINKOUSPAN }; enum MAIN_SIGNAL_MODE{ MODE_MAIN, MODE_SIGNAL };
MQL4 | MQL5 | Descrição |
---|---|---|
double iAC(string symbol, int timeframe, int shift) | double iACMQL4(string symbol, int tf, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iAC(symbol,timeframe); if(handle<0) { Print("The iAC object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iAC Calcula o oscilador do acelerador/desacelerador Bill Williams. iAC |
double iAD(string symbol, int timeframe, int shift) | double iADMQL4(string symbol, int tf, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=(int)iAD(symbol,timeframe,VOLUME_TICK); if(handle<0) { Print("The iAD object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iAD Calcula o indicador acumulação/distribuição e retorna com seu valor. iAD |
double iAlligator(string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int mode, int shift) | double iAlligatorMQL4(string symbol, int tf, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int method, int price, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_MA_METHOD ma_method=MethodMigrate(method); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iAlligator(symbol,timeframe,jaw_period,jaw_shift, teeth_period,teeth_shift, lips_period,lips_shift, ma_method,applied_price); if(handle<0) { Print("The iAlligator object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode-1,shift)); } | iAlligator Calcula o Bill Williams' Alligator e retorna com seu valor. iAlligator |
double iADX(string symbol, int timeframe, int period, int applied_price, int mode, int shift) | double iADXMQL4(string symbol, int tf, int period, int price, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iADX(symbol,timeframe,period); if(handle<0) { Print("The iADX object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode,shift)); } | iADX Calcula o índice direcional de movimento e retorna com seu valor. iADX |
double iATR(string symbol, int timeframe, int period, int shift) | double iATRMQL4(string symbol, int tf, int period, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iATR(symbol,timeframe,period); if(handle<0) { Print("The iATR object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iATR Calcula o indicador do intervalo verdadeiro médio e retorna com seu valor. iATR |
double iAO(string symbol, int timeframe, int shift) | double iAOMQL4(string symbol, int tf, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iAO(symbol,timeframe); if(handle<0) { Print("The iAO object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iAO Calcula o Oscilador Maravilhoso (Awesome Oscillator) de Bill Williams e retorna com seu valor. iAO |
double iBearsPower(string symbol, int timeframe, int period, int applied_price, int shift) | double iBearsPowerMQL4(string symbol, int tf, int period, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iBearsPower(symbol,timeframe,period); if(handle<0) { Print("The iBearsPower object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iBearsPower Calcula o indicador Bears Power e retorna com seu valor. iBearsPower |
double iBands(string symbol, int timeframe, int period, int deviation, int bands_shift, int applied_price, int mode, int shift) | double iBandsMQL4(string symbol, int tf, int period, double deviation, int bands_shift, int method, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_MA_METHOD ma_method=MethodMigrate(method); int handle=iBands(symbol,timeframe,period, bands_shift,deviation,ma_method); if(handle<0) { Print("The iBands object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode,shift)); } | iBands Calcula o indicador Bollinger bands e retorna com seu valor. iBands |
double iBandsOnArray(double array[], int total, int period, int deviation, int bands_shift, int mode, int shift) | - | iBandsOnArray Cálculo do indicador Bollinger Bands nos dados armazenados em um arranjo numérico. |
double iBullsPower(string symbol, int timeframe, int period, int applied_price, int shift) | double iBullsPowerMQL4(string symbol, int tf, int period, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iBullsPower(symbol,timeframe,period); if(handle<0) { Print("The iBullsPower object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iBullsPower Calcula o indicador Bulls Power e retorna com seu valor. iBullsPower |
double iCCI(string symbol, int timeframe, int period, int applied_price, int shift) | double iCCIMQL4(string symbol, int tf, int period, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iCCI(symbol,timeframe,period,price); if(handle<0) { Print("The iCCI object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iCCI Calcula o índice do canal Commodity e retorna com seu valor. iCCI |
double iCCIOnArray(double array[], int total, int period, int shift) | - | iCCIOnArray Cálculo do índice do canal Commodity nos dados armazenados em um arranjo numérico. |
double iCustom(string symbol, int timeframe, string name, ..., int mode, int shift) | int iCustom(string symbol, ENUM_TIMEFRAMES period, string name ...) | iCustom Calcula o indicador personalizado especificado e retorna com seu valor. iCustom |
double iDeMarker(string symbol, int timeframe, int period, int shift) | double iDeMarkerMQL4(string symbol, int tf, int period, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iDeMarker(symbol,timeframe,period); if(handle<0) { Print("The iDeMarker object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iDeMarker Calcula o indicador DeMarker e retorna com seu valor. iDeMarker |
double iEnvelopes(string symbol, int timeframe, int ma_period, int ma_method, int ma_shift, int applied_price, double deviation, int mode, int shift) | double EnvelopesMQL4(string symbol, int tf, int ma_period, int method, int ma_shift, int price, double deviation, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_MA_METHOD ma_method=MethodMigrate(method); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iEnvelopes(symbol,timeframe, ma_period,ma_shift,ma_method, applied_price,deviation); if(handle<0) { Print("The iEnvelopes object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode-1,shift)); } | iEnvelopes Calcula o indicador Envelopes e retorna com seu valor. iEnvelopes |
double iEnvelopesOnArray(double array[], int total, int ma_period, int ma_method, int ma_shift, double deviation, int mode, int shift) | - | iEnvelopesOnArray Cálculo do indicador Envelopes nos dados armazenados em um arranjo numérico. |
double iForce(string symbol, int timeframe, int period, int ma_method, int applied_price, int shift) | double iForceMQL4(string symbol, int tf, int period, int method, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_MA_METHOD ma_method=MethodMigrate(method); int handle=iForce(symbol,timeframe,period,ma_method,VOLUME_TICK); if(handle<0) { Print("The iForce object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iForce Calcula o índice Force e retorna com seu valor. iForce |
double iFractals(string symbol, int timeframe, int mode, int shift) | double iFractalsMQL4(string symbol, int tf, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iFractals(symbol,timeframe); if(handle<0) { Print("The iFractals object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode-1,shift)); } | iFractals Calcula o Fractals e retorna com seu valor. iFractals |
double iGator(string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int mode, int shift) | double iGatorMQL4(string symbol, int tf, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int method, int price, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_MA_METHOD ma_method=MethodMigrate(method); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iGator(symbol,timeframe,jaw_period,jaw_shift, teeth_period,teeth_shift, lips_period,lips_shift, ma_method,applied_price); if(handle<0) { Print("The iGator object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode-1,shift)); } | iGator Cálculo do oscilador Gator iGator |
double iIchimoku(string symbol, int timeframe, int tenkan_sen, int kijun_sen, int senkou_span_b, int mode, int shift) | double iIchimokuMQL4(string symbol, int tf, int tenkan_sen, int kijun_sen, int senkou_span_b, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iIchimoku(symbol,timeframe, tenkan_sen,kijun_sen,senkou_span_b); if(handle<0) { Print("The iIchimoku object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode-1,shift)); } | iIchimoku Calcula o Ichimoku Kinko Hyo e retorna seu valor. iIchimoku |
double iBWMFI(string symbol, int timeframe, int shift) | double iBWMFIMQL4(string symbol, int tf, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=(int)iBWMFI(symbol,timeframe,VOLUME_TICK); if(handle<0) { Print("The iBWMFI object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iBWMFI Calcula o índice de facilitação de mercado Bill Williams e retorna com seu valor. iBWMFI |
double iMomentum(string symbol, int timeframe, int period, int applied_price, int shift) | double iMomentumMQL4(string symbol, int tf, int period, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iMomentum(symbol,timeframe,period,applied_price); if(handle<0) { Print("The iMomentum object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iMomentum Calcula o indicador Momentum e retorna seu valor. iMomentum |
double iMomentumOnArray(double array[], int total, int period, int shift) | - | iMomentumOnArray Cálculo do indicador Momentum nos dados armazenados em um arranjo numérico. |
double iMFI(string symbol, int timeframe, int period, int shift) | double iMFIMQL4(string symbol, int tf, int period, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=(int)iMFI(symbol,timeframe,period,VOLUME_TICK); if(handle<0) { Print("The iMFI object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iMFI Calcula o índice de fluxo de dinheiro e retorna seu valor. iMFI |
double iMA(string symbol, int timeframe, int period, int ma_shift, int ma_method, int applied_price, int shift) | double iMAMQL4(string symbol, int tf, int period, int ma_shift, int method, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_MA_METHOD ma_method=MethodMigrate(method); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iMA(symbol,timeframe,period,ma_shift, ma_method,applied_price); if(handle<0) { Print("The iMA object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iMA Calcula o indicador de média móvel e retorna seu valor. iMA |
double iMAOnArray(double array[], int total, int period, int ma_shift, int ma_method, int shift) | double iMAOnArrayMQL4(double &array[], int total, int period, int ma_shift, int ma_method, int shift) { double buf[],arr[]; if(total==0) total=ArraySize(array); if(total>0 && total<=period) return(0); if(shift>total-period-ma_shift) return(0); switch(ma_method) { case MODE_SMA : { total=ArrayCopy(arr,array,0,shift+ma_shift,period); if(ArrayResize(buf,total)<0) return(0); double sum=0; int i,pos=total-1; for(i=1;i<period;i++,pos--) sum+="arr[pos];" while(pos>=0) { sum+=arr[pos]; buf[pos]=sum/period; sum-=arr[pos+period-1]; pos--; } return(buf[0]); } case MODE_EMA : { if(ArrayResize(buf,total)<0) return(0); double pr=2.0/(period+1); int pos=total-2; while(pos>=0) { if(pos==total-2) buf[pos+1]=array[pos+1]; buf[pos]=array[pos]*pr+buf[pos+1]*(1-pr); pos--; } return(buf[shift+ma_shift]); } case MODE_SMMA : { if(ArrayResize(buf,total)<0) return(0); double sum=0; int i,k,pos; pos=total-period; while(pos>=0) { if(pos==total-period) { for(i=0,k=pos;i<period;i++,k++) {="" sum+="array[k];" buf[k]="0; } } else sum=buf[pos+1]*(period-1)+array[pos]; buf[pos]=sum/period; pos--; } return(buf[shift+ma_shift]); } case MODE_LWMA : { if(ArrayResize(buf,total)<0) return(0); double sum=0.0,lsum=0.0; double price; int i,weight=0,pos=total-1; for(i=1;i<=period;i++,pos--) { price=array[pos]; sum+=price*i; lsum+=price; weight+=i; } pos++; i=pos+period; while(pos>=0) { buf[pos]=sum/weight; if(pos==0) break; pos--; i--; price=array[pos]; sum=sum-lsum+price*period; lsum-=array[i]; lsum+=price; } return(buf[shift+ma_shift]); } default: return(0); } return(0); } | |
double iOsMA(string symbol, int timeframe, int fast_ema_period, int slow_ema_period, int signal_period, int applied_price, int shift) | double iOsMAMQL4(string symbol, int tf, int fast_ema_period, int slow_ema_period, int signal_period, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iOsMA(symbol,timeframe, fast_ema_period,slow_ema_period, signal_period,applied_price); if(handle<0) { Print("The iOsMA object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iOsMA Calcula a média móvel do oscilador e retorna com seu valor. iOsMA |
double iMACD(string symbol, int timeframe, int fast_ema_period, int slow_ema_period, int signal_period, int applied_price, int mode, int shift) | double iMACDMQL4(string symbol, int tf, int fast_ema_period, int slow_ema_period, int signal_period, int price, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iMACD(symbol,timeframe, fast_ema_period,slow_ema_period, signal_period,applied_price); if(handle<0) { Print("The iMACD object is not created: Error ",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode,shift)); } | iMACD Calcula as médias móveis convergência/divergência e retorna com seu valor. iMACD |
double iOBV(string symbol, int timeframe, int applied_price, int shift) | double iOBVMQL4(string symbol, int tf, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iOBV(symbol,timeframe,VOLUME_TICK); if(handle<0) { Print("The iOBV object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iOBV Calcula o indicador de On Balance Volume (volume em balanço) e retorna com seu valor. iOBV |
double iSAR(string symbol, int timeframe, double step, double maximum, int shift) | double iSARMQL4(string symbol, int tf, double step, double maximum, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iSAR(symbol,timeframe,step,maximum); if(handle<0) { Print("The iSAR object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iSAR Calcula o Parabolic Stop (parada parabólica) e o Reverse system (sistema inverso) e retorna com seus valores. iSAR |
double iRSI(string symbol, int timeframe, int period, int applied_price, int shift) | double iRSIMQL4(string symbol, int tf, int period, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iRSI(symbol,timeframe,period,applied_price); if(handle<0) { Print("The iRSI object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iRSI Calcula o índice de força relativa e retorna com seu valor. iRSI |
double iRSIOnArray(double array[], int total, int period, int shift) | - | iRSIOnArray Cálculo do índice de força relativa nos dados armazenados em um arranjo numérico. |
double iRVI(string symbol, int timeframe, int period, int mode, int shift) | double iRVIMQL4(string symbol, int tf, int period, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iRVI(symbol,timeframe,period); if(handle<0) { Print("The iRVI object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode,shift)); } | iRVI Calcula o índice de vigor relativo e retorna com seu valor. iRVI |
double iStdDev(string symbol, int timeframe, int ma_period, int ma_shift, int ma_method, int applied_price, int shift) | double iStdDevMQL4(string symbol, int tf, int ma_period, int ma_shift, int method, int price, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_MA_METHOD ma_method=MethodMigrate(method); ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); int handle=iStdDev(symbol,timeframe,ma_period,ma_shift, ma_method,applied_price); if(handle<0) { Print("The iStdDev object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iStdDev Calcula o indicador de desvio padrão e retorna com seu valor. iStdDev |
double iStdDevOnArray(double array[], int total, int ma_period, int ma_shift, int ma_method, int shift) | - | iStdDevOnArray Cálculo do indicador de desvio padrão nos dados armazenados em um arranjo numérico. |
double iStochastic(string symbol, int timeframe, int%Kperiod, int%Dperiod, int slowing, int method, int price_field, int mode, int shift) | double iStochasticMQL4(string symbol, int tf, int Kperiod, int Dperiod, int slowing, int method, int field, int mode, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); ENUM_MA_METHOD ma_method=MethodMigrate(method); ENUM_STO_PRICE price_field=StoFieldMigrate(field); int handle=iStochastic(symbol,timeframe,Kperiod,Dperiod, slowing,ma_method,price_field); if(handle<0) { Print("The iStochastic object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,mode,shift)); } | iStochastic Calcula o oscilador Stochastic e retorna com seu valor. iStochastic |
double iWPR(string symbol, int timeframe, int period, int shift) | double iWPRMQL4(string symbol, int tf, int period, int shift) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); int handle=iWPR(symbol,timeframe,period); if(handle<0) { Print("The iWPR object is not created: Error",GetLastError()); return(-1); } else return(CopyBufferMQL4(handle,0,shift)); } | iWPR Calcula o indicador de intervalo percentual de Larry William e retorna com seu valor. iWPR |
18. Acesso de série temporal
MQL4 | MQL5 | Descrição |
---|---|---|
int iBars(string symbol, int timeframe) | int iBarsMQL4(string symbol,int tf) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); return(Bars(symbol,timeframe)); } | int iBarsMQL4(string symbol,int tf) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); return(Bars(symbol,timeframe)); }Bars Retorna com o número de barras no gráfico especificado. Bars |
int iBarShift(string symbol, int timeframe, datetime time, bool exact=false | int iBarShiftMQL4(string symbol, int tf, datetime time, bool exact=false) { if(time<0) return(-1); ENUM_TIMEFRAMES timeframe=TFMigrate(tf); datetime Arr[],time1; CopyTime(symbol,timeframe,0,1,Arr); time1=Arr[0]; if(CopyTime(symbol,timeframe,time,time1,Arr)>0) { if(ArraySize(Arr)>2) return(ArraySize(Arr)-1); if(time<time1) return(1); else return(0); } else return(-1); } | iBarShift Busca uma barra pelo tempo aberto. CopyTime, ArraySize |
double iClose(string symbol, int timeframe, int shift) | double iCloseMQL4(string symbol,int tf,int index){ if(index < 0) return(-1); double Arr[]; ENUM_TIMEFRAMES timeframe=TFMigrate(tf); if(CopyClose(symbol,timeframe, index, 1, Arr)>0) return(Arr[0]); else return(-1); } | Close Retorna com o valor de fechamento para a barra do símbolo indicado com o período de tempo e o deslocamento. Se o histórico local estiver vazio (não carregado), a função retorna como 0. CopyRates, MqlRates |
double iHigh(string symbol, int timeframe, int shift) | double iHighMQL4(string symbol,int tf,int index) { if(index < 0) return(-1); double Arr[]; ENUM_TIMEFRAMES timeframe=TFMigrate(tf); if(CopyHigh(symbol,timeframe, index, 1, Arr)>0) return(Arr[0]); else return(-1); } | High Retorna com valor alto para a barra do símbolo indicado com o período de tempo e o deslocamento. Se o histórico local estiver vazio (não carregado), a função retorna como 0. CopyRates, MqlRates |
int iHighest(string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0) | int iHighestMQL4(string symbol, int tf, int type, int count=WHOLE_ARRAY, int start=0) { if(start<0) return(-1); ENUM_TIMEFRAMES timeframe=TFMigrate(tf); if(count<=0) count=Bars(symbol,timeframe); if(type<=MODE_OPEN) { double Open[]; ArraySetAsSeries(Open,true); CopyOpen(symbol,timeframe,start,count,Open); return(ArrayMaximum(Open,0,count)+start); } if(type==MODE_LOW) { double Low[]; ArraySetAsSeries(Low,true); CopyLow(symbol,timeframe,start,count,Low); return(ArrayMaximum(Low,0,count)+start); } if(type==MODE_HIGH) { double High[]; ArraySetAsSeries(High,true); CopyHigh(symbol,timeframe,start,count,High); return(ArrayMaximum(High,0,count)+start); } if(type==MODE_CLOSE) { double Close[]; ArraySetAsSeries(Close,true); CopyClose(symbol,timeframe,start,count,Close); return(ArrayMaximum(Close,0,count)+start); } if(type==MODE_VOLUME) { long Volume[]; ArraySetAsSeries(Volume,true); CopyTickVolume(symbol,timeframe,start,count,Volume); return(ArrayMaximum(Volume,0,count)+start); } if(type>=MODE_TIME) { datetime Time[]; ArraySetAsSeries(Time,true); CopyTime(symbol,timeframe,start,count,Time); return(ArrayMaximum(Time,0,count)+start); //--- } return(0); } | iHighest Retorna com o deslocamento do valor máximo sobre um número especificado de períodos dependendo do tipo. CopyOpen, CopyLow, CopyHigh, CopyClose, CopyTickVolume, CopyTime, ArrayMaximum |
double iLow(string symbol, int timeframe, int shift) | double iLowMQL4(string symbol,int tf,int index) { if(index < 0) return(-1); double Arr[]; ENUM_TIMEFRAMES timeframe=TFMigrate(tf); if(CopyLow(symbol,timeframe, index, 1, Arr)>0) return(Arr[0]); else return(-1); } | iLow Retorna com o valor baixo para a barra do símbolo indicado com o período de tempo e o deslocamento. Se o histórico local estiver vazio (não carregado), a função retorna como 0. CopyRates, MqlRates |
int iLowest(string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0) | int iLowestMQL4(string symbol, int tf, int type, int count=WHOLE_ARRAY, int start=0) { if(start<0) return(-1); ENUM_TIMEFRAMES timeframe=TFMigrate(tf); if(count<=0) count=Bars(symbol,timeframe); if(type<=MODE_OPEN) { double Open[]; ArraySetAsSeries(Open,true); CopyOpen(symbol,timeframe,start,count,Open); return(ArrayMinimum(Open,0,count)+start); } if(type==MODE_LOW) { double Low[]; ArraySetAsSeries(Low,true); CopyLow(symbol,timeframe,start,count,Low); return(ArrayMinimum(Low,0,count)+start); } if(type==MODE_HIGH) { double High[]; ArraySetAsSeries(High,true); CopyHigh(symbol,timeframe,start,count,High); return(ArrayMinimum(High,0,count)+start); } if(type==MODE_CLOSE) { double Close[]; ArraySetAsSeries(Close,true); CopyClose(symbol,timeframe,start,count,Close); return(ArrayMinimum(Close,0,count)+start); } if(type==MODE_VOLUME) { long Volume[]; ArraySetAsSeries(Volume,true); CopyTickVolume(symbol,timeframe,start,count,Volume); return(ArrayMinimum(Volume,0,count)+start); } if(type>=MODE_TIME) { datetime Time[]; ArraySetAsSeries(Time,true); CopyTime(symbol,timeframe,start,count,Time); return(ArrayMinimum(Time,0,count)+start); } //--- return(0); } | iLowest Retorna com o deslocamento do valor mais baixo sobre um número de períodos especificados dependendo do tipo. CopyOpen, CopyLow, CopyHigh, CopyClose, CopyTickVolume, CopyTime, ArrayMinimum |
double iOpen(string symbol, int timeframe, int shift) | double iOpenMQL4(string symbol,int tf,int index) { if(index < 0) return(-1); double Arr[]; ENUM_TIMEFRAMES timeframe=TFMigrate(tf); if(CopyOpen(symbol,timeframe, index, 1, Arr)>0) return(Arr[0]); else return(-1); } | iLow Retorna com o valor de abertura para a barra do símbolo indicado com com o período de tempo e o deslocamento. Se o histórico local estiver vazio (não carregado), a função retorna como 0. CopyRates, MqlRates |
datetime iTime(string symbol, int timeframe, int shift) | datetime iTimeMQL4(string symbol,int tf,int index) { if(index < 0) return(-1); ENUM_TIMEFRAMES timeframe=TFMigrate(tf); datetime Arr[]; if(CopyTime(symbol, timeframe, index, 1, Arr)>0) return(Arr[0]); else return(-1); } | iTime Retorna com o valor do tempo para a barra do símbolo indicado com o período de tempo e o deslocamento. Se o histórico local estiver vazio (não carregado), a função retorna como 0. CopyRates, MqlRates |
double iVolume(string symbol, int timeframe, int shift) | int iVolumeMQL4(string symbol,int tf,int index) { if(index < 0) return(-1); long Arr[]; ENUM_TIMEFRAMES timeframe=TFMigrate(tf); if(CopyTickVolume(symbol, timeframe, index, 1, Arr)>0) return(Arr[0]); else return(-1); } | iVolume Retorna com o valor do volume de ponto para a barra do símbolo indicado com o período de tempo e o deslocamento. Se o histórico local estiver vazio (não carregado), a função retorna como 0. CopyRates, MqlRates |
19. Operações do gráfico
MQL4 | MQL5 | Descrição |
---|---|---|
void HideTestIndicators(bool hide) | - | HideTestIndicators A função ajusta um indicador de ocultação do sinalizador pelo Consultor Especialista. |
int Period() | ENUM_TIMEFRAMES Period() | Period Retorna com a quantidade de minutos determinando o período utilizado (período de tempo do gráfico). Period |
bool RefreshRates() | - | RefreshRates Atualização dos dados em variáveis pré-definidas e em arranjos de séries. |
string Symbol() | string Symbol() | Symbol Retorna com uma cadeia de texto com o nome do instrumento financeiro atual. Symbol |
int WindowBarsPerChart() | int ChartGetInteger(0,CHART_VISIBLE_BARS,0) | WindowBarsPerChart A função retorna com a quantidade de barras visíveis no gráfico. ChartGetInteger |
string WindowExpertName() | string MQLInfoString(MQL5_PROGRAM_NAME) | WindowExpertName Retorna com o nome do especialista executado, o script, o indicador personalizado, ou biblioteca, dependendo do programa do MQL4, do qual a função foi acionada. MQLInfoString |
int WindowFind(string name) | int WindowFindMQL4(string name) { int window=-1; if((ENUM_PROGRAM_TYPE)MQLInfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR) { window=ChartWindowFind(); } else { window=ChartWindowFind(0,name); if(window==-1) Print(__FUNCTION__+"(): Error = ",GetLastError()); } return(window); } | WindowFind Se o indicador com o nome foi localizado, a função retorna com o índice da janela contendo este indicador especificado, senão ele retorna como -1. ChartWindowFind, MQLInfoInteger |
int WindowFirstVisibleBar() | int ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0) | WindowFirstVisibleBar A função retorna com o número da primeira barra visível na janela atual do gráfico. ChartGetInteger |
int WindowHandle(string symbol, int timeframe) | int WindowHandleMQL4(string symbol, int tf) { ENUM_TIMEFRAMES timeframe=TFMigrate(tf); long currChart,prevChart=ChartFirst(); int i=0,limit=100; while(i<limit) {="" currchart="ChartNext(prevChart); if(currChart<0) break; if(ChartSymbol(currChart)==symbol && ChartPeriod(currChart)==timeframe) return((int)currChart); prevChart=currChart; i++; } return(0); } | WindowHandle Retorna com o gerenciador de janelas do sistema do gráfico especificado. ChartFirst, ChartNext, ChartSymbol, ChartPeriod |
bool WindowIsVisible(int index) | bool ChartGetInteger(0,CHART_WINDOW_IS_VISIBLE,index) | WindowIsVisible Retorna como TRUE se a subjanela do gráfico estiver visível, senão retorna como FALSE. ChartGetInteger |
int WindowOnDropped() | int ChartWindowOnDropped() | WindowOnDropped Retorna com o índice da janela onde o especialista, o indicador personalizado ou o script foram retirados. ChartWindowOnDropped |
double WindowPriceMax(int index=0) | double ChartGetDouble(0,CHART_PRICE_MAX,index) | WindowPriceMax Retorna com o valor máximo da escala vertical da subjanela especificada do gráfico atual (0-janela principal do gráfico, as subjanelas dos indicadores são numeradas começando de 1). ChartGetDouble |
double WindowPriceMin(int index=0) | double ChartGetDouble(0,CHART_PRICE_MIN,index) | WindowPriceMin Retorna com o valor mínimo da escala vertical da subjanela especificada do gráfico atual (0-janela principal do gráfico, as subjanelas dos indicadores são numeradas começando de 1). ChartGetDouble |
double WindowPriceOnDropped() | double ChartPriceOnDropped() | WindowPriceOnDropped Retorna com a parte de preços do ponto do gráfico onde o especialista ou o script foram retirados. ChartPriceOnDropped |
void WindowRedraw() | void ChartRedraw(0) | WindowRedraw Redesenha obrigatoriamente o gráfico atual. ChartRedraw |
bool WindowScreenShot(string filename, int size_x, int size_y, int start_bar=-1, int chart_scale=-1, int chart_mode=-1) | bool WindowScreenShotMQL4(string filename, int size_x, int size_y, int start_bar=-1, int chart_scale=-1, int chart_mode=-1) { if(chart_scale>0 && chart_scale<=5) ChartSetInteger(0,CHART_SCALE,chart_scale); switch(chart_mode) { case 0: ChartSetInteger(0,CHART_MODE,CHART_BARS); case 1: ChartSetInteger(0,CHART_MODE,CHART_CANDLES); case 2: ChartSetInteger(0,CHART_MODE,CHART_LINE); } if(start_bar<0) return(ChartScreenShot(0,filename,size_x,size_y,ALIGN_RIGHT)); else return(ChartScreenShot(0,filename,size_x,size_y,ALIGN_LEFT)); } | WindowScreenShot Grava uma captura de tela do gráfico atual como um GIF. ChartSetInteger, ChartScreenShot |
datetime WindowTimeOnDropped() | datetime ChartTimeOnDropped() | WindowTimeOnDropped Retorna com a parte do tempo do ponto do gráfico onde o especialista ou script foram retirados. ChartTimeOnDropped |
int WindowsTotal() | int ChartGetInteger(0,CHART_WINDOWS_TOTAL) | WindowsTotal Retorna com a contagem das janelas indicadoras no gráfico (incluindo o gráfico principal). ChartGetInteger |
int WindowXOnDropped() | int ChartXOnDropped() | WindowXOnDropped Retorna com o valor no eixo X em pixels para o área do ponto do cliente na janela do gráfico na qual o especialista ou script foram retirados. ChartXOnDropped |
int WindowYOnDropped() | int ChartYOnDropped() | WindowYOnDropped Retorna com o valor no eixo Y em pixels para o área do ponto do cliente na janela do gráfico na qual o especialista ou script foram retirados. ChartYOnDropped |
Conclusão
- Não consideramos funções de negociação, porque no MQL5 o conceito é diferente, e o original deve ser usado! é possível convertê-los, mas a lógica de negócios deve ser alterada. Em outras palavras, não faz sentido em convertê-las.
- A conversão de programas de uma linguagem para outra é sempre associada com a perda de funcionalidade e desempenho. Portanto, utilize este guia para uma busca rápida pelas funções análogas.
- Tenho planos de desenvolver o emulador do MQL4, o qual permitirá a você executar seus programas do MQL4 no novo terminal de cliente do MetaTrader 5.
Créditos: keiji, A. Williams.
Traduzido do russo pela MetaQuotes Ltd.
Artigo original: https://www.mql5.com/ru/articles/81





- Aplicativos de negociação gratuitos
- 8 000+ sinais para cópia
- Notícias econômicas para análise dos mercados financeiros
Você concorda com a política do site e com os termos de uso