Ayuda a la codificación - página 320

 

Hola a todos,

Hace tiempo que no estaba por aquí...

Estoy trabajando en una idea de EA, necesito añadir un indicador pero no sé cómo incluirlo en el EA, ¿me podéis ayudar por favor?

El indicador es Slope Directional Line, quiero que funcione en el gráfico diario y que active las órdenes en el gráfico TF inferior, el código del indicador es:

//+------------------------------------------------------------------+

//| slope directional line D.L.M.mq4 |||||||||||||||

//| DANIEL LUCHINGER 2014 ||||||||||||||||||||

//+------------------------------------------------------------------+

#property ventana_del_gráfico

#property indicator_buffers 2

#property indicator_color1 Blue

#property indicator_width1 3

#property indicator_color2 Rojo

#property indicator_width2 3

//---- parámetros de entrada

extern int period=14;

extern int method=3; // MODE_SMA

extern int price=0; // PRICE_CLOSE

//---- buffers

double Uptrend[];

double Dntrend[];

double ExtMapBuffer[];

//+------------------------------------------------------------------+

//| Función de inicialización de los indicadores personalizados

//+------------------------------------------------------------------+

int init()

{

IndicatorBuffers(3);

SetIndexBuffer(0, Uptrend);

SetIndexBuffer(1, Dntrend);

SetIndexBuffer(2, ExtMapBuffer);

ArraySetAsSeries(ExtMapBuffer, true);

SetIndexStyle(0,DRAW_LINE,STYLE_SOLID,3);

SetIndexStyle(1,DRAW_LINE,STYLE_SOLID,3);

IndicatorShortName("Línea de dirección de la pendiente");

return(0);

}

//+------------------------------------------------------------------+

//| Función de desinicialización del indicador personalizada |.

//+------------------------------------------------------------------+

int deinit(){return(0);}

double WMA(int x, int p)

{

return(iMA(NULL, 0, p, 0, método, precio, x));

}

//+------------------------------------------------------------------+

//| Función de iteración del indicador personalizada ||.

//+------------------------------------------------------------------+

int inicio()

{

int counted_bars = IndicatorCounted();

if(counted_bars < 0)

return(-1);

int x = 0;

int p = MathSqrt(period);

int e = Bars - counted_bars + period + 1;

double vect[], trend[];

if(e > Bars)

e = Bars;

ArrayResize(vect, e);

ArraySetAsSeries(vect, true);

ArrayResize(trend, e);

ArraySetAsSeries(trend, true);

for(x = 0; x < e; x++)

{

vect[x] = 2*WMA(x, period/2) - WMA(x, period);

}

for(x = 0; x < e-period; x++)

ExtMapBuffer[x] = iMAOnArray(vect, 0, p, 0, method, x);

for(x = e-period; x >= 0; x--)

{

trend[x] = trend[x+1];

if (ExtMapBuffer[x]> ExtMapBuffer[x+1]) trend[x] =1;

si (ExtMapBuffer[x]< ExtMapBuffer[x+1]) trend[x] =-1;

si (trend[x]>0)

{ Uptrend[x] = ExtMapBuffer[x];

si (trend[x+1]<0) Uptrend[x+1]=ExtMapBuffer[x+1];

Dntrend[x] = EMPTY_VALUE;

}

si no

si (tendencia[x]<0)

{

Dntrend[x] = ExtMapBuffer[x];

if (trend[x+1]>0) Dntrend[x+1]=ExtMapBuffer[x+1];

Uptrend[x] = EMPTY_VALUE;

}

}

return(0);

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

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

He codificado de la siguiente manera

double UpTrend = iCustom(NULL,1440, "slope directional line D.L.M",20,3,0,1); // donde 0 = UptrendBuffer

double DnTrend = iCustom(NULL,1440, "slope directional line D.L.M",20,3,1,1); // donde 1 = DntrendBuffer

double _sl = 0,_tp = 0;

{

if(haMode == 0 | haMode == 1)

{

if(UpTrend)

{label("Condición LONG OK");

if(Close[0] >= srDown && Close[0] < srUp)

//si(StopLoss > 0) _sl = Ask - StopLoss;

_sl = srDownHT-StopLossShift;

if(TakeProfit > 0) _tp = Ask + TakeProfit;

if(tt && orders<MaxTrades)

{

openOrder(getLots(),MagicNumber,OP_BUY, _sl,_tp);

}

}}

}

}

Alguien puede corregirme porque estoy seguro de que esto no funciona

Gracias

Daniel1983

 

Muchas gracias Mistertools por tu ayuda.

Pero ...

Lo que quiero hacer es aplicar una media móvil a la #_FullSSA_normalize correct mtf nmc.

Esto funciona sin problema cuando lo hago en el M5 de forma normal con la ayuda de la MA de MT4.

Es lo único que uso de MT4 ....

En la M1 a veces funciona, otras veces no. Puede que tenga que ver algo con la configuración.

Sólo mira la imagen, el SSA está bien, pero no la MA ...

He tratado de hacerlo yo mismo, pero es demasiado complicado para mí, aunque sólo tengo dos errores, después de 'mi trabajo' ..

Debe haber sido la suerte, pero, sin embargo, la SSA trabajó sin problemas, pero el MA no se ve en ninguna parte.

Por supuesto, la SSA es una élite ....

que compré hace algún tiempo y vale la pena ...

Archivos adjuntos:
ssa.png  72 kb
 
daniel1983:
Hola,

Hace tiempo que no estaba por aquí...

Estoy trabajando en una idea de EA, necesito añadir un indicador pero no sé cómo incluirlo en el EA, ¿pueden ayudarme por favor?

El indicador es Slope Directional Line, quiero que funcione en el gráfico diario y que active las órdenes en el gráfico TF inferior, el código del indicador es:

//+------------------------------------------------------------------+

//| slope directional line D.L.M.mq4 |||||||||||||||

//| DANIEL LUCHINGER 2014 ||||||||||||||||||||

//+------------------------------------------------------------------+

#property ventana_del_gráfico

#property indicator_buffers 2

#property indicator_color1 Blue

#property indicator_width1 3

#property indicator_color2 Rojo

#property indicator_width2 3

//---- parámetros de entrada

extern int period=14;

extern int method=3; // MODE_SMA

extern int price=0; // PRICE_CLOSE

//---- buffers

double Uptrend[];

double Dntrend[];

double ExtMapBuffer[];

//+------------------------------------------------------------------+

//| Función de inicialización de los indicadores personalizados

//+------------------------------------------------------------------+

int init()

{

IndicatorBuffers(3);

SetIndexBuffer(0, Uptrend);

SetIndexBuffer(1, Dntrend);

SetIndexBuffer(2, ExtMapBuffer);

ArraySetAsSeries(ExtMapBuffer, true);

SetIndexStyle(0,DRAW_LINE,STYLE_SOLID,3);

SetIndexStyle(1,DRAW_LINE,STYLE_SOLID,3);

IndicatorShortName("Línea de dirección de la pendiente");

return(0);

}

//+------------------------------------------------------------------+

//| Función de desinicialización del indicador personalizada |.

//+------------------------------------------------------------------+

int deinit(){return(0);}

double WMA(int x, int p)

{

return(iMA(NULL, 0, p, 0, método, precio, x));

}

//+------------------------------------------------------------------+

//| Función de iteración del indicador personalizada ||.

//+------------------------------------------------------------------+

int inicio()

{

int counted_bars = IndicatorCounted();

if(counted_bars < 0)

return(-1);

int x = 0;

int p = MathSqrt(period);

int e = Bars - counted_bars + period + 1;

double vect[], trend[];

if(e > Bars)

e = Bars;

ArrayResize(vect, e);

ArraySetAsSeries(vect, true);

ArrayResize(trend, e);

ArraySetAsSeries(trend, true);

for(x = 0; x < e; x++)

{

vect[x] = 2*WMA(x, period/2) - WMA(x, period);

}

for(x = 0; x < e-period; x++)

ExtMapBuffer[x] = iMAOnArray(vect, 0, p, 0, method, x);

for(x = e-period; x >= 0; x--)

{

trend[x] = trend[x+1];

if (ExtMapBuffer[x]> ExtMapBuffer[x+1]) trend[x] =1;

si (ExtMapBuffer[x]< ExtMapBuffer[x+1]) trend[x] =-1;

si (trend[x]>0)

{ Uptrend[x] = ExtMapBuffer[x];

si (trend[x+1]<0) Uptrend[x+1]=ExtMapBuffer[x+1];

Dntrend[x] = EMPTY_VALUE;

}

si no

si (tendencia[x]<0)

{

Dntrend[x] = ExtMapBuffer[x];

if (trend[x+1]>0) Dntrend[x+1]=ExtMapBuffer[x+1];

Uptrend[x] = EMPTY_VALUE;

}

}

return(0);

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

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

He codificado de la siguiente manera

double UpTrend = iCustom(NULL,1440, "slope directional line D.L.M",20,3,0,1); // donde 0 = UptrendBuffer

double DnTrend = iCustom(NULL,1440, "slope directional line D.L.M",20,3,1,1); // donde 1 = DntrendBuffer

double _sl = 0,_tp = 0;

{

if(haMode == 0 | haMode == 1)

{

if(UpTrend)

{label("Condición LONG OK");

if(Close[0] >= srDown && Close[0] < srUp)

//si(StopLoss > 0) _sl = Ask - StopLoss;

_sl = srDownHT-StopLossShift;

if(TakeProfit > 0) _tp = Ask + TakeProfit;

if(tt && orders<MaxTrades)

{

openOrder(getLots(),MagicNumber,OP_BUY, _sl,_tp);

}

}}

}

}

Alguien puede corregirme porque estoy seguro de que esto no funciona

Gracias

Daniel1983

Eso no funciona simplemente porque la línea direccional de pendiente es un indicador de repintado. Tome cualquier promedio normal de Hull ("slope directional line" es un promedio de Hull) y todo será más fácil

 

Gracias Mladen, aprecio su tiempo..

He encontrado a través de los puestos de HMA, uno que ha creado con el control de la velocidad,

Me gustaría probarlo en el EA, la misma idea que quería con el indicador direccional de la pendiente,

pero con este indicador HMA que publicaste "Hull Moving Averages 2.0 &SR lines"

¿cómo sería el código de esto para que funcione en mi EA?

He escrito:

input int IndicatorTF = 1440 //(indicador en Daily TimeFrame)

input int HMAPeriod = 35; //(me permite cambiar estos parámetros)

input ENUM_HMAPrice = PRICE_CLOSE; //(me permite cambiar estos parámetros)

input int HMASpeed = 2.0; //(permítame cambiar estos parámetros)

double trendUp = iCustom(Symbol(),IndicatorTF, "Hull moving average 2.0 & sr lines",HMAPeriod,ENUM_HMAPrice,HMASpeed,0,0);

double trendDn = iCustom(Symbol(),IndicatorTF, "Hull moving average 2.0 & sr lines",HMAPeriod,ENUM_HMAPrice,HMASpeed,1,0);

if(trendUp > 0)

{

Abrir Comprar

}

El código del indicador es:

//+------------------------------------------------------------------+

//| Promedio móvil de Hull |||

//| mladen |

//+------------------------------------------------------------------+

#property copyright"www.forex-tsd.com"

#property link "www.forex-tsd.com"

#property indicator_chart_window

#propiedad indicator_buffers 3

#property indicator_color1 LimeGreen

#property indicator_color2 PaleVioletRed

#property indicator_color3 PaleVioletRed

#propiedad indicator_width1 2

#Propiedad indicator_width2 2

#propiedad indicador_ancho3 2

//

//

//

//

//

extern string TimeFrame = "Marco temporal actual";

extern int HMAPeriod = 35;

extern int HMAPrice = PRICE_CLOSE;

extern double HMASpeed = 2.0

extern bool LinesVisible = false

extern int LinesNumber = 5;

extern color ColorUp = LimeGreen;

extern color ColorDown = PaleVioletRed;

extern string UniqueID = "HullLines1";

extern bool alertsOn = false

extern bool alertsOnCurrent = true;

extern bool alertsMessage = true

extern bool alertsSound = false

extern bool alertsEmail = false;

//

//

//

//

//

double hma[];

double hmada[];

doble hmadb[];

double work[];

double trend[];

int HalfPeriod;

int HullPeriod;

string indicatorFileName;

bool returnBars;

bool calculateValue;

int timeFrame;

//------------------------------------------------------------------

//

//------------------------------------------------------------------

//

//

//

//

//

int init()

{

IndicatorBuffers(5);

SetIndexBuffer(0,hma);

SetIndexBuffer(1,hmada);

SetIndexBuffer(2,hmadb);

SetIndexBuffer(3,trend);

SetIndexBuffer(4,work);

//

//

//

//

//

HMAPeriod = MathMax(2,HMAPeriod);

HalfPeriod = MathFloor(HMAPeriod/HMASpeed);

HullPeriod = MathFloor(MathSqrt(HMAPeriod));

indicatorFileName = WindowExpertName();

calculateValue = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }

returnBars = TimeFrame=="returnBars"; if (returnBars) { return(0); }

timeFrame = stringToTimeFrame(TimeFrame);

//

//

//

//

//

IndicatorShortName(timeFrameToString(timeFrame)+" HMA ("+HMAPeriod+")";

return(0);

}

void deinit()

{

deleteLines();

}

void deleteLines()

{

int lookForLength = StringLen(UniqueID);

for (int i= ObjectsTotal()-1; i>=0; i--)

{

string name = ObjectName(i);

if (StringSubstr(name,0,lookForLength)==UniqueID) ObjectDelete(name);

}

}

//------------------------------------------------------------------

//

//------------------------------------------------------------------

//

//

//

//

//

int inicio()

{

int,counted_bars = IndicadorContado();

if(counted_bars<0) return(-1);

if(counted_bars>0) counted_bars--;

int limit=MathMin(Bares-contados_barras,Bares-1);

if (returnBars) { hma[0] = MathMin(limit+1,Bars-1); return(0); }

//

//

//

//

//

if (calculateValue || timeFrame == Period())

{

if (trend[limit] == -1) CleanPoint(limit,hmada,hmadb);

for(i=limit; i>=0; i--) work = 2.0*iMA(NULL,0,HalfPeriod,0,MODE_LWMA,HMAPrice,i)-iMA(NULL,0,HMAPeriod,0,MODE_LWMA,HMAPrice,i);

for(i=limit; i>=0; i--)

{

hma = iMAOnArray(trabajo,0,HullPeriod,0,MODE_LWMA,i);

hmada = EMPTY_VALUE;

hmadb = EMPTY_VALUE;

trend = trend;

si (hma > hma) trend = 1;

si (hma < hma) trend = -1;

si (trend == -1) PlotPoint(i,hmada,hmadb,hma);

}

deleteLines();

si (LinesVisible)

{

int k = 0;

for (i=0; i<Bars && k<LinesNumber; i++)

si (¡tendencia!=tendencia)

{

string name = UniqueID+(string)Time;

ObjectCreate(name,OBJ_TREND,0,Time,hma,Time+Period()*60,hma);

si (tendencia==1)

ObjectSet(name,OBJPROP_COLOR,ColorUp);

else ObjectSet(name,OBJPROP_COLOR,ColorDown);

k++;

}

}

manageAlerts();

return(0);

}

//

//

//

//

//

limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName, "returnBars",0,0)*timeFrame/Period()));

if (trend[limit]==-1) CleanPoint(limit,hmada,hmadb);

for (i=limit; i>=0; i--)

{

int y = iBarShift(NULL,timeFrame,Time);

trend = iCustom(NULL,timeFrame,indicatorFileName, "calculateValue",HMAPeriod,HMAPrice,HMASpeed,LinesVisible,LinesNumber,ColorUp,ColorDown,UniqueID,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,3,y);

hma = iCustom(NULL,timeFrame,indicatorFileName, "calculateValue",HMAPeriod,HMAPrice,HMASpeed,LinesVisible,LinesNumber,ColorUp,ColorDown,UniqueID,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,0,y);

hmada = EMPTY_VALUE;

hmadb = EMPTY_VALUE;

}

for (i=limit;i>=0;i--) if (trend==-1) PlotPoint(i,hmada,hmadb,hma);

return(0);

}

//+-------------------------------------------------------------------

//|

//+-------------------------------------------------------------------

//

//

//

//

//

void manageAlerts()

{

si (alertsOn)

{

if (alertsOnCurrent)

int whichBar = 0

si no whichBar = 1;

if (trend[whichBar] != trend[whichBar+1])

{

if (trend[whichBar] == 1) doAlert(whichBar, "up");

si (trend[whichBar] == -1) doAlert(whichBar, "down");

}

}

}

//

//

//

//

//

void doAlert(int forBar, string doWhat)

{

static string previousAlert="nada";

static datetime previousTime;

mensaje de cadena;

if (previousAlert != doWhat || previousTime != Time[forBar]) {

previousAlert = doWhat;

previousTime = Time[forBar];

//

//

//

//

//

message = Symbol()+" "+timeFrameToString(Period())+" en "+TimeToStr(TimeLocal(),TIME_SECONDS)+" La tendencia del HMA cambió a "+doWhat;

if (alertsMessage) Alert(message);

if (alertsEmail) SendMail(Symbol()+" HMA ",mensaje);

if (alertsSound) PlaySound("alert2.wav");

}

}

//-------------------------------------------------------------------

//

//-------------------------------------------------------------------

//

//

//

//

//

void CleanPoint(int,double& first[],double& second[])

{

if ((second != EMPTY_VALUE) && (second != EMPTY_VALUE))

second = EMPTY_VALUE;

si no

if ((first != EMPTY_VALUE) && (first != EMPTY_VALUE) && (first == EMPTY_VALUE))

first = EMPTY_VALUE;

}

//

//

//

//

//

void PlotPoint(int,double& first[],double& second[],double& from[])

{

if (first == EMPTY_VALUE)

{

if (first == EMPTY_VALUE) {

first = from;

first = from;

segundo = EMPTY_VALUE;

}

else {

second = from;

second = from;

first = EMPTY_VALUE;

}

}

else

{

first = from;

segundo = EMPTY_VALUE;

}

}

//-------------------------------------------------------------------

//

//-------------------------------------------------------------------

//

//

//

//

//

string sTfTable[] = {"M1", "M5", "M15", "M30", "H1", "H4", "D1", "W1", "MN"};

int iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

//

//

//

//

//

int stringToTimeFrame(string tfs)

{

tfs = stringUpperCase(tfs);

for (int i=ArraySize(iTfTable)-1; i>=0; i--)

if (tfs==sTfTable || tfs==""+iTfTable) return(MathMax(iTfTable,Period());

return(Periodo());

}

string timeFrameToString(int tf)

{

for (int i=ArraySize(iTfTable)-1; i>=0; i--)

if (tf==iTfTable) return(sTfTable);

return("");

}

//

//

//

//

//

stringUpperCase(string str)

{

string s = str;

for (int length=StringLen(str)-1; length>=0; length--)

{

int tchar = StringGetChar(s, longitud);

if((tchar > 96 && tchar 223 && tchar < 256))

s = StringSetChar(s, length, tchar - 32);

else if(tchar > -33 && tchar < 0)

s = StringSetChar(s, length, tchar + 224);

}

return(s);

}

 
mladen:
No es un problema de que otro indicador interfiera (a menos que estés usando varias instancias de ese mismo indicador en el mismo gráfico). En ese caso puede ocurrir ya que ese indicador no está escrito para ser utilizado como indicador de múltiples instancias en el mismo gráfico

Hola MLaden , muchas gracias pero no es un caso en el que esté usando más de una instancia en un gráfico, solo una. solo las líneas se están desplazando.

si no es obvio no te preocupes lo mantendré como está, gracias por tu aporte! que tengas un buen día...

zigflip

 
zigflip:
Hola MLaden , muchas gracias pero no es un caso en el que esté usando más de una instancia en un gráfico, solo una. solo las líneas se están desplazando .

si no es obvio no te preocupes lo mantendré como está, ¡gracias por tu aportación! que tengas un buen día...

zigflip

He probado el que he posteado y no se desplazan

Pruébalo, tal vez te ayude

 

¿Cómo puedo llamar a un indicador HMA en un EA?

double (NULL,0, "HMA",??????)

Y las condiciones son

if(trendUp) entonces comprar, o if(trendUp =1) entonces comprar o algo así?

gracias

 
daniel1983:
¿Cómo puedo llamar a un indicador HMA en un EA?

double (NULL,0, "HMA",??????)

Y las condiciones son

if(trendUp) entonces comprar, o if(trendUp =1) entonces comprar o algo así?

gracias

Depende de los parámetros de los indicadores, pero tienes que usar iCustom() para eso

Mucha más información con bastantes ejemplos puedes encontrar aquí : https://www.mql5.com/en/forum/173108

 
mladen:
Depende de los parámetros de los indicadores, pero tienes que usar iCustom() para eso Mucha más información con bastantes ejemplos puedes encontrar aquí : https://www.mql5.com/en/forum/173108

Gracias por guiarme, todavía estoy confundido, encontré un indicador HMA similar al código de la línea de pendiente, es "HMA_Russian_Color", pero todavía tengo problemas con las condiciones, para filtrar la tendencia de compra de la tendencia de venta.

escribí

double Uptrend = iCustom(Symbol(),0, "HMA_Russian_Color",20,3,0,0); // donde último 0 = UptrendBuffer

double Dntrend = iCustom(Symbol(),0, "HMA_Russian_Color",20,3,0,1); // donde último 1 = DntrendBuffer

//periodo = 20 / tipo = 3 / precio = 0 ¿es correcto?

if(Uptrend) //¿Cómo escribo esto?

{

Abrir Comprar

}

Órdenes de compra todavía abierto mientras HMA tendencia a la baja o el color rojo ...

Por favor corrígeme, y o ayúdame a arreglar esto...

Gracias

 
daniel1983:
Gracias por guiarme, aun estoy confundido, encontre un indicador HMA similar al codigo de la linea de pendiente, es "HMA_Russian_Color", pero aun tengo problemas con las condiciones, para filtrar la tendencia de compra de la tendencia de venta.

i escribió

double Uptrend = iCustom(Symbol(),0, "HMA_Russian_Color",20,3,0,0); // donde último 0 = UptrendBuffer

double Dntrend = iCustom(Symbol(),0, "HMA_Russian_Color",20,3,0,1); // donde último 1 = DntrendBuffer

//periodo = 20 / tipo = 3 / precio = 0 ¿es correcto?

if(Uptrend) //¿Cómo escribo esto?

{

Abrir Comprar

}

Órdenes de compra todavía abierto mientras HMA tendencia a la baja o el color rojo ...

Por favor corrígeme, y o ayúdame a arreglar esto...

Gracias

Para el cambio de pendiente intente algo como esto :

double current = iCustom(Symbol(),0,"HMA_Russian_Color",20,3,0,0);

double previous1 = iCustom(Symbol(),0,"HMA_Russian_Color",20,3,0,1);

double previous2 = iCustom(Symbol(),0,"HMA_Russian_Color",20,3,0,2);

if (current>previous1 && previous1<previous2)

{

// slope changed to up

}

if (currentprevious2)

{

// slope changed to down

}

Razón de la queja: