voglio creare un Ea per mt4 basandomi su questo indicatore
//------------------------------------------------------------------
#property copyright "copyleft malden"
#property link "www.forex-station.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 7
#property indicator_width3 3
#property indicator_width4 3
#property indicator_width5 3
#property strict
//
//
//
//
//
#define _disBar 1
#define _disLin 2
#define _disZer 4
enum enDisplayType
{
dis_01=_disLin, // Display bb stops line
dis_02=_disBar, // Display bb stops bars
dis_03=_disZer, // Display bb stops "zero" line
dis_04=_disLin+_disBar, // Display bb stops line and bars
dis_05=_disLin+_disZer, // Display bb stops line and "zero" line
dis_06=_disBar+_disZer, // Display bb stops bars and "zero" line
dis_07=_disLin+_disBar+_disZer // Display all
};
enum enPrices
{
pr_close, // Close
pr_open, // Open
pr_high, // High
pr_low, // Low
pr_median, // Median
pr_typical, // Typical
pr_weighted, // Weighted
pr_average, // Average (high+low+open+close)/4
pr_medianb, // Average median body (open+close)/2
pr_tbiased, // Trend biased price
pr_tbiased2, // Trend biased (extreme) price
pr_haclose, // Heiken ashi close
pr_haopen , // Heiken ashi open
pr_hahigh, // Heiken ashi high
pr_halow, // Heiken ashi low
pr_hamedian, // Heiken ashi median
pr_hatypical, // Heiken ashi typical
pr_haweighted, // Heiken ashi weighted
pr_haaverage, // Heiken ashi average
pr_hamedianb, // Heiken ashi median body
pr_hatbiased, // Heiken ashi trend biased price
pr_hatbiased2 // Heiken ashi trend biased (extreme) price
};
enum enMaTypes
{
ma_sma, // Simple moving average
ma_ema, // Exponential moving average
ma_smma, // Smoothed MA
ma_lwma, // Linear weighted MA
ma_tema // Triple exponential moving average - TEMA
};
extern ENUM_TIMEFRAMES TimeFrame = PERIOD_CURRENT; // Time frame
extern int BandsPeriod = 20; // Bands period
extern double BandsDeviation = 1; // Bands deviation
extern bool BandsDeviationSample = false; // Bands deviation with sample correction?
extern double BandsRisk = 1; // Bands risk
extern enMaTypes BandsMaType = ma_sma; // Bands average type
extern enPrices Price = pr_close; // Price
extern bool alertsOn = false; // Turn alerts on?
extern bool alertsOnCurrent = false; // Alerts on still opened bar?
extern bool alertsMessage = true; // Alerts should display message?
extern bool alertsSound = false; // Alerts should play a sound?
extern bool alertsNotify = false; // Alerts should send a notification?
extern bool alertsEmail = false; // Alerts should send an email?
extern string soundFile = "alert2.wav"; // Sound file
extern enDisplayType DisplayWhat = _disLin+_disBar; // Display type
extern color ColorUp = clrLimeGreen; // Color for up
extern color ColorDn = clrOrangeRed; // Color for down
extern color ColorNe = clrDarkGray; // Color for neutral and "zero" line
extern bool Interpolate = true; // Interpolate in multi time frame mode?
//
//
//
//
//
Assistant
User
io vorrei tutto il codice per intero. utilizza più messaggi se necessario
double iCustomMa(int mode, double price, double length, int r, int instanceNo=0)
{
int bars = Bars; r = bars-r-1;
switch (mode)
{
case ma_sma : return(iSma(price,(int)length,r,bars,instanceNo));
case ma_ema : return(iEma(price,length,r,bars,instanceNo));
case ma_smma : return(iSmma(price,(int)length,r,bars,instanceNo));
case ma_lwma : return(iLwma(price,(int)length,r,bars,instanceNo));
case ma_tema : return(iTema(price,(int)length,r,bars,instanceNo));
default : return(price);
}
}
//
//
//
//
//
double workSma[][_maWorkBufferx2];
double iSma(double price, int period, int r, int _bars, int instanceNo=0)
{
if (ArrayRange(workSma,0)!= _bars) ArrayResize(workSma,_bars); instanceNo *= 2; int k;
double workEma[][_maWorkBufferx1];
double iEma(double price, double period, int r, int _bars, int instanceNo=0)
{
if (ArrayRange(workEma,0)!= _bars) ArrayResize(workEma,_bars);
double workSmma[][_maWorkBufferx1];
double iSmma(double price, double period, int r, int _bars, int instanceNo=0)
{
if (ArrayRange(workSmma,0)!= _bars) ArrayResize(workSmma,_bars);
double workLwma[][_maWorkBufferx1];
double iLwma(double price, double period, int r, int _bars, int instanceNo=0)
{
if (ArrayRange(workLwma,0)!= _bars) ArrayResize(workLwma,_bars);
workLwma[r][instanceNo] = price; if (period<=1) return(price);
double sumw = period;
double sum = period*price;
double iTema(double price, double period, int r, int bars, int instanceNo=0)
{
if (period<=1) return(price);
if (ArrayRange(workTema,0)!= bars) ArrayResize(workTema,bars); instanceNo*=3;
#define _devInstances 1
double workDev[][_devInstances];
double iDeviation(double value, int length, bool isSample, int i, int instanceNo=0)
{
if (ArrayRange(workDev,0)!=Bars) ArrayResize(workDev,Bars); i=Bars-i-1; workDev[i][instanceNo] = value;
#define priceInstances 1
double workHa[][priceInstances4];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int instanceNo=0)
{
if (tprice>=pr_haclose)
{
if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars); instanceNo=4;
int r = Bars-i-1;
code
//
//
//
//
//
double haOpen;
if (r>0)
haOpen = (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0;
else haOpen = (open[i]+close[i])/2;
double haClose = (open[i] + high[i] + low[i] + close[i]) / 4.0;
double haHigh = MathMax(high[i], MathMax(haOpen,haClose));
double haLow = MathMin(low[i] , MathMin(haOpen,haClose));
if(haOpen <haClose) { workHa[r][instanceNo+0] = haLow; workHa[r][instanceNo+1] = haHigh; }
else { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow; }
workHa[r][instanceNo+2] = haOpen;
workHa[r][instanceNo+3] = haClose;
//
//
//
//
//
switch (tprice)
{
case pr_haclose: return(haClose);
case pr_haopen: return(haOpen);
case pr_hahigh: return(haHigh);
case pr_halow: return(haLow);
case pr_hamedian: return((haHigh+haLow)/2.0);
case pr_hamedianb: return((haOpen+haClose)/2.0);
case pr_hatypical: return((haHigh+haLow+haClose)/3.0);
case pr_haweighted: return((haHigh+haLow+haClose+haClose)/4.0);
case pr_haaverage: return((haHigh+haLow+haClose+haOpen)/4.0);
case pr_hatbiased:
if (haClose>haOpen)
return((haHigh+haClose)/2.0);
else return((haLow+haClose)/2.0);
case pr_hatbiased2:
if (haClose>haOpen) return(haHigh);
if (haClose<haOpen) return(haLow);
return(haClose);
}
}
//
//
//
//
//
switch (tprice)
{
case pr_close: return(close[i]);
case pr_open: return(open[i]);
case pr_high: return(high[i]);
case pr_low: return(low[i]);
case pr_median: return((high[i]+low[i])/2.0);
case pr_medianb: return((open[i]+close[i])/2.0);
case pr_typical: return((high[i]+low[i]+close[i])/3.0);
case pr_weighted: return((high[i]+low[i]+close[i]+close[i])/4.0);
case pr_average: return((high[i]+low[i]+close[i]+open[i])/4.0);
case pr_tbiased:
if (close[i]>open[i])
return((high[i]+close[i])/2.0);
else return((low[i]+close[i])/2.0);
case pr_tbiased2:
if (close[i]>open[i]) return(high[i]);
if (close[i]<open[i]) return(low[i]);
return(close[i]);
}
return(0);
}
voglio che vengano utilizzate 2 versioni, una a 4h e una a 15m.
buy: 4h verde e appena la 15m diventa verde si apre la posizione
sell: il contrario
L'Ea deve utilizzarli entrambi in modalità TEMA
Creare un Expert Advisor (EA) in MetaTrader 4 basato su un indicatore personalizzato richiede diversi passaggi. Dovrai utilizzare il linguaggio di programmazione MQL4 per implementare la logica di trading desiderata, che in questo caso si basa sull'indicatore fornito nel tuo codice sorgente. Ecco una guida passo-passo per aiutarti a creare l'EA:
Comprendere l'indicatore: La parte di codice che hai fornito è un indicatore basato sulle BB Stops. Hai bisogno di due istanze dell'indicatore: una configurata su H4 e un'altra su M15. Entrambe devono utilizzare la media mobile TEMA.
Creazione di un nuovo EA: In MetaEditor, crea un nuovo Expert Advisor. Questo genererà automaticamente una struttura di base per il tuo EA.
Aggiungi l'indicatore al tuo EA:
Usa la funzione iCustom per accedere ai valori delle diverse istanze del tuo indicatore personalizzato.
Assicurati di passare i parametri corretti per ottenere il buffer che indica il trend (ad esempio, il buffer "trend" nell'indicatore che restituisce 1 o -1).
Struttura del Codice dell'EA:
Nelle funzioni OnInit(), OnDeinit(), e OnTick(), inserisci la logica di avvio, arresto e il nucleo dell'EA, rispettivamente.
Implementazione della Logica di Trading:
Nel metodo OnTick(), controlla lo stato dei due timeframe:
Carica i valori del trend dell'indicatore per entrambi i timeframe (H4 e M15) usando iCustom.
Implementa la logica di compravendita: se la condizione per l'apertura di una posizione long (4H verde e 15m diventa verde) o short (4H rosso e 15m diventa rosso) è soddisfatta, apri le posizioni di conseguenza.
Ecco un esempio di codice di base per l'EA:
mql4
//+------------------------------------------------------------------+
//| BB EA.mq4 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| www.metaquotes.net |
//+------------------------------------------------------------------+
#property strict
// Define input parameters for external settings
extern int buyOrderMagicNumber = 12345;
extern int sellOrderMagicNumber = 12346;
// Define indicator settings
ENUM_TIMEFRAMES H4_Timeframe = PERIOD_H4;
ENUM_TIMEFRAMES M15_Timeframe = PERIOD_M15;
int BandsPeriod = 20;
double BandsDeviation = 1;
bool BandsDeviationSample = false;
double BandsRisk = 1;
enMaTypes BandsMaType = ma_tema;
enPrices Price = pr_close;
string indicatorName = "YOUR_CUSTOM_INDICATOR_NAME";
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialization
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Deinitialize
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Fetch indicator values
double trendH4 = iCustom(NULL, H4_Timeframe, indicatorName, BandsPeriod, BandsDeviation, BandsDeviationSample, BandsRisk, BandsMaType, Price, /* others */, 11, 0);
double trendM15 = iCustom(NULL, M15_Timeframe, indicatorName, BandsPeriod, BandsDeviation, BandsDeviationSample, BandsRisk, BandsMaType, Price, /* others */, 11, 0);
// Implement buy logic
if (trendH4 == 1 && trendM15 == 1 && trendM15Prev != 1)
{
// Open buy order if no open orders
if (!orderExists(buyOrderMagicNumber))
{
openBuyOrder();
}
}
// Implement sell logic
if (trendH4 == -1 && trendM15 == -1 && trendM15Prev != -1)
{
// Open sell order if no open orders
if (!orderExists(sellOrderMagicNumber))
{
openSellOrder();
}
}
// Store previous M15 trend
trendM15Prev = trendM15;
}
//+------------------------------------------------------------------+
//| Open a buy order |
//+------------------------------------------------------------------+
void openBuyOrder()
{
// Code to open a buy order
}
//+------------------------------------------------------------------+
//| Open a sell order |
//+------------------------------------------------------------------+
void openSellOrder()
{
// Code to open a sell order
}
//+------------------------------------------------------------------+
//| Order existence check |
//+------------------------------------------------------------------+
bool orderExists(int magicNumber)
{
// Iterate through orders and return true if an order exists with the specified magic number
return false;
}
Questo codice è un punto di partenza ed è necessario completarlo con la logica che gestisce l'apertura e il controllo degli ordini, nonché eventuali altre cautele della gestione del rischio. Considera anche di aggiungere protezioni contro le condizioni di mercato avverse e test accurati su un conto demo prima di utilizzare il tuo EA in un ambiente di trading live.
Creare un Expert Advisor completo per MT4, basato su un indicatore personalizzato come quello che hai fornito, richiede attenzione ad alcuni dettagli di programmazione e una buona comprensione delle funzioni di trading di MQL4. Qui di seguito ti fornirò il codice completo diviso in sezioni per facilitarne la comprensione e l'implementazione. Assicurati di sostituire "YOUR_CUSTOM_INDICATOR_NAME" con il nome effettivo del file dell'indicatore (es: "BB_stops_indicator" se hai salvato l'indicatore come BB_stops_indicator.ex4).
1. Impostazione di Base dell'EA
mql4
//+------------------------------------------------------------------+
//| BB_EA.mq4 |
//| Copyright 2023, Your Name |
//| yourwebsite.com |
//+------------------------------------------------------------------+
#property strict
// Define magic numbers for identifying orders specific to this EA
#define BUY_MAGIC_NUMBER 12345
#define SELL_MAGIC_NUMBER 12346
// Input parameters for indicator settings
extern int BandsPeriod = 20;
extern double BandsDeviation = 1;
extern bool BandsDeviationSample = false;
extern double BandsRisk = 1;
extern enMaTypes BandsMaType = ma_tema;
extern enPrices Price = pr_close;
// Configure the timeframes for the indicator
extern ENUM_TIMEFRAMES H4_Timeframe = PERIOD_H4;
extern ENUM_TIMEFRAMES M15_Timeframe = PERIOD_M15;
// Custom indicator buffer indices for trend detection
#define TREND_BUFFER_INDEX 11
// Store previous trends for logic
double prevTrendM15 = 0.0;
// Define indicator file name (ensure this matches your .ex4 file)
string indicatorName = "YOUR_CUSTOM_INDICATOR_NAME";
2. Funzioni di Inizializzazione e Disabilitazione
mql4
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Initialize indicator settings or other global settings if needed
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Cleanup resources such as closing files or releasing handles if needed
}
3. Funzione principale OnTick()
mql4
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Fetch the current trend from both timeframes
double trendH4 = iCustom(NULL, H4_Timeframe, indicatorName, BandsPeriod, BandsDeviation,
BandsDeviationSample, BandsRisk, BandsMaType, Price, TREND_BUFFER_INDEX, 0);
double trendM15 = iCustom(NULL, M15_Timeframe, indicatorName, BandsPeriod, BandsDeviation,
BandsDeviationSample, BandsRisk, BandsMaType, Price, TREND_BUFFER_INDEX, 0);
// Implement buy logic: H4 is green (1) and M15 turns green (1)
if (trendH4 == 1 && trendM15 == 1 && prevTrendM15 != 1)
{
// Check if there are no existing buy orders
if (!orderExists(BUY_MAGIC_NUMBER))
{
openBuyOrder();
}
}
// Implement sell logic: H4 is red (-1) and M15 turns red (-1)
if (trendH4 == -1 && trendM15 == -1 && prevTrendM15 != -1)
{
// Check if there are no existing sell orders
if (!orderExists(SELL_MAGIC_NUMBER))
{
openSellOrder();
}
}
// Update the previous M15 trend for the next tick
prevTrendM15 = trendM15;
}
4. Funzioni di Gestione degli Ordini
mql4
//+------------------------------------------------------------------+
//| Open a buy order |
//+------------------------------------------------------------------+
void openBuyOrder()
{
// Define lot size, stop loss, and take profit as needed
double lotSize = 0.1;
double stopLoss = 0; // Set your stop loss value
double takeProfit = 0; // Set your take profit value
// Attempt to open a buy order
if (OrderSend(Symbol(), OP_BUY, lotSize, Ask, 2, stopLoss, takeProfit, "Buy Order", BUY_MAGIC_NUMBER, 0, clrGreen) < 0)
{
Print("Error opening buy order: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Open a sell order |
//+------------------------------------------------------------------+
void openSellOrder()
{
// Define lot size, stop loss, and take profit as needed
double lotSize = 0.1;
double stopLoss = 0; // Set your stop loss value
double takeProfit = 0; // Set your take profit value
// Attempt to open a sell order
if (OrderSend(Symbol(), OP_SELL, lotSize, Bid, 2, stopLoss, takeProfit, "Sell Order", SELL_MAGIC_NUMBER, 0, clrRed) < 0)
{
Print("Error opening sell order: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Check if an order exists |
//+------------------------------------------------------------------+
bool orderExists(int magicNumber)
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderMagicNumber() == magicNumber && OrderSymbol() == Symbol())
{
return true;
}
}
}
return false;
}
Considerazioni finali
Questo codice assume che non ci siano altri EA o ordini manuali che interferiscono con le posizioni attualmente gestite.
Dovresti personalizzare i valori di stopLoss, takeProfit e lotSize in base alla tua gestione del rischio.
Assicurati di fare dei test approfonditi su un conto demo prima di utilizzare l'EA su un conto reale per evitare perdite non intenzionali.
Puoi anche implementare ulteriori funzioni di controllo come la gestione del rischio, la chiusura delle posizioni in determinate condizioni, o notifiche per avvisarti quando viene aperta una posizione.