//+… · The Chat Archive
Explore / Money & finance //+------------------------------------------------------------------+ // DayTraderDynamicv1.1.mq5 // EA Day … Save Share Download ▾ Report//+------------------------------------------------------------------+
//| DayTraderDynamic_v1.1.mq5 |
//| EA Day Trading cu filtre dinamice si logging |
//| ©2024 Your Company |
//+------------------------------------------------------------------+
#property copyright "©2024 Your Company"
#property version "1.10"
#property strict
#include <Trade\Trade.mqh>
enum MARKET_CONDITION
{
MARKET_TRENDING_UP,
MARKET_TRENDING_DOWN,
MARKET_RANGING
};
//--- Input parameters
input double RiskPercent = 0.5; // Risc pe tranzactie [%]
input int ATR_Period = 14;
input int MA_Period = 20;
input int RSI_Period = 10;
input int RSILookback = 50; // Perioada pentru praguri RSI dinamice
input int ADX_Period = 14;
input double ATR_Threshold_Coeff = 0.5; // Prag ATR pt detectie trend
input double ADX_Threshold = 25.0;
input bool UseADXFilter = true;
input bool UseMacroEMAFilter = true;
input int TradingStartHour = 7;
input int TradingEndHour = 16;
input bool UseTrailingStop = true;
input double ATR_Trailing_Multiplier = 1.0;
input int TrailingActivationPoints = 30;
input double MaxSpreadPoints = 10.0;
input int MaxPositions = 3;
input int TradeCooldownBuySeconds = 30;
input int TradeCooldownSellSeconds = 30;
input double ATR_SL_Multiplier = 1.5;
input double ATR_TP_Multiplier = 2.0;
input double MaxDailyLossPercent = 2.0; // Opreste trading cand pierdere zilnica
//--- Global Variables
CTrade trade;
int atrHandle = INVALID_HANDLE;
int maHandle = INVALID_HANDLE;
int rsiHandle = INVALID_HANDLE;
int adxHandle = INVALID_HANDLE;
int maHandle_H1 = INVALID_HANDLE;
double atrBuffer[];
double maBuffer[];
double rsiBuffer[];
double adxBuffer[];
double maBuffer_H1[];
double rsiHistory[];
double dynamicRSI_Upper;
double dynamicRSI_Lower;
datetime lastTradeTime = 0;
datetime lastBuyTime = 0;
datetime lastSellTime = 0;
//+------------------------------------------------------------------+
//| Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
atrHandle = iATR(_Symbol,_Period,ATR_Period);
maHandle = iMA(_Symbol,_Period,MA_Period,0,MODE_EMA,PRICE_CLOSE);
rsiHandle = iRSI(_Symbol,_Period,RSI_Period,PRICE_CLOSE);
adxHandle = iADX(_Symbol,_Period,ADX_Period);
maHandle_H1 = iMA(_Symbol,PERIOD_H1,MA_Period,0,MODE_EMA,PRICE_CLOSE);
if(atrHandle == INVALID_HANDLE || maHandle == INVALID_HANDLE || rsiHandle == INVALID_HANDLE ||
adxHandle == INVALID_HANDLE || maHandle_H1 == INVALID_HANDLE)
{
Print("Eroare creare indicatori");
return(INIT_FAILED);
}
Assistant2025-05-22 16:21 UTC Copy response
Mesajul de eroare 'FILE_APPEND' - undeclared identifier înseamnă că în codul tău, la linia unde ai apelul FileOpen cu flag-ul FILE_APPEND, acest identificator (constanta) nu este definit în MQL5.
scrie codul pentru compilare refacut
Assistant2025-05-22 16:21 UTC Copy response
Sigur, mai jos este funcția LogTrade refăcută cu corectarea pentru problema cu FILE_APPEND în MQL5:
//+------------------------------------------------------------------+
//| Log tranzactie in fisier CSV |
//+------------------------------------------------------------------+
void LogTrade(string type, double lot, double openPrice, double sl, double tp, double profit)
{
string fileName = "DayTraderDynamic_Trades.csv";
int handle = FileOpen(fileName, FILE_WRITE | FILE_CSV);
if(handle != INVALID_HANDLE)
{
// Poziționare la sfârșitul fișierului pentru a adăuga date noi (append)
FileSeek(handle, 0, SEEK_END);
FileWrite(handle,
TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS),
type,
DoubleToString(lot, 2),
DoubleToString(openPrice, _Digits),
DoubleToString(sl, _Digits),
DoubleToString(tp, _Digits),
DoubleToString(profit, 2));
FileClose(handle);
}
else
Print("Eroare deschidere fisier log: ", GetLastError());
}
codul complet cu această modificare aplicată în context
Assistant2025-05-22 16:25 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 3 (6 messages)
Language —
Conversation date May 22, 2025
Added to archive Nov 16, 2026
ID 01m7h42vn7e7ns5s0fksvbp3bnSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 8119e5c6e2f51cc0c71462f9eaf7b1f0
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
ArraySetAsSeries(atrBuffer,true);
ArraySetAsSeries(maBuffer,true);
ArraySetAsSeries(rsiBuffer,true);
ArraySetAsSeries(adxBuffer,true);
ArraySetAsSeries(maBuffer_H1,true);
ArrayResize(rsiHistory,RSILookback);
ArraySetAsSeries(rsiHistory,true);
Print("DayTraderDynamic v1.1 - Initializat cu succes");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Deinitialization |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if(atrHandle != INVALID_HANDLE)
IndicatorRelease(atrHandle);
if(maHandle != INVALID_HANDLE)
IndicatorRelease(maHandle);
if(rsiHandle != INVALID_HANDLE)
IndicatorRelease(rsiHandle);
if(adxHandle != INVALID_HANDLE)
IndicatorRelease(adxHandle);
if(maHandle_H1 != INVALID_HANDLE)
IndicatorRelease(maHandle_H1);
}
//+------------------------------------------------------------------+
//| Verifica daca tradingul este permis |
//+------------------------------------------------------------------+
bool IsTradingAllowed()
{
long spread = SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
if(spread < 0 || spread > (long)MaxSpreadPoints)
return false;
MqlDateTime tm;
TimeToStruct(TimeCurrent(),tm);
if(tm.hour < TradingStartHour || tm.hour >= TradingEndHour)
return false;
// Verificare drawdown zilnic
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double dailyLoss = balance - equity;
if(dailyLoss > balance * MaxDailyLossPercent / 100.0)
{
PrintFormat("Drawdown zilnic maxime atins: %.2f%% -> Oprire trading", MaxDailyLossPercent);
return false;
}
//+------------------------------------------------------------------+
//| Actualizeaza datele indicatorilor |
//+------------------------------------------------------------------+
bool UpdateIndicators()
{
if(CopyBuffer(atrHandle,0,0,3,atrBuffer) != 3)
return false;
if(CopyBuffer(maHandle,0,0,3,maBuffer) != 3)
return false;
if(CopyBuffer(rsiHandle,0,0,RSILookback,rsiHistory) != RSILookback)
return false;
if(CopyBuffer(rsiHandle,0,0,3,rsiBuffer) != 3)
return false;
if(CopyBuffer(adxHandle,1,0,3,adxBuffer) != 3)
return false;
if(CopyBuffer(maHandle_H1,0,0,3,maBuffer_H1) != 3)
return false;
//+------------------------------------------------------------------+
//| Calculeaza praguri RSI dinamice |
//+------------------------------------------------------------------+
void CalculateDynamicRSILevels()
{
// Calcul medie simple si dev standard pe rsiHistory
double sum = 0;
for(int i=0; i<RSILookback; i++)
sum += rsiHistory[i];
double mean = sum / RSILookback;
double sumDev = 0;
for(int i=0; i<RSILookback; i++)
sumDev += MathPow(rsiHistory[i]-mean, 2);
double stdDev = MathSqrt(sumDev / RSILookback);
dynamicRSI_Upper = MathMin(80, mean + stdDev);
dynamicRSI_Lower = MathMax(20, mean - stdDev);
}
//+------------------------------------------------------------------+
//| Calculeaza scor de incredere pe piata |
//+------------------------------------------------------------------+
double MarketConfidenceScore()
{
double score=0;
if(adxBuffer[0] >= 30)
score +=40;
else
if(adxBuffer[0] >=20)
score +=20;
double price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
if(price > maBuffer_H1[0])
score +=30;
else
if(price < maBuffer_H1[0])
score -=30;
if(rsiBuffer[0] > dynamicRSI_Lower && rsiBuffer[0] < dynamicRSI_Upper)
score +=30;
return MathMax(0, MathMin(100, score));
}
//+------------------------------------------------------------------+
//| Detecteaza conditia pietei |
//+------------------------------------------------------------------+
MARKET_CONDITION DetectMarketCondition()
{
double price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
if(rsiBuffer[0] >= dynamicRSI_Upper || rsiBuffer[0] <= dynamicRSI_Lower)
return MARKET_RANGING;
if(UseADXFilter && adxBuffer[0] < ADX_Threshold)
return MARKET_RANGING;
double atrThreshold = atrBuffer[0]*ATR_Threshold_Coeff;
bool isUp = price > maBuffer[0] && (price - maBuffer[0]) > atrThreshold;
bool isDown = price < maBuffer[0] && (maBuffer[0] - price) > atrThreshold;
if(UseMacroEMAFilter)
{
if(isUp && price < maBuffer_H1[0])
return MARKET_RANGING;
if(isDown && price > maBuffer_H1[0])
return MARKET_RANGING;
}
if(isUp)
return MARKET_TRENDING_UP;
if(isDown)
return MARKET_TRENDING_DOWN;
//+------------------------------------------------------------------+
//| Calculeaza dimensiunea lotului |
//+------------------------------------------------------------------+
double CalculatePositionSize()
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0)
return 0;
double slDistance = ATR_SL_Multiplier*atrBuffer[0];
if(slDistance <= 0)
return 0;
double tickValue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
if(tickValue <=0 || tickSize <=0)
return 0;
double riskMoney = balance*(RiskPercent/100.0);
double riskPerPoint = tickValue/tickSize;
double lot = riskMoney / (slDistance*riskPerPoint);
double minLot = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
double lotStep = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
if(lotStep <= 0)
lotStep=0.01;
lot = MathMax(minLot, MathMin(maxLot, MathFloor(lot/lotStep)*lotStep));
//+------------------------------------------------------------------+
//| Executa ordine bazate pe semnale |
//+------------------------------------------------------------------+
void ExecuteTrade(MARKET_CONDITION cond)
{
datetime nowTime = TimeCurrent();
// Verificare cooldown directionat
if(cond == MARKET_TRENDING_UP && nowTime - lastBuyTime < TradeCooldownBuySeconds)
return;
if(cond == MARKET_TRENDING_DOWN && nowTime - lastSellTime < TradeCooldownSellSeconds)
return;
if(CountOpenPositions() >= MaxPositions)
return;
double lot = CalculatePositionSize();
if(lot <= 0)
return;
double slPrice, tpPrice, entryPrice;
switch(cond)
{
case MARKET_TRENDING_UP:
CloseAllSellPositions();
if(!HasBuyPosition())
{
entryPrice = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
slPrice = entryPrice - ATR_SL_Multiplier * atrBuffer[0];
tpPrice = entryPrice + ATR_TP_Multiplier * atrBuffer[0];
if(trade.Buy(lot,_Symbol,entryPrice,slPrice,tpPrice,"Long Trend UP"))
{
lastBuyTime = nowTime;
LogTrade("BUY", lot, entryPrice, slPrice, tpPrice, 0);
}
else
Print("BUY failed, err: ", GetLastError());
}
break;
case MARKET_TRENDING_DOWN:
CloseAllBuyPositions();
if(!HasSellPosition())
{
entryPrice = SymbolInfoDouble(_Symbol,SYMBOL_BID);
slPrice = entryPrice + ATR_SL_Multiplier * atrBuffer[0];
tpPrice = entryPrice - ATR_TP_Multiplier * atrBuffer[0];
if(trade.Sell(lot,_Symbol,entryPrice,slPrice,tpPrice,"Short Trend DOWN"))
{
lastSellTime = nowTime;
LogTrade("SELL", lot, entryPrice, slPrice, tpPrice, 0);
}
else
Print("SELL failed, err: ", GetLastError());
}
break;
case MARKET_RANGING:
// Nu tranzactionam
break;
}
//+------------------------------------------------------------------+
//| Trailing Stop Adaptiv |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol)
continue;
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ?
SymbolInfoDouble(_Symbol,SYMBOL_BID) :
SymbolInfoDouble(_Symbol,SYMBOL_ASK);
double profitPoints = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ?
(currentPrice - openPrice) / _Point :
(openPrice - currentPrice) / _Point;
if(profitPoints < TrailingActivationPoints)
continue;
double newSL, slOld = PositionGetDouble(POSITION_SL);
double atrTrailingDist = ATR_Trailing_Multiplier * atrBuffer[0];
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
newSL = currentPrice - atrTrailingDist;
if(newSL > slOld || slOld == 0)
if(!trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP)))
Print("Trailing BUY failed: ", GetLastError());
}
else
{
newSL = currentPrice + atrTrailingDist;
if(newSL < slOld || slOld == 0)
if(!trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP)))
Print("Trailing SELL failed: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Log tranzactie in fisier CSV |
//+------------------------------------------------------------------+
void LogTrade(string type, double lot, double openPrice, double sl, double tp, double profit)
{
string fileName = "DayTraderDynamic_Trades.csv";
int handle = FileOpen(fileName, FILE_WRITE|FILE_CSV|FILE_READ|FILE_APPEND);
if(handle != INVALID_HANDLE)
{
FileSeek(handle,0,SEEK_END);
FileWrite(handle,
TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS),
type,
DoubleToString(lot,2),
DoubleToString(openPrice, _Digits),
DoubleToString(sl, _Digits),
DoubleToString(tp, _Digits),
DoubleToString(profit,2));
FileClose(handle);
}
}
//+------------------------------------------------------------------+
//| Functii suport pozitiilor |
//+------------------------------------------------------------------+
int CountOpenPositions()
{
int cnt=0;
for(int i=0; i<PositionsTotal(); i++)
{
ulong ticket = PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol)
cnt++;
}
return cnt;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool HasBuyPosition()
{
for(int i=0; i<PositionsTotal(); i++)
{
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool HasSellPosition()
{
for(int i=0; i<PositionsTotal(); i++)
{
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CloseAllBuyPositions()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
{
if(!trade.PositionClose(ticket))
Print("Eroare inchidere BUY: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CloseAllSellPositions()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
{
if(!trade.PositionClose(ticket))
Print("Eroare inchidere SELL: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Tick principal |
//+------------------------------------------------------------------+
void OnTick()
{
if(!IsTradingAllowed())
return;
if(!UpdateIndicators())
return;
CalculateDynamicRSILevels();
double confidence = MarketConfidenceScore();
Comment(
"Piata Status: ", DetectMarketCondition() == MARKET_TRENDING_UP ? "Trend UP" :
DetectMarketCondition() == MARKET_TRENDING_DOWN ? "Trend DOWN" : "Ranging",
"\nConfidence: ", DoubleToString(confidence,0), "%",
"\nATR: ", DoubleToString(atrBuffer[0],5),
"\nRSI: ", DoubleToString(rsiBuffer[0],2), " (Dyn U=", DoubleToString(dynamicRSI_Upper,2), " L=", DoubleToString(dynamicRSI_Lower,2), ")",
"\nADX: ", DoubleToString(adxBuffer[0],2),
"\nPozitii Deschise: ", CountOpenPositions()
);
if(confidence < 60)
{
// Piata instabila, nu tranzactionam
return;
}
MARKET_CONDITION cond = DetectMarketCondition();
if(UseTrailingStop)
ManageTrailingStop();
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
Trade.mqh
Object.mqh
StdLibErr.mqh
OrderInfo.mqh
HistoryOrderInfo.mqh
PositionInfo.mqh
DealInfo.mqh
'FILE_APPEND' - undeclared identifier 777_METAROO_Ultra_Win_v0.8.mq5 407 66
1 errors, 0 warnings 2 1
Problema În MQL5, pentru deschiderea fișierelor, flag-urile folosite sunt:
FILE_READ
FILE_WRITE
FILE_CSV
FILE_BIN (pentru binar)
FILE_COMMON (pentru folderul common)
FILE_SHARE_READ (pentru împărțirea accesului)
FILE_SHARE_WRITE
FILE_ANSI
Nu există flag-ul FILE_APPEND.
Acesta este un flag folosit în alte limbaje (precum C++ sau PHP), dar în MQL5 este necesar să deschizi fișierul în mod scriere și să poziționezi cursorul la sfârșit cu FileSeek pentru a adăuga date la final.
Soluția în codul tău (funcția LogTrade) int handle = FileOpen(fileName, FILE_WRITE|FILE_CSV|FILE_READ|FILE_APPEND);
Să eviți folosirea FILE_APPEND
Să deschizi fișierul numai cu FILE_WRITE | FILE_CSV (flags adecvate pentru scriere CSV)
După deschiderea fișierului, să poziționezi cursorul la sfârșitul fișierului
int handle = FileOpen(fileName, FILE_WRITE|FILE_CSV);
if(handle != INVALID_HANDLE)
{
FileSeek(handle, 0, SEEK_END); // Poziționează la sfârșit pentru append
FileWrite(handle,
TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS),
type,
DoubleToString(lot,2),
DoubleToString(openPrice, _Digits),
DoubleToString(sl, _Digits),
DoubleToString(tp, _Digits),
DoubleToString(profit,2));
FileClose(handle);
}
Explicații suplimentare
FILE_READ nu are sens să fie setat simultan cu FILE_WRITE
FILE_APPEND nu există în MQL5
FileSeek cu SEEK_END poziționează cursorul de scriere la finalul fișierului, comportament identic cu append-ul din alte limbaje
Rezumat Înlocuiește linia cu FileOpen în funcția LogTrade cu:
int handle = FileOpen(fileName, FILE_WRITE|FILE_CSV);
și asigură-te că poziționezi cursorul cu:
FileSeek(handle, 0, SEEK_END);
Acest lucru va rezolva problema cu FILE_APPEND nedefinit și va face logarea să funcționeze corect, adăugând liniile în fișier fără suprascriere.
Tot funcția LogTrade este singura modificare necesară în codul tău pentru a remedia eroarea.
Restul codului rămâne neschimbat.
Sfat suplimentar Înainte de utilizare, verifică dacă în directorul MQL5/Files/ există permisiunile pentru scriere.
Dacă dorești, pot să-ți ofer codul complet cu această modificare aplicată în context. Spune-mi!
Desigur! Mai jos ai codul complet al Expert Advisor-ului tău, cu funcția LogTrade modificată pentru a elimina eroarea FILE_APPEND și a face logging-ul corect:
//+------------------------------------------------------------------+
//| DayTraderDynamic_v1.1.mq5 |
//| EA Day Trading cu filtre dinamice si logging |
//| ©2024 Your Company |
//+------------------------------------------------------------------+
#property copyright "©2024 Your Company"
#property version "1.10"
#property strict
#include <Trade\Trade.mqh>
enum MARKET_CONDITION
{
MARKET_TRENDING_UP,
MARKET_TRENDING_DOWN,
MARKET_RANGING
};
//--- Input parameters
input double RiskPercent = 0.5; // Risc pe tranzactie [%]
input int ATR_Period = 14;
input int MA_Period = 20;
input int RSI_Period = 10;
input int RSILookback = 50; // Perioada pentru praguri RSI dinamice
input int ADX_Period = 14;
input double ATR_Threshold_Coeff = 0.5; // Prag ATR pt detectie trend
input double ADX_Threshold = 25.0;
input bool UseADXFilter = true;
input bool UseMacroEMAFilter = true;
input int TradingStartHour = 7;
input int TradingEndHour = 16;
input bool UseTrailingStop = true;
input double ATR_Trailing_Multiplier = 1.0;
input int TrailingActivationPoints = 30;
input double MaxSpreadPoints = 10.0;
input int MaxPositions = 3;
input int TradeCooldownBuySeconds = 30;
input int TradeCooldownSellSeconds = 30;
input double ATR_SL_Multiplier = 1.5;
input double ATR_TP_Multiplier = 2.0;
input double MaxDailyLossPercent = 2.0; // Opreste trading cand pierdere zilnica
//--- Global Variables
CTrade trade;
int atrHandle = INVALID_HANDLE;
int maHandle = INVALID_HANDLE;
int rsiHandle = INVALID_HANDLE;
int adxHandle = INVALID_HANDLE;
int maHandle_H1 = INVALID_HANDLE;
double atrBuffer[];
double maBuffer[];
double rsiBuffer[];
double adxBuffer[];
double maBuffer_H1[];
double rsiHistory[];
double dynamicRSI_Upper;
double dynamicRSI_Lower;
datetime lastTradeTime = 0;
datetime lastBuyTime = 0;
datetime lastSellTime = 0;
//+------------------------------------------------------------------+
//| Initialization |
//+------------------------------------------------------------------+
int OnInit()
{
atrHandle = iATR(_Symbol,_Period,ATR_Period);
maHandle = iMA(_Symbol,_Period,MA_Period,0,MODE_EMA,PRICE_CLOSE);
rsiHandle = iRSI(_Symbol,_Period,RSI_Period,PRICE_CLOSE);
adxHandle = iADX(_Symbol,_Period,ADX_Period);
maHandle_H1 = iMA(_Symbol,PERIOD_H1,MA_Period,0,MODE_EMA,PRICE_CLOSE);
if(atrHandle == INVALID_HANDLE || maHandle == INVALID_HANDLE || rsiHandle == INVALID_HANDLE ||
adxHandle == INVALID_HANDLE || maHandle_H1 == INVALID_HANDLE)
{
Print("Eroare creare indicatori");
return(INIT_FAILED);
}
ArraySetAsSeries(atrBuffer,true);
ArraySetAsSeries(maBuffer,true);
ArraySetAsSeries(rsiBuffer,true);
ArraySetAsSeries(adxBuffer,true);
ArraySetAsSeries(maBuffer_H1,true);
ArrayResize(rsiHistory,RSILookback);
ArraySetAsSeries(rsiHistory,true);
Print("DayTraderDynamic v1.1 - Initializat cu succes");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Deinitialization |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
if(atrHandle != INVALID_HANDLE)
IndicatorRelease(atrHandle);
if(maHandle != INVALID_HANDLE)
IndicatorRelease(maHandle);
if(rsiHandle != INVALID_HANDLE)
IndicatorRelease(rsiHandle);
if(adxHandle != INVALID_HANDLE)
IndicatorRelease(adxHandle);
if(maHandle_H1 != INVALID_HANDLE)
IndicatorRelease(maHandle_H1);
}
//+------------------------------------------------------------------+
//| Verifica daca tradingul este permis |
//+------------------------------------------------------------------+
bool IsTradingAllowed()
{
long spread = SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
if(spread < 0 || spread > (long)MaxSpreadPoints)
return false;
MqlDateTime tm;
TimeToStruct(TimeCurrent(),tm);
if(tm.hour < TradingStartHour || tm.hour >= TradingEndHour)
return false;
// Verificare drawdown zilnic
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double dailyLoss = balance - equity;
if(dailyLoss > balance * MaxDailyLossPercent / 100.0)
{
PrintFormat("Drawdown zilnic maxime atins: %.2f%% -> Oprire trading", MaxDailyLossPercent);
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Actualizeaza datele indicatorilor |
//+------------------------------------------------------------------+
bool UpdateIndicators()
{
if(CopyBuffer(atrHandle,0,0,3,atrBuffer) != 3)
return false;
if(CopyBuffer(maHandle,0,0,3,maBuffer) != 3)
return false;
if(CopyBuffer(rsiHandle,0,0,RSILookback,rsiHistory) != RSILookback)
return false;
if(CopyBuffer(rsiHandle,0,0,3,rsiBuffer) != 3)
return false;
if(CopyBuffer(adxHandle,1,0,3,adxBuffer) != 3)
return false;
if(CopyBuffer(maHandle_H1,0,0,3,maBuffer_H1) != 3)
return false;
return true;
}
//+------------------------------------------------------------------+
//| Calculeaza praguri RSI dinamice |
//+------------------------------------------------------------------+
void CalculateDynamicRSILevels()
{
// Calcul medie simple si dev standard pe rsiHistory
double sum = 0;
for(int i=0; i<RSILookback; i++)
sum += rsiHistory[i];
double mean = sum / RSILookback;
double sumDev = 0;
for(int i=0; i<RSILookback; i++)
sumDev += MathPow(rsiHistory[i]-mean, 2);
double stdDev = MathSqrt(sumDev / RSILookback);
dynamicRSI_Upper = MathMin(80, mean + stdDev);
dynamicRSI_Lower = MathMax(20, mean - stdDev);
}
//+------------------------------------------------------------------+
//| Calculeaza scor de incredere pe piata |
//+------------------------------------------------------------------+
double MarketConfidenceScore()
{
double score=0;
if(adxBuffer[0] >= 30)
score +=40;
else
if(adxBuffer[0] >=20)
score +=20;
double price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
if(price > maBuffer_H1[0])
score +=30;
else
if(price < maBuffer_H1[0])
score -=30;
if(rsiBuffer[0] > dynamicRSI_Lower && rsiBuffer[0] < dynamicRSI_Upper)
score +=30;
return MathMax(0, MathMin(100, score));
}
//+------------------------------------------------------------------+
//| Detecteaza conditia pietei |
//+------------------------------------------------------------------+
MARKET_CONDITION DetectMarketCondition()
{
double price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
if(rsiBuffer[0] >= dynamicRSI_Upper || rsiBuffer[0] <= dynamicRSI_Lower)
return MARKET_RANGING;
if(UseADXFilter && adxBuffer[0] < ADX_Threshold)
return MARKET_RANGING;
double atrThreshold = atrBuffer[0]*ATR_Threshold_Coeff;
bool isUp = price > maBuffer[0] && (price - maBuffer[0]) > atrThreshold;
bool isDown = price < maBuffer[0] && (maBuffer[0] - price) > atrThreshold;
if(UseMacroEMAFilter)
{
if(isUp && price < maBuffer_H1[0])
return MARKET_RANGING;
if(isDown && price > maBuffer_H1[0])
return MARKET_RANGING;
}
if(isUp)
return MARKET_TRENDING_UP;
if(isDown)
return MARKET_TRENDING_DOWN;
return MARKET_RANGING;
}
//+------------------------------------------------------------------+
//| Calculeaza dimensiunea lotului |
//+------------------------------------------------------------------+
double CalculatePositionSize()
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0)
return 0;
double slDistance = ATR_SL_Multiplier*atrBuffer[0];
if(slDistance <= 0)
return 0;
double tickValue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
if(tickValue <=0 || tickSize <=0)
return 0;
double riskMoney = balance*(RiskPercent/100.0);
double riskPerPoint = tickValue/tickSize;
double lot = riskMoney / (slDistance*riskPerPoint);
double minLot = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
double lotStep = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
if(lotStep <= 0)
lotStep=0.01;
lot = MathMax(minLot, MathMin(maxLot, MathFloor(lot/lotStep)*lotStep));
return lot;
}
//+------------------------------------------------------------------+
//| Executa ordine bazate pe semnale |
//+------------------------------------------------------------------+
void ExecuteTrade(MARKET_CONDITION cond)
{
datetime nowTime = TimeCurrent();
// Verificare cooldown directionat
if(cond == MARKET_TRENDING_UP && nowTime - lastBuyTime < TradeCooldownBuySeconds)
return;
if(cond == MARKET_TRENDING_DOWN && nowTime - lastSellTime < TradeCooldownSellSeconds)
return;
if(CountOpenPositions() >= MaxPositions)
return;
double lot = CalculatePositionSize();
if(lot <= 0)
return;
double slPrice, tpPrice, entryPrice;
switch(cond)
{
case MARKET_TRENDING_UP:
CloseAllSellPositions();
if(!HasBuyPosition())
{
entryPrice = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
slPrice = entryPrice - ATR_SL_Multiplier * atrBuffer[0];
tpPrice = entryPrice + ATR_TP_Multiplier * atrBuffer[0];
if(trade.Buy(lot,_Symbol,entryPrice,slPrice,tpPrice,"Long Trend UP"))
{
lastBuyTime = nowTime;
LogTrade("BUY", lot, entryPrice, slPrice, tpPrice, 0);
}
else
Print("BUY failed, err: ", GetLastError());
}
break;
case MARKET_TRENDING_DOWN:
CloseAllBuyPositions();
if(!HasSellPosition())
{
entryPrice = SymbolInfoDouble(_Symbol,SYMBOL_BID);
slPrice = entryPrice + ATR_SL_Multiplier * atrBuffer[0];
tpPrice = entryPrice - ATR_TP_Multiplier * atrBuffer[0];
if(trade.Sell(lot,_Symbol,entryPrice,slPrice,tpPrice,"Short Trend DOWN"))
{
lastSellTime = nowTime;
LogTrade("SELL", lot, entryPrice, slPrice, tpPrice, 0);
}
else
Print("SELL failed, err: ", GetLastError());
}
break;
case MARKET_RANGING:
// Nu tranzactionam
break;
}
}
//+------------------------------------------------------------------+
//| Trailing Stop Adaptiv |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol)
continue;
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ?
SymbolInfoDouble(_Symbol,SYMBOL_BID) :
SymbolInfoDouble(_Symbol,SYMBOL_ASK);
double profitPoints = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ?
(currentPrice - openPrice) / _Point :
(openPrice - currentPrice) / _Point;
if(profitPoints < TrailingActivationPoints)
continue;
double newSL, slOld = PositionGetDouble(POSITION_SL);
double atrTrailingDist = ATR_Trailing_Multiplier * atrBuffer[0];
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
newSL = currentPrice - atrTrailingDist;
if(newSL > slOld || slOld == 0)
if(!trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP)))
Print("Trailing BUY failed: ", GetLastError());
}
else
{
newSL = currentPrice + atrTrailingDist;
if(newSL < slOld || slOld == 0)
if(!trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP)))
Print("Trailing SELL failed: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Log tranzactie in fisier CSV |
//+------------------------------------------------------------------+
void LogTrade(string type, double lot, double openPrice, double sl, double tp, double profit)
{
string fileName = "DayTraderDynamic_Trades.csv";
int handle = FileOpen(fileName, FILE_WRITE | FILE_CSV);
if(handle != INVALID_HANDLE)
{
// Poziționare la sfârșitul fișierului pentru a adăuga date noi (append)
FileSeek(handle, 0, SEEK_END);
FileWrite(handle,
TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS),
type,
DoubleToString(lot, 2),
DoubleToString(openPrice, _Digits),
DoubleToString(sl, _Digits),
DoubleToString(tp, _Digits),
DoubleToString(profit, 2));
FileClose(handle);
}
else
Print("Eroare deschidere fisier log: ", GetLastError());
}
//+------------------------------------------------------------------+
//| Functii suport pozitiilor |
//+------------------------------------------------------------------+
int CountOpenPositions()
{
int cnt=0;
for(int i=0; i<PositionsTotal(); i++)
{
ulong ticket = PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol)
cnt++;
}
return cnt;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool HasBuyPosition()
{
for(int i=0; i<PositionsTotal(); i++)
{
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
bool HasSellPosition()
{
for(int i=0; i<PositionsTotal(); i++)
{
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
return true;
}
return false;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CloseAllBuyPositions()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
{
if(!trade.PositionClose(ticket))
Print("Eroare inchidere BUY: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void CloseAllSellPositions()
{
for(int i=PositionsTotal()-1; i>=0; i--)
{
ulong ticket=PositionGetTicket(i);
if(ticket==0)
continue;
if(!PositionSelectByTicket(ticket))
continue;
if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
{
if(!trade.PositionClose(ticket))
Print("Eroare inchidere SELL: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Tick principal |
//+------------------------------------------------------------------+
void OnTick()
{
if(!IsTradingAllowed())
return;
if(!UpdateIndicators())
return;
CalculateDynamicRSILevels();
double confidence = MarketConfidenceScore();
MARKET_CONDITION cond = DetectMarketCondition();
Comment(
"Piata Status: ", cond == MARKET_TRENDING_UP ? "Trend UP" :
cond == MARKET_TRENDING_DOWN ? "Trend DOWN" : "Ranging",
"\nConfidence: ", DoubleToString(confidence,0), "%",
"\nATR: ", DoubleToString(atrBuffer[0],5),
"\nRSI: ", DoubleToString(rsiBuffer[0],2), " (Dyn U=", DoubleToString(dynamicRSI_Upper,2), " L=", DoubleToString(dynamicRSI_Lower,2), ")",
"\nADX: ", DoubleToString(adxBuffer[0],2),
"\nPozitii Deschise: ", CountOpenPositions()
);
if(confidence < 60)
{
// Piata instabila, nu tranzactionam
return;
}
ExecuteTrade(cond);
if(UseTrailingStop)
ManageTrailingStop();
}
//+------------------------------------------------------------------+
Ce s-a modificat?
Funcția LogTrade():
Am eliminat flag-ul FILE_APPEND (care nu există în MQL5)
Am deschis fișierul doar cu FILE_WRITE | FILE_CSV
Am folosit FileSeek(handle, 0, SEEK_END); pentru a poziționa cursorul la sfârșitul fișierului, adăugând astfel noile înregistrări fără să suprascriem cele anterioare
Am adăugat un mesaj de eroare în cazul în care deschiderea fișierului eșuează
Testare
Pentru a testa logging-ul:
Asigură-te că folderul MQL5/Files are permisiuni de scriere.
Execută EA pe un grafic.
După plasarea primei tranzacții, verifică fisierul DayTraderDynamic_Trades.csv din MQL5\Files, conținutul ar trebui să conțină liniile cu tranzacțiile logate.
Dacă întâmpini alte probleme sau dorești alte ajustări – sunt aici să te ajut!
Copy first response
Not yet included in a published release.