asesor experto - preguntas varias - página 21

 
Marco vd Heijden:

O puedes iniciar un contador una vez que se ha detectado el arrastre hay muchas maneras de hacerlo.,

( Yo sólo " tengo "una manera por ahora para hacerlo para mí - de esa manera en su último comentario )
Sr. Marco me ha salvado el día, muchas gracias hombre.

No por ahora, pero voy a tratar más tarde que quiero añadir adicionalmente algunas funciones a este ' SL y TP ' funciones. Solo necesito investigar muchas cosas sobre eso antes de empezar a escribir el script para eso.

¡Todo lo mejor para ti hombre!

 

Si recuerdo bien - He visto hace mucho tiempo un "modificador de orden" de trabajo de EA como este: que no era actualizaciones mientras se arrastra, cuando "Arrastre OFF" línea de arrastre, después de arrastrar y luego " Stop Loss y Take Profit " valores podrían cambiar sólo una vez.
Así que tres y más veces leer su último comentario y también trató de cambiar un poco un poco más que podía dejar de actualizaciones, mientras que el arrastre.

P: ¿Entonces no es posible, por favor?

Gracias de antemano.

 

Bueno, mientras la bandera booleana drag == 1 se puede utilizar esta misma bandera para desactivar las actualizaciones.

Como dije también puedes iniciar un contador aquí hay un ejemplo de eso:

//+------------------------------------------------------------------+
//|                                                  Drag Hline2.mq4 |
//|      Copyright 2017, Marco vd Heijden, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, Marco vd Heijden, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

double price;
bool drag;
int cnt=0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create timer
   EventSetTimer(1);
   ObjectCreate(0,"line",OBJ_HLINE,0,0,Ask);
   price=ObjectGetDouble(0,"line",OBJPROP_PRICE,0);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---
   if(price!=ObjectGetDouble(0,"line",OBJPROP_PRICE,0))
     {
      drag=1;
     }

   if(drag==1)
     {
      cnt++;       // increase counter
        {
         if(cnt>=2)// if counter == 2 seconds
           {
            price=ObjectGetDouble(0,"line",OBJPROP_PRICE,0); // store new value
            Print(" New price: ",DoubleToString(price));
            PlaySound("ok.wav");
            cnt=0;  // reset counter
            drag=0; // reset drag
           }
        }
     }
  }
//+------------------------------------------------------------------+

O simplemente usar un bucle while este funciona muy bien:

//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---
   while(price!=ObjectGetDouble(0,"line",OBJPROP_PRICE,0))
    {
     PlaySound("ok.wav");
     price=ObjectGetDouble(0,"line",OBJPROP_PRICE,0);
     Comment(price);
    }
  }
//+------------------------------------------------------------------+
Solo dice mientras (estoy arrastrando) actualiza el precio hasta que ambos sean iguales (cuando deje de arrastrar)
 
Marco vd Heijden:

Bueno, mientras la bandera booleana arrastre == 1 podrías usar esta misma bandera para deshabilitar las actualizaciones.
Como dije también puedes iniciar un contador aquí hay un ejemplo de eso:
O simplemente usar un bucle while este funciona muy bien:
Solo dice mientras (estoy arrastrando) actualiza el precio hasta que ambos sean iguales (cuando deje de arrastrar)

( y sus códigos )

¡Que ejemplos tan brillantes hombre?! Realmente es un comentario muy muy útil, muchas gracias. Y ahora estoy tratando de añadir más cosas para esas líneas ( diseños y funciones ).
( Por favor, no me culpen por mi esta pregunta: Tengo " graphics() " que lo estoy usando para objetos gráficos, y lo estoy llamando a través de Init() y necesito llamarlo a través de OnTimer(), así que mi pregunta es: ¿Estoy haciendo mal, por favor? )

¡Todo lo mejor para ti!

 

Puedes encontrarte con el error 4200 que dice que ha fallado la creación del objeto porque ya existe.

Así que tienes que ver si el objeto existe antes de intentar (re)-crearlo o modificarlo.

Puede utilizar:

   if(ObjectFind(0,"Long")<0)
     {
      //Object does not exist

     }
  
and/or

   if(ObjectFind(0,"Long")>=0)
     {
      // Object already exists
    
     }
 
Marco vd Heijden:

Puedes usarla:

Hmm, esto es realmente nuevo Función para mí.
Podría intentar después de investigar sobre eso. ( Lo he visto muchas veces pero nunca lo he usado para mí. )

Muchas gracias.

 

#Convertir el precio en píxeles - Abrir

Utilizo " HLine " para la función Take Profit.
Tengo algunos objetos ( Label, RecLabel... y así sucesivamente ) y me gustaría que los objetos pudieran moverse con el objeto " HLine ". Así que he encontrado la siguiente función. Pero no me gustaría convertir "X". Quiero convertir sólo el precio en Y.
Nunca he intentado nada con el código de abajo.
P:
Porque quiero estar seguro de que podría ayudarme con este problema.
( si sé que me puede ayudar entonces empezaré a probarlo para mi preocupación ).
P:¿Y hay algún método para que algunos objetos puedan moverse con "HLine"?

// this is just example for that what I am thinking
datetime time = 0; // I just want to ignore this because I just want to give to X = 20; fixed mode ( should not change ever )
double price = ObjectGetDouble( 0, "line", OBJPROP_PRICE, 0 );

int x,y;

ChartTimePriceToXY( long chart_id, int sub_window, datetime time, double price, int& x, int& y );

Gracias de antemano.

 

Tendrás que ser un poco más específico, puedes hacer muchas cosas de muchas maneras.

Estas funciones se utilizan en la función OnChartEvent().

ChartPriceToXY - le dará la conversión del precio en tiempo a coordenadas, ¿es esto realmente lo que necesita?

¿Quizás te refieres a ChartXYToTimePrice() ?

https://www.mql5.com/en/docs/chart_operations/chartxytotimeprice

Si no necesitas el valor, puedes pasarlo como un cero, ver el ejemplo de abajo.

//+------------------------------------------------------------------+
//|                                                    CrossHair.mq4 |
//|      Copyright 2017, Marco vd Heijden, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, Marco vd Heijden, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create some lines
   ObjectCreate(0,"X",OBJ_HLINE,0,0,Ask);          // X = Horizontal Axis (time==0)
   ObjectCreate(0,"Y",OBJ_VLINE,0,TimeCurrent(),0);// Y = Vertical Axis (price==0)      
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- clean up  
   ObjectsDeleteAll(0,0,EMPTY);  
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
  
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//--- If this is an event of a mouse click on the chart
   if(id==CHARTEVENT_CLICK)
     {
      //--- Prepare variables
      int      x     =(int)lparam;
      int      y     =(int)dparam;
      datetime time  =0;
      double   price =0;
      int      window=0;
      //--- Convert the X and Y coordinates in terms of date/time
      if(ChartXYToTimePrice(0,x,y,window,time,price))
        {
         ObjectMove(0,"X",0,0,price); // notice time==0 because horizontal axis
         ObjectMove(0,"Y",0,time,0);  // notice price==0 because vertical axis
        }
      else
         Print("ChartXYToTimePrice return error code: ",GetLastError());
      Print("+--------------------------------------------------------------+");
     }
  }  
//+------------------------------------------------------------------+



Documentation on MQL5: Chart Operations / ChartXYToTimePrice
Documentation on MQL5: Chart Operations / ChartXYToTimePrice
  • www.mql5.com
Chart Operations / ChartXYToTimePrice - Reference on algorithmic/automated trading language for MetaTrader 5
 

Ya leí esa documentación pero no lo tenía claro hasta tu último comentario. En realidad, pero no he probado todavía, porque lucho por debajo de código, ya he intentado algunas maneras de buenos resultados, pero no puedo.
Sr. Marco
gracias por su último gran comentario que es siento que puedo utilizar a mis objetos se mueve cuestión.

Realmente pasé mucho tiempo para encontrar la solución a mi preocupación, no puedo obtener buenos resultados.
Pero de todos modos puedo conseguir ( actualmente la apertura de posiciones ) Tome los precios de beneficio que es lo que quiero a " hline " objetos podrían llamar a los precios de Take Profit a sí mismo, y es el trabajo. Y es sólo funciona tiempos iniciales. Sí, lo sé porque está en "Init()". Pero he intentado ponerlo en " OnTimer() " pero no funciona correctamente.

Por favor, déjenme saber algo que me ayude a averiguar lo que podría aprender, y hacer para mi este problema.
Empezaré a investigar de nuevo sobre este tema después de 7 horas.
Si recibo un buen comentario será mejor para mí.

// init()------------------------------------------------------------

for ( i = OrdersTotal() - 1; i >= 0; i-- )
{
    if  ( ! OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) ) continue;
    if  ( OrderSymbol() == Symbol() ) tpprice = OrderTakeProfit();

    ObjectCreate    (
                        "#" + IntegerToString( OrderTicket() ) + " -" + "tphline", // name
                        OBJ_HLINE,
                        0,      // subwindow
                        0,      // time
                        tpprice // price1
                    );
    tpprice =
    ObjectGetDouble (
                        0,
                        "#" + IntegerToString( OrderTicket() ) + " -" + "tphline", // name
                        OBJPROP_PRICE, 0
                    );

}
// ontimer() --------------------------------------------------------

if  ( tpprice != ObjectGetDouble( 0, "#" + IntegerToString( OrderTicket() ) + " -" + "tphline", OBJPROP_PRICE, 0 ) )
{
    tpdrag = 1;
}

if  ( tpdrag == 1 )
{
    tpprice = ObjectGetDouble( 0, "#" + IntegerToString( OrderTicket() ) + " -" + "tphline", OBJPROP_PRICE, 0 );
    Print( "tpdrag: ", tpdrag, " - Price: ", DoubleToString( tpprice, Digits ) );

    // actually here is a graphical objects functin()
    // here one of them
    // also which one soon I will try to  below objects could moves together " tphline " - but I can't take a time to research about your latest comment and so...
    ObjectCreate( "recl object", OBJ_RECTANGLE, 0, 0, tpprice ); // I feel I could add something to " string name " - I already tried few things not good results

    tpdrag = 0;
}

//---
return;

Gracias de antemano.
Todo lo mejor para ti.

 

Por favor, utiliza el estilizador que está en la pestaña de Herramientas.

No tengo ni idea de lo que estás tratando de lograr así que tengo que adivinar lo que quieres hacer esto nunca es bueno.

Pero puedes ver el ejemplo aquí:

//+------------------------------------------------------------------+
//|                                                    Stealth 4.mq4 |
//|      Copyright 2017, Marco vd Heijden, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, Marco vd Heijden, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

static input int takeprofit=500;// Take Profit
static input int stoploss=500;  // Stop Loss

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create timer
   EventSetTimer(1);

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
   for(int order=OrdersTotal(); order>=0; order--)
     {
      bool selected=OrderSelect(order,SELECT_BY_POS);
        {
         if(selected==1)
           {
            if(Symbol()==OrderSymbol()) // only for current chart symbol
              {
               switch(OrderType())
                 {
                  case OP_BUY: // for buy order
                    {
                     // if objects not found - create them
                     if(ObjectFind(0,"#"+IntegerToString(OrderTicket())+"-TP")<0)
                       {
                        ObjectCreate(0,"#"+IntegerToString(OrderTicket())+"-TP",OBJ_HLINE,0,0,OrderOpenPrice()+takeprofit*Point());
                        ObjectSet("#"+IntegerToString(OrderTicket())+"-TP",7,3);
                       }
                     if(ObjectFind(0,"#"+IntegerToString(OrderTicket())+"-SL")<0)
                       {
                        ObjectCreate(0,"#"+IntegerToString(OrderTicket())+"-SL",OBJ_HLINE,0,0,OrderOpenPrice()-stoploss*Point());
                        ObjectSet("#"+IntegerToString(OrderTicket())+"-SL",7,3);
                       }
                     // if objects exist
                     if(ObjectFind(0,"#"+IntegerToString(OrderTicket())+"-TP")>=0)
                       {
                        if(Bid>ObjectGetDouble(0,"#"+IntegerToString(OrderTicket())+"-TP",OBJPROP_PRICE,0))
                          {
                           bool close=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,clrBlue);
                             {
                              if(close==0)
                                {
                                 Alert(" Order Close Error! # "+IntegerToString(OrderTicket()));
                                }
                              if(close==1)
                                {
                                 Alert(" Order: "+IntegerToString(OrderTicket())+" Closed due to TP Profit = "+DoubleToString(OrderProfit(),2));
                                 ObjectDelete(0,"#"+IntegerToString(OrderTicket())+"-TP");
                                 ObjectDelete(0,"#"+IntegerToString(OrderTicket())+"-SL");
                                }
                             }
                          }
                       }
                     if(ObjectFind(0,"#"+IntegerToString(OrderTicket())+"-SL")>=0)
                       {
                        if(Ask<ObjectGetDouble(0,"#"+IntegerToString(OrderTicket())+"-SL",OBJPROP_PRICE,0))
                          {
                           bool close=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,clrBlue);
                             {
                              if(close==0)
                                {
                                 Alert(" Order Close Error! # "+IntegerToString(OrderTicket()));
                                }
                              if(close==1)
                                {
                                 Alert(" Order: "+IntegerToString(OrderTicket())+" Closed due to SL Profit = "+DoubleToString(OrderProfit(),2));
                                 ObjectDelete(0,"#"+IntegerToString(OrderTicket())+"-TP");
                                 ObjectDelete(0,"#"+IntegerToString(OrderTicket())+"-SL");
                                }
                             }
                          }
                       }
                    }
                  break;

                  case OP_SELL: // for sell order
                    {
                     // if objects not found - create them
                     if(ObjectFind(0,"#"+IntegerToString(OrderTicket())+"-TP")<0)
                       {
                        ObjectCreate(0,"#"+IntegerToString(OrderTicket())+"-TP",OBJ_HLINE,0,0,OrderOpenPrice()-takeprofit*Point());
                        ObjectSet("#"+IntegerToString(OrderTicket())+"-TP",7,3);
                       }
                     if(ObjectFind(0,"#"+IntegerToString(OrderTicket())+"-SL")<0)
                       {
                        ObjectCreate(0,"#"+IntegerToString(OrderTicket())+"-SL",OBJ_HLINE,0,0,OrderOpenPrice()+stoploss*Point());
                        ObjectSet("#"+IntegerToString(OrderTicket())+"-SL",7,3);
                       }
                     // if objects exist
                     if(ObjectFind(0,"#"+IntegerToString(OrderTicket())+"-TP")>=0)
                       {
                        if(Ask<ObjectGetDouble(0,"#"+IntegerToString(OrderTicket())+"-TP",OBJPROP_PRICE,0))
                          {
                           bool close=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,clrBlue);
                             {
                              if(close==0)
                                {
                                 Alert(" Order Close Error! # "+IntegerToString(OrderTicket()));
                                }
                              if(close==1)
                                {
                                 Alert(" Order: "+IntegerToString(OrderTicket())+" Closed due to TP Profit = "+DoubleToString(OrderProfit(),2));
                                 ObjectDelete(0,"#"+IntegerToString(OrderTicket())+"-TP");
                                 ObjectDelete(0,"#"+IntegerToString(OrderTicket())+"-SL");
                                }
                             }
                          }
                       }
                     if(ObjectFind(0,"#"+IntegerToString(OrderTicket())+"-SL")>=0)
                       {
                        if(Bid>ObjectGetDouble(0,"#"+IntegerToString(OrderTicket())+"-SL",OBJPROP_PRICE,0))
                          {
                           bool close=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,clrBlue);
                             {
                              if(close==0)
                                {
                                 Alert(" Order Close Error! # "+IntegerToString(OrderTicket()));
                                }
                              if(close==1)
                                {
                                 Alert(" Order: "+IntegerToString(OrderTicket())+" Closed due to SL Profit = "+DoubleToString(OrderProfit(),2));
                                 ObjectDelete(0,"#"+IntegerToString(OrderTicket())+"-TP");
                                 ObjectDelete(0,"#"+IntegerToString(OrderTicket())+"-SL");
                                }
                             }
                          }
                       }
                    }
                  break;
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+


Así puedes ver que puedes usar ObjectGetDouble directamente, no hay necesidad de copiar el valor a otro double porque el propio objeto mantiene el valor, y cuando arrastras la línea ese valor cambia automáticamente, y se verá la próxima vez que lo leas.

Razón de la queja: