questo è il codice aggiornato con le utlime modifiche, ma nel tester mt4 non apre nessuna operazione
//+----------------------------------------------------------------------------------------------------------+//
// //
// ██ ██ ████████ ████████ ██ ███████ ███████ ████████ █████ ██████ ███████ █████ //
// ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ //
// ██ ██ ██ ██ ██ █████ ███████ ██ ███████ ██████ █████ ███████ //
// ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ //
// ███████ ██ ██ ██ ███████ ███████ ███████ ██ ██ ██ ██ ██ ███████ ██ ██ //
// //
//+----------------------------------------------------------------------------------------------------------+//
#property copyright "Little Star EA";
#property version "1.00";
#property copyright "Gabriele Bassi"
#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 = 50;
extern double TakeProfit = 10;
extern int MaxOrders = 5;
//extern string INFO2=""; //===== FILTERS SECTION =======================
extern int WPR_Period = 450;
extern int WPR_Overbough = -30;
extern int WPR_Oversold = -70;
extern int HST_Period = 240;
extern int Volume_Filter_Period = 15;
extern bool WPR_Filter = true;
extern bool Jorge_Mode = false;
extern double RangeFilter = 0.4;
//extern string INFO4=""; //===== TRAILING STOP SECTION ===============
input bool Trailing_Stop_ON=false;
input double TrailingStop = 5;
extern int TrailingStep = 5;
/*
/////////////////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
*/
//////////////////////////////////////
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];
int totalBarsAvailable; // Numero totale di barre disponibili su M1
int barsPer4HourBlock = 240; // 240 minuti in un blocco di 4 ore
double lastStopLossUpdatePrice[];
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;
currentHistoryIndex = (int)(totalBarsAvailable / barsPer4HourBlock) * barsPer4HourBlock - 1;
/////////////////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 WPR_Filter
message += "\nWPR Filter: " + (WPR_Filter ? "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 WPR_Filter
message += "\nWPR Filter: " + (WPR_Filter ? "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 ((WPR_Filter) && (!Jorge_Mode) && (iWPR(_Symbol, 0, WPR_Period, 0) >= WPR_Overbough)) return;
if ((Jorge_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 ((WPR_Filter) && (!Jorge_Mode) && (iWPR(_Symbol, 0, WPR_Period, 0) <= WPR_Oversold)) return;
if ((Jorge_Mode) && (((iWPR(_Symbol, 0, WPR_Period, 0) - 90) <= -99))) return;
/////////////////////////////////////////////////////
historyRead();
// Aggiorna currentHistoryIndex all’ultima barra del blocco di 4 ore più recente
currentHistoryIndex = (totalBarsAvailable / barsPer4HourBlock) * barsPer4HourBlock - 1;
// Ottenere la “chiusura” dell’ultima barra completa di 4 ore
double last4HourBlockClose = priceHistory[currentHistoryIndex % barsPer4HourBlock, 1]; // Utilizzare modulo per riciclaggio dell’indice
if (last4HourBlockClose > 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);
if (openOrder > 0) {
Print("Buy order sent with ticket #", openOrder);
if (ArraySize(lastStopLossUpdatePrice) <= openOrder) {
ArrayResize(lastStopLossUpdatePrice, openOrder + 1);
}
lastStopLossUpdatePrice[openOrder] = Ask; // Memorizza il prezzo di Ask al momento dell’ordine
} else {
Print("Error sending BUY order: ", GetLastError());
}
closeSellOrders();
}
if (last4HourBlockClose < 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);
if (openOrder > 0) {
Print("Sell order sent with ticket #", openOrder);
if (ArraySize(lastStopLossUpdatePrice) <= openOrder) {
ArrayResize(lastStopLossUpdatePrice, openOrder + 1);
}
lastStopLossUpdatePrice[openOrder] = Bid; // Memorizza il prezzo di Bid al momento dell’ordine
} else {
Print("Error sending SELL order: ", GetLastError());
}
closeBuyOrders();
}
}
void OnDeinit(const int reason)
{
ObjectsDeleteAll(-1, -1);
ChartRedraw(0);
}
void historyRead() {
totalBarsAvailable = iBars(_Symbol, PERIOD_M1);
// Invece di definire prevMidnight e barsFromMidnight, potremmo usare direttamente totalBarsAvailable
// Calcola il numero di blocchi completi di 4 ore disponibili
int numberOfComplete4HourBlocks = totalBarsAvailable / barsPer4HourBlock;
// Punto di partenza per l’ultimo serie completa di 4 ore
int startBar = totalBarsAvailable - (numberOfComplete4HourBlocks * barsPer4HourBlock);
// Assicurati che priceHistory possa contenere dati sufficienti
ArrayResize(priceHistory, barsPer4HourBlock);
// Carica le ultime barre di 4 ore disponibili
for (int i = 0; i < barsPer4HourBlock; i++) {
if (startBar + i >= totalBarsAvailable) break;
priceHistory[i][1] = iClose(_Symbol, PERIOD_M1, startBar + i);
priceHistory[i][0] = iTime(_Symbol, PERIOD_M1, startBar + i);
}
// Aggiorna recordsCount usato forse in altre parti del codice
recordsCount = barsPer4HourBlock;
}
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;
for (int i = OrdersTotal() - 1; i >= 0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == MagicID && OrderSymbol() == _Symbol) {
double currentPrice = (OrderType() == OP_BUY ? Bid : Ask);
double lastUpdatedPrice = lastStopLossUpdatePrice[OrderTicket()];
double stopLossAdjustment = TrailingStop * pointValue;
double stepAdjustment = TrailingStep * pointValue;
if ((OrderType() == OP_BUY && currentPrice - lastUpdatedPrice >= stepAdjustment) ||
(OrderType() == OP_SELL && lastUpdatedPrice - currentPrice >= stepAdjustment)) {
double newStopLoss = (OrderType() == OP_BUY ? currentPrice - stopLossAdjustment : currentPrice + stopLossAdjustment);
if ((OrderType() == OP_BUY && newStopLoss > OrderStopLoss()) ||
(OrderType() == OP_SELL && newStopLoss < OrderStopLoss())) {
if (OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, CLR_NONE)) {
Print("Stop loss updated for order #", OrderTicket());
lastStopLossUpdatePrice[OrderTicket()] = currentPrice;
} else {
Print("Error updating stop loss for order #", OrderTicket(), ": ", GetLastError());
}
}
}
}
}
}