Friday 11 August 2017

Scrittura Forex Esperti Consulenti


MetaTrader 5 - Trading Systems Step-by-Step Guida alla scrittura di un Expert Advisor in MQL5 per principianti Introduzione Questo articolo è rivolto a principianti che vogliono imparare a scrivere semplici Expert Advisors nella nuova lingua MQL5. Inizieremo prima definendo ciò che vogliamo che il nostro EA (Expert Advisor) per fare, e poi passare a come vogliamo l'EA per farlo. 1. Trading strategia Quello che il nostro EA farà: sarà monitorare un particolare indicatore, e quando una certa condizione è soddisfatta (o vengono soddisfatte determinate condizioni), sarà posto un mestiere (o un di vendita allo scoperto o LongBuy), a seconda della condizione attuale che è stato raggiunto. Quanto sopra si chiama una strategia di trading. Prima di poter scrivere un EA, è necessario innanzitutto sviluppare la strategia che si desidera automatizzare in EA. Quindi, in questo caso, cerchiamo di modificare l'istruzione di cui sopra in modo che rifletta la strategia che vogliamo sviluppare in un EA. Useremo un indicatore chiamato media mobile con un periodo di 8 (È possibile scegliere qualsiasi periodo, ma per lo scopo della nostra strategia, useremo 8) Vogliamo che il nostro EA per posizionare un commercio a lungo (Buy) quando il Moving media - 8 (per il bene della nostra discussione, farò riferimento ad esso come mA-8) è in aumento verso l'alto e il prezzo è vicino al di sopra di esso e si sarà posto un corto (vendita) quando mA-8 è in calo verso il basso e il prezzo è vicino sotto di esso. Stiamo anche andando a utilizzare un altro indicatore chiamato Average Directional Movement (ADX) con periodo di 8 anche per aiutare a determinare se il mercato è in trend o meno. Stiamo facendo questo perché vogliamo solo entrare nel commercio quando il mercato è in trend e rilassarsi quando il mercato è che vanno (cioè non trend). Per raggiungere questo obiettivo, ci sarà solo mettere il nostro commercio (comprare o vendere) quando sopra condizioni sono soddisfatte e il valore ADX è maggiore che 22. Se ADX è maggiore che il 22, ma in diminuzione, o ADX è inferiore a 22, non commerciali, anche se la condizione B è stato raggiunto. Vogliamo proteggere anche noi stessi impostando uno stop loss di 30 pip, e per il nostro obiettivo di profitto ci sarà obiettivo un profitto di 100 pips. Vogliamo anche il nostro EA a cercare nuove opportunità BuySell solo quando un nuovo bar è stato formato e ci sarà anche fare in modo apriamo una posizione di acquisto se sono soddisfatte le condizioni Compro e noi non ne hai già uno aperto, e aprire una posizione vendere quando Vendere le condizioni sono soddisfatte e che non ne hai già uno aperto. Ora abbiamo sviluppato la nostra strategia è giunto il momento di iniziare a scrivere il nostro codice. 2. Scrivere un Expert Advisor Iniziare con il lancio del MetaQuotes Language Editor 5. Quindi premere CtrlN oppure fare clic sul pulsante Nuovo sulla barra dei menu Figura 1. Avvio di un nuovo documento MQL5 Nella finestra MQL5 guidata, selezionare Expert Advisor e fare clic su Next come illustrato nella Fig. 2: Figura 2. Selezione tipo di programma Nella finestra successiva, digitare il nome che si vuole dare al vostro EA nella casella Nome. In questo caso, ho digitato MyFirstEA. È quindi possibile digitare il nome nella casella autore e anche il tuo indirizzo web o l'indirizzo e-mail nella casella Collegamento (se ne avete uno). Figura 3. Proprietà generali della Expert Advisor Dal momento che vogliamo essere in grado di modificare alcuni dei parametri per il nostro EA per vedere quale dei valori ci può dare il miglior risultato, li aggiungeremo facendo clic sul pulsante Aggiungi. Figura parametri di input EA 4. impostazione nel nostro EA, ci vogliono essere in grado di sperimentare con il nostro Stop Loss, Take Profit, ADX Periodo, e spostamento impostazioni media del periodo, in modo da noi li definire a questo punto. Fare doppio clic nella sezione Nome e digitare il nome del parametro, quindi fare doppio clic sotto la Type per selezionare il tipo di dati per il parametro, e fare doppio clic nella sezione Valore iniziale e digitare il valore iniziale per il parametro. Una volta che hai finito, dovrebbe essere simile a questo: Figura 5. Tipi di dati di parametri di input EA Come potete vedere sopra, ho selezionato intero (int) tipo di dati per tutti i parametri. Parliamo un po 'di tipi di dati. char: Il tipo char richiede 1 byte di memoria (8 bit) e permette esprimendo in notazione binaria 28256 valori. Il tipo char può contenere valori sia positivi che negativi. L'intervallo di valori è da -128 a 127. uchar: il tipo intero uchar occupa anche 1 byte di memoria, come pure il tipo char, ma a differenza uchar è destinato solo per valori positivi. Il valore minimo è zero, il valore massimo è 255. La prima lettera u nel nome del tipo uchar è l'abbreviazione di segno. breve: La dimensione del tipo corto è 2 byte (16 bit) e, di conseguenza, permette esprimendo la gamma di valori pari a 2 alla potenza 16: 216 65 536. Poiché il tipo corto è segno uno, e contiene sia valori positivi e negativi, l'intervallo di valori è compreso tra -32 e 768 32 767. ushort: il tipo corto senza segno è il tipo ushort. che ha anche una dimensione di 2 byte. Il valore minimo è 0, il valore massimo è 65 535. int: La dimensione del tipo int è di 4 byte (32 bit). Il valore minimo è -2 147 483 648, quella massima è di 2 147 483 647. uint: il tipo intero senza segno è uint. Ci vogliono 4 byte di memoria e permette di esprimere numeri interi da 0 a 4 294 967 295. lungo: La dimensione del tipo lungo è di 8 byte (64 bit). Il valore minimo è 223 372 036 -9 854 775 808, il valore massimo è 9 223 372 036 854 775 807. ulong: il tipo ulong occupa anche 8 byte e può memorizzare valori da 0 a 18 446 744 073 709 551 615. Dal la descrizione sopra fatta di vari tipi di dati, i tipi interi senza segno non sono progettati per memorizzare valori negativi, qualsiasi tentativo di impostare un valore negativo può portare a conseguenze imprevedibili. Ad esempio, se si desidera memorizzare i valori negativi, non è possibile conservarli all'interno dei tipi senza segno (cioè uchar, uint, ushort, ulong). Torniamo al nostro EA. Guardando i tipi di dati, sarete d'accordo con me che ci sono supponiamo di utilizzare i tipi di dati char o UCHAR in quanto i dati che intendiamo conservare in questi parametri sono meno di 127 o 255, rispettivamente. Per una buona gestione della memoria, questa è la cosa migliore da fare. Tuttavia, per il bene della nostra discussione, ci sarà ancora aderire al tipo int. Una volta che hai finito di impostare tutti i parametri necessari, fare clic sul pulsante Finito e l'Editor MetaQuotes creerà lo scheletro del codice per voi, come mostrato nella figura seguente. Consente di rompere il codice in varie sezioni per una migliore comprensione. La parte superiore (Header) del codice è dove è definita la proprietà della EA. Si può vedere che qui ci sono i valori compilato in MQL5 guidata in figura 3. In questa sezione del codice, è possibile definire i parametri aggiuntivi come descrizione (breve descrizione del testo della EA), dichiarare costanti, includere file aggiuntivi o funzioni di importazione . Quando una dichiarazione inizia con un simbolo, si parla di una direttiva del preprocessore e non finisce con un punto e virgola altro esempio di direttive del preprocessore include: La direttiva definisce viene utilizzato per una dichiarazione di costanti. E 'scritto in forma define identificatore tokenstring Quello che fa è sostituto ogni occorrenza di identificatore nel codice con il valore di tokenstring. definiscono ABC 100 definiscono COMPANYNAME MetaQuotes Software Corp. Essa sostituirà ogni occorrenza di COMPANYNAME con la stringa MetaQuotes Software Corp. o andrà a sostituire ogni occorrenza di ABC con il carattere (o intero) 100 nel codice. Si può leggere di più circa le direttive del preprocessore nel Manuale MQL5. Vediamo ora continuiamo con la nostra discussione. La seconda parte dell'intestazione del nostro codice è la sezione parametri di ingresso: Si precisa tutti i parametri, che saranno utilizzati nella nostra EA in questa sezione. Questi includono tutte le variabili che verranno utilizzate da tutte le funzioni che sarà iscritto nel nostro EA. Le variabili dichiarate a questo livello sono chiamate variabili globali perché sono accessibili da ogni funzione del nostro EA che possono avere bisogno di loro. I parametri di input sono parametri che possono essere modificati solo al di fuori del nostro EA. Possiamo anche dichiarare altre variabili che ci manipolano nel corso della nostra EA, ma non sarà disponibile al di fuori del nostro EA in questa sezione. Successiva è la funzione di inizializzazione EA. Questa è la prima funzione che viene chiamata quando l'EA viene lanciato o legato ad un grafico e viene chiamato solo una volta. Questa sezione è il posto migliore per fare alcuni controlli importanti al fine di assicurarsi che il nostro EA funziona molto bene. Possiamo decidere di sapere se il grafico ha abbastanza bar per il nostro EA al lavoro, ecc E 'anche il posto migliore per ottenere le maniglie che useremo per i nostri indicatori (ADX e spostamento indicatori di media). Per il nostro EA, si rendono disponibili le maniglie create per i nostri indicatori durante l'inizializzazione in questa sezione. Questo processo funzione l'evento NewTick. che viene generato in caso di nuove quote è ricevuto per un simbolo. Si noti che Expert Advisor non può eseguire operazioni di commercio se l'uso di consulenti esperti nel terminale del cliente non è consentito (pulsante Auto Trading). Figura 6. Autotrading è abilitata La maggior parte dei nostri codici che implementeranno la nostra strategia di trading, sviluppati in precedenza, verrà scritta all'interno di questa sezione. Ora che abbiamo esaminato le varie sezioni del codice per il nostro EA, cominciamo aggiungendo carne allo scheletro. 2.2 PARAMETRI DI INGRESSO SEZIONE Come potete vedere, abbiamo aggiunto più parametri. Prima di continuare a discutere i nuovi parametri, cerchiamo di discutere qualcosa che si può vedere ora. Le due barre ci permette di mettere commenti nei nostri codici. Con i commenti, siamo in grado di sapere quali sono le nostre variabili rappresentano, o quello che stiamo facendo in quel punto nel tempo nel nostro codice. Si dà anche una migliore comprensione del nostro codice. Ci sono due modi fondamentali di scrivere commenti: Questo è un singolo riga di commento Questo è un commento su più righe Questo è un commento su più righe. commenti multi-linea di partenza con la coppia di simboli e alla fine con quello. Il compilatore ignora tutti i commenti quando si compila il codice. Utilizzando commenti a riga singola per i parametri di input è un buon modo di fare i nostri utenti EA capire che cosa questi parametri rappresenta. Sulle proprietà di input EA, i nostri utenti non vedranno il parametro stesso, ma invece vedranno i commenti come illustrato di seguito: Figura 7. parametri di input Expert Advisor Ora, tornando al nostro codice abbiamo deciso di aggiungere ulteriori parametri per il nostro EA. L'EAMagic è il numero magico per tutti gli ordini dal nostro EA. Il valore minimo ADX (AdxMin) è dichiarata come tipo di dati double. Un doppio è utilizzato per memorizzare le costanti in virgola mobile, che contengono una parte intera, un punto decimale, e una parte frazionaria. doppia MySum 123.5678 doppia b7 0,09,876 mila The Lot al commercio (Lot) rappresenta il volume dello strumento finanziario che vogliamo per il commercio. Poi abbiamo dichiarato altri parametri che noi useremo: L'adxHandle deve essere utilizzato per memorizzare l'indicatore ADX maniglia, mentre il maHandle memorizzerà la maniglia per il Moving Average dell'indicatore. Il plsDI, Mindi, adxVal sono matrici dinamiche che conterranno i valori di DI, - DI e ADX principale (dell'indicatore ADX) per ogni barra sul grafico. Il Maval è un array dinamico che conterrà i valori del Moving indicatore medio per ogni barra sul grafico. A proposito, quali sono gli array dinamici Un array dinamico è un array dichiarato senza una dimensione. In altre parole, viene specificato alcun valore nella coppia di parentesi quadre. Un array statico, d'altra parte ha le dimensioni definite nel punto di dichiarazione. doppie allbars 20 questo richiederà 20 elementi pclose è una variabile che useremo per memorizzare il prezzo di chiusura della barra che ci accingiamo a monitorare per il controllo dei nostri commerci BuySell. STP e TKP stanno per essere utilizzata per memorizzare lo Stop Loss e Take Profit i valori del nostro EA. 2.3. EA intialization SEZIONE Qui otteniamo le maniglie del nostro indicatore utilizzando le rispettive funzioni degli indicatori. L'indicatore ADX impugnatura è ottenuto utilizzando la funzione iADX. Prende il simbolo grafico (NULL significa anche il simbolo corrente sul grafico corrente), il periodtimeframe grafico (0 significa anche il lasso di tempo corrente sul grafico corrente), il periodo ADX mediato per il calcolo dell'indice (che abbiamo definito in precedenza sotto parametri di input sezione) come parametri o argomenti. int iADX (simbolo stringa, nome del simbolo ENUMTIMEFRAMES periodo, periodo int adxperiod periodo di media) The Moving Average maniglia indicatore si ottiene utilizzando la funzione iMA. Ha le seguenti argomenti: (. Che può essere ottenuto usando simbolo simbolo () o NULL per il simbolo corrente sul grafico corrente) il simbolo grafico, il periodtimeframe grafico (che può essere ottenuto usando periodo periodo () o 0 per.. i termini attuali sul grafico corrente), il Moving periodo medio di media (che abbiamo definito in precedenza sotto parametri di ingresso sezione), lo spostamento dell'indicatore rispetto al grafico dei prezzi (spostamento qui è 0), il tipo di smoothing media mobile (potrebbe essere uno qualsiasi dei seguenti metodi di calcolo della media: semplice calcolo della media-MODESMA, esponenziale della media-MODEEMA, levigate della media-MODESMMA o lineare-Weighted della media-MODELWMA), e il prezzo utilizzato per il calcolo della media (qui usiamo il prezzo di chiusura). int iMA (stringa di simboli. nome del simbolo ENUMTIMEFRAMES periodo. int periodo maperiod. periodo di media int mashift. spostamento orizzontale ENUMMAMETHOD mamethod. Tipo Tipo di lisciatura ENUMAPPLIEDPRICE appliedprice del prezzo o la maniglia) Si prega di leggere il manuale MQL5 per avere maggiori dettagli su queste funzioni dell'indicatore. Vi darà una migliore comprensione di come utilizzare ogni indicatore. Abbiamo ancora una volta cerchiamo di verificare la presenza di eventuali errori nel caso in cui la funzione non ha prodotto con successo la maniglia, si otterrà un errore INVALIDHANDLE. Usiamo la funzione di allarme per visualizzare l'errore utilizzando la funzione GetLastError. Si decide per memorizzare la Stop Loss e Take Profit i valori nelle variabili STP e TKP abbiamo dichiarato in precedenza. Perché stiamo facendo questo suo perché i valori memorizzati nei parametri di input sono di sola lettura, non possono essere modificati. Così qui vogliamo fare in modo che il nostro EA funziona molto bene con tutti i broker. Cifre o digit () r eturns il numero di cifre decimali che determinano l'accuratezza del prezzo del simbolo grafico corrente. Per un grafico dei prezzi a 5 cifre o 3 cifre, moltiplichiamo sia la Stop Loss e Take Profit per 10. 2.4. EA DEINTIALIZATION SEZIONE Poiché questa funzione viene chiamata ogni volta che l'EA è disabilitato o rimosso da un grafico, si rendono disponibili tutte le maniglie indicatori creati durante il processo di inizializzazione qui. Abbiamo creato due maniglie, una per ADX e un altro manico per il Moving Average dell'indicatore. Useremo la funzione IndicatorRelease () per raggiungere questo obiettivo. Ci vuole solo argomento (il manico indicatore) bool IndicatorRelease (int indicatorhandle. Indicatore maniglia) La funzione rimuove una maniglia indicatore e rilasciare il blocco di calcolo dell'indicatore, se non utilizzata. 2.5 L'onTick EA SEZIONE La prima cosa che dobbiamo fare è quello di verificare se abbiamo abbastanza bar sulla presente scheda. Siamo in grado di ottenere le barre totale nella storia di qualsiasi grafico utilizzando la funzione di Bars. Prende due parametri, il simbolo (può essere ottenuto utilizzando Simbolo o simbolo (). Questi due ritorno il simbolo corrente per il grafico corrente su cui è attaccato il nostro EA) e il periodo o intervallo di tempo della presente tabella (può essere ottenuta utilizzando Periodo o Periodo (). Questi due restituirà i tempi del grafico corrente sul quale è fissato l'EA). Se le barre totali disponibili sono meno di 60, vogliamo che il nostro EA per rilassarsi finché non avremo abbastanza bar disponibili sul grafico. La funzione di avviso viene visualizzato un messaggio in una finestra separata. Si impiegano i valori separati da virgole come parametersarguments. In questo caso, abbiamo un solo valore di stringa. Il ritorno esce l'inizializzazione del nostro EA. L'Expert Advisor eseguirà le operazioni commerciali all'inizio di una nuova barra, per cui il suo necessario per risolvere il problema con la nuova identificazione bar. In altri termini, vogliamo essere sicuri che il nostro EA non controlla per configurazioni LongShort su ogni tick, vogliamo solo la nostra EA per verificare le posizioni LongShort quando c'è un nuovo bar. Iniziamo dichiarando un datetime variabile statica oldtime. che conterrà la barra del tempo. Abbiamo dichiarato come statico perché vogliamo il valore da conservare in memoria fino al successivo richiamo della funzione onTick. Poi saremo in grado di confrontare il valore con la variabile Newtime (anche di tipo di dati datetime), che è un array di un elemento per contenere la nuova (attuale) tempo bar. Abbiamo anche dichiarato un tipo di dati bool IsNewBar variabile e imposta il suo valore su false. Questo perché vogliamo che il suo valore sia vero solo quando abbiamo un nuovo bar. Usiamo la funzione CopyTime per ottenere il tempo della barra corrente. Copia la barra del tempo al Newtime array con un elemento se è successo, si confronta il tempo di un nuovo bar con il tempo barra precedente. Se i tempi arent uguale, significa che abbiamo un nuovo bar, e noi impostare l'IsNewBar variabile su TRUE e salvare il valore del tempo barra di corrente alla oldtime variabile. La variabile IsNewBar indica che abbiamo un nuovo bar. Se il suo FALSE, terminiamo l'esecuzione della funzione di onTick. Date un'occhiata al codice verifica per l'esecuzione modalità di debug, verrà stampata il messaggio circa i tempi della barra quando la modalità di debug, si prenderà in considerazione ulteriormente. La prossima cosa che vogliamo fare qui è quello di verificare se abbiamo abbastanza bar con cui lavorare. Perché ripeterlo Vogliamo solo essere sicuri che il nostro EA funziona correttamente. Va notato che, mentre la funzione OnInit viene chiamato solo una volta quando l'EA è attaccato a un grafico, la funzione onTick viene chiamata ogni volta che c'è un nuovo tick (preventivo). Si osserva che abbiamo fatto di nuovo in modo diverso qui. Decidiamo di memorizzare le barre totale nella storia, che abbiamo ottenuto dalla espressione in una nuova variabile, Mybars. dichiarata all'interno della funzione onTick. Questo tipo di variabile è una variabile locale, a differenza della variabile abbiamo dichiarato al PARAMETRI DI INGRESSO sezione del nostro codice. Mentre le variabili, dichiarate nella sezione parametri di ingresso del nostro codice, sono a disposizione di tutte le funzioni, all'interno del nostro codice che possono avere bisogno di loro, le variabili dichiarate all'interno di una singola funzione è limitata e disponibile per solo quella funzione. Non può essere utilizzato al di fuori di tale funzione. Avanti, abbiamo dichiarato alcune variabili di tipo MQL5 struttura che verranno utilizzati in questa sezione del nostro EA. MQL5 ha un certo numero di costruito in strutture che rende le cose piuttosto facile per gli sviluppatori di EA. Consente di prendere delle Strutture uno dopo l'altro. Si tratta di una struttura utilizzata per la memorizzazione gli ultimi prezzi di simboli. struct MqlTick tempo datetime Ora degli ultimi prezzi aggiornare dell'offerta doppio prezzo di offerta corrente doppia chiedere attuale Chiedi prezzo doppio ultimo prezzo dell'ultimo contratto (Last) ulong del volume per l'attuale Ultimo prezzo Qualsiasi variabile dichiarata di tipo MqlTick può essere facilmente utilizzati per ottenere i valori correnti di Fai, Bid, Ultima e volume una volta che si chiama la funzione SymbolInfoTick (). Così abbiamo dichiarato latestprice come un tipo MqlTick in modo da poter utilizzare per ottenere i prezzi chiedere e di offerta Questa struttura viene utilizzata per eseguire tutte le richieste commerciali per un'operazione commerciale. Esso contiene, nella sua struttura, tutti i campi necessari per l'esecuzione di un accordo commerciale. struct MqlTradeRequest ENUMTRADEREQUESTACTIONS tipo di operazione azione commerciale ulong magia Expert Advisor ID (numero magico) ordine ulong Order simbolo stringa biglietto commerciale simbolo doppio volume del volume richiesto per un accordo in un sacco doppia Tariffa prezzo doppia stoplimit livello StopLimit della doppia sl livello di Stop Loss ordine del ordinare doppio livello tp Take Profit della deviazione ordine ulong massima deviazione possibile dal momento in tipo tipo prezzo richiesto ENUMORDERTYPE ordinare tipo di esecuzione ENUMORDERTYPEFILLING typefilling ordinare ENUMORDERTYPETIME typetime ordinare tempo di esecuzione datetime scadenza dell'Ordine di scadenza (per gli ordini di tipo ORDERTIMESPECIFIED) stringa di commento di commento di ordine Qualsiasi variabile dichiarata ad essere del tipo MqlTradeRequest può essere utilizzato per inviare gli ordini per le nostre operazioni commerciali. Qui abbiamo dichiarato mrequest come un tipo MqlTradeRequest. Il risultato di qualsiasi operazione di commercio viene restituito come una speciale struttura predefinita di tipo MqlTradeResult. Qualsiasi variabile dichiarata di tipo MqlTradeResult sarà in grado di accedere ai risultati di richiesta commercio. struct MqlTradeResult uint retcode Operazione codice di ritorno biglietto ulong Deal Deal, se viene eseguita biglietto ordinando ulong, se l'immagine è doppio volume del volume Deal, confermato dal mediatore di prezzo doppio prezzo Deal, confermato dal mediatore di doppia offerta prezzo di offerta corrente doppia chiedere Corrente Chiedi stringa di prezzo commento Broker commento al funzionamento (per impostazione predefinita è riempito dalla descrizione del funzionamento) The Price (Aperto, Chiuso, alto, basso), l'ora, i volumi di ogni barra e la diffusione di un simbolo viene memorizzato in questa struttura. Ogni matrice dichiarata ad essere del tipo MqlRates può essere utilizzato per memorizzare i prezzi, volumi e diffondere la storia di un simbolo. MqlRates struct tempo datetime periodo di avviamento tempo aperto del doppio prezzo di apertura a doppia altezza Il prezzo più alto del periodo di doppia volume basso Commercio lungo realvolume Il prezzo più basso del periodo di doppia chiudi chiudi prezzi a lungo tickvolume Tick volume di int diffusione Stendere qui abbiamo dichiarato mrate serie che saranno utilizzati per memorizzare queste informazioni. Successivo decidiamo di impostare tutti gli array che useremo per memorizzare Bar dettagli come serie. Questo per garantire che i valori che verranno copiati agli array saranno indicizzati come i timeseries, cioè, 0, 1, 2, 3, (per corrispondere con l'indice barre. Quindi utilizzare i ArraySetAsSeries () funzione. Bool ArraySetAsSeries (array vuoto. matrice per bool insieme di riferimento vero denota ordine inverso di indicizzazione) occorre notare che questo può anche essere fatto una volta alla sezione di inizializzazione del nostro codice. Tuttavia, ho deciso di mostrare a questo punto per amore della nostra spiegazione. ora utilizziamo la funzione SymbolInfoTick per ottenere l'ultimo preventivo. Questa funzione richiede due argomenti simbolo grafico e la variabile struttura MqlTick (latestprice). Anche in questo caso, se c'è errore, abbiamo riportato. Poi abbiamo copiato le informazioni su le ultime tre bar nel nostro tipo di matrice Mqlrates utilizzando la funzione CopyRates. la funzione CopyRates viene utilizzato per ottenere dati di storia di struttura MqlRates di un simbolo-determinato periodo in quantità specificata in una matrice di tipo MqlRates. int CopyRates (stringa symbolName. nome del simbolo ENUMTIMEFRAMES lasso di tempo. periodo Int startpos. posizione iniziale int count. conteggio dati per copiare MqlRates ratesarray matrice di destinazione per copiare) Il nome del simbolo viene ottenuta mediante simbolo. la periodtimeframe corrente è ottenuta utilizzando periodo. Per la posizione di partenza, inizieremo dalla barra corrente, Bar 0 e noi conteremo solo tre bar, 0, 1 e 2. Il risultato sarà negozio nel nostro array, mrate. L'array mrate ora contiene tutti i prezzi, il tempo, i volumi e le informazioni diffuse per bar 0. 1 e 2. Quindi per ottenere i dettagli di ogni bar, useremo il seguente: per esempio, possiamo avere le seguenti informazioni su ogni barra : mrate1.time bar 1 ora di inizio mrate1.open bar 1 Aprire prezzo mrate0.high bar 0 (barra corrente) alto prezzo, ecc Poi abbiamo, copiato tutti i valori degli indicatori nelle array dinamici abbiamo dichiarato usando la funzione CopyBuffer. int CopyBuffer (int indicatorhandle, indicatore maniglia int buffernum, indicatore numero tampone int startpos, posizione iniziale int count, pari a copiare doppia matrice di destinazione buffer per copiare) La maniglia indicatore è la maniglia abbiamo creato nella sezione OnInit. Numerazioni tampone, l'indicatore ADX ha tre (3) tamponi: L'indicatore media mobile ha un solo (1) buffer: Copiamo dal presente bar (0) per le ultime due barre. Così quantità di record da copiare è 3 (bar 0, 1 e 2). Il buffer è l'array dinamici obiettivo che avevamo in precedenza dichiarati adxVal, plsDI, Mindi e Maval. Come si può vedere di nuovo qui, cerchiamo di catturare eventuali errori che potrebbero verificarsi nel processo di copia. Se non v'è errore, non c'è bisogno di andare oltre. E 'importante notare che il CopyBuffer () e le CopyRates () restituisce il numero totale di record copiati sul successo mentre restituisce -1 in caso di un errore. È per questo che stiamo controllando per un valore inferiore a 0 (zero) nelle funzioni di controllo degli errori qui. A questo punto vogliamo verificare se abbiamo già un acquisto o di vendita posizione aperta, in altri termini, vogliamo essere sicuri di avere un solo vendere o comprare commercio aperto alla volta. Noi non vogliamo aprire un nuovo Buy se abbiamo già uno, e noi non vogliamo aprire una nuova vendita, se ne abbiamo già uno aperto. Per realizzare ci sarà prima di tutto dichiarare due variabili di tipo di dati bool (Buyopened e Sellopened) che terrà un valore TRUE se abbiamo già una posizione aperta sia per comprare o vendere. Usiamo la funzione commercio PositionSelect per sapere se abbiamo una posizione aperta. Questa funzione restituisce TRUE se abbiamo una posizione aperta e già FALSE se abbiamo nessuno. Ci vuole, come il maggiore argumentparameter, il simbolo (coppia di valute) si desidera controllare. Qui, usiamo il simbolo perché stiamo verificando il simbolo corrente (valuta-coppia). Se questa espressione restituisce TRUE, allora vogliamo verificare se la posizione aperta è un acquisto o una vendita. Usiamo la funzione PositionGetInteger per questo. ci dà il tipo di posizione aperta quando l'usiamo con il modificatore POSITIONTYPE. Restituisce il tipo di identificatore di posizione che può essere sia POSITIONTYPEBUY o POSITIONTYPESELL Nel nostro caso, abbiamo usato per determinare quale della posizione abbiamo già aperto. Se si tratta di una vendita, abbiamo memorizzare un valore TRUE in Sellopened e se si tratta di un Buy, abbiamo memorizzare un valore TRUE in Buyopened. Saremo in grado di utilizzare queste due variabili più tardi, quando stiamo controllando per vendere o comprare condizioni più avanti nel nostro codice. E 'giunto il momento di archiviare il prezzo di chiusura della barra che useremo per la nostra messa a punto BuySell. Ricordate abbiamo dichiarato una variabile per che all'inizio di aver fatto questo, avremo ora procedere alla fase successiva. E 'giunto il momento di avviare il controllo per un Buy opportunità. Analizziamo l'espressione di cui sopra in quanto rappresenta la strategia che abbiamo progettato in precedenza. Stiamo dichiara una variabile di tipo bool per ciascuno dei nostri condizioni che devono essere soddisfatte prima di un ordine può essere collocato. Una variabile di tipo bool può contenere solo TRUE o FALSE. Quindi, la nostra strategia Buy è stato suddiviso in quattro condizioni. Se una delle condizioni è soddisfatta o soddisfatto, allora un valore TRUE viene memorizzato nella nostra variabile di tipo bool, tuttavia, un valore FALSE verrà memorizzato. Vediamo uno per uno. Qui siamo di fronte a dei valori MA-8 su Bar 0, 1 e 2. Se il valore di MA-8 sulla barra corrente è superiore al suo valore sul precedente Bar 1 e anche il valore MA-8 su Bar 1 è superiore al suo valore su Bar 2. vuol dire che MA-8 è in aumento verso l'alto. Ciò soddisfa una delle nostre condizioni per una messa a punto Buy. Questa espressione è il controllo per vedere se Bar 1 prezzo di chiusura è superiore al valore di MA-8 allo stesso periodo (Bar 1 punto). Se il prezzo è più alto, allora la nostra seconda condizione è stato anche soddisfatto, quindi siamo in grado di verificare la presenza di altre condizioni. Tuttavia, se le due condizioni che abbiamo appena considerato non sono state soddisfatte, allora non ci sarà alcun bisogno di controllare le altre condizioni. È per questo che abbiamo deciso di includere i seguenti espressioni all'interno di queste due condizioni iniziali (espressioni). Ora vogliamo verificare se il valore corrente di ADX (valore ADX su Bar 0) è superiore al valore minimo ADX dichiarato nei parametri di input. Se questa espressione è vero, cioè, il valore corrente di ADX è maggiore del valore minimo richiesto vogliamo anche essere sicuri che il valore plusDI è maggiore del valore minusDI. Questo è ciò che abbiamo raggiunto nella prossima espressione Se sono soddisfatte tutte queste condizioni, cioè, se ritornano vero, allora vogliamo essere sicuri che non aprire una nuova posizione di acquisto se abbiamo già uno. E 'giunto il momento di verificare il valore della variabile Buyopened abbiamo dichiarato in precedenza nel nostro codice. Se Buyopened è vero, noi non vogliamo aprire un'altra posizione Compro, quindi, che viene visualizzato un avviso per informare noi e poi tornare in modo che il nostro EA sarà ora attendere il prossimo Tick. Tuttavia, se Buyopened è falso, allora prepariamo i nostri record utilizzando la variabile di tipo MqlTradeRequest (mrequest), che abbiamo dichiarato in precedenza per inviare il nostro ordine. L'azione qui, che è il tipo di operazione commercio, è TRADEACTIONDEAL perché stiamo mettendo un ordine commerciale per un'esecuzione immediata. Se stiamo modificando un ordine, quindi useremo TRADEACTIONMODIFY. Per eliminare un ordine useremo TRADEACTIONREMOVE. Abbiamo utilizzato il nostro tipo MqlTick latestprice per ottenere l'ultima Chiedi prezzo. L'ordine di prezzo di stop loss si ottiene sottraendo la nostra StopLoss in punti dal prezzo Chiedi mentre il prezzo profitto ordine prendere si ottiene sommando il nostro TakeProfit punti al prezzo Ask. Sarà inoltre osservare che abbiamo usato la funzione NormalizeDouble per il prezzo Chiedi, i valori StopLoss e TakeProfit, è buona pratica per normalizzare sempre questi prezzi al numero di cifre di coppia di valute prima di inviarlo al server commercio. Il simbolo è il simbolo corrente (Symbol o simbolo ()). Il tipo di ordine è il tipo di ordine che stiamo ponendo, qui stiamo mettendo un ORDERTYPEBUY ordine di acquisto. Per un ordine di vendita, sarà ORDERTYPESELL. Il typefilling ordine è il tipo di elaborazione dell'ordine ORDERFILLINGFOK significa che l'operazione può essere eseguita esclusivamente con un volume specificato al prezzo uguale o superiore al prezzo specificato ordine. Se non c'è sufficiente volume di offerte sul simbolo dell'ordine, non verrà eseguito l'ordine. La funzione OrderSend () accetta due argomenti, il tipo di variabile MqlTradeRequest e la variabile del tipo MqlTradeResult. Come potete vedere, abbiamo usato la nostra variabile di tipo MqlTradeRequest e la variabile di tipo MqlTradeResult nella effettuato il nostro ordine utilizzando OrderSend. Dopo aver inviato il nostro ordine, noi ora utilizzare la variabile di tipo MqlTradeResult per controllare il risultato del nostro ordine. Se il nostro ordine viene eseguito con successo, vogliamo essere informati, e se no, vogliamo sapere troppo. Con il tipo MqlTradeResult mresult variabile si può accedere al codice di ritorno di funzionamento e anche il numero del biglietto ordine se l'ordine viene effettuato. Il codice di ritorno 10009 dimostra che la richiesta è stata completata con successo OrderSend, mentre 10008 dimostra che il nostro ordine è stato collocato. È per questo che abbiamo controllato per uno di questi due codici di ritorno. Se abbiamo uno di essi, siamo sicuri che il nostro ordine è stato completato o è stato collocato. Per verificare la presenza di una vendita Opportunità, controlliamo per l'opposto di quello che abbiamo fatto per Acquista Opportunità tranne per la nostra ADX che deve essere maggiore del valore minimo specificato. Proprio come abbiamo fatto nella sezione affare, noi dichiariamo una variabile di tipo bool per ciascuno dei nostri condizioni che devono essere soddisfatte prima di un ordine può essere collocato. Una variabile di tipo bool può contenere solo TRUE o FALSE. Quindi, la nostra strategia di vendita è stato suddiviso in quattro condizioni. Se una delle condizioni è soddisfatta o soddisfatto, allora un valore TRUE viene memorizzato nella nostra variabile di tipo bool, tuttavia, un valore FALSE verrà memorizzato. Vediamo uno per uno, come abbiamo fatto per la sezione Buy Qui siamo di fronte a dei valori MA-8 su Bar 0, 1 e 2. Se il valore di MA-8 sulla barra corrente è inferiore al suo valore sul precedente Bar 1 e anche il valore MA-8 su Bar 1 è inferiore al suo valore su Bar 2. ciò significa che MA-8 è decrescente verso il basso. Ciò soddisfa una delle nostre condizioni per una messa a punto di vendita. This expression is checking to see if Bar 1 Close price is lower than the value of MA-8 at the same period (Bar 1 period). If the price is lower, then our second condition has also been satisfied, then we can check for other conditions. However, if the two conditions we have just considered were not met, then there will be no need to check other conditions. That is why we decide to include the next expressions within these two initial conditions (expressions). Now we want to check if the current value of ADX (ADX value on Bar 0) is greater than the Minimum ADX value declared in the input parameters. If this expression is true, that is, the current value of ADX is greater than the Minimum required value we also want to be sure that the MinusDI value is greater than the plusDI value. This is what we achieved in the next expression If these conditions are met, that is, if they return true, then we want to be sure that we do not open a new Buy position if we already have one. It is now time to check the value of the Buyopened variable we declared earlier in our code. If Sellopened is true, we do not want to open another Sell position, so, we display an alert to inform us and then return so that our EA will now wait for the next Tick. However, if Sellopened is FALSE, then we setup our Sell trade request as we did for Buying order. The major difference here is the way we calculated our stop loss price and take profit price. Also since we are selling, we sell at the Bid price that is why we used our MqlTick type variable latestprice to get the latest bid price. The other type here, as explained earlier, is ORDERTYPESELL. Also here, we used the NormalizeDouble function for the Bid price, the StopLoss and TakeProfit values, it is good practice to always normalize these prices to the number of digits of currency pair before sending it to the trade server. Just as we did for our Buy order, we must also check if our Sell order is successful or not. So we used the same expression as in our Buy order. 3. Debugging and Testing our Expert Advisor At this point, we need to test our EA to know it our strategy works or not. Also, it is possible that there are one or two errors in our EA code. This will be discovered in the next step. Debugging our code helps us to see how our code performs line by line (if we set breakpoints) and there and then we can notice any error or bug in our code and quickly make the necessary corrections before using our code in real trade. Here, we are going to go through the step by step process of debugging our Expert Advisor, first of all, by setting breakpoints and secondly, without breakpoints. To do this, Make sure you have not closed the Editor. First of all, let us select the chart we want to use to test our EA. On the Editor Menu bar, click on Tools and click on Options as shown below: Figure 8. Setting Debugging options Once the Options window appears, select the currency pair, and the periodtimeframe to use and click the OK button: Before we start the debugger, let us set breakpoints. Breakpoints allow us to monitor the behaviorperformance of our code at certain selected locations or lines. Rather than running through all the code at once, the debugger will stop whenever it see a breakpoint, waiting for your net action. By this we will be able to analyze our code and monitor its behavior as it reaches every set break-points. We will also be able to evaluate the values of some of our variables to see if things are actually the way we envisaged. To insert a breakpoint, go to the line in your code where you want to set the breakpoint. By the left hand side, on the gray field near the border of the code line, double-click and you will see a small round blue button with a white square inside it. Or on the alternative, place the cursor of your mouse anywhere on the code line where you want the breakpoint to appear and press F9 . To remove the breakpoint, press F9 again or double-click on it. Figure 10. Setting a breakpoint For our code, we are going to set breakpoint on five different lines. I will also label them form 1 to 5 for the sake of explanation. To continue, set breakpoint at the seven code lines as shown in the figure below. Breakpoint 1 is the one we have created above. Figure 11. Setting additional breakpoints Once we have finished setting our breakpoints, we are now set to start debugging our code. To start the debugger, press F5 or click the green button on the Toolbar of the MetaEditor: Figure 12. Starting the Debugger The first thing the editor does is to compile the code, if there is any error at the point, it will display it and if no error, it will let you know that the code compiled successfully. Figure 13. Compilation Report Please note that the fact that the code compiled successfully does not mean there may not be errors in your code. Depending on how your code is written, there may be runtime errors. For example, if any of our expressions does not evaluate correctly due to any little oversight, the code will compile correctly but may not run correctly. Too much of the talk, lets see it in action Once the debugger has finished compiling the code, it takes you to the trading terminal, and attach the EA to the chart you have specified on the MetaEditor Options settings. At the same time, it shows you the Input parameters section of the EA. Since we are not adjusting anything yet, just click the OK button. Figure 14. Expert Advisor Input Parameters for Debugging You will now see the EA clearly on the top-right hand corner of the chart. Once it starts the OnTick() . it will stop as soon as it gets to our breakpoint 1. Figure 15. Debugger stops at the first breakpoint You will notice a green arrow at that code line. That tells you that previous code line had been executed we are now ready to execute the present line. Let me make some explanations before we proceed. If you look at the Editors Tool Bar, you will observe that the three buttons with curved arrows which were earlier grayed out are now activated. This is because we are now running the debugger. These buttonscommands are used to step through our code (Step into, Step over or Step out) Figure 16. Step into command The Step Into is used to go from one step of the program execution into the next step, entering into any called functions within that code line. Click on the button or press F11 to invoke the command. (We will use this command in our Step-by-Step debugging of our code.) Figure 17. Step over command The Step over . on the other hand does not enter into any called function within that code line. Click on the button or press F10 to invoke the command Figure 18. Step out command To execute a program step that is one level higher, you click this button or press ShiftF11 . Also, at the lower part of the Editor, you will see the Toolbox window . The Debug tab in this window has the following headings: File : This displays the name of the file been called Function : This displays the present function from the file been called Line : This displays the number of the code line in the file from which the function is called. Expression : This is where you can type the name of any expressionvariable you are interested in monitoring from our code. Value : This will display the value of the expressionvariable we typed at the Expression area. Type : This will display the data type of the expressionvariable been monitored. Back to our debugging process The next thing we want to do is now to type in the variablesexpressions from our code that we are interested in monitoring. Make sure you only monitor the variablesexpressions that really matters in your code. For our example, we will monitor the following: OldTime (old bar time) NewTime0 (current bar time) IsNewBar (flag that indicates the new bar) Mybars (Total bars in History) Our EA depends on it You can add other ones like the ADX values, the MA-8 values, etc. To add the expressionvariable, double-click under the Expressions area or right-click under the Expressions area and select Add as shown in the figure above. Type the expressionvariable to monitor or watch. Figure 19. The expressions watching window Type all the necessary variablesexpressions Figure 20. Adding expressions or variables to watch If the variable hasnt been declared yet, its type is Unknown identifier (except the static variables). Now, lets move on Figure 21. Step into command in action Click the Step into button or press F11 and observe what happens. Keep on pressing this button or F11 until you get to breakpoint no 2 . continue until you get to breakpoint no 4 as shown below and observe the expressions watching window. Figure 22. Watching the expressions or variables Figure 23. Watching the expressions or variables Figure 24. Watching the expressions or variables Once there is a new tick, it will return to the fist code line of the OnTick() function. And all the values of our variablesexpression will now be reset because this is a new tick except if any of them is declared as a static variable. In our case we have one static variable OldTime. Figure 25. Values of variables on NewTick event To go over the process again, continue pressing the F11 key and keep monitoring the variables at the expressions watching window. You can stop the debugger and then remove all the breakpoints. As we see, in Debug mode it prints the message We have new bar here. . Figure 26. Expert Advisor prints the message in Debug mode Start the debugging process again but this time without breakpoints. Keep watching at every tick and if any of our BuySell condition is met, it will place a trade and since we have written our code to tell us if an order is placed successful or otherwise, we will see an alert. Figure 27. Expert Advisor places trade during debugging I think you can leave the EA to work for a few more minutes while you take a coffee. Once you are back and you have made some money ( just kidding ), then click the STOP (Red) button on the MetaEditor to stop debugging. Figure 28. Stopping the debugger What we have actually done here is to see that our EA only checks for a trade at the opening of a new Bar and that our EA actually works. There is still a lot of room for adjustments to our EA code. Let me make it clear, at this point that, the Trading terminal must be connected to the internet, otherwise, debugging will not work because the terminal will not be able to trade. 3.2 TESTING OUR EA STRATEGY At this point we now want to test our EA using the Strategy Tester built into the Trading Terminal. To start the Strategy Tester, press CONTROLR or click the View menu on the Terminal Menu Bar and click on Strategy Tester as shown below Figure 26. Starting the Strategy Testing The Tester (Strategy Tester) is shown at the lower part of the terminal. For you to see all the Testers settings, you need to expandresize it. To do this, move your mouse pointer to the point shown by the red arrow (as shown below) Figure 27. The Strategy Tester window The mouse pointer changes to a double-end arrow, hold down the mouse and drag the line upwards. Stop when you discover that you can see everything on the settings tab. Figure 28. The Strategy Tester Settings Tab Select the EA you want to test Select the Currency pair to use for the test Select the PeriodTimeframe to use for the test Select Custom Period and set the dates in 5 Set the dates for the custom period to be used for the test Execution is Normal Select the deposit amount in USD to be used for the test Set Optimization to Disable (We are not optimizing now, we just want to test) Click this button when you are ready to start test. Before we click the Start button, lets look at the other tabs on the Tester The processor used by the Tester for the Test. Depending on your Computers processor type. Mine is only one (1) core processor. Figure 29. The Strategy Tester Agents tab Once the agent, you will see something similar to the figure below Figure 30. The Strategy Tester Agents tab during a test This is where all the events going on during the test period is displayed Figure 31. The Strategy Tester Journal tab showing trade activities This is where you can specify the input parameters for the EA. Figure 32. The Strategy Tester Inputs tab If we are optimizing our EA, then we will need to set the values in the circled area. The Start is the values you want the Tester to begin with. The Step is the increment rate for the value you selected, and The Stop is the value at which the Tester will stop incrementing the value for that parameter. However, in our case we are not optimizing our EA, so we will not need to touch that for now. Once everything is set, we now go back to the Settings tab and click the Start button. Then the tester begins its work. All you need to do now is to go and take another cup of coffee if you like, or, if you are like me, you may want to monitor every event, then turn to the Journal tab. Once you begin to see messages about orders been sent on the Journal Tab, you may then wish to turn to a NEW tab named Graph which has just been created. Once you switch to the Graph tab, you will see the graph keep on increasing or decreasing as the case may be depending on the outcome of your trades. Figure 33. The graph result for the Expert Advisor Test Once the test is completed, you will see another tab called Results . Switch to the Results tab and you will see the summary of the test we have just carried out. Figure 34. The Strategy Tester Results tab showing test results summary You can see the total Gross Profit, Net Profit, total trades total loss trades and many more. Its really interesting to see that we have about USD 1,450.0 within the period we selected for our test. At least we have some profit. Let me make something very clear to you here. You will discover that the settings for the EA parameters that you see in the Strategy tester is different from the initial settings in the Input parameters of the EA. I have just demonstrated to you that you can change any of those input parameters to get the best out of your EA. Instead of using a period of 8 each for the Moving Average and ADX, I changed it to 10 for Moving Average and 14 for ADX. I also change the Stop Loss from 30 to 35. Last but not the least, I decided to use 2 Hour timeframe. Remember, this is the Strategy Tester. If you want to view a complete report of the test, then right-click on anywhere in the Results tab, you will see a menu. From this menu, Select Save as Report . Figure 35. Saving the result of the test The save dialog window will appear, type a name for your report (if you want, otherwise leave the default name) and click the save button. The whole report will be saved in HTML format for you. To view the chart for the test that was carried out, click Open Chart and you will see the chart displayed Figure 36. The chart showing the test Thats it, we have successfully written and tested our EA and we now have a result to work with. You can now go back to the strategy tester Settings tab and make the test for other TimeframesPeriod. I want you to carry out the test using different currency pairs, different timeframes, different Stop Loss, different Take profit and see how the EA performs. You can even try new Moving Average and ADX values. As I said earlier, that is the essence of the Strategy tester. I will also like you to share your results with me. Conclusion In this step by step guide, we have been able to look at the basic steps required in writing a simple Expert Advisor based on a developed trading strategy. We have also looked at how we check our EA for errors using the debugger. We also discussed how to test the performance of our EA using the Strategy Tester. With this, we have been able to see the power and robustness of the new MQL5 language. Our EA is not yet perfect or complete as many more adjustments must still be made in order to used it for real trading. There is still more to learn and I want you to read the article over again together with the MQL5 manual, and try everything you have learn in this article, I can assure you that you will be a great EA developer in no distant future. Forex Expert Advisor Inexperienced beginners are always interested in finding a trade robot that does all the work, so that the trader does not have to lift a finger. This idea has been pursued by all traders of the computer age. The burden of responsibility for decision making, which wears out a traders nerves, now falls squarely on the trading forex expert advisors. What is a Forex Expert Advisor The forex expert advisor is a program capable of performing in the terminal any action following the instructions of a trader, without his direct involvement. All tasks are performed automatically or mechanically, which is why the advisors are called experts or mechanical trading systems (MTS). Simply put, this is a program sending applications to a broker without any intervention on the part of the trader. You install a profit forex expert advisor to the existing forex online trading platform, which is connected to the server broker, adjust all the settings, and the advisor will begin trading according to a preset strategy. Benefits of Forex Expert Advisors From a psychological point of view, the forex expert advisor is irreplaceable. A trader decreases the responsibility for decision-making, and the trades become less stressful. The trader does not need to have an in-depth knowledge of technical and fundamental analysis, since all the calculations are already included in the program. Besides, the advisor is able to handle the trading signals even when the trader is absent from the workplace. Writing An Forex Expert Advisor Forex Expert Advisors for MetaTrader4 are written in the MQL4 programming language. This language was developed by the manufacturer of the trading terminal specifically for writing expert advisors. It allows the trader to program the trading system without any difficulty, which will trade in online mode day and night. Programmers familiar with this language will not have any difficulty in doing the job. For ordinary users this will be a more difficult task. Forex Expert Advisors Indicators You can create your own technical indicators for more effective work by the advisors. They will be a great addition to the existing indicators in the MetaTrader4 terminal. The purpose of using advisors indicators is to implement analytic functions and generate trading signals. Built-in And Own Forex Expert Advisors The MetaTrader4 trading terminal has several built-in expert advisors. They have the function of an independent trading system and dub the trading signals. They are very popular among beginners and were created specifically to demonstrate the abilities of programming the MetaTrader 4 Client Terminal. The possibilities in creating your own advisor are simply dazzling. You can set various orders by price and time, automatically open the counter orders, etc. These programs are able to replace the trader at their workplace. Testing Forex Expert Advisors The trading terminal can not only write advisors, but also check them on historical data before using, which is another unique feature of using the advisors. Testing is very useful, since it helps to measure the ability and effectiveness of a mechanical trading system on historical data, estimating the chances of future earnings and errors. If you have tested the advisor, and know how it will behave in different market conditions, you can begin trading without needing to intervene. For this purpose, the terminal has a special window where you can also optimize the input parameters of advisors. Parting Words For Beginners Beginners may think that trading with advisors is it very complicated. It is not so. After about a month any trader can begin to program their own automated trading system. Even if you are hesitant about trusting your money to a computer program, you can configure the advisor to five sound alerts, which will greatly facilitate your work so that you spend less time on graphical analysis expecting a signal to open and close positions. You can find lots of advisors on the Internet, but getting a profitable one is very difficult, and using every single one is exhausting and may result in depleting your deposit. That is why you are advised against buying the first advisor you come across. Many advisors demonstrate excellent results when tested on one currency pair, but perform poorly on others. It is better to use the advisor for those instruments that you have tested on. programma clientquot quotVIP ottenere i privilegi eccezionali per far parte del nostro programma VIP. Crea il tuo trading robot in 5 minuti, anche se si donrsquot avere competenze di programmazione stock. roboforex Accesso diretto da 100 USD al reale mercato azionario. quotRebates (Cashback) Programma quot commerciale e di ricevere sconti mensili al tuo account fino a 10 sul saldo del conto Ricevi profitto supplementare per il volume degli scambi si fanno. Rischi C'è un alto livello di rischio quando trading prodotti con leva, come ForexCFDs. Si consiglia di non rischiare più di quello che può permettersi di perdere, è possibile che si rischia di perdere l'intero importo del saldo del conto. Si consiglia di non commerciare o investire a meno che non si comprende appieno la reale portata della vostra esposizione al rischio di perdita. Quando si fa trading o investire, si deve sempre prendere in considerazione il livello della vostra esperienza. servizi di copia-negoziazione implicano rischi aggiuntivi per l'investimento a causa della natura di tali prodotti. If the risks involved seem unclear to you, please apply to an outside specialist for an independent advice. Advanced Guide To MetaTrader 4 - Expert Advisors Expert Advisor Creation Expert Advisors are programs that allow automation of the analytical and trading processes in the MT4 platform. To create an Expert Advisor (or Expert), the expert editing program - MetaEditor - has to be opened from within the MT4 platform. To open the editor (see Figure 1):13 In the Navigator window, right-click on Expert Advisors and select Create or In the Main Menu gt Tools gt MetaQuotes Language Editor or Click on the MetaEditor icon in the Standard Toolbar: or Press F4 on the computer keyboard. 13 13 Figure 1 - There are several ways to open the MetaEditor. 13Any of these actions will open the Expert Creation Wizard. The Wizard can be used to create Expert Advisors, Custom Indicators, Scripts and DLLs. To create an Expert Advisor, select Expert Advisor and click Next to continue, as shown in Figure 2. 13 Figure 2 - MT4s Expert Advisor Wizard is used to create Expert Advisors, Custom Indicators, Scripts and Libraries (DLLs). 13The General Properties of the Expert Advisor window appears. Here, traders must specify the: Name - A user-created name for the Expert. Developer - The developers name. Link - To the developers website, if applicable. Inputs - the list of Expert inputs 13 13To add a new parameter to the Inputs field, press the Add button. For each Parameter, the trader must specify the Name, Type and Initial Value, as shown in Figure 3. To delete a parameter, highlight the parameter and press Delete. These become the Input Variables within the Expert. Once all the inputs have been listed, click Finish to continue.13 Figure 3 - Create the input variables by identifying Name, Type and Initial Value. 13A new window appears in the programming environment. The Experts name appears at the top of the window, and the previously entered input parameters are listed near the top of the code, as shown in Figure 4. 13 Figure 4 - The Expert name and inputs appear in the code window. 13From here, the Expert code can be entered into the window using the MQL4 programming language and syntax (see Figure 5). Nota . Specifics regarding programming are outside the scope of this tutorial understanding programming logic and learning a specific language require significant effort. Gli operatori possono imparare di più sulla programmazione in ambiente MQL4 leggendo le MT4 Guida Guide e partecipando ai forum della community MQL4 attivi. MQL4, like other proprietary languages, has a list of Reserved Words and Standard Constants that are used during programming. Examples of constants for trade operations, along with their descriptions, include:13 OPBUY - Buying position OPSELL - Selling position OPBUYLIMIT - Buy limit pending position OPSELLLIMIT - Sell limit pending position OPBUYSTOP - Buy stop pending position OPSELLSTOP - Sell stop pending position 13 13 Figure 5 - part of the code for an Expert Advisor. Certain words have predefined uses here, OPSELL instructs the computer to sell if other criteria are met ( if statements). Traders can find a MQL4 Reference in the Help tab of the Toolbox in the MetaEditor window. This Reference includes information that is helpful to beginner and experienced programmers including: Expert Advisor Compiling After the Expert development has been completed, it must be compiled in order to ensure that the code has been written in the proper format needed to run the Expert. To compile the Expert: Select File gt Compile (see Figure 6) or Click the Compile button on the toolbar or Press F5 on the computer keyboard. 13 13Once compiling has been initiated, an update appears in the Toolbox beneath the code in the MetaEditor window, as shown in Figure 6. An errors or warnings will be listed.13 Figure 6 - Successful compiling with zero errors and zero warnings. 13After successful compilation, the new Expert will appear in the Navigator - Expert Advisors window, as shown in Figure 7. If the Expert did not compile successfully, it will still appear but its icon will be gray and the Expert cannot be used. 13 Figure 7 - The new Expert now appears in the Navigator-Expert Advisors window. Expert Advisor Setup Before the Expert can be used, its parameters must be defined in the Terminal Settings window. To open the window:13 In the Main Menu gt Tools gt Options or Pressing CTRL O on the computer keyboard. Either action will open the Options window. Select the Expert Advisors tab, as shown in Figure 8. 13 Figure 8 - Select the Expert Advisors tab in the Options window to define an Experts parameters. 13 13The following settings are available in the Expert Advisors tab: Enable Expert Advisors - this option allows the user to enable (check) or disable (uncheck) the use of all Experts. Disable experts when the account has been changed - this option disables the Expert if the account has been changes, such as from a demo to a live account. Disable experts when the profile has been changed - this option prevents Experts from launching if the profile has changed. Allow live trading - to enable Experts in real-time mode (rather than testing an Expert on historical data). Ask manual confirmation - to send trade confirmation prior to submitting the order. Allow DLL imports - to use DLLs to enhance Expert functionality. Confirm DLL function calls - to allow control over the execution of each called function. Allow external experts imports - to allow the Expert to access functions from other Experts or MQL4 libraries. 13 13Once the selections have been made, click OK to close the window. Expert Advisor Launch 13 After the Expert has been created and setup, it is ready to be launched. To launch an Expert: 13 Right-click on the Expert in the Navigator - Expert Advisors window and select Attach to a chart or13 Double-click on the Expert in the Navigator - Expert Advisors window or13 Drag-and-drop the Expert to the desired chart.13 13A window appears with Common and Inputs tabs, as shown in Figure 9. Review the settings in each tab and make any necessary changes, and then click OK to attach the Expert to the active price chart.13 Figure 9 - Make any changes to the Common and Inputs tabs before attaching the Expert to the active price chart. 13The Expert will now be attached to the price chart. Its name will appear in the upper right-hand corner of the chart. The Experts name will be followed by a smiley face, as shown in Figure 10, if live trading is enabled. Otherwise, the Experts name will appear with a frowny face, a dagger after the name indicates that all experts are disabled. 13 Figure 10 - An Expert with a smiley face indicates that live trading has been enabled. 13The Expert is now ready to begin analytical and trading functions. Expert Advisor Shutdown To shut down an Expert, it has to be removed from the chart. To remove an Expert, right-click on the active price chart, select Expert Advisors and then Remove, as shown in Figure 11. 13 Figure 11 - To remove an Expert, right-click the active price chart, select Expert Advisors from the drop-down menu, and then select Remove. Notes About Expert Advisors All Experts are shutdown if the Terminal is closed. If a chart is closed, the Expert attached to the chart will shut down as well. Adding another Expert to a chart will remove the previous one (a confirmation appears). Deleting the Expert from the Navigator window does not shut down an Expert of the same name on an active price chart. 13 13SEE: Trading Systems CodingWriting a Forex Expert Advisor Forex Expert Advisors for MetaTrader4 are written in the MQL4 software design language. This linguistic was industrialized by the constructor of the trading fatal definitely for writing forex ea . It permits the trader to plug-in the trading structure without any struggle, which will trade in online style day and night. Computer operator familiar with this linguistic will not have any trouble in doing the job. For normal users this will be an extra trying job. Forex Expert Generator is an instrument with which you can produce your own forex expert advisor for your strategy. You need to have at least MQL4 software design knowledge to use this tool. MQL4 is the software designing language that is rummage-sale to write forex expert advisors . If you are a single designer and would comparable to view the MQL4 code also for the forex ea you made, you must to purchase expert edition single certificate which is 139. If you purchase the normal edition you cannot interpretation the program. I accepted the expert version single certificate and after emerging my forex expert advisor I usually copy the code and paste it in the MQL 4 publishing superior and save it with some name, collect it and back trial it. This is a very easy tool as you dont actually essential to write the code but use the lumps on the left hand side and make your forex expert advisor . Once you collect it if there any mistakes you can see those mistakes below the Compilation tab at the lowest. If there are no mistakes you can vision the code below the tab Source Code . MT4 Expert Advisor Programming If you are a Forex trader and are in need of an experienced programmer to convert your trading strategy into an Expert Advisor (EA) then you have come to the right place. We would be happy to consider your idea and have the experience and knowledge to make it happen. Sentiti libero di contattarci in qualsiasi momento.

No comments:

Post a Comment