Cualquier pregunta de novato, para no saturar el foro. Profesionales, no pasen de largo. En ninguna parte sin ti - 6. - página 539

 
tatianati:

Gracias. Funcionó, fui feliz como un niño, pero el asesor dejó de mostrar "lo nuevo". ¿Puede decirme en qué me he equivocado?

Huh, encontré el error, no donde estaba buscando originalmente. No puedo hacer frente a la siguiente tarea por mí mismo.

Por favor, indique cómo establecer el rango de desviación - distancia del precio de la MA.

extern string s10                = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>";
extern string s11                = ">>> Вход против МА";
extern int    iMA_Period         = 365;
extern int    iMA_OpenDistance   = 60;     // как задать диапазон? например 60-85 за его пределами не открывать ордеров

Esta es la parte de la entrada

int GetSignal()
{
  int Signal = 0;

  double iMA_Signal = iMA(Symbol(), 0, iMA_Period, 0, MODE_SMMA, PRICE_CLOSE, 0);
  
  int Ma_Bid_Diff = MathAbs(iMA_Signal - Bid)/vPoint;
  
  if(Ma_Bid_Diff > iMA_OpenDistance && Bid > iMA_Signal) Signal = -1;
  if(Ma_Bid_Diff > iMA_OpenDistance && Bid < iMA_Signal) Signal = 1;
  
  return(Signal);
}
 
tatianati:

Huh, encontrado el error, no donde yo estaba buscando originalmente. No puedo encargarme de la siguiente tarea por mí mismo.

Me puede decir cómo establecer el rango de desviación - distancia del precio de la MA.

Aquí está la parte de la entrada


extern int    Min_iMA_OpenDistance   = 60;
extern int    Max_iMA_OpenDistance   = 85;

Y en consecuencia la condición

if(Ma_Bid_Diff > Min_iMA_OpenDistance && Ma_Bid_Diff < Max_iMA_OpenDistance && Bid > iMA_Signal)
 

Tenemos que cambiar los datos brutos en el asesor correctamente a (1 compra, -1 venta)

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

//| SimpleBars_rob.mq4 ||
//| Copyright © 2010, Equipo ENSED |
//| http://www.ensed.org |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, ENSED Team"
#enlace de propiedad "http://www.ensed.org"

extern int SL = 50; // valor de stop loss (en pips)
TP = 150; // Valor de Take Profit (en puntos)
extern double Lotes = 0.1; // lote de trabajo (micro lotes - 0.01, mini lotes - 0.1, lotes normales - 1.0)
extern string Orden_Comentario = "robot"; // comentario que se aplicará a los pedidos
extern int Slipage = 5; // nivel máximo de deslizamiento permitido (en puntos)
extern int int Número_mágico = 777; // número mágico de pedidos para el robot (para distinguir los tratos "amistosos")
extern bool Reproducir_Sonido = false; // reproducción del sonido en la apertura: true - permitido, false - prohibido

//--------------------------------------------------------------------------------------------------------------------+
//+ configuración de los plazos y parámetros del indicador SimpleBars |
extern int period = 6;
extern bool useClose = true;
extern int anchura = 3;
//+ ajuste de los plazos y parámetros del indicador SimpleBars |
//--------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//+ trailing stop |
extern bool UseTrailing = true; // activación/desactivación del trailing stop
extern int TrailingStop = 50; // tamaño fijo del trailing stop (en pips)
extern int TrailingStep = 1; // paso del trailing stop (en puntos)
//+ trailing stop
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| la función se ejecuta en la inicialización del programa |
void init() {
if(GlobalVariableCheck("this_bar "+Symbol()+Period())
GlobalVariableDel("esta_barra "+Símbolo()+Periodo());
volver;
}
//| función, que se ejecuta durante la inicialización del programa |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| La función se ejecuta al desinicializar el programa.
void deinit() {
if(GlobalVariableCheck("this_bar "+Symbol()+Period())
GlobalVariableDel("esta_barra "+Símbolo()+Periodo());
volver;
}
//| función, que se ejecuta en la desinicialización del programa ||
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| función de búsqueda de una señal de comercio |
int fsignals() {
double signal = iCustom(NULL, 0, "SimpleBars", period, 0, 1, 4, 0);
return(0); // señal para abrir una compra
return(1); //abrir señal de venta
return(-1); // no hay señal
} //fin int fsignals()
//| función de búsqueda de una señal comercial
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| función de seguimiento del trabajo del robot en la barra dada
bool esta_barra() {
si(
(!GlobalVariableCheck("this_bar "+Symbol()+Period()))
|| (GlobalVariableGet("this_bar "+Symbol()+Period()!=Time[0])
) {
GlobalVariableSet("esta_barra "+Símbolo()+Periodo(),Tiempo[0]);
return(false);
} si no {
return(true);
} //fin if (. (!GlobalVariableCheck("this_bar "+Symbol()+Period()))
} //end bool this_bar()
//| función de seguimiento del hecho del trabajo del robot en la barra dada
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| función de búsqueda de pedidos de este tipo |
bool find_orders(int magic=-1, int type=-1, string symb="NULL") {
/* devuelve true si al menos un pedido del tipo dado con el número mágico dado es encontrado por el símbolo dado */
for (int i=TotalPedidos()-1; i>=0; i--) {
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) break;
if(((OrderType()==tipo) || (tipo==-1))
&& ((OrderMagicNumber()==magic) | (magic==-1))
&& ((OrderSymbol()==Symbol() || (symb=="NONE")))) {
//si se encuentra un pedido, return(true) y se sale del bucle
return(true);
romper;
} //end if((OrderType()==type) && (OrderMagicNumber()==magic) && (OrderSymbol()==Symbol())
} //end for (int i2=OrdersTotal()-1; i2>=0; i2--)

return(false); //devolver false
} //end bool find_orders(int magic, int type)
//| función de búsqueda de pedidos del tipo dado |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| función de cálculo del valor de Stop Loss para las órdenes |
double sl(int sl_value, int type, double price=0.0, string symb="NONE", int rmode=1) {
//tipo=0 -> compras en el mercado
//tipo=1 -> ventas del mercado
if(symb=="NONE") symb=Símbolo();
if(type==0) price=NormalizeDouble(MarketInfo(symb,MODE_ASK),MarketInfo(symb,MODE_DIGITS))
if(type==1) price=NormalizeDouble(MarketInfo(symb,MODE_BID),MarketInfo(symb,MODE_DIGITS));
if(sl_value<=0) return(0);
if(rmode==1) {
if((type==0) || (type==2) | (type==4)) return(MarketInfo(symb,MODE_ASK)-sl_value*MarketInfo(symb,MODE_POINT)); //para compras
if((type==1) || (type==3) | (type==5)) return(MarketInfo(symb,MODE_BID)+sl_value*MarketInfo(symb,MODE_POINT)); //para ventas
}
if(rmode==2) {
if((type==0) || (type==2) | (type==4)) return(MarketInfo(symb,MODE_BID)-sl_value*MarketInfo(symb,MODE_POINT)); //para comprar
if((type==1) || (type==3) | (type==5)) return(MarketInfo(symb,MODE_ASK)+sl_value*MarketInfo(symb,MODE_POINT)); //para vender
}
} //end double sl(int sl_value, int type, double price=0.0, string symb="NONE", int rmode=1)
//| función para el cálculo del valor de Stop Loss para las órdenes ||
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| función para calcular los valores de Take Profit para las órdenes
double tp(int tp_value, int type, double price=0.0, string symb="NONE") {
//tipo=0 -> compra de mercado
//tipo=1 -> ventas del mercado
if(symb=="NONE") symb=Símbolo();
if(type==0) price=NormalizeDouble(MarketInfo(symb,MODE_ASK),MarketInfo(symb,MODE_DIGITS);
if(type==1) price=NormalizeDouble(MarketInfo(symb,MODE_BID),MarketInfo(symb,MODE_DIGITS));
if(tp_value<=0) return(0);
if((type==0) || (type==2) | (type==4)) return(price+tp_value*MarketInfo(symb,MODE_POINT)); //para compras
if((type==1) || (type==3) | (type==5)) return(MarketInfo(symb,MODE_BID)-tp_value*MarketInfo(symb,MODE_POINT)); //para ventas
} //end double tp(int tp_value, int type, double price=0.0, string symb="NONE")
//| función para el cálculo del valor de Take Profit para las órdenes ||
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| función de apertura de pedidos
void abrir_posiciones(int señal, double lote, double precio=0,0, string simb="NONE") {
/señal=0 -> señal de apertura de compra
//señal=1 -> señal de apertura de venta
/* externo */ int Count_Of_Trade_Try=5, Pause_Of_Trade_Try=5;

int i = 0; //variable para el contador del bucle
int err = 0;

if(symb=="NONE") symb=Símbolo();
si(señal==0)
price=NormalizeDouble(MarketInfo(symb,MODE_ASK),MarketInfo(symb,MODE_DIGITS)); //precio de apertura para la compra
si(señal==1)
price=NormalizeDouble(MarketInfo(symb,MODE_BID),MarketInfo(symb,MODE_DIGITS)); //precio de venta

while(i<=Count_Of_Trade_Try) {
La //función de apertura de la orden (incorporada). Para facilitar la percepción, los parámetros se colocan en líneas diferentes:
int ticket = OrderSend(Symbol(), //símbolo
señal, /tipo de orden
lote, //volumen
precio, //precio abierto
Deslizamiento, //nivel de recotización permitido
sl(SL,signal), // valor del Stop Loss
tp(TP,señal), //tomar valor de beneficio
Order_Comment, /comentario de pedido
Magic_Number, //número mágico
0, //tiempo de expiración (usado para órdenes pendientes)
CLR_NONE); //color de la flecha mostrada en el gráfico (CLR_NONE - la flecha no se dibuja)
if(ticket!=-1) //si la apertura fue exitosa, dibuja un objeto gráfico y sale del bucle
romper;
err=GetLastError();
if(err!=0) Print("Error: "+Market_Err_To_Str(err));
i++;
Sleep(Pause_Of_Trade_Try*1000); //en caso de error, pausa antes de reintentar
} //fin while(i<=count)
} //end void open_positions(int signal, double lot, double price=0.0, string symb="NONE")
//| función de apertura de órdenes |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------+
//| función de decodificación de códigos de error |
string Mercado_Err_To_Str(int err) {
/* la función sólo cubre los códigos de error de las operaciones comerciales */
switch(err) {
case(0): return("No hay error");
case(1): return("No hay error, pero el resultado es desconocido");
case(2): return("Error general");
case(3): return("Parámetros incorrectos");
case(4): return("El servidor comercial está ocupado");
case(5): return("Versión antigua del terminal cliente");
case(6): return("No hay conexión con el servidor comercial");
case(7): return("No hay suficientes derechos");
case(8): return("Solicitudes demasiado frecuentes");
case(9): return("Operación no válida que interrumpe el funcionamiento del servidor");
case(64): return("Cuenta bloqueada");
case(65): return("Número de cuenta incorrecto");
case(128): return("El plazo de la transacción ha expirado");
case(129): return("Precio incorrecto");
case(130): return("Paradas incorrectas");
case(131): return("Volumen incorrecto");
case(132): return("El mercado está cerrado");
case(133): return("Comercio prohibido");
case(134): return("No hay suficiente dinero para ejecutar la transacción");
case(135): return("El precio ha cambiado");
case(136): return("Sin precio");
case(137): return("El corredor está ocupado");
case(138): return("Nuevos precios");
case(139): return("El pedido está bloqueado y ya se está procesando");
case(140): return("Sólo se permite comprar");
case(141): return("Demasiadas solicitudes");
case(145): return("No se permite la modificación, porque la orden está demasiado cerca del mercado");
case(146): return("El subsistema de comercio está ocupado");
case(147): return("El uso de la fecha de caducidad está prohibido por el corredor");
case(148): return("El número de órdenes abiertas y pendientes ha alcanzado el límite establecido por el broker;)
case(149): return("Intento de abrir una posición opuesta a una posición existente si la cobertura está prohibida");
case(150): return("Intento de cerrar una posición en un símbolo contraviniendo la regla FIFO");

por defecto: return("");
} //end switch(err)
} //fin string Err_To_Str(int err)
//| función para decodificar los códigos de error |
//+-------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------+
//| Operaciones de cierre de transacciones |||
//+----------------------------------------------------------------------------------------------------+
//| función de cerrar una orden por su número (ticket) |


bool close_by_ticket(int c_ticket, int slipage) {
/*
función de cerrar una operación por su número (ticket).
Al cerrar una orden de mercado, se tiene en cuenta el nivel de deslizamiento máximo permitido (slipage)
*/
/* externo */ int Count_Of_Trade_Try=5, Pause_Of_Trade_Try=5;

int i = 0; //variable para el contador del bucle
int err = 0;
bool ticket = false; //variable para el cierre (no) exitoso de una operación
double price = 0.0; //precio de la operación a cerrar (para órdenes de mercado)
if(OrderSelect(c_ticket,SELECT_BY_TICKET,MODE_TRADES)) { //selección de orden por billete
if(OrderType()==OP_BUY) precio = NormalizeDouble(Bid,Digits); //precio de compra
if(OrderType()==OP_SELL) precio = NormalizeDouble(Ask,Digits); //precio de venta
for(i=0;i<=Count_Of_Trade_Try;i++) {
if(OrderType()<=1) //si la orden es de mercado, cerrarla, si es una orden pendiente, eliminarla
ticket=OrderClose(OrderTicket(),OrderLots(),price,slipage,CLR_NONE);
si no
ticket=OrderDelete(OrderTicket());

if(ticket) { //si el cierre o el borrado fueron exitosos - devuelve true y sale del bucle
return(true);
romper;
} //fin if(ticket)
err=GetLastError();
if(err!=0) Print("Error: "+Market_Err_To_Str(err));
Sleep(Pause_Of_Trade_Try*1000); //en caso de error, pausa antes de reintentar
} //end for(i=0;i<=Count_Of_Trade_Try;i++)
} //end if(OrderSelect(c_ticket,SELECT_BY_TICKET,MODE_TRADES))

return(false); //devolver false
} //end bool close_by_ticket(int c_ticket)
//| función de cerrar una orden por su número (ticket) |
//+----------------------------------------------------------------------------------------------------+

bool cbm(int magic, int slipage, int type) {
/*
Cerrar por magia (cerrar todas las órdenes del tipo dado con el MagicNumber dado)
Se tiene en cuenta el deslizamiento máximo permitido
Se utiliza la función close_by_ticket.
*/
int n = 0;
while (find_orders(magic, type))
for (int i2=Total de pedidos()-1; i2>=0; i2--) {
if (!OrderSelect(i2,SELECT_BY_POS,MODE_TRADES)) break;

if ((OrderType()==type) && (OrderMagicNumber()==magic)) {
close_by_ticket(OrderTicket(), slip;)
n++;
} //end if (((OrderType()==OP_BUY) || (OrderType()==OP_SELL)) && (OrderMagicNumber()==magic))
} //end for (int i2=OrdersTotal()-1; i2>=0; i2--)

si(n>0)
return(true);

return(false);
} //end bool cbm(int magic, int slipage, int type)
//| Operaciones de cierre de operaciones |
//+-------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| trailing stop loss |
void T_SL() {
if(!UseTrailing) return;
int i = 0;
for(i=0; i<TotalPedidos(); i++) {
if(!(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if(OrderSymbol() != Symbol() || OrderMagicNumber()!=Magic_Number) continue;

if(OrderType()==OP_BUY) {
if(NormalizeDouble(Bid-OrderOpenPrice(),Digits)>NormalizeDouble(TrailingStop*Point,Digits)) {
if(NormalizeDouble(OrderStopLoss(),Digits)<NormalizeDouble(Bid-(TrailingStop+TrailingStep-1)*Point,Digits))
OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(Bid-TrailingStop*Point,Digits), OrderTakeProfit(), 0, CLR_NONE)
} //fin if(NormalizeDouble(Bid-OrderOpenPrice(),Digits)>NormalizeDouble(TrailingStop*Point,Digits))
} //fin if(OrderType()==OP_BUY)

if(OrderType()==OP_SELL) {
if(NormalizeDouble(OrderOpenPrice()-Ask,Digits)>NormalizeDouble(TrailingStop*Point,Digits)) {
if(NormalizeDouble(OrderStopLoss(),Digits)>NormalizeDouble(Ask+(TrailingStop+TrailingStep-1)*Point,Digits))
OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(Ask+TrailingStop*Point,Digits), OrderTakeProfit(), 0, CLR_NONE)
} //end if(NormalizeDouble(OrderOpenPrice()-Ask,Digits)>NormalizeDouble(TrailingStop*Point,Digits))
} //fin if(OrderType()==OP_SELL)
} //fin for(i=0; i<Total de pedidos(); i++)
} //fin void T_SL()
//| trailing stop loss |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| función principal |
void start() {

int sig = fsignals();

if(!find_orders(Magic_Number)) {
si((sig!=-1)) {
if(!this_bar()) {
open_positions(sig, Lots);
if(Reproducir_Sonido)
PlaySound("alert.wav");
}
} //fin if((sig!=-1) && (!this_bar())
} si no {
if(sig==0) {
if(cbm(Número_mágico, deslizamiento, 1)) {
open_positions(sig, Lots);
if(Reproducir_Sonido)
PlaySound("alert.wav");
} //fin if(cbm(Magic_Number, Slipage, 1))
} //fin if(sig==0)
if(sig==1) {
if(cbm(Número_mágico, deslizamiento, 0)) {
open_positions(sig, Lots);
if(Reproducir_Sonido)
PlaySound("alert.wav");
} //fin if(cbm(Magic_Number, Slipage, 0))
} //fin if(sig==1)
T_SL();
} //fin if(!find_orders(Magic_Number) (si no)
volver;
}
//| función principal |
//+-------------------------------------------------------------------------------------------------------------------+
 

Hola conocedores. Ayuda - no funciona. Creo que me confundí con la inicialización de variables . Mi cabeza da vueltas, pero no puedo encontrar ningún error.

En lugar de abrir posiciones, el EA debe dibujar flechas al precio Klose(0) y, en lugar de cerrar, cruzar e imprimir los datos ( fExpiration_func(Expiration), fop_time, cl_time, fop_price, cl_price, ftype) en una nueva línea.

Aquí el estocástico se toma sólo como ejemplo.

 //+------------------------------------------------------------------+
//|                                                     binar_v1.mq4 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link        "https://www.mql5.com"
#property version    "1.00"


//--- input Time parameters
input uchar     hs = 9 ; 
input uchar     ms = 0 ; 
input uchar     he = 18 ; 
input uchar     me = 0 ;
//--- input Indicator parameters

//--- input Expiration parameters
input uchar     Expiration = 2 ; //время експирации в минутах


input bool      strategy_1  =   true ;


bool poz;                                   //открытая/закрытая позиция
datetime op_time;                         //время открытия
double op_price;                           //цена открытия
char type;                                 //тип открытой позиции -1 СЕЛЛ, 1- БАИ
//+=================================================================================+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit ()
  {
//--- 
   
      
//---
   return ( INIT_SUCCEEDED );
  }
//+=================================================================================+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
//--- destroy timer
   
      
  }
//+=================================================================================+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick ()
  {
   //подщитаем арифметическое среднее OC за прошлую неделю
   //Пощет один раз в неделю    
     /* if(isNewBar("",PERIOD_W1)){      
         uchar iPr=iBarShift(NULL,PERIOD_M1,iTime(NULL,PERIOD_W1,1));
         uchar iPn=iBarShift(NULL,PERIOD_M1,iTime(NULL,PERIOD_W1,1))+10080;
         double avgM1=AvgOC(iPr,iPn,0);                                     // M1 OC цредняя за прошлую неделю               
      }*/
       if (!fisTradeTimeInt( 9 , 0 , 18 , 0 )) return ;                                 //Время торгов
       if (strategy_1== true )fStrategy1();
  }
//+=================================================================================+
//| Timer function                                                   |
//+------------------------------------------------------------------+

//+=================================================================================+
void fStrategy1
   (
   
   )
//--------------------   
{
   

   if (poz== true )                             //если есть открыта позиция
      fClose_Pos(op_time,op_price,type);       //закрываем
   if (poz== false ){                           //если нет открытой
      fOpen_buy(poz,op_time,op_price,type);   //покупка   
      fOpen_sell(poz,op_time,op_price,type);   //продажа
   }       
}
//+=================================================================================+
void fOpen_buy
   (
   bool & op,                                 //открытая/закрытая позиция
   datetime & out_op_time,                       //время открытия
   double & out_op_price,                         //цена открытия
   char & out_type                               //тип открытой позиции -1 СЕЛЛ, 1- БАИ
   )
//--------------------
{
   double stoch_M0_1 = iStochastic ( NULL , 0 , 5 , 3 , 3 , MODE_SMA , 0 , MODE_MAIN , 1 );
   double stoch_M0_2 = iStochastic ( NULL , 0 , 5 , 3 , 3 , MODE_SMA , 0 , MODE_MAIN , 2 );
   double stoch_M0_1s= iStochastic ( NULL , 0 , 5 , 3 , 3 , MODE_SMA , 0 , MODE_SIGNAL , 1 );
   double stoch_M0_2s= iStochastic ( NULL , 0 , 5 , 3 , 3 , MODE_SMA , 0 , MODE_SIGNAL , 2 );
   
   string arrowName;
   
   if (!op){      
       if (stoch_M0_1 < 20 && stoch_M0_2 < stoch_M0_2s && stoch_M0_1s < stoch_M0_1){
          out_type=- 1 ;
          op= true ;
          out_op_price= Close [ 0 ];
          out_op_time= Time [ 0 ];
          arrowName= "Buy" + TimeToStr ( TimeCurrent (), TIME_DATE | TIME_SECONDS );
          fDrawArrow(arrowName= "" ,out_op_price,out_op_time,Blue, 240 );               //стрелка открытой позиции
      }
          
   }     
}
//+=================================================================================+
void fOpen_sell
   (
   bool op,                                 //открытая/закрытая позиция
   datetime & out_op_time,                       //время открытия
   double & out_op_price,                         //цена открытия
   char & out_type                               //тип открытой позиции -1 СЕЛЛ, 1- БАИ
   )
//--------------------   
{      
   double stoch_M0_1 = iStochastic ( NULL , 0 , 5 , 3 , 3 , MODE_SMA , 0 , MODE_MAIN , 1 );
   double stoch_M0_2 = iStochastic ( NULL , 0 , 5 , 3 , 3 , MODE_SMA , 0 , MODE_MAIN , 2 );
   double stoch_M0_1s= iStochastic ( NULL , 0 , 5 , 3 , 3 , MODE_SMA , 0 , MODE_SIGNAL , 1 );
   double stoch_M0_2s= iStochastic ( NULL , 0 , 5 , 3 , 3 , MODE_SMA , 0 , MODE_SIGNAL , 2 );
   
   string arrowName;
   
   if (!op){      
       if (stoch_M0_1 > 80 && stoch_M0_2 > stoch_M0_2s && stoch_M0_1s > stoch_M0_1){
          out_type=- 1 ;
          op= true ;
          out_op_price= Close [ 0 ];
          out_op_time= Time [ 0 ];
          arrowName= "Sell" + TimeToStr ( TimeCurrent (), TIME_DATE | TIME_SECONDS );
          fDrawArrow(arrowName= "" ,out_op_price,out_op_time,Red, 240 );               //стрелка открытой позиции
      }
          
   }     
}
//+=================================================================================+
void fClose_Pos //jei yra atidaryta, uzdarom
   (
   datetime fop_time,                       //время открытия
   double fop_price,                       //цена открытия
   char ftype                               //тип открытой позиции -1 СЕЛЛ, 1- БАИ
   )
//-------------------   
{
   string arrowName= "Close" + TimeToStr ( TimeCurrent (), TIME_DATE | TIME_SECONDS );    
   double cl_price;
   string fileName= StringConcatenate ( "Strategy_1  " ,Expiration, " " , Period (), ".csv" );
   
   if (Expiration<= 5 ){                     //
       datetime cl_time= Expiration* 60 +op_time;                                         //время закрытия
       if ( TimeCurrent ()>=cl_time){
         
         cl_price= Close [ 0 ];               //цена закрытия         
         fDrawArrow(arrowName,cl_price,cl_time,Yellow, 251 );                             //наносим крестик на график
         fSaveToFile(fileName,Expiration, fop_time, cl_time, fop_price, cl_price, ftype);   //в новую строку сохроняем в файле
      }   
   }
   else {
      cl_time= fExpiration_func(Expiration)* 60 +op_time;                                 //время закрытия
      
       if ( TimeMinute ( TimeCurrent ())>= TimeMinute (cl_time)){
         
         cl_price= Close [ 0 ];      
         fDrawArrow(arrowName,cl_price,cl_time,Yellow, 251 );                             //наносим крестик на график
         fSaveToFile(fileName,fExpiration_func(Expiration), fop_time, cl_time, fop_price, cl_price, ftype); //в новую строку сохроняем в файле
     }
   }   
}
//+=================================================================================+
bool fisNewBar 
   (
   string f_sy,   
   int f_tf
   )
{
     int iIndex = - 1 ;
//----
     switch (f_tf)
    {
         case 1     : iIndex = 0 ; break ;
         case 5     : iIndex = 1 ; break ;
         case 15    : iIndex = 2 ; break ;
         case 30    : iIndex = 3 ; break ;
         case 60    : iIndex = 4 ; break ;
         case 240   : iIndex = 5 ; break ;
         case 1440 : iIndex = 6 ; break ;
         case 10080 : iIndex = 7 ; break ;
         default    : iIndex =- 1 ; break ;
    }
    
     static int LastBar[ 8 ]= { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }; 
     datetime curbar = iTime (f_sy, f_tf, 0 );
     if (LastBar[iIndex] != curbar)
    {
        LastBar[iIndex] = curbar;
         return ( true );
    }
     else
    { return ( false );
 }
 }
//+=================================================================================+
int fExpiration_func
   (
   uchar e
   )
//--------------------   
{  
   uchar ex= 0 ;
   uchar mod= 0 ;
   if (e< 6 ) 
      ex=e; //return(e);
   else {
      mod= fmod (e, 5 );
       if (mod== 4 ) 
         ex=e+mod; //return(e+mod);
       else
         if (mod < 4 ) 
            ex=e-mod; //return(e-mod);
    }     
   return (ex); //grazina laiko tarpa minutemis
}
//+=================================================================================+
bool fisTradeTimeInt     //время торгов
   (
   uchar hstart= 0 , 
   uchar mstart= 0 , 
   uchar hend= 0 , 
   uchar mend= 0
   ) 
//--------------------   
{
   datetime db, de;           
   uchar       hc;              

  db= StrToTime ( TimeToStr ( TimeCurrent (), TIME_DATE )+ " " +hstart+ ":" +mstart);
  de= StrToTime ( TimeToStr ( TimeCurrent (), TIME_DATE )+ " " +hend+ ":" +mend);
  hc= TimeHour ( TimeCurrent ());
   if (db>=de) {
     if (hc>=hend) de+= 24 * 60 * 60 ; 
     else db-= 24 * 60 * 60 ;
  }
   if ( TimeCurrent ()>=db && TimeCurrent ()<=de) return ( True );
   else return ( False );
}
//+=================================================================================+
void fDrawArrow //наносим стрелки на график
   (
   string arrowName= "" ,
   double dwPrice= 0 ,
   datetime dwTime= 0 ,
   color dwColor=Silver,
   uchar dwArrowIndex= 0
   )
//--------------------   
{
   ObjectCreate       ( 0 ,arrowName, OBJ_ARROW , 0 , 0 , 0 , 0 , 0 );                 // создадим стрелку
   ObjectSetInteger   ( 0 ,arrowName, OBJPROP_ARROWCODE ,dwArrowIndex);       // установим код стрелки
   ObjectSetInteger   ( 0 ,arrowName, OBJPROP_COLOR ,dwTime);                 // зададим время
   ObjectSetInteger   ( 0 ,arrowName, OBJPROP_COLOR ,dwColor);               // зададим Цвет
   ObjectSetDouble    ( 0 ,arrowName, OBJPROP_PRICE ,dwPrice);               // зададим цену
   ChartRedraw ( 0 );
}
//+=================================================================================+
//Aritmetinis vidurkis

double fAvgOC
   (
   uchar count_start,       //nuo kurio baro pradesim skaiciuoti
   uchar end_count,         //iki kurio baro skaiciuosime
   uchar j= 0                //keli barai is eiles
   )
//--------------------   
{
   static double sum= 0 ;
   if (sum== 0 ){
       int n= 0 ;
       for ( int i=end_count; i<count_start; i++){
         double h= iClose ( NULL , PERIOD_M1 ,i);  
         double l= iOpen ( NULL , PERIOD_M1 ,i+j); 
         sum+= fabs (h-l);                   //padidinam avg 
         n++;                             //kie kartu buvo didintas avg
      }
       double avg=sum/n;                           //Surandam Mean aritmetini vidurki                 
   }   
   return (avg);                           //grazina kainu skirtumo vidurki
}
//+=================================================================================+
void fSaveToFile
   (
   string fileName,
   char expirration,       //realus ekspiracijos laikas minutemis
   datetime fop_time,
   datetime fcl_time,
   double fop_price,
   double fcl_price,
   uchar ftype
   )
//--------------------   
{
   //--- правильный способ работы в "файловой песочнице"
   ResetLastError ();
  
   int filehandle= FileOpen (fileName, FILE_WRITE | FILE_CSV );
   if (filehandle!= INVALID_HANDLE )
     {
      FileWrite(filehandle,
               expirration, //real expiration time
               fop_time, //TimeToStr(op_time,TIME_DATE|TIME_SECONDS),
               fcl_time, //TimeToStr(cl_time,TIME_DATE|TIME_SECONDS),
               op_price,
               fcl_price,
               type);
       FileClose (filehandle);
       Print ( "FileOpen OK" );
     }
   else Print ( "Операция FileOpen неудачна, ошибка " ,GetLastError());
}
//+=================================================================================+
/*int gUrdala_News()
{
   HideTestIndicators(true);
   int nResult = iCustom(NULL, PERIOD_M1, "Urdala_News", MinDo, MinPosle, ChasPoyasServera, 0, 0);
   HideTestIndicators(false);
   return(nResult);
}*/
//+=================================================================================+
/*datetime SecondsAfter    //grazinamas laiko tarpas po timeOp
   (
   datetime timeOp,      //laiko atskaitos pradzia
   datetime t
   ) 
{
     
   if (t<timeOp) t=timeOp;          
   return(TimeCurrent()-t);
}*/
//+=================================================================================+
//---------------------------------------------------
   /* void click
   (
   int x, 
   int y
   ) 
   {    
      SetCursorPos(x,y); // см. тут _http://www.vsokovikov.narod.ru/New_MSDN_API/Cursor/fn_setcursorpos.htm 
      mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0); 
      mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0); 
   }*/
//+=================================================================================+
//---------------------------------------------------
   /*void key
   (
   uchar kodas
   )
   {  
      keybd_event(kodas,0,0,0);      
      keybd_event(kodas,0,KEYEVENTF_KEYUP,0); 
   } */   
 

Entonces la cuestión es cómo devolver los dos valores. Lo he intentado, pero hay errores

void OnTick()
  {
//---
   
   xy(10,20,100,100);
   Print("x=",x,"y=",y);
  }
//+------------------------------------------------------------------+
void xy(int xx,int xxx, int yy,int yyy,int & x,int & y){
   x=xx*xxx;
   y=yy+yyy;
}
 
gince:

Entonces la cuestión es cómo devolver los dos valores. Lo he intentado, pero hay errores


void OnTick()
  {
//---
   int x,y;
   xy(10,20,100,100,x,y);
   Print("x=",x,"y=",y);
  }
//+------------------------------------------------------------------+
void xy(int xx,int xxx, int yy,int yyy, int &x,int &y){
   x=xx*xxx;
   y=yy+yyy;
}
 
gince:

Entonces la cuestión es cómo devolver los dos valores. Lo he intentado, pero hay errores


¿Has probado a utilizar variables? Tal vez sea de ayuda.

void OnTick()
  {
//---
   int x=100.0, y=100.0;
   xy(10,20,100, 100, x,y);
   Print("x=",x,"y=",y);
  }
//+------------------------------------------------------------------+
void xy(int xx,int xxx, int yy,int yyy,int & x,int & y){
   x=xx*xxx;
   y=yy+yyy;
}
 

Ayuda si no te importa

para enseñar a un Asesor Experto a operar por el indicador

BS_Living Now ver #1.mq4 https://www.mql5.com/ru/code/11014#50910

UP= iCustom(Symbol(),NULL, "Now",BQuant,0,0);

DOW= iCustom(Symbol(),NULL, "Now",BQuant,1,0);


if(DOW){OrderSend(Symbol(), OP_SELL, Lot, Bid, Slip, 0, 0, "Forex-Robots.ru SELL", Magic, 0,Red);}


if(UP ){OrderSend(Symbol(), OP_BUY, Lot, Ask, Slip, 0, 0, "Forex-Robots.ru BUY", Magic, 0,Blue);}


Comentario

(

"\N - Beneficio: ", UP,

"\N - Beneficio: ", DOW

);

He intentado leer los valores en el comentario pero siempre son estáticos.

 
Vinin:


¿Has probado a utilizar variables? Podría ayudar.


Gracias, funciona.

 
sannin:

Ayuda si no te importa

para enseñar a un Asesor Experto a operar por el indicador

BS_Living Now ver #1.mq4 https://www.mql5.com/ru/code/11014#50910


UP= iCustom(Symbol(),NULL,"Now",BQuant,0,2);//

DOW= iCustom(Symbol(),NULL,"Now",BQuant,1,2);


if(DOW != 0){OrderSend(Symbol(), OP_SELL, Lot, Bid, Slip, 0, 0, "Forex-Robots.ru SELL", Magic, 0,Red);}



if(UP != 0){OrderSend(Symbol(), OP_BUY, Lot, Ask, Slip, 0, 0, "Forex-Robots.ru BUY", Magic, 0,Blue);}
No me he puesto a ello, pero creo que es algo así.