voglio che scrivi il codice di un EA per mt4 che utilizza iSar su più timeframe.
regole del buy
prezzo > iSar 4h
prezzo > iSar 1h
appena prezzo diventa > iSar 15M (corrente) scatta il buy. 1 solo ogni volta che il prezzo passa considerando le condizioni precedenti.
per il SELL il contrario
stop loss e take profit da impostare con input
Assistant
User
no così apre una posizione ogni tick in cui è vera la condizione. deve aprire una posizione quando il prezzo passa da sotto a sopra iSAR 15m.
Assistant
User
io credo sarebbe meglio usare solo valori di barre chiuse (shift 1)
Assistant
User
ci deve essere un errore con i shift perchè non apre più nesuna posizione
Assistant
Certamente! Creare un Expert Advisor (EA) per MetaTrader 4 utilizzando il Parabolic SAR (iSAR) su più timeframe è un compito interessante. Ti fornirò un esempio di codice che segue le regole che hai descritto. Questo EA aprirà una posizione Buy quando il prezzo supera il livello dell'indicatore Parabolic SAR su tre timeframe differenti (4H, 1H, 15M), e una posizione Sell in caso contrario. Gli input per lo Stop Loss (SL) e il Take Profit (TP) sono inclusi.
cpp
//+------------------------------------------------------------------+
//| MultiTFsSAR.mq4 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property strict
// Input parameters for Stop Loss and Take Profit
input double StopLoss = 50; // Stop Loss in pips
input double TakeProfit = 100; // Take Profit in pips
// Global variables
double sar4H, sar1H, sar15M;
bool buyOn = false;
bool sellOn = false;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialization
buyOn = false;
sellOn = false;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Cleanup code can go here
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate SAR values for different timeframes
sar4H = iSAR(NULL, PERIOD_H4, 0.02, 0.2, 0);
sar1H = iSAR(NULL, PERIOD_H1, 0.02, 0.2, 0);
sar15M = iSAR(NULL, PERIOD_M15, 0.02, 0.2, 0);
double currentPrice = iClose(NULL, PERIOD_M15, 0);
// Buy condition
if (currentPrice > sar4H && currentPrice > sar1H && currentPrice > sar15M && !buyOn)
{
// Open a buy order
OpenOrder(OP_BUY);
buyOn = true;
sellOn = false;
}
// Sell condition
if (currentPrice < sar4H && currentPrice < sar1H && currentPrice < sar15M && !sellOn)
{
// Open a sell order
OpenOrder(OP_SELL);
sellOn = true;
buyOn = false;
}
}
//+------------------------------------------------------------------+
//| Function to open a new order |
//+------------------------------------------------------------------+
void OpenOrder(int orderType)
{
double lotSize = 0.1; // Define your lot size
double slippage = 3; // Slippage in pips
double price, sl, tp;
if (orderType == OP_BUY)
{
price = Ask;
sl = price - StopLoss * Point;
tp = price + TakeProfit * Point;
}
else if (orderType == OP_SELL)
{
price = Bid;
sl = price + StopLoss * Point;
tp = price - TakeProfit * Point;
}
else
return;
int ticket = OrderSend(Symbol(), orderType, lotSize, price, slippage, sl, tp, "", 0, 0, clrGreen);
if (ticket < 0)
Print("OrderSend failed with error #", GetLastError());
else
Print("OrderSend succeeded with ticket #", ticket);
}
//+------------------------------------------------------------------+
Note:
Lot Size: Modifica il valore di lotSize nel codice in funzione delle tue esigenze.
Slippage: Puoi aggiustare il valore dello slippage slippage.
Gestione degli errori: Considera di migliorare la gestione degli errori per situazioni reali.
Assicurati di testare questo EA in un ambiente demo prima di utilizzarlo in live trading. Verifica che i parametri di input, come Stop Loss e Take Profit, siano adatti al tuo stile di trading e alla volatilità del mercato.
Capisco, desideri aprire una posizione solo quando c'è un passaggio netto del prezzo da sotto a sopra il Parabolic SAR su timeframe di 15 minuti, dopo che le condizioni sugli altri timeframe sono soddisfatte. Dobbiamo quindi assicurare che una posizione venga aperta solo quando c'è un cambio di condizione.
Per fare ciò, memorizzeremo lo stato precedente del prezzo rispetto al SAR sul timeframe di 15 minuti, e apriremo una posizione solo se quel passaggio avviene. Ecco come puoi modificare il codice per ottenere questo comportamento:
cpp
//+------------------------------------------------------------------+
//| MultiTFsSAR.mq4 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property strict
// Input parameters for Stop Loss and Take Profit
input double StopLoss = 50; // Stop Loss in pips
input double TakeProfit = 100; // Take Profit in pips
// Global variables
double sar4H, sar1H, sar15M;
bool wasBelow15M = false;
bool wasAbove15M = false;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialization
wasBelow15M = false;
wasAbove15M = false;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Cleanup code can go here
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate SAR values for different timeframes
sar4H = iSAR(NULL, PERIOD_H4, 0.02, 0.2, 0);
sar1H = iSAR(NULL, PERIOD_H1, 0.02, 0.2, 0);
sar15M = iSAR(NULL, PERIOD_M15, 0.02, 0.2, 0);
double currentPrice = iClose(NULL, PERIOD_M15, 0);
// Logic for Buy condition
bool currentBelow15M = currentPrice < sar15M;
if (currentPrice > sar4H && currentPrice > sar1H && !currentBelow15M && wasBelow15M)
{
// Open a buy order
OpenOrder(OP_BUY);
wasBelow15M = false; // Reset the flag
}
if (currentBelow15M)
{
wasBelow15M = true;
}
// Logic for Sell condition
bool currentAbove15M = currentPrice > sar15M;
if (currentPrice < sar4H && currentPrice < sar1H && !currentAbove15M && wasAbove15M)
{
// Open a sell order
OpenOrder(OP_SELL);
wasAbove15M = false; // Reset the flag
}
if (currentAbove15M)
{
wasAbove15M = true;
}
}
//+------------------------------------------------------------------+
//| Function to open a new order |
//+------------------------------------------------------------------+
void OpenOrder(int orderType)
{
double lotSize = 0.1; // Define your lot size
double slippage = 3; // Slippage in pips
double price, sl, tp;
if (orderType == OP_BUY)
{
price = Ask;
sl = price - StopLoss * Point;
tp = price + TakeProfit * Point;
}
else if (orderType == OP_SELL)
{
price = Bid;
sl = price + StopLoss * Point;
tp = price - TakeProfit * Point;
}
else
return;
int ticket = OrderSend(Symbol(), orderType, lotSize, price, slippage, sl, tp, "", 0, 0, clrGreen);
if (ticket < 0)
Print("OrderSend failed with error #", GetLastError());
else
Print("OrderSend succeeded with ticket #", ticket);
}
//+------------------------------------------------------------------+
Modifiche apportate:
Stato precedente: Utilizzo delle variabili wasBelow15M e wasAbove15M per tracciare lo stato precedente del prezzo rispetto al SAR sul timeframe di 15 minuti.
Condizione di attraversamento: Si verifica un'attraversamento netto quando il prezzo cambia stato rispetto al SAR dopo aver soddisfatto le condizioni sugli altri timeframe.
Questo dovrebbe prevenire aperture multiple di posizioni su ogni tick e rispettare il comportamento desiderato quando c'è un passaggio netto del prezzo rispetto al SAR su 15 minuti. Ricorda sempre di testare accuratamente questo EA in un ambiente demo.
Utilizzare i valori delle barre chiuse è una buona pratica quando si implementano strategie di trading automatizzato, perché ciò riduce il rumore del mercato e le false segnalazioni dovute a fluttuazioni temporanee del prezzo.
Vediamo come modificare il codice per utilizzare i valori delle barre chiuse (shift 1) per il calcolo del Parabolic SAR e del prezzo di chiusura:
cpp
//+------------------------------------------------------------------+
//| MultiTFsSAR.mq4 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property strict
// Input parameters for Stop Loss and Take Profit
input double StopLoss = 50; // Stop Loss in pips
input double TakeProfit = 100; // Take Profit in pips
// Global variables
bool wasBelow15M = false;
bool wasAbove15M = false;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialization
wasBelow15M = false;
wasAbove15M = false;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Cleanup code can go here
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate SAR values for different timeframes using closed bars
double sar4H = iSAR(NULL, PERIOD_H4, 0.02, 0.2, 1);
double sar1H = iSAR(NULL, PERIOD_H1, 0.02, 0.2, 1);
double sar15M = iSAR(NULL, PERIOD_M15, 0.02, 0.2, 1);
// Get previous (closed) price for 15M
double prevClose15M = iClose(NULL, PERIOD_M15, 1);
// Logic for Buy condition
bool wasBelow = prevClose15M < sar15M;
bool currentAbove = iClose(NULL, PERIOD_M15, 0) > sar15M;
if (iClose(NULL, PERIOD_H4, 1) > sar4H && iClose(NULL, PERIOD_H1, 1) > sar1H && currentAbove && wasBelow)
{
// Open a buy order
OpenOrder(OP_BUY);
wasBelow15M = false; // Reset the flag
}
// Logic for Sell condition
bool wasAbove = prevClose15M > sar15M;
bool currentBelow = iClose(NULL, PERIOD_M15, 0) < sar15M;
if (iClose(NULL, PERIOD_H4, 1) < sar4H && iClose(NULL, PERIOD_H1, 1) < sar1H && currentBelow && wasAbove)
{
// Open a sell order
OpenOrder(OP_SELL);
wasAbove15M = false; // Reset the flag
}
}
//+------------------------------------------------------------------+
//| Function to open a new order |
//+------------------------------------------------------------------+
void OpenOrder(int orderType)
{
double lotSize = 0.1; // Define your lot size
double slippage = 3; // Slippage in pips
double price, sl, tp;
if (orderType == OP_BUY)
{
price = Ask;
sl = price - StopLoss * Point;
tp = price + TakeProfit * Point;
}
else if (orderType == OP_SELL)
{
price = Bid;
sl = price + StopLoss * Point;
tp = price - TakeProfit * Point;
}
else
return;
int ticket = OrderSend(Symbol(), orderType, lotSize, price, slippage, sl, tp, "", 0, 0, clrGreen);
if (ticket < 0)
Print("OrderSend failed with error #", GetLastError());
else
Print("OrderSend succeeded with ticket #", ticket);
}
//+------------------------------------------------------------------+
Modifiche apportate:
Valore delle candele chiuse: Utilizziamo iSAR e iClose con lo shift 1 per ottenere il valore del Parabolic SAR e del prezzo di chiusura dalla candela chiusa precedente per le condizioni su 4H, 1H e 15M.
Verifica del cross: Confrontiamo prevClose15M con sar15M per stabilire se c'era un passaggio (sotto a sopra) per l'apertura di un ordine di acquisto, e viceversa per la vendita.
Queste modifiche dovrebbero garantire che le operazioni vengano aperte solo ad ogni cambio di condizione basato su candele chiuse, minimizzando l'impatto della volatilità intra-barra. Assicurati di eseguire test su un conto demo prima di implementare questi cambiamenti nel trading reale.
Assicurati che il codice stia utilizzando correttamente i valori delle candele chiuse per determinare i segnali di trading. Inoltre, controlla bene l'uso degli indici per l'accesso ai dati delle barre precedenti. Di seguito ti fornisco un esempio rivisto, cercando di correggere eventuali errori nei calcoli degli indici e delle condizioni di ordine.
cpp
//+------------------------------------------------------------------+
//| MultiTFsSAR.mq4 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property strict
// Input parameters for Stop Loss and Take Profit
input double StopLoss = 50; // Stop Loss in pips
input double TakeProfit = 100; // Take Profit in pips
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Cleanup code can go here
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate SAR values for different timeframes using closed bars
double sar4H = iSAR(NULL, PERIOD_H4, 0.02, 0.2, 1);
double sar1H = iSAR(NULL, PERIOD_H1, 0.02, 0.2, 1);
double sar15M = iSAR(NULL, PERIOD_M15, 0.02, 0.2, 1);
// Get previous closed price for 15M
double prevClose15M = iClose(NULL, PERIOD_M15, 1);
double currentClose15M = iClose(NULL, PERIOD_M15, 0);
// Logic for Buy condition
bool wasBelow = prevClose15M < sar15M;
if (iClose(NULL, PERIOD_H4, 1) > sar4H && iClose(NULL, PERIOD_H1, 1) > sar1H && currentClose15M > sar15M && wasBelow)
{
// Open a buy order
OpenOrder(OP_BUY);
}
// Logic for Sell condition
bool wasAbove = prevClose15M > sar15M;
if (iClose(NULL, PERIOD_H4, 1) < sar4H && iClose(NULL, PERIOD_H1, 1) < sar1H && currentClose15M < sar15M && wasAbove)
{
// Open a sell order
OpenOrder(OP_SELL);
}
}
//+------------------------------------------------------------------+
//| Function to open a new order |
//+------------------------------------------------------------------+
void OpenOrder(int orderType)
{
double lotSize = 0.1; // Define your lot size
double slippage = 3; // Slippage in pips
double price, sl, tp;
if (orderType == OP_BUY)
{
price = Ask;
sl = price - StopLoss * Point;
tp = price + TakeProfit * Point;
}
else if (orderType == OP_SELL)
{
price = Bid;
sl = price + StopLoss * Point;
tp = price - TakeProfit * Point;
}
else
return;
int ticket = OrderSend(Symbol(), orderType, lotSize, price, slippage, sl, tp, "", 0, 0, clrGreen);
if (ticket < 0)
Print("OrderSend failed with error #", GetLastError());
else
Print("OrderSend succeeded with ticket #", ticket);
}
//+------------------------------------------------------------------+
Considerazioni:
Indice di barra chiusa: Quando utilizziamo iSAR e iClose con uno shift di 1, ci riferiamo alla barra chiusa precedente.
Condizioni per il trade: Il prezzo chiude sopra o sotto iSAR di 15 minuti solo se il prezzo chiuso precedente era sotto/sopra il rispettivo valore SAR. Questo controllo dovrebbe gestire correttamente il "passaggio" netto del prezzo rispetto a SAR.
Testing: Testa questo EA con attenzione in un ambiente demo per garantire che funzioni come previsto.
Se questo ancora non funziona come previsto, assicurati che ci siano abbastanza dati disponibili in MetaTrader per i calcoli dei timeframe più lunghi e verifica se ci sono errori nei registri di MetaTrader che chiariscano ulteriormente il problema.