Sử dụng OnTimer() cho periodic tasks, scheduled actions và time-based operations.
OnTimer() được gọi theo chu kỳ cố định (ví dụ mỗi 60 giây). Hữu ích cho tasks không cần chạy mỗi tick.
int OnInit() {
// Set timer: every 60 seconds
if(EventSetTimer(60)) {
Print("Timer set: 60 seconds");
return INIT_SUCCEEDED;
} else {
Print("Failed to set timer");
return INIT_FAILED;
}
}
void OnTimer() {
Print("Timer event at ", TimeToString(TimeCurrent()));
// Code runs every 60 seconds
}
void OnDeinit(const int reason) {
EventKillTimer();
Print("Timer stopped");
}
void OnTimer() {
// Check account status every minute
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double margin = AccountInfoDouble(ACCOUNT_MARGIN);
double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
Print("=== Account Status ===");
Print("Balance: $", balance);
Print("Equity: $", equity);
Print("Margin: $", margin);
Print("Free Margin: $", freeMargin);
// Check risk
double drawdown = (balance - equity) / balance * 100;
if(drawdown > 10) {
Print("⚠️ WARNING: Drawdown > 10%!");
SendEmail("Risk Alert", "Drawdown exceeded 10%");
}
}