Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 539

 
tatianati:

Huh, found the error, not where I was originally looking. I can't handle the next task on my own.

Can you tell me how to set the deviation range - distance of the price from the MA.

Here is the entry part


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

And accordingly the condition

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

We need to correctly change the initial data in the advisor to (1 buy, -1 sell)

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

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

extern int SL = 50; // stop loss value (in pips)
TP = 150; // Take Profit value (in points)
extern double Lots = 0.1; // working lot (micro lots - 0.01, mini lots - 0.1, normal lots - 1.0)
extern string Order_Comment = "robot"; // comment that will be used to place orders
extern int Slipage = 5; // maximum allowable slippage level (in points)
extern int int Magic_Number = 777; // magic number of orders for the robot (to distinguish "friendly" deals)
extern bool Play_Sound = false; // playback of sound at opening: true - allowed, false - prohibited

//--------------------------------------------------------------------------------------------------------------------+
//+ setup of timeframes and parameters of the SimpleBars indicator |
extern int period = 6;
extern bool useClose = true;
extern int width = 3;
//+ adjustment of timeframes and parameters of the indicator SimpleBars |
//--------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//+ trailing stop |
extern bool UseTrailing = true; // trailing stop on/off
extern int TrailingStop = 50; // fixed trailing stop size (in pips)
extern int TrailingStep = 1; // trailing stop step (in points)
//+ trailing stop
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| function is executed at program initialization |
void init() {
if(GlobalVariableCheck("this_bar "+Symbol()+Period()))
GlobalVariableDel("this_bar "+Symbol()+Period());
return;
}
//| function, which is executed during program initialization |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| function is executed at program deinitialisation |
void deinit() {
if(GlobalVariableCheck("this_bar "+Symbol()+Period()))
GlobalVariableDel("this_bar "+Symbol()+Period());
return;
}
//| function, which is executed on program deinitialization |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| function of searching for a trading signal |
int fsignals() {
double signal = iCustom(NULL, 0, "SimpleBars", period, 0, 1, 4, 0);
return(0); // signal to open a Buy
return(1); //open Sell signal
return(-1); // no signal
} //end int fsignals()
//| function of searching for a trading signal
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| function of tracking the robot's work on the given bar
bool this_bar() {
if(
(!GlobalVariableCheck("this_bar "+Symbol()+Period()))
|| (GlobalVariableGet("this_bar "+Symbol()+Period()!=Time[0])
) {
GlobalVariableSet("this_bar "+Symbol()+Period(),Time[0]);
return(false);
} else {
return(true);
} //end if (. (!GlobalVariableCheck("this_bar "+Symbol()+Period()))
} //end bool this_bar()
//| function of tracking the fact of the robot work on the given bar
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| function of searching for orders of this type |
bool find_orders(int magic=-1, int type=-1, string symb="NULL") {
/* returns true if at least one order of the given type with the given magic number is found by the given symbol */
for (int i=OrdersTotal()-1; i>=0; i--) {
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) break;
if(((OrderType()==type) || (type==-1))
&& ((OrderMagicNumber()==magic) || (magic==-1))
&& ((OrderSymbol()==Symbol() || (symb=="NONE")))) {
//if an order is found, return(true) and exit the loop
return(true);
break;
} //end if((OrderType()==type) && (OrderMagicNumber()==magic) && (OrderSymbol()==Symbol())
} //end for (int i2=OrdersTotal()-1; i2>=0; i2--)

return(false); //return false
} //end bool find_orders(int magic, int type)
//| function of search for orders of the given type |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| function of calculation of Stop Loss value for orders |
double sl(int sl_value, int type, double price=0.0, string symb="NONE", int rmode=1) {
//type=0 -> market purchases
//type=1 -> market sales
if(symb=="NONE") symb=Symbol();
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)); //for purchases
if((type==1) || (type==3) || (type==5)) return(MarketInfo(symb,MODE_BID)+sl_value*MarketInfo(symb,MODE_POINT)); //for selling
}
if(rmode==2) {
if((type==0) || (type==2) || (type==4)) return(MarketInfo(symb,MODE_BID)-sl_value*MarketInfo(symb,MODE_POINT)); //for buying
if((type==1) || (type==3) || (type==5)) return(MarketInfo(symb,MODE_ASK)+sl_value*MarketInfo(symb,MODE_POINT)); //for selling
}
} //end double sl(int sl_value, int type, double price=0.0, string symb="NONE", int rmode=1)
//| function for calculation of Stop Loss value for orders |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| function for calculating Take Profit values for orders
double tp(int tp_value, int type, double price=0.0, string symb="NONE") {
//type=0 -> market buy
//type=1 -> market sales
if(symb=="NONE") symb=Symbol();
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)); //for purchases
if((type==1) || (type==3) || (type==5)) return(MarketInfo(symb,MODE_BID)-tp_value*MarketInfo(symb,MODE_POINT)); //for sales
} //end double tp(int tp_value, int type, double price=0.0, string symb="NONE")
//| function for calculation of Take Profit value for orders |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| function of opening of orders
void open_positions(int signal, double lot, double price=0.0, string symb="NONE") {
//signal=0 -> signal to open buy
//signal=1 -> signal to open sell
/* extern */ int Count_Of_Trade_Try=5, Pause_Of_Trade_Try=5;

int i = 0; //variable for the loop counter
int err = 0;

if(symb=="NONE") symb=Symbol();
if(signal==0)
price=NormalizeDouble(MarketInfo(symb,MODE_ASK),MarketInfo(symb,MODE_DIGITS)); //open price for buying
if(signal==1)
price=NormalizeDouble(MarketInfo(symb,MODE_BID),MarketInfo(symb,MODE_DIGITS)); //open price for selling

while(i<=Count_Of_Trade_Try) {
The //function for opening the order (built-in). For the convenience of perception, the parameters are placed on different lines:
int ticket = OrderSend(Symbol(), //symbol
signal, //order type
lot, //volume
price, //open price
Slipage, //level of allowable requote
sl(SL,signal), // value of Stop Loss
tp(TP,signal), //take profit value
Order_Comment, //order comment
Magic_Number, //magic number
0, //expiration time (used for pending orders)
CLR_NONE); //colour of the arrow displayed on the chart (CLR_NONE - arrow is not drawn)
if(ticket!=-1) //if the opening was successful, draw a graphic object and exit the loop
break;
err=GetLastError();
if(err!=0) Print("Error: "+Market_Err_To_Str(err));
i++;
Sleep(Pause_Of_Trade_Try*1000); //in case of error, pause before retry
} //end while(i<=count)
} //end void open_positions(int signal, double lot, double price=0.0, string symb="NONE")
//| function of opening orders |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------+
//| function of decoding error codes |
string Market_Err_To_Str(int err) {
/* function covers only error codes of trade operations */
switch(err) {
case(0): return("No error");
case(1): return("No error, but the result is unknown");
case(2): return("General error");
case(3): return("Incorrect parameters");
case(4): return("Trade server is busy");
case(5): return("Old version of client terminal");
case(6): return("No connection to the trade server");
case(7): return("Not enough rights");
case(8): return("Too frequent requests");
case(9): return("Invalid operation disrupting server operation");
case(64): return("Account blocked");
case(65): return("Incorrect account number");
case(128): return("The deadline for the transaction has expired");
case(129): return("Incorrect price");
case(130): return("Incorrect stops");
case(131): return("Incorrect volume");
case(132): return("Market is closed");
case(133): return("Trading prohibited");
case(134): return("Not enough money to execute the transaction");
case(135): return("The price has changed");
case(136): return("No price");
case(137): return("The broker is busy");
case(138): return("New prices");
case(139): return("The order is blocked and is already being processed");
case(140): return("Buy only allowed");
case(141): return("Too many requests");
case(145): return("Modification is not allowed, because the order is too close to the market");
case(146): return("The trading subsystem is busy");
case(147): return("Use of expiry date is prohibited by the broker");
case(148): return("The number of open and pending orders has reached the limit set by the broker;)
case(149): return("Attempting to open an opposite position to an existing position if hedging is prohibited");
case(150): return("Attempting to close a position on a symbol in contravention of the FIFO rule");

default: return("");
} //end switch(err)
} //end string Err_To_Str(int err)
//| function to decode error codes |
//+-------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------+
//| Transaction closing operations ||
//+----------------------------------------------------------------------------------------------------+
//| function of closing an order by its number (ticket) |


bool close_by_ticket(int c_ticket, int slipage) {
/*
function of closing a trade by its number (ticket).
When closing a market order, the level of maximum allowable slippage is taken into account (slipage)
*/
/* extern */ int Count_Of_Trade_Try=5, Pause_Of_Trade_Try=5;

int i = 0; //variable for the loop counter
int err = 0;
bool ticket = false; //variable for the (un)successful closure of a trade
double price = 0.0; //price for the transaction to be closed (for market orders)
if(OrderSelect(c_ticket,SELECT_BY_TICKET,MODE_TRADES)) { //select order by ticket
if(OrderType()==OP_BUY) price = NormalizeDouble(Bid,Digits); //price for buying
if(OrderType()==OP_SELL) price = NormalizeDouble(Ask,Digits); //price for selling
for(i=0;i<=Count_Of_Trade_Try;i++) {
if(OrderType()<=1) //if the order is a market order, close it, if it is a pending order, delete it
ticket=OrderClose(OrderTicket(),OrderLots(),price,slipage,CLR_NONE);
else
ticket=OrderDelete(OrderTicket());

if(ticket) { //if the close or delete was successful - return true and exit the loop
return(true);
break;
} //end if(ticket)
err=GetLastError();
if(err!=0) Print("Error: "+Market_Err_To_Str(err));
Sleep(Pause_Of_Trade_Try*1000); //in case of an error, pause before retry
} //end for(i=0;i<=Count_Of_Trade_Try;i++)
} //end if(OrderSelect(c_ticket,SELECT_BY_TICKET,MODE_TRADES))

return(false); //return false
} //end bool close_by_ticket(int c_ticket)
//| function of closing an order by its number (ticket) |
//+----------------------------------------------------------------------------------------------------+

bool cbm(int magic, int slipage, int type) {
/*
Close by magic (close all orders of the given type with the given MagicNumber)
The maximum allowable slippage is taken into account
The close_by_ticket function is used.
*/
int n = 0;
while (find_orders(magic, type))
for (int i2=OrdersTotal()-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--)

if(n>0)
return(true);

return(false);
} //end bool cbm(int magic, int slipage, int type)
//| Trade closing operations |
//+-------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| trailing stop loss |
void T_SL() {
if(!UseTrailing) return;
int i = 0;
for(i=0; i<OrdersTotal(); 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)
} //end if(NormalizeDouble(Bid-OrderOpenPrice(),Digits)>NormalizeDouble(TrailingStop*Point,Digits))
} //end 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))
} //end if(OrderType()==OP_SELL)
} //end for(i=0; i<OrdersTotal(); i++)
} //end void T_SL()
//| trailing stop loss |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| main function |
void start() {

int sig = fsignals();

if(!find_orders(Magic_Number)) {
if((sig!=-1)) {
if(!this_bar()) {
open_positions(sig, Lots);
if(Play_Sound)
PlaySound("alert.wav");
}
} //end if((sig!=-1) && (!this_bar())
} else {
if(sig==0) {
if(cbm(Magic_Number, Slipage, 1)) {
open_positions(sig, Lots);
if(Play_Sound)
PlaySound("alert.wav");
} //end if(cbm(Magic_Number, Slipage, 1))
} //end if(sig==0)
if(sig==1) {
if(cbm(Magic_Number, Slipage, 0)) {
open_positions(sig, Lots);
if(Play_Sound)
PlaySound("alert.wav");
} //end if(cbm(Magic_Number, Slipage, 0))
} //end if(sig==1)
T_SL();
} //end if(!find_orders(Magic_Number) (else)
return;
}
//| main function |
//+-------------------------------------------------------------------------------------------------------------------+
 

Hello connoisseurs. Help - not working. I think I got confused by the initialization of variables . My head is spinning, but I can't find any mistakes.

Instead of opening positions, the EA should draw arrows at the Klose(0) price, and instead of closing - a cross and print the data ( fExpiration_func(Expiration), fop_time, cl_time, fop_price, cl_price, ftype) into a new line.

Here the stochastic is taken only as an example.

 //+------------------------------------------------------------------+
//|                                                     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); 
   } */   
 

Then the question is how to return the two values. Tried this, but errors

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:

Then the question is how to return the two values. Tried this, but errors


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:

Then the question is how to return the two values. Tried this, but errors


Have you tried using variables? Maybe it will help.

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;
}
 

Help if you don't mind

to teach an Expert Advisor to trade by the indicator

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);}


Comment

(

"\n Profit: ", UP,

"\n Profit: ", DOW

);

I tried to read the values in the comment but they are always static.

 
Vinin:


Have you tried using variables? It might help.


Thank you, it works.

 
sannin:

Help if you don't mind

to teach an Expert Advisor to trade by the indicator

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);}
I haven't really gotten into it, but I think it's something like this.
 
My trading system is based on the analysis of historical data. I have built a function to calculate the signal directly in the EA. However, as far as I understood, when testing, the Expert Advisor uses only the data in the visual window (it has much less bars than in standard windows with history loaded from the archive). I need at least several tens of thousands of history bars to calculate the signal. Is there any way to solve this problem, i.e. to allow the EA under test to use the entire history, even if the period under test is smaller? I am using MT4 and MQL4
Reason: