Qualsiasi domanda da principiante, per non ingombrare il forum. Professionisti, non passate oltre. Da nessuna parte senza di te - 6. - pagina 539

 
tatianati:

Grazie! Ha funzionato, ero felice come un bambino, ma il consulente ha smesso di visualizzare "nuovo". Puoi dirmi dove ho sbagliato?

Huh, ho trovato l'errore, non dove stavo cercando inizialmente. Non posso affrontare il prossimo compito da solo.

Si prega di consigliare come impostare l'intervallo di deviazione - distanza del prezzo dalla MA.

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

Ecco la parte dell'ingresso

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, trovato l'errore, non dove stavo cercando inizialmente. Non posso gestire il prossimo compito da solo.

Puoi dirmi come impostare il range di deviazione - distanza del prezzo dalla MA.

Ecco la parte di ingresso


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

E di conseguenza la condizione

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

Dobbiamo cambiare correttamente i dati iniziali nell'advisor in (1 acquisto, -1 vendita)

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

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

extern int SL = 50; // valore di stop loss (in pip)
TP = 150; // valore di Take Profit (in punti)
extern double Lots = 0.1; // lotto di lavoro (micro lotti - 0.01, mini lotti - 0.1, lotti normali - 1.0)
extern string Order_Comment = "robot"; // commento che sarà usato per piazzare gli ordini
extern int Slipage = 5; // livello di slittamento massimo consentito (in punti)
extern int int Magic_Number = 777; // numero magico di ordini per il robot (per distinguere gli affari "amichevoli")
extern bool Play_Sound = false; // riproduzione del suono all'apertura: true - permesso, false - vietato

//--------------------------------------------------------------------------------------------------------------------+
//+ impostazione di timeframes e parametri dell'indicatore SimpleBars |
extern int periodo = 6;
extern bool useClose = true;
extern int width = 3;
//+ regolazione dei timeframes e dei parametri dell'indicatore SimpleBars |
//--------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//+ trailing stop |
extern bool UseTrailing = true; // trailing stop on/off
extern int TrailingStop = 50; // dimensione fissa del trailing stop (in pip)
extern int TrailingStep = 1; // passo di trailing stop (in punti)
//+ trailing stop
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| la funzione viene eseguita all'inizializzazione del programma
void init() {
if(GlobalVariableCheck("this_bar "+Symbol()+Period()))
GlobalVariableDel("this_bar "+Symbol()+Period());
ritorno;
}
//| funzione che viene eseguita durante l'inizializzazione del programma
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| la funzione viene eseguita alla deinizializzazione del programma |
void deinit() {
if(GlobalVariableCheck("this_bar "+Symbol()+Period()))
GlobalVariableDel("this_bar "+Symbol()+Period());
ritorno;
}
//| funzione che viene eseguita alla deinizializzazione del programma.
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| funzione di ricerca di un segnale di trading
int fsignals() {
doppio segnale = iCustom(NULL, 0, "SimpleBars", periodo, 0, 1, 4, 0);
return(0); // segnale per aprire un Buy
return(1); //aprire il segnale Sell
return(-1); // nessun segnale
} //end int fsignals()
//| funzione di ricerca di un segnale di trading
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| funzione di tracciamento del lavoro del robot sulla barra data
bool this_bar() {
se(
(!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()
//| funzione di monitoraggio del fatto del lavoro del robot sulla barra data
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| funzione di ricerca di ordini di questo tipo
bool find_orders(int magic=-1, int type=-1, string symb="NULL") {
/* restituisce true se almeno un ordine del tipo dato con il numero magico dato è trovato dal simbolo dato */
for (int i=OrdersTotal()-1; i>=0; i--) {
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) break;
if(((OrderType()==type) || (type==-1))
&& ((OrderMagicNumber()==magica) || (magic==-1))
&& ((OrderSymbol()==Symbol() || (symb=="NONE")))) {
//se viene trovato un ordine, return(true) e uscire dal ciclo
return(true);
pausa;
} //end if((OrderType()==type) && (OrderMagicNumber()==magic) && (OrderSymbol()==Symbol())
} //end for (int i2=OrdersTotal()-1; i2>=0; i2--)

return(false); //ritornare false
} //end bool find_orders(int magic, int type)
//| funzione di ricerca di ordini del tipo dato |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| funzione di calcolo del valore di Stop Loss per gli ordini
double sl(int sl_value, int type, double price=0.0, string symb="NONE", int rmode=1) {
//tipo=0 -> acquisti sul mercato
//tipo=1 -> vendite sul mercato
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);
se(rmode==1) {
if((type==0) || (type==2) || (type==4)) return(MarketInfo(symb,MODE_ASK)-sl_value*MarketInfo(symb,MODE_POINT)); //per gli acquisti
if((type==1) || (type==3) || (type==5)) return(MarketInfo(symb,MODE_BID)+sl_value*MarketInfo(symb,MODE_POINT)); //per le vendite
}
se(rmode==2) {
if((type==0) || (type==2) || (type==4)) return(MarketInfo(symb,MODE_BID)-sl_value*MarketInfo(symb,MODE_POINT)); //per comprare
if((type==1) || (type==3) || (type==5)) return(MarketInfo(symb,MODE_ASK)+sl_value*MarketInfo(symb,MODE_POINT)); //per vendere
}
} //end double sl(int sl_value, int type, double price=0.0, string symb="NONE", int rmode=1)
//| funzione per il calcolo del valore di Stop Loss per gli ordini
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| funzione per calcolare i valori di Take Profit per gli ordini
double tp(int tp_value, int type, double price=0.0, string symb="NONE") {
//type=0 -> market buy
//tipo=1 -> vendite sul mercato
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)); //per gli acquisti
if((type==1) || (type==3) || (type==5)) return(MarketInfo(symb,MODE_BID)-tp_value*MarketInfo(symb,MODE_POINT)); //per le vendite
} //end double tp(int tp_value, int type, double price=0.0, string symb="NONE")
//| funzione per il calcolo del valore di Take Profit per gli ordini
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| funzione di apertura degli ordini
void open_positions(int signal, double lot, double price=0.0, string symb="NONE") {
//signal=0 -> segnale per aprire l'acquisto
//signal=1 -> segnale per aprire la vendita
/* extern */ int Count_Of_Trade_Try=5, Pause_Of_Trade_Try=5;

int i = 0; //variabile per il contatore del ciclo
int err = 0;

if(symb=="NONE") symb=Symbol();
se(segnale==0)
price=NormalizeDouble(MarketInfo(symb,MODE_ASK),MarketInfo(symb,MODE_DIGITS)); //prezzo aperto per comprare
se(segnale==1)
price=NormalizeDouble(MarketInfo(symb,MODE_BID),MarketInfo(symb,MODE_DIGITS)); //prezzo aperto per la vendita

while(i<=Count_Of_Trade_Try) {
La //funzione di apertura dell'ordine (integrata). Per comodità di percezione, i parametri sono collocati su linee diverse:
int ticket = OrderSend(Symbol(), //symbol
segnale, //tipo di ordine
lotto, //volume
prezzo, //prezzo aperto
Slipage, //livello di requote ammissibile
sl(SL,segnale), // valore di Stop Loss
tp(TP,segnale), //prendere il valore del profitto
Order_Comment, //commento d'ordine
Magic_Number, //numero magico
0, //tempo di scadenza (usato per gli ordini in sospeso)
CLR_NONE); //colore della freccia visualizzata sul grafico (CLR_NONE - la freccia non viene disegnata)
if(ticket!=-1) //se l'apertura ha avuto successo, disegnate un oggetto grafico e uscite dal ciclo
pausa;
err=GetLastError();
if(err!=0) Print("Errore: "+Market_Err_To_Str(err));
i++;
Sleep(Pause_Of_Trade_Try*1000); //in caso di errore, pausa prima di riprovare
} //fine mentre(i<=conteggio)
} //end void open_positions(int signal, double lot, double price=0.0, string symb="NONE")
//| funzione per aprire gli ordini
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------+
//| funzione di decodifica dei codici di errore
stringa Market_Err_To_Str(int err) {
/* la funzione copre solo i codici di errore delle operazioni commerciali */
switch(err) {
caso(0): return("Nessun errore");
caso(1): return("Nessun errore, ma il risultato è sconosciuto");
caso(2): return("Errore generale");
caso(3): return("Parametri errati");
caso(4): return("Il server commerciale è occupato");
caso(5): return("Vecchia versione del terminale client");
caso(6): return("Nessuna connessione al server commerciale");
caso(7): return("Non abbastanza diritti");
caso(8): return("Richieste troppo frequenti");
caso(9): return("Operazione non valida che interrompe il funzionamento del server");
caso(64): return("Account bloccato");
caso(65): return("Numero di conto errato");
caso(128): return("Il termine della transazione è scaduto");
caso(129): return("Prezzo errato");
caso(130): return("Fermate errate");
caso(131): return("Volume errato");
caso(132): return("Il mercato è chiuso");
caso(133): return("Commercio proibito");
caso(134): return("Non ci sono abbastanza soldi per eseguire la transazione");
caso(135): return("Il prezzo è cambiato");
caso(136): return("Nessun prezzo");
caso(137): return("Il broker è occupato");
caso(138): return("Nuovi prezzi");
caso(139): return("L'ordine è bloccato ed è già in elaborazione");
caso(140): return("Acquisto solo permesso");
caso(141): return("Troppe richieste");
caso(145): return("La modifica non è permessa, perché l'ordine è troppo vicino al mercato");
caso(146): return("Il sottosistema commerciale è occupato");
caso(147): return("L'uso della data di scadenza è vietato dal broker");
caso(148): return("Il numero di ordini aperti e pendenti ha raggiunto il limite fissato dal broker;)
caso(149): return("Tentativo di aprire una posizione opposta ad una posizione esistente se la copertura è proibita");
caso(150): return("Tentativo di chiudere una posizione su un simbolo in violazione della regola FIFO");

default: return("");
} //end switch(err)
} //end string Err_To_Str(int err)
//| funzione per decodificare i codici di errore
//+-------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------+
//| Operazioni di chiusura delle transazioni
//+----------------------------------------------------------------------------------------------------+
//| funzione di chiusura di un ordine per il suo numero (ticket) |


bool close_by_ticket(int c_ticket, int slipage) {
/*
funzione di chiusura di un trade per il suo numero (ticket).
Quando si chiude un ordine a mercato, si tiene conto del livello di slippage massimo consentito (slipage)
*/
/* extern */ int Count_Of_Trade_Try=5, Pause_Of_Trade_Try=5;

int i = 0; //variabile per il contatore del ciclo
int err = 0;
bool ticket = false; //variabile per la chiusura (non) riuscita di un trade
double price = 0.0; //prezzo per la transazione da chiudere (per ordini a mercato)
if(OrderSelect(c_ticket,SELECT_BY_TICKET,MODE_TRADES)) { //selezionare l'ordine per biglietto
if(OrderType()==OP_BUY) price = NormalizeDouble(Bid,Digits); //price for buying
if(OrderType()==OP_SELL) price = NormalizeDouble(Ask,Digits); //prezzo di vendita
for(i=0;i<=Count_Of_Trade_Try;i++) {
if(OrderType()<=1) //se l'ordine è un ordine a mercato, chiudilo, se è un ordine in sospeso, cancellalo
ticket=OrderClose(OrderTicket(),OrderLots(),price,slipage,CLR_NONE);
else
ticket=OrderDelete(OrderTicket());

if(ticket) { //se la chiusura o la cancellazione ha avuto successo - restituisce true e esce dal ciclo
return(true);
pausa;
} //end if(ticket)
err=GetLastError();
if(err!=0) Print("Errore: "+Market_Err_To_Str(err));
Sleep(Pause_Of_Trade_Try*1000); //in caso di errore, fare una pausa prima di riprovare
} //end for(i=0;i<=Count_Of_Trade_Try;i++)
} //end if(OrderSelect(c_ticket,SELECT_BY_TICKET,MODE_TRADES))

return(false); //ritornare false
} //end bool close_by_ticket(int c_ticket)
//| funzione di chiusura di un ordine per il suo numero (ticket) |
//+----------------------------------------------------------------------------------------------------+

bool cbm(int magic, int slipage, int type) {
/*
Chiudere per magia (chiudere tutti gli ordini del tipo dato con il MagicNumber dato)
Si tiene conto dello slittamento massimo consentito
Viene usata la funzione close_by_ticket.
*/
int n = 0;
mentre (find_orders(magic, type))
for (int i2=OrdersTotal()-1; i2>=0; i2--) {
if (!OrderSelect(i2,SELECT_BY_POS,MODE_TRADES)) break;

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

se(n>0)
return(true);

return(false);
} //end bool cbm(int magic, int slipage, int type)
//| operazioni di chiusura del commercio
//+-------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| 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))) continua;
if(OrderSymbol() != Symbol() || OrderMagicNumber()!=Magic_Number) continua;

if(OrderType()==OP_BUY) {
se(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) {
se(NormalizeDouble(OrderOpenPrice()-Ask,Digits)>NormalizeDouble(TrailingStop*Point,Digits)) {
se(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 |
//+-------------------------------------------------------------------------------------------------------------------+

//+-------------------------------------------------------------------------------------------------------------------+
//| funzione principale |
void start() {

int sig = fsignals();

if(!find_orders(Magic_Number)) {
se((sig!=-1)) {
if(!this_bar()) {
open_positions(sig, Lots);
if(Play_Sound)
PlaySound("alert.wav");
}
} //end if((sig!=-1) && (!this_bar())
} else {
se(sig==0) {
se(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)
se(sig==1) {
se(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) (altro)
ritorno;
}
//| funzione principale |
//+-------------------------------------------------------------------------------------------------------------------+
 

Ciao intenditori. Aiuto - non funziona. Penso di essere stato confuso dall'inizializzazione delle variabili . Mi gira la testa, ma non trovo errori.

Invece di aprire posizioni, l'EA dovrebbe disegnare frecce al prezzo Klose(0), e invece di chiudere - una croce e stampare i dati ( fExpiration_func(Expiration), fop_time, cl_time, fop_price, cl_price, ftype) in una nuova riga.

Qui lo stocastico è preso solo come esempio.

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

Allora la domanda è come restituire i due valori. Provato questo, ma errori

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:

Allora la domanda è come restituire i due valori. Provato questo, ma errori


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:

Allora la domanda è come restituire i due valori. Provato questo, ma errori


Avete provato a usare le variabili? Forse vi aiuterà.

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

Aiuto se non ti dispiace

per insegnare a un Expert Advisor a fare trading in base all'indicatore

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, 0, "Forex-Robots.ru SELL", Magic, 0,Red);}


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


Commento

(

"Un profitto: ", UP,

"Un profitto: ", DOW

);

Ho provato a leggere i valori nel commento ma sono sempre statici.

 
Vinin:


Avete provato a usare le variabili? Potrebbe aiutare.


Grazie, funziona.

 
sannin:

Aiuto se non ti dispiace

per insegnare a un Expert Advisor a fare trading in base all'indicatore

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);}
Non ho approfondito molto, ma credo che sia qualcosa del genere.