si può dire che la strategia diquesto EA per mt4 sia mean reverse?…
- User
si può dire che la strategia diquesto EA per mt4 sia mean reverse? //+----------------------------------------------------------------------------------------------------------+// // // // ██ ██ ████████ ████████ ██ ███████ ███████ ████████ █████ ██████ ███████ █████ // // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ // // ██ ██ ██ ██ ██ █████ ███████ ██ ███████ ██████ █████ ███████ // // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ // // ███████ ██ ██ ██ ███████ ███████ ███████ ██ ██ ██ ██ ██ ███████ ██ ██ // // // //+----------------------------------------------------------------------------------------------------------+//
#property copyright "Little Star EA"; #property version "1.00"; #property strict
#import "kernel32.dll"
int CreateFileW(string,int,int,int,int,int,int); int GetFileSize(int,int); int SetFilePointer(int,int,int&,int); int ReadFile(int,uchar&[],int,int&[],int); int CloseHandle(int);
#import //extern string INFO1=""; //===== LOTS SECTION ======================= extern int MagicID = 260289; extern double FixedLot = 0.01; extern int AutoLot = 1; extern double StopLoss = 200; extern double TakeProfit = 10; extern int MaxOrders = 10;
//extern string INFO2=""; //===== FILTERS SECTION ======================= extern int WPR_Period = 450; extern int HST_Period = 240; extern int Volume_Filter_Period = 15;
extern bool Conservative_Mode = true; extern double RangeFilter = 0.4;
/////////////////funzioni da codificare per future versioni //extern string INFO3=""; //===== ATR SECTION ========================= extern bool ATR_StopLoss = true; extern double ATR_StopLoss_Value = 20;
//valore da moltiplicare per ATR extern bool ATR_TakeProfit = true; extern double ATR_TakeProfit_value = 10;
//valore da moltiplicare per ATR//extern string INFO4=""; //===== TRAILING STOP SECTION =============== input bool Trailing_Stop_ON=true; input double TrailingStop = 10; extern int TrailingStep = 1; //////////////////////////////////////
union Price { public: uchar bytes[8]; double value; };
double pointValue; int slippage; int fileHandle; long lastTickTime; long currentBarVolume; bool isHistoryDataAvailable; int recordsCount; int isValidData; double filteredPriceRange; int validDaysCount; int currentBar; double medianFilteredPriceRange; int Gi_0000F; //da rinominare int ordersNumber; int buyOrdersCounter; int sellOrdersCounter; double lotSize; double minLot; double maxLot; int openOrder; string historyBarTimestamp; uchar timestamp0; uchar timestamp1; uchar timestamp2; uchar timestamp3; uchar timestamp4; uchar timestamp5; uchar timestamp6; uchar timestamp7; double priceHistory[][2];
Price historyBarValue;
bool order_check;
int init() { string historyFilePath; int currentHistoryIndex; string accountInfo;
slippage = 3; recordsCount = 0; pointValue = 0; openOrder = 0; lastTickTime = 0;
if (IsDllsAllowed() != true) { Alert("Make Sure DLL Import is Allowed"); ExpertRemove(); currentHistoryIndex = 1; return currentHistoryIndex; }
pointValue = _Point; if (_Digits == 5 || _Digits == 3) {
pointValue = (pointValue * 10); slippage = slippage * 10; } ChartSetInteger(0, 17, 0, 0); ChartSetInteger(0, 0, 1); accountInfo = AccountInfoString(3); if (accountInfo == "") { accountInfo = "default"; } historyFilePath = TerminalInfoString(3); historyFilePath = historyFilePath + "\history\"; historyFilePath = historyFilePath + accountInfo; historyFilePath = historyFilePath + "\"; historyFilePath = historyFilePath + _Symbol; historyFilePath = historyFilePath + IntegerToString(HST_Period); historyFilePath = historyFilePath + ".hst"; historyRead(historyFilePath); currentHistoryIndex = 0;
return currentHistoryIndex; }
//+------------------------------------------------------------------+ //| counter ordini totali | //+------------------------------------------------------------------+ int countTotalOrders() { int totalOrdersCount = 0; int ordersCounter = OrdersTotal() - 1;
// Ciclo attraverso tutti gli ordini while (ordersCounter >= 0) { if (OrderSelect(ordersCounter, SELECT_BY_POS)) { if (OrderMagicNumber() == MagicID && OrderSymbol() == _Symbol) { // Se l’ordine corrisponde al MagicID e al Symbol, incrementa il contatore totalOrdersCount++; } } ordersCounter--; } return totalOrdersCount;} //+------------------------------------------------------------------+
void OnTick() { string orderComment; string buySignalMessage; string sellSignalMessage; int currentHistoryIndex; int openOrderIndex; double williamPRange; double awesomeOscillator; double stopLoss; double takeProfit; double historyPriceLevel;
/////////////////richiamo funzione counter ordini totali
int totalOrders = countTotalOrders(); ///////////////////////// Gestisce il trailing stop per ordini aperti ManageTrailingStop();
if (lastTickTime == Time[0]) return; // Controlla se l’ultimo tick processato è lo stesso del tick corrente per evitare duplicati lastTickTime = Time[0]; // Aggiorna il tempo dell’ultimo tick processato
ChartRedraw(0); // Ricalcola il grafico per assicurare che i dati visualizzati siano aggiornati
currentBarVolume = iVolume(_Symbol, Volume_Filter_Period, 0); // Recupera il volume dell’ultima barra sul timeframe corrente e lo confronta con quello della barra precedente if (currentBarVolume > iVolume(_Symbol, Volume_Filter_Period, 1)) return; // Se il volume dell’ultima barra è superiore a quello della barra precedente, esce (potenziale segnale di volatilità) if (recordsCount <= 0) return; // Esci se non ci sono record storici disponibili per l’analisi
currentHistoryIndex = -1; // Inizializza l’indice che terrà traccia della posizione corrente nell’array dei prezzi storici openOrderIndex = 0; // Inizializza l’indice per iterare attraverso i record dei prezzi storici int lastValidIndex = recordsCount - 1; // Calcola l’indice dell’ultimo record valido nell’array dei prezzi storici
// Itera attraverso i record dei prezzi storici per trovare una corrispondenza con il tempo corrente do { if (priceHistory[openOrderIndex][0] >= Time[0]) break; // Se il tempo del record corrente è maggiore o uguale al tempo corrente, termina il ciclo currentHistoryIndex = openOrderIndex + 1; // Aggiorna l’indice della storia corrente per l’ultima corrispondenza trovata openOrderIndex += 1; // Passa al record successivo } while (openOrderIndex < lastValidIndex); // Continua fino a che non si raggiunge l’ultimo record valido
williamPRange = iWPR(_Symbol, 0, WPR_Period, 0); awesomeOscillator = iAO(_Symbol, 0, 0);
historyPriceLevel = NormalizeDouble(priceHistory[currentHistoryIndex, 1], _Digits); ObjectDelete("level"); orderComment = "level";
if (ObjectFind(orderComment) != -1) { ObjectMove(orderComment, 0, iTime(_Symbol, 1, 0), historyPriceLevel); } else { ObjectCreate(0, orderComment, OBJ_HLINE, 0, 0, historyPriceLevel, 0, 0, 0, 0); ObjectSet(orderComment, OBJPROP_COLOR, 16776960); ObjectSet(orderComment, OBJPROP_STYLE, 0); ObjectSet(orderComment, OBJPROP_WIDTH, 1); ObjectSet(orderComment, OBJPROP_BACK, 1); }
if ((priceHistory[currentHistoryIndex, 1] > Open[0])) { // Calcola lo spread in pips se necessario double spread = MarketInfo(_Symbol, MODE_SPREAD); if (_Digits == 5 || _Digits == 3) { spread /= 10.0; // Correzione per i broker con 5 cifre decimali } // Inizia a costruire il messaggio string message = "\nSpread: " + DoubleToStr(spread, 2) + " pips"; // Aggiungi informazioni riguardanti la Conservative_Mode message += "\nConservative Mode: " + (Conservative_Mode ? "On" : "Off"); // Continua a costruire il messaggio message += "\n\nBUY Signals"; // + DoubleToStr(priceHistory[currentHistoryIndex, 1], _Digits); Commentato se non serve message += "\nOrders Open: " + IntegerToString(totalOrders); // Mostra il messaggio sul grafico Comment(message); }
if ((priceHistory[currentHistoryIndex, 1] < Open[0])) { // Calcola lo spread in pips se necessario double spread = MarketInfo(_Symbol, MODE_SPREAD); if (_Digits == 5 || _Digits == 3) { spread /= 10.0; // Correzione per i broker con 5 cifre decimali } // Inizia a costruire il messaggio string message = "\nSpread: " + DoubleToStr(spread, 2) + " pips"; // Aggiungi informazioni riguardanti la Conservative_Mode message += "\nConservative Mode: " + (Conservative_Mode ? "On" : "Off"); // Continua a costruire il messaggio message += "\n\nSELL Signals"; // + DoubleToStr(priceHistory[currentHistoryIndex, 1], _Digits); Commentato se non serve message += "\nOrders Open: " + IntegerToString(totalOrders); // Mostra il messaggio sul grafico Comment(message); }
/////////////////// CONTATORE ORDINI BUY /////////////////////////
ordersNumber = 0; buyOrdersCounter = OrdersTotal() - 1; if (buyOrdersCounter >= 0) { do { order_check = OrderSelect(buyOrdersCounter, 0, 0); if (OrderMagicNumber() == MagicID && OrderSymbol() == _Symbol && OrderType() == OP_BUY) { ordersNumber = ordersNumber + 1; } buyOrdersCounter = buyOrdersCounter - 1; } while (buyOrdersCounter >= 0); } if (ordersNumber >= MaxOrders) return; if ((Conservative_Mode) && (((iWPR(_Symbol, 0, WPR_Period, 0) - 10) >= -1))) return;
/////////////////// CONTATORE ORDINI SELL /////////////////////////
ordersNumber = 0; sellOrdersCounter = OrdersTotal() - 1; if (sellOrdersCounter >= 0) { do { order_check = OrderSelect(sellOrdersCounter, 0, 0); if (OrderMagicNumber() == MagicID && OrderSymbol() == _Symbol && OrderType() == OP_SELL) { ordersNumber = ordersNumber + 1; } sellOrdersCounter = sellOrdersCounter - 1; } while (sellOrdersCounter >= 0); } if (ordersNumber >= MaxOrders) return; if ((Conservative_Mode) && (((iWPR(_Symbol, 0, WPR_Period, 0) - 90) <= -99))) return;
/////////////////////////////////////////////////////
if ((priceHistory[currentHistoryIndex, 1] > Open[0]) && buyConditions()) { stopLoss = NormalizeDouble((Ask - (StopLoss * pointValue)), _Digits); takeProfit = NormalizeDouble(((TakeProfit * pointValue) + Ask), _Digits); minLot = MarketInfo(_Symbol, MODE_MINLOT); maxLot = MarketInfo(_Symbol, MODE_MAXLOT);
if (AutoLot != 0) { lotSize = NormalizeDouble((((AccountBalance() * AutoLot) / 10) / 10000), 2); if ((lotSize < minLot)) { lotSize = minLot; } if ((lotSize > maxLot)) { lotSize = maxLot; }} else{ lotSize = FixedLot; } if ((AccountFreeMarginCheck(_Symbol, 1, lotSize) <= 0)) return;
openOrder = OrderSend(_Symbol, 0, lotSize, Ask, slippage, stopLoss, takeProfit, "Ultimate EA - Buy", MagicID, 0, 32768); closeSellOrders(); }
if ((priceHistory[currentHistoryIndex, 1] < Open[0]) && sellConditions()) {
stopLoss = NormalizeDouble(((StopLoss * pointValue) + Bid), _Digits); takeProfit = NormalizeDouble((Bid - (TakeProfit * pointValue)), _Digits); minLot = MarketInfo(_Symbol, MODE_MINLOT); maxLot = MarketInfo(_Symbol, MODE_MAXLOT);
if (AutoLot != 0) { lotSize = NormalizeDouble((((AccountBalance() * AutoLot) / 10) / 10000), 2); if ((lotSize < minLot)) { lotSize = minLot; } if ((lotSize > maxLot)) { lotSize = maxLot; }} else{ lotSize = FixedLot; } if ((AccountFreeMarginCheck(_Symbol, 1, lotSize) <= 0)) return;
openOrder = OrderSend(_Symbol, 1, lotSize, Bid, slippage, stopLoss, takeProfit, "Ultimate EA - Sell", MagicID, 0, 32768); closeBuyOrders();
} }
void OnDeinit(const int reason) { ObjectsDeleteAll(-1, -1); ChartRedraw(0); }
void historyRead(string filePath) { string orderComment; int currentHistoryIndex; string accountInfo; int byteCount; int fileSize; int Li_FFFE4 = 0; int Li_FFF78; int Li_FFF3C; double historyBarClosePrice;
currentHistoryIndex = 0; byteCount = 0; fileSize = 0; char buffer[]; Li_FFF78 = 0; int readResult[1]; Li_FFF3C = 0; historyBarClosePrice = 0; accountInfo = ""; fileHandle = CreateFileW(filePath, -2147483648, 3, 0, 3, 0, 0); byteCount = fileHandle; if (fileHandle == -1) { Comment(""); ArrayFree(readResult); ArrayFree(buffer); return; } fileSize = GetFileSize(byteCount, 0); if (fileSize <= 0) { ArrayFree(readResult); ArrayFree(buffer); return ; } fileHandle = fileSize - 148; fileHandle = fileHandle / 60; if (fileHandle == recordsCount) { ArrayFree(readResult); ArrayFree(buffer); return ; } SetFilePointer(byteCount, 148, Li_FFFE4, 0); fileHandle = fileSize - 148; recordsCount = fileHandle / 60; ArrayResize(priceHistory, recordsCount, 0); ArrayResize(buffer, 60, 0); Li_FFF3C = 0; if (recordsCount > 0) { do { ReadFile(byteCount, buffer, 60, readResult, 0); if (readResult[0] == 60) { timestamp0 = buffer[0]; timestamp1 = buffer[1]; timestamp2 = buffer[2]; timestamp3 = buffer[3]; timestamp4 = buffer[4]; timestamp5 = buffer[5]; timestamp6 = buffer[6]; timestamp7 = buffer[7];
historyBarTimestamp = StringFormat("0x%02x%02x%02x%02x%02x%02x%02x%02x", timestamp7, timestamp6, timestamp5, timestamp4, timestamp3, timestamp2, timestamp1, timestamp0);
historyBarValue.bytes[0] = buffer[32]; historyBarValue.bytes[1] = buffer[33]; historyBarValue.bytes[2] = buffer[34]; historyBarValue.bytes[3] = buffer[35]; historyBarValue.bytes[4] = buffer[36]; historyBarValue.bytes[5] = buffer[37]; historyBarValue.bytes[6] = buffer[38]; historyBarValue.bytes[7] = buffer[39];
historyBarClosePrice = historyBarValue.value;
priceHistory[currentHistoryIndex, 0] = StringToDouble(historyBarTimestamp); priceHistory[currentHistoryIndex, 1] = historyBarClosePrice; currentHistoryIndex = currentHistoryIndex + 1;
} else { CloseHandle(byteCount); ArrayFree(readResult); ArrayFree(buffer); return ; } Li_FFF3C = Li_FFF3C + 1; } while (Li_FFF3C < recordsCount); }
}
void closeBuyOrders() { bool orderClose; int openOrderIndex;
orderClose = false;
openOrderIndex = OrdersTotal() - 1; if (openOrderIndex >= 0) { do { if (OrderSelect(openOrderIndex, 0, 0) && OrderSymbol() == _Symbol && OrderMagicNumber() == MagicID && OrderType() == OP_BUY) { orderClose = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), slippage, 16776960); } openOrderIndex = openOrderIndex - 1; } while (openOrderIndex >= 0); }
}
void closeSellOrders() { bool orderClose; int openOrderIndex;
orderClose = false; openOrderIndex = OrdersTotal() - 1; if (openOrderIndex >= 0) { do { if (OrderSelect(openOrderIndex, 0, 0) && OrderSymbol() == _Symbol && OrderMagicNumber() == MagicID && OrderType() == OP_SELL) { orderClose = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), slippage, 16776960); } openOrderIndex = openOrderIndex - 1; } while (openOrderIndex >= 0); } }
bool buyConditions() { double priceRange; double adjustedPriceRange; bool orderClose;
priceRange = 0; adjustedPriceRange = 0;
priceRange = (High[0] - Low[1]); // priceRange = (High[0] - Low[1]); = più trades filteredPriceRange = (priceRange * RangeFilter); adjustedPriceRange = (High[0] - filteredPriceRange); //(High[0] - filteredPriceRange);
filteredPriceRange = 0; validDaysCount = 0; currentBar = 1; do { if (TimeDayOfWeek(Time[currentBar]) != 0) { filteredPriceRange = ((High[currentBar] - Low[currentBar]) + filteredPriceRange); validDaysCount = validDaysCount + 1; } currentBar = currentBar + 1; } while (validDaysCount < 4); medianFilteredPriceRange = (filteredPriceRange / 4); if ((Open[1] <= adjustedPriceRange)) return false; if ((Close[1] <= adjustedPriceRange)) return false;
if ((priceRange <= (medianFilteredPriceRange * 0.5))) return false; if ((((priceRange * 0.25) + Low[1]) >= Low[2])) return false;Gi_0000F = ArrayMinimum(Low, 3, 3); if ((Low[Gi_0000F] <= Low[1])) return false; orderClose = true; return orderClose;
orderClose = false;
return orderClose; }
bool sellConditions()
{ double priceRange; double adjustedPriceRange; bool orderClose;
priceRange = 0; adjustedPriceRange = 0; priceRange = (High[1] - Low[0]); // (High[1] - Low[0]); filteredPriceRange = (priceRange * RangeFilter); adjustedPriceRange = (filteredPriceRange + Low[0]); // (filteredPriceRange + Low[0]) filteredPriceRange = 0;
validDaysCount = 0; currentBar = 1; do { if (TimeDayOfWeek(Time[currentBar]) != 0) { filteredPriceRange = ((High[currentBar] - Low[currentBar]) + filteredPriceRange); validDaysCount = validDaysCount + 1; } currentBar = currentBar + 1; } while (validDaysCount < 4); medianFilteredPriceRange = (filteredPriceRange / 4);
if ((Close[1] >= adjustedPriceRange)) return false; if ((Open[1] >= adjustedPriceRange)) return false; if ((priceRange <= (medianFilteredPriceRange * 0.5))) return false; if (((High[1] - (priceRange * 0.25)) <= High[2])) return false;
Gi_0000F = ArrayMaximum(High, 3, 3); if ((High[Gi_0000F] >= High[1])) return false; orderClose = true; return orderClose;
orderClose = false;
return orderClose; }
void ManageTrailingStop() { if(!Trailing_Stop_ON) return; // Esce se il trailing stop è disattivato
for(int i = OrdersTotal() - 1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS) && OrderMagicNumber() == MagicID && OrderSymbol() == _Symbol) { double tradeProfitPips = 0.0; double newStopLoss = 0.0; double currentStopLoss = OrderStopLoss(); double orderOpenPrice = OrderOpenPrice(); // Calcola il profitto in pips per l’ordine selezionato if(OrderType() == OP_BUY) { tradeProfitPips = (Bid - orderOpenPrice) / pointValue; newStopLoss = Bid - (TrailingStop + TrailingStep) * pointValue; // Verifica se il nuovo stop loss supera il vecchio stop loss più il TrailingStep if(newStopLoss > currentStopLoss + TrailingStep * pointValue) { bool modifyResult = OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, CLR_NONE); if(!modifyResult) { Print("Errore nel modificare l’ordine buy: ", GetLastError()); } } } else if(OrderType() == OP_SELL) { tradeProfitPips = (orderOpenPrice - Ask) / pointValue; newStopLoss = Ask + (TrailingStop + TrailingStep) * pointValue; // Verifica se il nuovo stop loss è inferiore al vecchio stop loss meno il TrailingStep if(newStopLoss < currentStopLoss - TrailingStep * pointValue) { bool modifyResult = OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, CLR_NONE); if(!modifyResult) { Print("Errore nel modificare l’ordine sell: ", GetLastError()); } } } } }}
- Assistant
Basandomi sul codice fornito, sembra che l'Expert Advisor (EA) per MT4 non sia specificamente progettato secondo una strategia di mean reversion ("mean reverse").
Invece, il codice sembra incorporare vari elementi, tra cui:
- Controllo del volume di scambio e del movimento dei prezzi per determinare opportunità di trading.
- Uso dell'oscillatore Awesome (AO) e del Williams Percent Range (WPR) come parte dell'analisi indicativa per generare segnali di acquisto o vendita.
- Gestione dinamica delle dimensioni delle posizioni basata su condizioni di mercato specifiche.
- Implementazione di un meccanismo di stop loss e take profit, con la possibilità di utilizzare valori basati sull'indicatore ATR per queste soglie.
- Un sistema di trailing stop per proteggere i profitti da inversioni improvvise del mercato.
La mean reversion è una strategia che prevede che i prezzi e i ritorni degli asset si muoveranno verso la media o il valore medio nel tempo. Tipicamente, un EA basato su strategia di mean reversion cercherà di identificare quando un asset è significativamente deviato dalla sua media storica e quindi ipotizza che ritornerà a quella media, generando un'opportunità di trading.
Tuttavia, il codice fornito sembra concentrarsi più sull'identificazione dei punti di ingresso basati su indicatori specifici e sulle condizioni del mercato piuttosto che su un'esplicita logica di mean reversion. Si potrebbe argomentare che alcuni aspetti, come la gestione degli stop loss e il controllo del volume, possano contribuire alla mitigazione dei rischi in una strategia di mean reversion, ma non c'è evidenza diretta che questa sia la strategia centrale dell'EA.
In conclusione, per determinare se l'EA segue una strategia di mean reversion, sarebbe necessario un'analisi più dettagliata del modo in cui i segnali commerciali vengono generati e gestiti nel contesto dell'intero algoritmo di trading. Il codice fornito, tuttavia, suggerisce che l'EA incorpora un mix di tecniche e strategie piuttosto che una pura implementazione di mean reversion.