Quaisquer perguntas de recém-chegados sobre MQL4 e MQL5, ajuda e discussão sobre algoritmos e códigos - página 745

 

É possível ocultar todas as bandas de nível de reversão no indicador, não testadas e as demais, e deixar apenas as testadas, ou seja, ocultar extern bool zone_show_weak = true; e abaixo no código if (zone_strength[i] == ZONE_WEAK && zone_show_weak == false) e outros não podem ser ocultados, tentei defini-los todos para preto, mas se não estiverem lá, impedem que você veja o preço no gráfico em uma escala vertical. Talvez alguém entenda e corrija o código ou remova os níveis que descrevi acima. Código do indicador:

#propriedade copyright "Copyright © 2017 Andrew Sumner"

#link de propriedade ""

#property indicator_chart_window

#property Indicator_buffers 4

#property indicator_color1 Vermelho

#property indicator_color2 Vermelho

#property Indicator_color3 DodgerBlue

#property Indicator_color4 DodgerBlue


extern int BackLimit = 300; //Voltar - voltar

extern int TimeFrame = 0;

string externa TimeString = "0=Atual, 60=H1, 240=H4, 1440=Dia, 10080=Semana, 43200=Mês";


extern color color_support_weak = MediumAquamarine; //support - suporte para DarkSlateGray fraco

extern color color_support_utested = SeaGreen; //desmarcado

extern color color_support_verified = Verde;

cor externa color_support_proven = LimeGreen;

extern color color_support_turncoat = Olive Drab;

cor externa color_resist_weak = Sienna;

extern color color_resist_utested = Orquídea;

extern color color_resist_verified = Carmesim;

cor externa color_resist_proven = Vermelho;

cor externa color_resist_turncoat = DarkOrange;


extern bool zone_show_weak = true;

extern double zone_fuzzfactor = 0,2;

extern bool zone_solid = false; // true se false, não haverá zonas de listras completas, mas enquadradas por um retângulo com largura largura

extern int zone_linewidth = 2;

extern int zone_style = 0;

extern bool zone_show_info = true;

extern int zone_label_shift = 22; // deslocamento horizontal dos rótulos, mas somente após remover o indicador

extern bool zone_show_alerts = false;

extern bool zone_alert_popups = true;

extern bool zone_alert_sounds = true;

extern bool send_email = false;

extern int zone_alert_waitseconds = 300;

extern bool zone_merge = true;

extern bool zona_extend = true;


extern bool fractals_show = false;

externo duplo fractal_fast_factor = 3.0;

externo duplo fractal_slow_factor = 6,0;

extern bool SetGlobals = true;


double FastDnPts[], FastUpPts[];

double SlowDnPts[], SlowUpPts[];


double zone_hi[1000], zone_lo[1000];

int zone_start[1000], zone_hits[1000], zone_type[1000], zone_strength[1000], zone_count = 0;

boolzone_turn[1000];


#define ZONE_SUPPORT 1

#define ZONE_RESIST 2


#define ZONE_WEAK 0

#define ZONE_TURNCOAT 1

#define ZONE_UNTESTED 2

#define ZONE_VERIFIED 3

#define ZONE_PROVEN 4


#define UP_POINT 1

#define DN_POINT -1


int tempo_offset = 0;


int init()

{

IndicatorBuffers(4);


SetIndexBuffer(0, SlowDnPts);

SetIndexBuffer(1, SlowUpPts);

SetIndexBuffer(2, FastDnPts);

SetIndexBuffer(3, FastUpPts);


if (fractals_show == true)

{

SetIndexStyle(0, DRAW_ARROW, 0, 3);

SetIndexStyle(1, DRAW_ARROW, 0, 3);

SetIndexStyle(2, DRAW_ARROW, 0, 1);

SetIndexStyle(3, DRAW_ARROW, 0, 1);

SetIndexArrow(0, 218);

SetIndexArrow(1, 217);

SetIndexArrow(2, 218);

SetIndexArrow(3, 217);

}

senão

{

SetIndexStyle(0, DRAW_NONE);

SetIndexStyle(1, DRAW_NONE);

SetIndexStyle(2, DRAW_NONE);

SetIndexStyle(3, DRAW_NONE);

}


if (TimeFrame != 1 && TimeFrame != 5 && TimeFrame != 15 &&

TimeFrame != 60 && TimeFrame != 240 && TimeFrame != 1440 &&

TimeFrame != 10080 && TimeFrame != 43200)

intervalo de tempo = 0;


if(TimeFrame < Period())

prazo = period();


retorno(0);

}


int deinit()

{

DeleteZones();

DeleteGlobalVars();

retorno(0);

}


int start()

{

if (NewBar() == true)

{

int old_zone_count = zone_count;


Fractais Rápidos();

SlowFractals();

DeleteZones();

LocalizarZonas();

DesenharZonas();

if (zone_count < old_zone_count)

DeleteOldGlobalVars(old_zone_count);

}


if (zone_show_info == true)

{

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

{

cadeia lbl;

if (zone_strength[i] == ZONE_PROVEN)

lb=""; // Comprovado

senão se (zone_strength[i] == ZONE_VERIFIED)

lb=""; // Verificado

senão se (zone_strength[i] == ZONE_UNTESTED)

lb=""; // NÃO teste

senão se (zone_strength[i] == ZONE_TURNCOAT)

lb=""; // Reversão

senão

lb=""; // Fraco


if (zone_type[i] == ZONE_SUPPORT)

lbl = lbl + "sob"; //Apoio, suporte

senão

lbl = lbl + "sop"; //Resistência


if (zone_hits[i] > 0 && zone_strength[i] > ZONE_UNTESTED)

{

if (zone_hits[i] == 1)

lbl = lbl + ",T=" + zona_hits[i]; //Contagem de teste

senão

lbl = lbl + ",T=" + zona_hits[i]; //Contagem de teste

}


int ajuste_hpos;

int wbpc = WindowBarsPerChart();

intk;

k = Period() * 60 + (20 + StringLen(lbl));

se (wbpc < 80)

ajuste_hpos = Tempo[0] + k * 4;

senão se (wbpc < 125)

ajuste_hpos = Tempo[0] + k * 8;

senão se (wbpc < 250)

ajuste_hpos = Tempo[0] + k * 15;

senão se (wbpc < 480)

ajuste_hpos = Tempo[0] + k * 29;

senão se (wbpc < 950)

ajuste_hpos = Tempo[0] + k * 58;

senão

ajuste_hpos = Tempo[0] + k * 115;


int deslocamento = k * zone_label_shift;

double vpos = zone_hi[i] - (zone_hi[i] - zone_lo[i]) / 2;


// Texto das descrições dos níveis

string s = "SSSR#"+i+"LBL";

ObjectCreate(s, OBJ_TEXT, 0, 0, 0);

ObjectSet(s, OBJPROP_TIME1, ajuste_hpos + shift);

ObjectSet(s, OBJPROP_PRICE1, vpos);

ObjectSetText(s, StringRightPad(lbl, 36, " "), 11, "Courier New",clrWhite); //Preto

}

}


VerificarAlertas();


retorno(0);

}


void CheckAlerts()

{

static int lastalert = 0;


if (zone_show_alerts == false)

Retorna;


if (Time[0] - lastalert > zone_alert_waitseconds)

if (CheckEntryAlerts() == true)

último alerta = Tempo[0];

}


bool CheckEntryAlerts()

{

// verifica os registros

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

{

if (Fechar[0] >= zone_lo[i] && Fechar[0] < zone_hi[i])

{

if (zone_show_alerts == true)

{

if (zone_alert_popups == true)

{

if (zone_type[i] == ZONE_SUPPORT)

Alert(Symbol() + TimeFrameToString(TimeFrame) + ": Zona de suporte inserida"); //Introdução da zona de suporte

senão

Alert(Symbol() + TimeFrameToString(TimeFrame) + ": Zona de resistência inserida"); //Introduziu zona de resistência

}


if (zone_alert_sounds == true)

PlaySound("alerta.wav");

}

if (send_email == true)

{

cadeia dir = "";

string msg = StringConcatenate(Symbol(), "-", TimeFrameToString(TimeFrame), " at ", TimeToStr(Time[0], TIME_DATE|TIME_SECONDS),

" ", dir, "Zona inserida");

if (zone_type[i] == ZONE_SUPPORT)

{

dir = "Suporte";

SendMail("SS_SupRes_v04c alerta", msg);

}

senão

{

dir="resistência";

SendMail("SS_SupRes_v04c alerta", msg);

}

}

retorno(verdadeiro);

}

}


retorna falso);

}


void DeleteGlobalVars()

{

if(SetGlobals==false)

Retorna;


GlobalVariableDel("SSSR_Count_"+Symbol()+TimeFrame);

GlobalVariableDel("SSSR_Updated_"+Symbol()+TimeFrame);


int old_count = zone_count;

zona_conta = 0;

DeleteOldGlobalVars(old_count);

}


void DeleteOldGlobalVars(int old_count)

{

if(SetGlobals==false)

Retorna;


for (int i=zone_count; i<old_count; i++)

{

GlobalVariableDel("SSSR_HI_"+Symbol()+TimeFrame+i);

GlobalVariableDel("SSSR_LO_"+Symbol()+TimeFrame+i);

GlobalVariableDel("SSSR_HITS_"+Symbol()+TimeFrame+i);

GlobalVariableDel("SSSR_STRENGTH_"+Symbol()+TimeFrame+i);

GlobalVariableDel("SSSR_AGE_"+Symbol()+TimeFrame+i);

}

}


void LocalizarZonas()

{

int i, j, deslocamento, bustcount=0, testcount = 0;

dupla hival, loval;

bool virou = false, hasturned = false;


double temp_hi[1000], temp_lo[1000];

int temp_start[1000], temp_hits[1000], temp_strength[1000], temp_count = 0;

bool temp_turn[1000], temp_merge[1000];

int merge1[1000], merge2[1000], merge_count = 0;


// percorre as zonas da mais antiga para a menor (ignore as últimas 5 barras),

// encontrando aqueles que sobreviveram até o presente...

for (shift=MathMin(iBars(NULL, TimeFrame)-1, BackLimit); shift>5; shift--)

{

double atr = iATR(NULL, TimeFrame, 7, shift);

double fu = atr/2 * zone_fuzzfactor;

bool é Fraco;

bool touchOk = false;

bool isBust = false;

double close = iClose(NULL, TimeFrame, shift);

double high = iHigh(NULL, TimeFrame, shift);

double low = iLow(NULL, TimeFrame, shift);

duplo hi_i;

duplo lo_i;


if (FastUpPts[shift]> 0,001)

{

// ponto alto em ziguezague

éFraco = verdadeiro;

if (SlowUpPts[shift]> 0,001)

éFraco = falso;


hival=alta;

if (zone_extend == true)

hival += fu;


loval = MathMax(MathMin(próximo, alto-fu), alto-fu*2);

turno=falso;

virou=falso;

isbust=falso;


buscount = 0;

contagem de testes = 0;


para (i=shift-1; i>=0; i--)

{

hi_i = iHigh(NULL, TimeFrame, i);

lo_i = iLow(NULL, TimeFrame, i);


if ((virou == falso && FastUpPts[i] >= loval && FastUpPts[i] <= hival) ||

(virou == true && FastDnPts[i] <= hival && FastDnPts[i] >= loval))

{

// Toque potencial, apenas certifique-se de que foram mais de 10 velas desde a última vez

toqueOk = verdadeiro;

para (j=i+1; j<i+11; j++)

{

if ((virou == falso && FastUpPts[j] >= loval && FastUpPts[j] <= hival) ||

(virou == true && FastDnPts[j] <= hival && FastDnPts[j] >= loval))

{

toqueOk = false;

pausa;

}

}


if (touchOk == true)

{

// temos um toque. Se foi preso uma vez, remova a contagem de bustos

// já que sabemos que este nível ainda é válido e apenas trocamos de lado

buscount = 0;

contagem de testes++;

}

}


if ((virou == falso && hi_i > hival) ||

(virou == verdadeiro && lo_i < loval))

{

// este nível foi eliminado pelo menos uma vez

busto++;


if (bustcount > 1 || isWeak == true)

{

// dois ou mais

isBust = true;

pausa;

}


if (virou == verdadeiro)

turno=falso;

senão se (virou == falso)

turno=verdadeiro;


virou = verdadeiro;


// esquece hits anteriores

contagem de testes = 0;

}

}


if(isBust==false)

{

// nível ainda é válido, adicione à nossa lista

temp_hi[temp_count] = hival;

temp_lo[temp_count] = loval;

temp_turn[temp_count] = virou;

temp_hits[temp_count] = testcount;

temp_start[temp_count] = turno;

temp_merge[temp_count] = false;

if (contagem de testes > 3)

temp_strength[temp_count] = ZONE_PROVEN;

senão se (testcount > 0)

temp_strength[temp_count] = ZONE_VERIFIED;

senão se (hasturned == true)

temp_strength[temp_count] = ZONE_TURNCOAT;

senão se (é Fraco == falso)

temp_strength[temp_count] = ZONE_UNTESTED;

senão

temp_strength[temp_count] = ZONE_WEAK;


temp_count++;

}

}

senão se (FastDnPts[shift]> 0,001)

{

// ponto de ziguezague baixo

éFraco = verdadeiro;

if (SlowDnPts[shift]> 0,001)

éFraco = falso;


amor = baixo;

if (zone_extend == true)

amor = fu;


hival = MathMin(MathMax(perto, baixo+fu), baixo+fu*2);

turno=falso;

virou=falso;


buscount = 0;

contagem de testes = 0;

isbust=falso;


para (i=shift-1; i>=0; i--)

{

hi_i = iHigh(NULL, TimeFrame, i);

lo_i = iLow(NULL, TimeFrame, i);


if ((virou == true && FastUpPts[i] >= loval && FastUpPts[i] <= hival) ||

(virou == falso && FastDnPts[i] <= hival && FastDnPts[i] >= loval))

{

// Toque potencial, apenas certifique-se de que foram mais de 10 velas desde a última vez

toqueOk = verdadeiro;

para (j=i+1; j<i+11; j++)

{

if ((virou == verdadeiro && FastUpPts[j] >= loval && FastUpPts[j] <= hival) ||

(virou == falso && FastDnPts[j] <= hival && FastDnPts[j] >= loval))

{

toqueOk = false;

pausa;

}

}


if (touchOk == true)

{

// temos um toque. Se foi preso uma vez, remova a contagem de bustos

// já que sabemos que este nível ainda é válido e apenas trocamos de lado

buscount = 0;

contagem de testes++;

}

}


if ((virou == verdadeiro && hi_i > hival) ||

(virou == falso && lo_i < loval))

{

// este nível foi eliminado pelo menos uma vez

busto++;


if (bustcount > 1 || isWeak == true)

{

// dois ou mais

isBust = true;

pausa;

}


if (virou == verdadeiro)

turno=falso;

senão se (virou == falso)

turno=verdadeiro;


virou = verdadeiro;


// esquece hits anteriores

contagem de testes = 0;

}

}


if(isBust==false)

{

// nível ainda é válido, adicione à nossa lista

temp_hi[temp_count] = hival;

temp_lo[temp_count] = loval;

temp_turn[temp_count] = virou;

temp_hits[temp_count] = testcount;

temp_start[temp_count] = turno;

temp_merge[temp_count] = false;


if (contagem de testes > 3)

temp_strength[temp_count] = ZONE_PROVEN;

senão se (testcount > 0)

temp_strength[temp_count] = ZONE_VERIFIED;

senão se (hasturned == true)

temp_strength[temp_count] = ZONE_TURNCOAT;

senão se (é Fraco == falso)

temp_strength[temp_count] = ZONE_UNTESTED;

senão

temp_strength[temp_count] = ZONE_WEAK;


temp_count++;

}

}

}


// procura por zonas sobrepostas...

if (zone_merge == true)

{

merge_count = 1;

iterações = 0;

while (merge_count > 0 && iterações < 3)

{

merge_count = 0;

iterações++;


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

temp_merge[i] = false;


for (i = 0; i < temp_count-1; i++)

{

if (temp_hits[i] == -1 || temp_merge[j] == true)

Prosseguir;


para (j = i+1; j < temp_count; j++)

{

if (temp_hits[j] == -1 || temp_merge[j] == true)

Prosseguir;


if ((temp_hi[i] >= temp_lo[j] && temp_hi[i] <= temp_hi[j]) ||

(temp_lo[i] <= temp_lo[j] && temp_lo[i] >= temp_lo[j]) ||

(temp_hi[j] >= temp_lo[i] && temp_hi[j] <= temp_hi[i]) ||

(temp_lo[j] <= temp_lo[i] && temp_lo[j] >= temp_lo[i])))

{

merge1[merge_count] = i;

merge2[merge_count] = j;

temp_merge[i] = true;

temp_merge[j] = verdadeiro;

merge_count++;

}

}

}


// ... e combiná-los ...

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

{

int destino = merge1[i];

int fonte = merge2[i];


temp_hi[target] = MathMax(temp_hi[target], temp_hi[source]);

temp_lo[destino] = MathMin(temp_lo[destino], temp_lo[fonte]);

temp_hits[destino] += temp_hits[origem];

temp_start[target] = MathMax(temp_start[target], temp_start[source]);

temp_strength[target] = MathMax(temp_strength[target], temp_strength[source]);

if (temp_hits[target] > 3)

temp_strength[target] = ZONE_PROVEN;


if (temp_hits[target] == 0 && temp_turn[target] == false)

{

temp_hits[destino] = 1;

if (temp_strength[target] < ZONE_VERIFIED)

temp_strength[target] = ZONE_VERIFIED;

}


if (temp_turn[target] == false || temp_turn[source] == false)

temp_turn[destino] = false;

if (temp_turn[target] == true)

temp_hits[destino] = 0;


temp_hits[fonte] = -1;

}

}

}


// copia o resto da lista para nossas zonas oficiais

zona_conta = 0;

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

{

if (temp_hits[i] >= 0 && zone_count < 1000)

{

zone_hi[zone_count] = temp_hi[i];

zone_lo[zone_count] = temp_lo[i];

zone_hits[zone_count] = temp_hits[i];

zone_turn[zone_count] = temp_turn[i];

zone_start[zone_count] = temp_start[i];

zone_strength[zone_count] = temp_strength[i];

if (zone_hi[zone_count] < Fechar[4])

zone_type[zone_count] = ZONE_SUPPORT;

else if (zone_lo[zone_count] > Fechar[4])

zone_type[zone_count] = ZONE_RESIST;

senão

{

para (j=5; j<1000; j++)

{

if (iClose(NULL, TimeFrame, j) < zone_lo[zone_count])

{

zone_type[zone_count] = ZONE_RESIST;

pausa;

}

else if (iClose(NULL, TimeFrame, j) > zone_hi[zone_count])

{

zone_type[zone_count] = ZONE_SUPPORT;

pausa;

}

}


se (j == 1000)

zone_type[zone_count] = ZONE_SUPPORT;

}


zone_count++;

}

}

}


void DrawZones()

{

if(SetGlobals==true)

{

GlobalVariableSet("SSSR_Count_"+Symbol()+TimeFrame, zone_count);

GlobalVariableSet("SSSR_Updated_"+Symbol()+TimeFrame, TimeCurrent());

}


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

{

if (zone_strength[i] == ZONE_WEAK && zone_show_weak == false)

Prosseguir;


string s = "SSSR#"+i+" Força=";

if (zone_strength[i] == ZONE_PROVEN)

s = s + "Comprovado, Contagem de Teste=" + zone_hits[i];

senão se (zone_strength[i] == ZONE_VERIFIED)

s = s + "Verificado, Contagem de Teste=" + zone_hits[i];

senão se (zone_strength[i] == ZONE_UNTESTED)

s = s + "Não testado";

senão se (zone_strength[i] == ZONE_TURNCOAT)

s = s + "Casaco";

senão

s = s + "fraco";


ObjectCreate(s, OBJ_RECTANGLE , 0, 0, 0, 0, 0);

ObjectSet(s, OBJPROP_TIME1, iTime(NULL, TimeFrame, zone_start[i]));

ObjectSet(s, OBJPROP_TIME2, TimeCurrent());

ObjectSet(s, OBJPROP_PRICE1, zone_hi[i]);

ObjectSet(s, OBJPROP_PRICE2, zone_lo[i]);

ObjectSet(s, OBJPROP_BACK, zone_solid);

ObjectSet(s, OBJPROP_WIDTH, zone_linewidth);

ObjectSet(s, OBJPROP_STYLE, zone_style);


if (zone_type[i] == ZONE_SUPPORT)

{

// zona de suporte

if (zone_strength[i] == ZONE_TURNCOAT)

ObjectSet(s, OBJPROP_COLOR, color_support_turncoat);

senão se (zone_strength[i] == ZONE_PROVEN)

ObjectSet(s, OBJPROP_COLOR, color_support_proven);

senão se (zone_strength[i] == ZONE_VERIFIED)

ObjectSet(s, OBJPROP_COLOR, color_support_verified);

senão se (zone_strength[i] == ZONE_UNTESTED)

ObjectSet(s, OBJPROP_COLOR, color_support_untested);

senão

ObjectSet(s, OBJPROP_COLOR, color_support_weak);

}

senão

{

// zona de resistência

if (zone_strength[i] == ZONE_TURNCOAT)

ObjectSet(s, OBJPROP_COLOR, color_resist_turncoat);

senão se (zone_strength[i] == ZONE_PROVEN)

ObjectSet(s, OBJPROP_COLOR, color_resist_proven);

senão se (zone_strength[i] == ZONE_VERIFIED)

ObjectSet(s, OBJPROP_COLOR, color_resist_verified);

senão se (zone_strength[i] == ZONE_UNTESTED)

ObjectSet(s, OBJPROP_COLOR, color_resist_untested);

senão

ObjectSet(s, OBJPROP_COLOR, color_resist_weak);

}




if(SetGlobals==true)

{

GlobalVariableSet("SSSR_HI_"+Symbol()+TimeFrame+i, zone_hi[i]);

GlobalVariableSet("SSSR_LO_"+Symbol()+TimeFrame+i, zone_lo[i]);

GlobalVariableSet("SSSR_HITS_"+Symbol()+TimeFrame+i, zone_hits[i]);

GlobalVariableSet("SSSR_STRENGTH_"+Symbol()+TimeFrame+i, zone_strength[i]);

GlobalVariableSet("SSSR_AGE_"+Symbol()+TimeFrame+i, zone_start[i]);

}

}

}


bool Fractal(int M, int P, int shift)

{

if (TimeFrame > P)

P = prazo;

P = P / TimeFrame*2 + MathCeil(P / TimeFrame / 2);

if(shift<p)

retorna falso);


if (shift > iBars(Symbol(), TimeFrame)-P)

retorna falso);

for (int i=1; i<=P; i++)

{

se (M == UP_POINT)

{

if (iHigh(NULL, TimeFrame, shift+i) > iHigh(NULL, TimeFrame, shift))

retorna falso);

if (iHigh(NULL, TimeFrame, shift-i) >= iHigh(NULL, TimeFrame, shift))

retorna falso);

}

se (M == DN_POINT)

{

if (iLow(NULL, TimeFrame, shift+i) < iLow(NULL, TimeFrame, shift))

retorna falso);

if (iLow(NULL, TimeFrame, shift-i) <= iLow(NULL, TimeFrame, shift))

retorna falso);

}

}

retorno(verdadeiro);

}


void FastFractals()

{

int-shift;

int limite = MathMin(Bars-1, BackLimit);

int P = TimeFrame * fractal_fast_factor;


FastUpPts[0] = 0,0; FastUpPts[1] = 0,0;

FastDnPts[0] = 0,0; FastDnPts[1] = 0,0;


for (shift=limit; shift>1; shift--)

{

if (Fractal(UP_POINT, P, shift) == true)

FastUpPts[shift] = iHigh(NULL, TimeFrame, shift);

senão

FastUpPts[shift] = 0,0;


if (Fractal(DN_POINT, P, deslocamento) == verdadeiro)

FastDnPts[shift] = iLow(NULL, TimeFrame, shift);

senão

FastDnPts[shift] = 0,0;

}

}


void SlowFractals()

{

int-shift;

int limit = MathMin(iBars(Symbol(), TimeFrame) - 1, BackLimit);

int P = TimeFrame * fractal_slow_factor;


SlowUpPts[0] = 0,0; SlowUpPts[1] = 0,0;

SlowDnPts[0] = 0,0; SlowDnPts[1] = 0,0;


for (shift=limit; shift>1; shift--)

{

if (Fractal(UP_POINT, P, shift) == true)

SlowUpPts[shift] = iHigh(NULL, TimeFrame, shift);

senão

SlowUpPts[shift] = 0,0;


if (Fractal(DN_POINT, P, deslocamento) == verdadeiro)

SlowDnPts[shift] = iLow(NULL, TimeFrame, shift);

senão

SlowDnPts[shift] = 0,0;

}

}


bool NewBar()

{

estático datetime LastTime = 0;

if (iTime(NULL, TimeFrame, 0) != Última Hora)

{

LastTime = iTime(NULL, TimeFrame, 0)+time_offset;

retorno(verdadeiro);

}

senão

retorna falso);

}


void ExcluirZonas()

{

int = 5;

int;


while (i < ObjectsTotal())

{

string objName = ObjectName(i);

if (StringSubstr(objName, 0, len) != "SSSR#")

{

i++;

Prosseguir;

}

ObjectDelete(objName);

}

}


string TimeFrameToString(int tf) // código do TRO

{

string tfs;


interruptor (tf)

{

caso PERIOD_M1:

tfs="M1" ;

pausa;

caso PERIOD_M5:

tfs="M5" ;

pausa;

caso PERIOD_M15:

tfs="M15" ;

pausa;

caso PERIOD_M30:

tfs="M30" ;

pausa;

caso PERIOD_H1:

tfs="H1" ;

pausa;

caso PERIOD_H4:

tfs="H4" ;

pausa;

caso PERIOD_D1:

tfs="D1" ;

pausa;

caso PERIOD_W1:

tfs="W1" ;

pausa;

caso PERIOD_MN1:

tfs="MN";

}


return(tf);

}


string StringRepeat(string str, int n = 1)

{

string outstr = "";

for(int i = 0; i < n; i++) outstr = outstr + str;

return(outstr);

}


string StringRightPad(string str, int n=1, string str2=" ")

{

return(str + StringRepeat(str2,n-StringLen(str)));


 

Mudança para MT5. Ajude-me com uma palavra. Como em MT5 está escrito em código, o que está errado?

//+------------------------------------------------------------------+
//|                                                          123.mq5 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   1
//+----------------------------------------------+
//|  Параметры отрисовки индикатора 1            |
//+----------------------------------------------+
#property indicator_type1   DRAW_ARROW
#property indicator_color1  Blue
#property indicator_style1  STYLE_DASHDOTDOT
#property indicator_width1  0
#property indicator_label1  "Label 1"
//----
input int MAPeriod=13;
//---=
int handle_ma;
double ExtLineBuffer[];
double BufferPrice[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   SetIndexBuffer(0,ExtLineBuffer,INDICATOR_DATA);
   SetIndexBuffer(3,BufferPrice,INDICATOR_CALCULATIONS);
//---- символы для индикатора
   PlotIndexSetInteger(0,PLOT_ARROW,108);
//---- создание метки для отображения в DataWindow
   PlotIndexSetString(0,PLOT_LABEL,"PROBA");
//----
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   IndicatorSetString(INDICATOR_SHORTNAME," 123");
//---- массива будет производиться как в таймсериях
   ArraySetAsSeries(ExtLineBuffer,true);
   ArraySetAsSeries(BufferPrice,true);
//--- create MA's handles
   ResetLastError();
      handle_ma=iMA(NULL,Period(),MAPeriod,0,MODE_SMA,PRICE_CLOSE); 
   if(handle_ma==INVALID_HANDLE)
     {
      Print("The iMA (1) object was not created: Error ",GetLastError());
      return INIT_FAILED;
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 | 
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
 {
 Comment("");
 }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
//--- Проверка количества доступных баров
   if(rates_total<4) return 0;
//--- Проверка и расчёт количества просчитываемых баров
   int limit=rates_total-prev_calculated;
   if(limit>1)
     {
      limit=rates_total-1;
   ArrayInitialize(ExtLineBuffer,EMPTY_VALUE);
   ArrayInitialize(BufferPrice,0);
     }
//--- Подготовка данных
   int count=(limit>1 ? rates_total : 2),copied=0;
   copied=CopyBuffer(handle_ma,0,0,count,BufferPrice);
   if(copied!=count) return 0;
//----   
 for(int i=limit; i>0 && !IsStopped(); i--)
   {
//----------------------------------------- ОСНОВНОЙ МОДУЛЬ КОТОРЫЙ НЕ РАБОТАЕТ ----------------------------
 if(PERIOD_H1==Period())
  {
//--- High signal
 if(BufferPrice[i]>open[i] && BufferPrice[i]<close[i])   
   ExtLineBuffer[i]=high[i];
//--- Low signal
 if(BufferPrice[i]<open[i] && BufferPrice[i]>close[i])
   ExtLineBuffer[i]=low[i];
  } /*
  else
  {
  ExtLineBuffer[i]=0.0;
  ExtLineBuffer[i]=0.0;
  } */
  }    
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

PERGUNTA: Por que todo tipo de lixo está caindo no buffer?

Estou no estágio de construtor de Lego, ou seja, copio o módulo e tento entender as peculiaridades do MT5 pela experiência. Documentação, é claro.

 
kopeyka2:

Mudança para MT5. Ajude-me com uma palavra. Como o MT5 escreve no código, o que está errado?

PERGUNTA: Por que todo tipo de lixo está caindo dentro do buffer?

no mt5 a série Timeseries vai ao contrário
se você precisar dela da mesma forma que no mt4, ou seja,ArraySetAsSeries

 
kopeyka2:

Mudança para MT5. Ajude-me com uma palavra. Como o MT5 escreve em código, o que está errado?

PERGUNTA: Por que todo tipo de lixo está caindo no buffer?

Estou no estágio de construtor Lego, ou seja, copio o módulo e entendo as peculiaridades da MT% pela experiência. Documentação, é claro.

//+------------------------------------------------------------------+
//|                                                          123.mq5 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   1
//+----------------------------------------------+
//|  Параметры отрисовки индикатора 1            |
//+----------------------------------------------+
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrBlue
#property indicator_width1  1
#property indicator_label1  "Label 1"
//----
input int MAPeriod=13;
//---=
int handle_ma;
double ExtLineBuffer[];
double BufferPrice[];
//---
int    period;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   period=(MAPeriod<1 ? 1 : MAPeriod);
//---
   SetIndexBuffer(0,ExtLineBuffer,INDICATOR_DATA);
   SetIndexBuffer(1,BufferPrice,INDICATOR_CALCULATIONS);
//---- символы для индикатора
   PlotIndexSetInteger(0,PLOT_ARROW,108);
//---- создание метки для отображения в DataWindow
   PlotIndexSetString(0,PLOT_LABEL,"PROBA");
//----
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   IndicatorSetString(INDICATOR_SHORTNAME," 123");
//---- массива будет производиться как в таймсериях
   ArraySetAsSeries(ExtLineBuffer,true);
   ArraySetAsSeries(BufferPrice,true);
//--- create MA's handles
   ResetLastError();
   handle_ma=iMA(NULL,PERIOD_CURRENT,period,0,MODE_SMA,PRICE_CLOSE);
   if(handle_ma==INVALID_HANDLE)
     {
      Print("The iMA (",(string)period,") object was not created: Error ",GetLastError());
      return INIT_FAILED;
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 | 
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   Comment("");
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//--- 
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true); 
//--- Проверка количества доступных баров
   if(rates_total<4) return 0;
//--- Проверка и расчёт количества просчитываемых баров
   int limit=rates_total-prev_calculated;
   if(limit>1)
     {
      limit=rates_total-1;
      ArrayInitialize(ExtLineBuffer,EMPTY_VALUE);
      ArrayInitialize(BufferPrice,0);
     }
//--- Подготовка данных
   int count=(limit>1 ? rates_total : 2),copied=0;
   copied=CopyBuffer(handle_ma,0,0,count,BufferPrice);
   if(copied!=count) return 0;
//----   
   for(int i=limit; i>=0 && !IsStopped(); i--)
     {
      //----------------------------------------- ОСНОВНОЙ МОДУЛЬ КОТОРЫЙ НЕ РАБОТАЕТ ----------------------------
      if(Period()==PERIOD_H1)
        {
         //--- High signal
         if(BufferPrice[i]>open[i] && BufferPrice[i]<close[i])
            ExtLineBuffer[i]=high[i];
         //--- Low signal
         if(BufferPrice[i]<open[i] && BufferPrice[i]>close[i])
            ExtLineBuffer[i]=low[i];
        }
/*
  else
  {
  ExtLineBuffer[i]=0.0;
  ExtLineBuffer[i]=0.0;
  } */
     }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
Artyom Trishkin:

Obrigado pela resposta.

Verificado em MT5... Que bagunça... Os pontos estão espalhados por todo o gráfico de uma forma estranha, em algum lugar profundo da história... Eu não entendo o que e por que a MT5 não gosta? O problema é simples!!!

TOME EM MT4

.ISTO É O QUE PARECE NO MT4


E TÃO EM MT5. É claro que em um buffer. Mas o problema é que o indicador está capturando pontos, mas não aqueles e não aqueles ali...(((


Por favor, diga-me novamente. O que eu fiz de errado no código MT5????

Eu tenho algo no MT5. Mas tampões ... um mistério

 
kopeyka2:

Obrigado pela resposta.

Verificado em MT5... Que bagunça... Os pontos estão espalhados por todo o gráfico de uma forma estranha, em algum lugar profundo da história... Eu não entendo o que e por que a MT5 não gosta? O problema é simples!!!

TOME EM MT4

.


E ASSIM EM MT5 . É claro que em um buffer. Mas o problema é que o indicador está capturando pontos, mas não aqueles e não aqueles ali...(((


Por favor, diga-me novamente. O que eu fiz de errado no código MT5????

Eu tenho algo no MT5. Mas tampões ... um mistério

Não há nenhum mistério. A numeração é diferente do mql4 e os amortecedores indicadores não são zerados automaticamente. Para limpar o "lixo", o programador deve cuidar da limpeza dos índices para que eles não contenham valores.

 
Alexey Viktorov:

Nenhum mistério. A numeração é diferente do mql4 e os amortecedores indicadores não são zerados automaticamente. Para limpar o "lixo", o programador deve cuidar da pureza dos índices se não quiser que eles contenham valores.

A questão é: por que as marcas (pontos) são colocadas em qualquer lugar? Eu defini no código o algoritmo!!!! A condição de MA no corpo da vela. Isto não é suficiente?

 
kopeyka2:

A questão é: por que as marcas (pontos) são colocadas em qualquer lugar? Eu defini no código o algoritmo!!!! A condição de MA no corpo da vela. Isto não é suficiente?

Veja aqui.

kopeyka2:
Mudança para MT5. Ajude-me com uma palavra.


Artem deu o código completo ao invés da palavra ajuda. Cada um tem a sua própria abordagem. Eu tento não dar código pronto, mas ainda falho algumas vezes.

kopeyka2:

Obrigado pela resposta.

Verificado em MT5... É um pouco confuso...


Mas os gráficos para comparação são tempos completamente diferentes. Como se pode julgar se os pontos estão certos ou errados???

Daí uma palavra de ajuda.

Fórum sobre comércio, sistemas automatizados de comércio e testes estratégicos

Qualquer pergunta, ajuda e discussão sobre algoritmos e códigos para iniciantes da MQL4

Alexey Viktorov, 2019.01.21 11:04

Nenhum mistério. A numeração é diferente do mql4 e os amortecedores indicadores não são zerados automaticamente. Para limpar o "lixo", o próprio programador deve cuidar da limpeza dos índices se eles não devem conter valores.

Ajuda: Na MT5 eles fizeram uma seqüência inadequada de execuções OnInit e OnDeinit, portanto pode haver problemas também. Mas é em alguns casos especiais, e o recálculo do indicador deve SEMPRE ser consecutivo. Desde que pré-cálculo == 0, recalcule em todas as barras e em cada iteração do laço, se não houver valor no buffer, preencha este índice da matriz com o valor EMPTY_VALUE ou 0 dependendo da configuração PLOT_EMPTY_VALUE
 
Alexey Viktorov:

Aqui está um olhar.

Artyom deu o código completo em vez de ajudar com a palavra. Cada um tem uma abordagem diferente para isto. Eu tento não dar código pronto, mas ainda assim às vezes falha.

Mas os gráficos para comparação são tempos completamente diferentes. Como se pode julgar se os pontos estão certos ou errados?

Daí uma palavra de ajuda.

Mais ajuda em palavras: em MT5 eles fizeram uma seqüência inadequada de execuções OnInit e OnDeinit, portanto pode haver problemas também. Mas é em alguns casos especiais, e o recálculo do indicador deve SEMPRE ser consecutivo. Desde que pré-cálculo == 0, o recálculo deve ser feito para todas as barras e a cada iteração do laço, se não houver nenhum valor no buffer, então preencha este índice de array com o valor EMPTY_VALUE ou 0 dependendo da configuração PLOT_EMPTY_VALUE

Aleluia!!!!! Alterado aberto[i] e fechado[i] para iOpen(NULL,PERÍODO_H1,i)



 
kopeyka2:

Aleluia!!!!! Alterado aberto[i] e fechado[i] para iOpen(NULL,PERÍODO_H1,i)



Qual é a diferença? Se o indicador estiver em H1, está apenas na velocidade de acesso - você tem um mais lento. No meu exemplo, você deve ter perdido o fato de ter que definir a indexação em série para matrizes abertas e fechadas. Destaquei o que você não tinha. Você tem um loop do começo ao fim - do limite ao 0, e não indexou arrays - por isso foi puxado para trás e para frente.

Razão: