1544 lines
No EOL
52 KiB
MQL5
1544 lines
No EOL
52 KiB
MQL5
//+------------------------------------------------------------------+
|
|
//| PropFirmGuard.mq5 |
|
|
//| Copyright 2026, MetaQuotes Ltd. |
|
|
//| https://www.mql5.com |
|
|
//+------------------------------------------------------------------+
|
|
#property copyright "Copyright 2026, MetaQuotes Ltd."
|
|
#property link "https://www.mql5.com"
|
|
#property version "1.00"
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Standard Library |
|
|
//+------------------------------------------------------------------+
|
|
#include <Trade\Trade.mqh>
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Enumerations |
|
|
//+------------------------------------------------------------------+
|
|
//| Represents the general compliance condition of the account. |
|
|
//+------------------------------------------------------------------+
|
|
enum ENUM_COMPLIANCE_STATUS
|
|
{
|
|
COMPLIANCE_SAFE = 0, // Account is operating within configured limits
|
|
COMPLIANCE_WARNING, // Account is approaching a compliance limit
|
|
COMPLIANCE_CRITICAL, // Account is very close to a compliance limit
|
|
COMPLIANCE_BREACHED // A configured compliance limit has been breached
|
|
};
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Profit target status |
|
|
//+------------------------------------------------------------------+
|
|
//| Represents progress toward the configured account profit target. |
|
|
//+------------------------------------------------------------------+
|
|
enum ENUM_TARGET_STATUS
|
|
{
|
|
TARGET_IN_PROGRESS = 0, // Target is still being pursued
|
|
TARGET_NEARING, // At least 90% of the target has been reached
|
|
TARGET_REACHED // Required target balance has been achieved
|
|
};
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Protection action |
|
|
//+------------------------------------------------------------------+
|
|
//| Defines what Prop Firm Guard should do when a monitored rule |
|
|
//| requires protective action. |
|
|
//+------------------------------------------------------------------+
|
|
enum ENUM_PROTECTION_ACTION
|
|
{
|
|
PROTECTION_WARN_ONLY = 0, // Report the condition without closing positions
|
|
PROTECTION_CLOSE_AFFECTED, // Close positions affected by the triggering rule
|
|
PROTECTION_CLOSE_ALL // Close every open account position
|
|
};
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Inputs |
|
|
//+------------------------------------------------------------------+
|
|
input group "General"
|
|
input int InpTimerSeconds = 1; // Dashboard update interval in seconds
|
|
input int InpDashboardX = 10; // Dashboard horizontal position
|
|
input int InpDashboardY = 105; // Dashboard vertical position
|
|
input bool InpEnableAlerts = true; // Enable terminal alerts
|
|
input bool InpEnablePushNotifications = false; // Enable mobile push notifications
|
|
|
|
input group "Prop Firm Rules"
|
|
input double InpInitialAccountBalance = 20000.0; // Initial prop-firm account balance
|
|
input double InpDailyDrawdownPercent = 5.0; // Maximum permitted daily drawdown
|
|
input double InpOverallDrawdownPercent = 10.0; // Maximum permitted overall drawdown
|
|
input double InpProfitTargetPercent = 8.0; // Required profit target
|
|
|
|
input group "Warning Levels"
|
|
input double InpWarningLevelPercent = 70.0; // Loss limit usage that triggers warning
|
|
input double InpCriticalLevelPercent = 90.0; // Loss limit usage that triggers critical state
|
|
|
|
input group "News Filter"
|
|
input bool InpEnableNewsFilter = true; // Enable economic news monitoring
|
|
input ENUM_CALENDAR_EVENT_IMPORTANCE InpNewsImportance = CALENDAR_IMPORTANCE_HIGH; // Minimum monitored importance
|
|
input int InpMinutesBeforeNews = 10; // Restricted minutes before news
|
|
input int InpMinutesAfterNews = 10; // Restricted minutes after news
|
|
input bool InpAllowNewsHolding = true; // Allow positions to remain open during news
|
|
|
|
input group "Protection Actions"
|
|
input ENUM_PROTECTION_ACTION InpDailyDrawdownAction = PROTECTION_WARN_ONLY; // Daily breach action
|
|
input ENUM_PROTECTION_ACTION InpOverallDrawdownAction = PROTECTION_WARN_ONLY; // Overall breach action
|
|
input ENUM_PROTECTION_ACTION InpNewsRestrictionAction = PROTECTION_WARN_ONLY; // News restriction action
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Account state structure |
|
|
//+------------------------------------------------------------------+
|
|
//| Holds the live account values required by the monitoring logic. |
|
|
//+------------------------------------------------------------------+
|
|
struct SAccountState
|
|
{
|
|
long login; // Trading account login number
|
|
double balance; // Current account balance
|
|
double equity; // Current account equity
|
|
double floatingPL; // Current floating profit or loss
|
|
ENUM_COMPLIANCE_STATUS status; // Current overall compliance status
|
|
};
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Account settings structure |
|
|
//+------------------------------------------------------------------+
|
|
//| Stores the main prop-firm rules associated with this account. |
|
|
//+------------------------------------------------------------------+
|
|
struct SAccountSettings
|
|
{
|
|
long accountLogin; // Trading account login
|
|
string accountServer; // Broker trading server
|
|
double initialBalance; // Initial prop-firm account balance
|
|
double dailyDrawdownPercent; // Maximum daily drawdown
|
|
double overallDrawdownPercent; // Maximum overall drawdown
|
|
double profitTargetPercent; // Required profit target
|
|
datetime updatedAt; // Last settings update time
|
|
};
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Daily session structure |
|
|
//+------------------------------------------------------------------+
|
|
//| Represents the persistent state associated with one trading day. |
|
|
//+------------------------------------------------------------------+
|
|
struct SDailySession
|
|
{
|
|
long accountLogin; // Trading account login
|
|
string accountServer; // Broker trading server
|
|
string tradingDate; // Trading date represented by this session
|
|
double startingBalance; // Confirmed daily starting balance
|
|
double startingEquity; // Equity captured when the baseline is confirmed
|
|
bool balanceConfirmed; // Whether the starting balance has been confirmed
|
|
double latestBalance; // Most recently recorded account balance
|
|
double latestEquity; // Most recently recorded account equity
|
|
double dailyLoss; // Persisted daily loss value
|
|
double maximumDailyLossReached; // Highest daily loss recorded during the session
|
|
double targetProgress; // Persisted profit-target progress
|
|
string sessionStatus; // Current persisted session status
|
|
datetime createdAt; // Time the session record was created
|
|
datetime updatedAt; // Time the session record was last updated
|
|
};
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Global variables |
|
|
//+------------------------------------------------------------------+
|
|
SAccountState g_accountState; // Latest monitored account state
|
|
SAccountSettings g_accountSettings; // Persisted prop-firm settings
|
|
SDailySession g_dailySession; // Current trading-day record
|
|
|
|
string g_startBalanceEdit = "PFG_StartBalanceEdit"; // Starting balance input field
|
|
string g_confirmButton = "PFG_ConfirmBalance"; // Daily balance confirmation button
|
|
string g_databaseName = "prop_firm_compliance.sqlite"; // SQLite database file
|
|
|
|
int g_database = INVALID_HANDLE; // Active SQLite database handle
|
|
bool g_hasDailySession = false; // Current-day session availability
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Validate compliance inputs |
|
|
//+------------------------------------------------------------------+
|
|
bool ValidateComplianceInputs()
|
|
{
|
|
//--- Validate the initial account balance
|
|
if(InpInitialAccountBalance <= 0.0)
|
|
{
|
|
Print("Prop Firm Guard: Initial account balance must be greater than zero.");
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Validate the daily drawdown percentage
|
|
if(InpDailyDrawdownPercent <= 0.0 ||
|
|
InpDailyDrawdownPercent > 100.0)
|
|
{
|
|
Print("Prop Firm Guard: Daily drawdown percentage must be between 0 and 100.");
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Validate the overall drawdown percentage
|
|
if(InpOverallDrawdownPercent <= 0.0 ||
|
|
InpOverallDrawdownPercent > 100.0)
|
|
{
|
|
Print("Prop Firm Guard: Overall drawdown percentage must be between 0 and 100.");
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Validate the profit target percentage
|
|
if(InpProfitTargetPercent <= 0.0 ||
|
|
InpProfitTargetPercent > 100.0)
|
|
{
|
|
Print("Prop Firm Guard: Profit target percentage must be between 0 and 100.");
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Validate the warning threshold
|
|
if(InpWarningLevelPercent <= 0.0 ||
|
|
InpWarningLevelPercent >= InpCriticalLevelPercent)
|
|
{
|
|
Print("Prop Firm Guard: Warning level must be greater than 0 and below the critical level.");
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Validate the critical threshold
|
|
if(InpCriticalLevelPercent <= InpWarningLevelPercent ||
|
|
InpCriticalLevelPercent >= 100.0)
|
|
{
|
|
Print("Prop Firm Guard: Critical level must be above the warning level and below 100.");
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Validate the news restriction windows
|
|
if(InpMinutesBeforeNews < 0 ||
|
|
InpMinutesAfterNews < 0)
|
|
{
|
|
Print("Prop Firm Guard: News restriction minutes cannot be negative.");
|
|
|
|
return(false);
|
|
}
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Update account state |
|
|
//+------------------------------------------------------------------+
|
|
void UpdateAccountState()
|
|
{
|
|
//--- Read the current account values
|
|
g_accountState.login = AccountInfoInteger(ACCOUNT_LOGIN);
|
|
g_accountState.balance = AccountInfoDouble(ACCOUNT_BALANCE);
|
|
g_accountState.equity = AccountInfoDouble(ACCOUNT_EQUITY);
|
|
|
|
//--- Derive the current floating profit or loss
|
|
g_accountState.floatingPL = g_accountState.equity - g_accountState.balance;
|
|
|
|
//--- Initialize compliance status before rule calculations are added
|
|
g_accountState.status = COMPLIANCE_SAFE;
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Get trading date |
|
|
//+------------------------------------------------------------------+
|
|
string GetTradingDate()
|
|
{
|
|
//--- Build the session date from trading-server time
|
|
datetime serverTime = TimeCurrent();
|
|
|
|
return(TimeToString(serverTime, TIME_DATE));
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Open database |
|
|
//+------------------------------------------------------------------+
|
|
bool OpenDatabase()
|
|
{
|
|
//--- Open or create the SQLite database
|
|
ResetLastError();
|
|
|
|
g_database = DatabaseOpen(g_databaseName,
|
|
DATABASE_OPEN_READWRITE |
|
|
DATABASE_OPEN_CREATE);
|
|
|
|
if(g_database == INVALID_HANDLE)
|
|
{
|
|
Print("Prop Firm Guard: Could not open database ",
|
|
g_databaseName,
|
|
". Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
Print("Prop Firm Guard: Database opened successfully: ",
|
|
g_databaseName);
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Close database |
|
|
//+------------------------------------------------------------------+
|
|
void CloseDatabase()
|
|
{
|
|
//--- Ignore the request when no database connection is active
|
|
if(g_database == INVALID_HANDLE)
|
|
return;
|
|
|
|
//--- Close the active SQLite connection
|
|
ResetLastError();
|
|
|
|
DatabaseClose(g_database);
|
|
|
|
int errorCode = GetLastError();
|
|
|
|
if(errorCode != 0)
|
|
{
|
|
Print("Prop Firm Guard: Database close reported error: ",
|
|
errorCode);
|
|
}
|
|
else
|
|
{
|
|
Print("Prop Firm Guard: Database closed successfully.");
|
|
}
|
|
|
|
//--- Clear the stored database handle
|
|
g_database = INVALID_HANDLE;
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Check whether database column exists |
|
|
//+------------------------------------------------------------------+
|
|
bool DatabaseColumnExists(const string tableName,
|
|
const string columnName)
|
|
{
|
|
//--- Inspect the current table schema
|
|
string sql = "PRAGMA table_info(" + tableName + ");";
|
|
|
|
ResetLastError();
|
|
|
|
int request = DatabasePrepare(g_database,
|
|
sql);
|
|
|
|
if(request == INVALID_HANDLE)
|
|
{
|
|
Print("Prop Firm Guard: Could not inspect table ",
|
|
tableName,
|
|
". Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
bool columnFound = false;
|
|
|
|
//--- Search the returned schema rows for the requested column
|
|
while(true)
|
|
{
|
|
ResetLastError();
|
|
|
|
if(!DatabaseRead(request))
|
|
{
|
|
int errorCode = GetLastError();
|
|
|
|
if(errorCode != ERR_DATABASE_NO_MORE_DATA)
|
|
{
|
|
Print("Prop Firm Guard: Could not read schema for ",
|
|
tableName,
|
|
". Error: ",
|
|
errorCode);
|
|
}
|
|
|
|
break;
|
|
}
|
|
|
|
string currentColumn;
|
|
|
|
//--- PRAGMA table_info returns the column name at index 1
|
|
if(!DatabaseColumnText(request,
|
|
1,
|
|
currentColumn))
|
|
{
|
|
Print("Prop Firm Guard: Could not read database column name. Error: ",
|
|
GetLastError());
|
|
|
|
break;
|
|
}
|
|
|
|
if(currentColumn == columnName)
|
|
{
|
|
columnFound = true;
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
//--- Release the schema request
|
|
FinalizeDatabaseRequest(request);
|
|
|
|
return(columnFound);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Ensure database column exists |
|
|
//+------------------------------------------------------------------+
|
|
bool EnsureDatabaseColumn(const string tableName,
|
|
const string columnName,
|
|
const string columnDefinition)
|
|
{
|
|
//--- Leave an existing column unchanged
|
|
if(DatabaseColumnExists(tableName,
|
|
columnName))
|
|
return(true);
|
|
|
|
//--- Add the missing column
|
|
string sql =
|
|
"ALTER TABLE " +
|
|
tableName +
|
|
" ADD COLUMN " +
|
|
columnName +
|
|
" " +
|
|
columnDefinition +
|
|
";";
|
|
|
|
ResetLastError();
|
|
|
|
if(!DatabaseExecute(g_database,
|
|
sql))
|
|
{
|
|
Print("Prop Firm Guard: Could not add column ",
|
|
columnName,
|
|
" to ",
|
|
tableName,
|
|
". Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
Print("Prop Firm Guard: Added database column ",
|
|
tableName,
|
|
".",
|
|
columnName,
|
|
".");
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Ensure runtime daily-session columns exist |
|
|
//+------------------------------------------------------------------+
|
|
bool EnsureDailySessionRuntimeColumns()
|
|
{
|
|
//--- Add runtime persistence columns when missing
|
|
if(!EnsureDatabaseColumn("daily_sessions",
|
|
"latest_balance",
|
|
"REAL NOT NULL DEFAULT 0"))
|
|
return(false);
|
|
|
|
if(!EnsureDatabaseColumn("daily_sessions",
|
|
"latest_equity",
|
|
"REAL NOT NULL DEFAULT 0"))
|
|
return(false);
|
|
|
|
if(!EnsureDatabaseColumn("daily_sessions",
|
|
"daily_loss",
|
|
"REAL NOT NULL DEFAULT 0"))
|
|
return(false);
|
|
|
|
if(!EnsureDatabaseColumn("daily_sessions",
|
|
"maximum_daily_loss_reached",
|
|
"REAL NOT NULL DEFAULT 0"))
|
|
return(false);
|
|
|
|
if(!EnsureDatabaseColumn("daily_sessions",
|
|
"target_progress",
|
|
"REAL NOT NULL DEFAULT 0"))
|
|
return(false);
|
|
|
|
if(!EnsureDatabaseColumn("daily_sessions",
|
|
"session_status",
|
|
"TEXT NOT NULL DEFAULT 'AWAITING_CONFIRMATION'"))
|
|
return(false);
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Ensure database tables exist |
|
|
//+------------------------------------------------------------------+
|
|
bool EnsureDatabaseTables()
|
|
{
|
|
//--- Define account-level settings storage
|
|
string settingsTable =
|
|
"CREATE TABLE IF NOT EXISTS settings ("
|
|
"account_login INTEGER NOT NULL,"
|
|
"account_server TEXT NOT NULL,"
|
|
"initial_balance REAL NOT NULL,"
|
|
"daily_drawdown_percent REAL NOT NULL,"
|
|
"overall_drawdown_percent REAL NOT NULL,"
|
|
"profit_target_percent REAL NOT NULL,"
|
|
"updated_at INTEGER NOT NULL,"
|
|
"PRIMARY KEY(account_login, account_server)"
|
|
");";
|
|
|
|
//--- Define persistent trading-day storage
|
|
string dailySessionsTable =
|
|
"CREATE TABLE IF NOT EXISTS daily_sessions ("
|
|
"account_login INTEGER NOT NULL,"
|
|
"account_server TEXT NOT NULL,"
|
|
"trading_date TEXT NOT NULL,"
|
|
"starting_balance REAL NOT NULL,"
|
|
"starting_equity REAL NOT NULL,"
|
|
"balance_confirmed INTEGER NOT NULL,"
|
|
"latest_balance REAL NOT NULL DEFAULT 0,"
|
|
"latest_equity REAL NOT NULL DEFAULT 0,"
|
|
"daily_loss REAL NOT NULL DEFAULT 0,"
|
|
"maximum_daily_loss_reached REAL NOT NULL DEFAULT 0,"
|
|
"target_progress REAL NOT NULL DEFAULT 0,"
|
|
"session_status TEXT NOT NULL DEFAULT 'AWAITING_CONFIRMATION',"
|
|
"created_at INTEGER NOT NULL,"
|
|
"updated_at INTEGER NOT NULL,"
|
|
"PRIMARY KEY(account_login, account_server, trading_date)"
|
|
");";
|
|
|
|
//--- Ensure the account settings table exists
|
|
ResetLastError();
|
|
|
|
if(!DatabaseExecute(g_database,
|
|
settingsTable))
|
|
{
|
|
Print("Prop Firm Guard: Could not create settings table. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Ensure the daily-session table exists
|
|
ResetLastError();
|
|
|
|
if(!DatabaseExecute(g_database,
|
|
dailySessionsTable))
|
|
{
|
|
Print("Prop Firm Guard: Could not create daily_sessions table. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Extend an existing daily-session table when required
|
|
if(!EnsureDailySessionRuntimeColumns())
|
|
return(false);
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Check for new trading day |
|
|
//+------------------------------------------------------------------+
|
|
void CheckForNewTradingDay()
|
|
{
|
|
//--- Read the current server-based trading date
|
|
string currentDate = GetTradingDate();
|
|
|
|
//--- Keep the active session when it already belongs to today
|
|
if(g_hasDailySession &&
|
|
g_dailySession.tradingDate == currentDate)
|
|
return;
|
|
|
|
Print("Prop Firm Guard: New trading day detected: ",
|
|
currentDate);
|
|
|
|
//--- Restore or create the session for the new trading date
|
|
if(!InitializeDailySession())
|
|
{
|
|
Print("Prop Firm Guard: Could not initialize the new daily session.");
|
|
|
|
return;
|
|
}
|
|
|
|
//--- Rebuild the confirmation controls for the newly loaded session
|
|
DeleteDailySessionControls();
|
|
|
|
if(!CreateDailySessionControls())
|
|
{
|
|
Print("Prop Firm Guard: Could not create daily session controls.");
|
|
}
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Finalize database request |
|
|
//+------------------------------------------------------------------+
|
|
void FinalizeDatabaseRequest(const int request)
|
|
{
|
|
//--- Ignore invalid database requests
|
|
if(request == INVALID_HANDLE)
|
|
return;
|
|
|
|
//--- Release the prepared database request
|
|
ResetLastError();
|
|
|
|
DatabaseFinalize(request);
|
|
|
|
int errorCode = GetLastError();
|
|
|
|
if(errorCode != 0)
|
|
{
|
|
Print("Prop Firm Guard: Could not finalize database request. Error: ",
|
|
errorCode);
|
|
}
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Execute prepared database request |
|
|
//+------------------------------------------------------------------+
|
|
bool ExecuteDatabaseRequest(const int request,
|
|
const string operation)
|
|
{
|
|
//--- Execute the prepared database statement
|
|
ResetLastError();
|
|
|
|
bool result = DatabaseRead(request);
|
|
|
|
int errorCode = GetLastError();
|
|
|
|
//--- Write statements return no result rows after successful execution
|
|
bool success =
|
|
(result || errorCode == ERR_DATABASE_NO_MORE_DATA);
|
|
|
|
if(!success)
|
|
{
|
|
Print("Prop Firm Guard: Database error while ",
|
|
operation,
|
|
". Error: ",
|
|
errorCode);
|
|
}
|
|
|
|
//--- Release the request after execution
|
|
FinalizeDatabaseRequest(request);
|
|
|
|
return(success);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Save account settings |
|
|
//+------------------------------------------------------------------+
|
|
bool SaveAccountSettings()
|
|
{
|
|
//--- Prepare the account-settings write statement
|
|
string sql =
|
|
"INSERT OR REPLACE INTO settings ("
|
|
"account_login,"
|
|
"account_server,"
|
|
"initial_balance,"
|
|
"daily_drawdown_percent,"
|
|
"overall_drawdown_percent,"
|
|
"profit_target_percent,"
|
|
"updated_at"
|
|
") VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7);";
|
|
|
|
int request = DatabasePrepare(g_database, sql);
|
|
|
|
if(request == INVALID_HANDLE)
|
|
{
|
|
Print("Prop Firm Guard: Could not prepare settings save request. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Bind the current account settings to the prepared statement
|
|
if(!DatabaseBind(request, 0, g_accountSettings.accountLogin) ||
|
|
!DatabaseBind(request, 1, g_accountSettings.accountServer) ||
|
|
!DatabaseBind(request, 2, g_accountSettings.initialBalance) ||
|
|
!DatabaseBind(request, 3, g_accountSettings.dailyDrawdownPercent) ||
|
|
!DatabaseBind(request, 4, g_accountSettings.overallDrawdownPercent) ||
|
|
!DatabaseBind(request, 5, g_accountSettings.profitTargetPercent) ||
|
|
!DatabaseBind(request, 6, g_accountSettings.updatedAt))
|
|
{
|
|
Print("Prop Firm Guard: Could not bind settings values. Error: ",
|
|
GetLastError());
|
|
|
|
FinalizeDatabaseRequest(request);
|
|
return(false);
|
|
}
|
|
|
|
//--- Execute and finalize the prepared write request
|
|
if(!ExecuteDatabaseRequest(request, "saving account settings"))
|
|
return(false);
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Load account settings |
|
|
//+------------------------------------------------------------------+
|
|
bool LoadAccountSettings()
|
|
{
|
|
//--- Build the current account/server lookup
|
|
string accountServer = AccountInfoString(ACCOUNT_SERVER);
|
|
|
|
string sql =
|
|
"SELECT "
|
|
"account_login,"
|
|
"account_server,"
|
|
"initial_balance,"
|
|
"daily_drawdown_percent,"
|
|
"overall_drawdown_percent,"
|
|
"profit_target_percent,"
|
|
"updated_at "
|
|
"FROM settings "
|
|
"WHERE account_login = ?1 AND account_server = ?2;";
|
|
|
|
int request = DatabasePrepare(g_database, sql);
|
|
|
|
if(request == INVALID_HANDLE)
|
|
{
|
|
Print("Prop Firm Guard: Could not prepare settings load request. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Bind the current account identity
|
|
if(!DatabaseBind(request, 0, g_accountState.login) ||
|
|
!DatabaseBind(request, 1, accountServer))
|
|
{
|
|
Print("Prop Firm Guard: Could not bind settings search values. Error: ",
|
|
GetLastError());
|
|
|
|
FinalizeDatabaseRequest(request);
|
|
return(false);
|
|
}
|
|
|
|
//--- Read the matching settings record
|
|
ResetLastError();
|
|
|
|
if(!DatabaseRead(request))
|
|
{
|
|
int errorCode = GetLastError();
|
|
|
|
FinalizeDatabaseRequest(request);
|
|
|
|
//--- No row means this account/server pair has not been saved yet
|
|
if(errorCode == ERR_DATABASE_NO_MORE_DATA)
|
|
return(false);
|
|
|
|
Print("Prop Firm Guard: Could not read account settings. Error: ",
|
|
errorCode);
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Read and validate the stored column values
|
|
long accountLogin;
|
|
string storedServer;
|
|
double initialBalance;
|
|
double dailyDrawdown;
|
|
double overallDrawdown;
|
|
double profitTarget;
|
|
long updatedAt;
|
|
|
|
if(!DatabaseColumnLong(request, 0, accountLogin) ||
|
|
!DatabaseColumnText(request, 1, storedServer) ||
|
|
!DatabaseColumnDouble(request, 2, initialBalance) ||
|
|
!DatabaseColumnDouble(request, 3, dailyDrawdown) ||
|
|
!DatabaseColumnDouble(request, 4, overallDrawdown) ||
|
|
!DatabaseColumnDouble(request, 5, profitTarget) ||
|
|
!DatabaseColumnLong(request, 6, updatedAt))
|
|
{
|
|
Print("Prop Firm Guard: Could not read stored settings columns. Error: ",
|
|
GetLastError());
|
|
|
|
FinalizeDatabaseRequest(request);
|
|
return(false);
|
|
}
|
|
|
|
//--- Restore the stored values into the account settings structure
|
|
g_accountSettings.accountLogin = accountLogin;
|
|
g_accountSettings.accountServer = storedServer;
|
|
g_accountSettings.initialBalance = initialBalance;
|
|
g_accountSettings.dailyDrawdownPercent = dailyDrawdown;
|
|
g_accountSettings.overallDrawdownPercent = overallDrawdown;
|
|
g_accountSettings.profitTargetPercent = profitTarget;
|
|
g_accountSettings.updatedAt = (datetime)updatedAt;
|
|
|
|
//--- Release the completed read request
|
|
FinalizeDatabaseRequest(request);
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Initialize daily session |
|
|
//+------------------------------------------------------------------+
|
|
bool InitializeDailySession()
|
|
{
|
|
//--- Identify the current trading day
|
|
string tradingDate = GetTradingDate();
|
|
|
|
//--- Restore today's session when it already exists
|
|
if(DailySessionExists(tradingDate))
|
|
{
|
|
if(!LoadDailySession())
|
|
return(false);
|
|
|
|
g_hasDailySession = true;
|
|
|
|
Print("Prop Firm Guard: Daily session restored for ",
|
|
tradingDate,
|
|
".");
|
|
|
|
return(true);
|
|
}
|
|
|
|
//--- Create a new unconfirmed session for the current trading day
|
|
g_dailySession.accountLogin = g_accountState.login;
|
|
g_dailySession.accountServer = AccountInfoString(ACCOUNT_SERVER);
|
|
g_dailySession.tradingDate = tradingDate;
|
|
g_dailySession.startingBalance = 0.0;
|
|
g_dailySession.startingEquity = 0.0;
|
|
g_dailySession.balanceConfirmed = false;
|
|
g_dailySession.latestBalance = g_accountState.balance;
|
|
g_dailySession.latestEquity = g_accountState.equity;
|
|
g_dailySession.dailyLoss = 0.0;
|
|
g_dailySession.maximumDailyLossReached = 0.0;
|
|
g_dailySession.targetProgress = 0.0;
|
|
g_dailySession.sessionStatus = "AWAITING_CONFIRMATION";
|
|
g_dailySession.createdAt = TimeCurrent();
|
|
g_dailySession.updatedAt = TimeCurrent();
|
|
|
|
//--- Persist the new daily-session record
|
|
if(!SaveDailySession())
|
|
return(false);
|
|
|
|
g_hasDailySession = true;
|
|
|
|
Print("Prop Firm Guard: New daily session created for ",
|
|
tradingDate,
|
|
".");
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Initialize account settings |
|
|
//+------------------------------------------------------------------+
|
|
bool InitializeAccountSettings()
|
|
{
|
|
//--- Check whether this account/server pair already has stored settings
|
|
bool settingsFound = LoadAccountSettings();
|
|
|
|
//--- Associate the settings with the current trading account
|
|
g_accountSettings.accountLogin = g_accountState.login;
|
|
g_accountSettings.accountServer = AccountInfoString(ACCOUNT_SERVER);
|
|
|
|
//--- Synchronize persistence with the current Inputs values
|
|
g_accountSettings.initialBalance = InpInitialAccountBalance;
|
|
g_accountSettings.dailyDrawdownPercent = InpDailyDrawdownPercent;
|
|
g_accountSettings.overallDrawdownPercent = InpOverallDrawdownPercent;
|
|
g_accountSettings.profitTargetPercent = InpProfitTargetPercent;
|
|
g_accountSettings.updatedAt = TimeCurrent();
|
|
|
|
//--- Save the synchronized configuration
|
|
if(!SaveAccountSettings())
|
|
return(false);
|
|
|
|
//--- Report whether the record was created or synchronized
|
|
if(settingsFound)
|
|
Print("Prop Firm Guard: Account settings restored and synchronized.");
|
|
else
|
|
Print("Prop Firm Guard: New account settings saved.");
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Save daily session |
|
|
//+------------------------------------------------------------------+
|
|
bool SaveDailySession()
|
|
{
|
|
//--- Prepare the complete daily-session record
|
|
string sql =
|
|
"INSERT OR REPLACE INTO daily_sessions ("
|
|
"account_login,"
|
|
"account_server,"
|
|
"trading_date,"
|
|
"starting_balance,"
|
|
"starting_equity,"
|
|
"balance_confirmed,"
|
|
"latest_balance,"
|
|
"latest_equity,"
|
|
"daily_loss,"
|
|
"maximum_daily_loss_reached,"
|
|
"target_progress,"
|
|
"session_status,"
|
|
"created_at,"
|
|
"updated_at"
|
|
") VALUES ("
|
|
"?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14"
|
|
");";
|
|
|
|
ResetLastError();
|
|
|
|
int request = DatabasePrepare(g_database,
|
|
sql,
|
|
g_dailySession.accountLogin,
|
|
g_dailySession.accountServer,
|
|
g_dailySession.tradingDate,
|
|
g_dailySession.startingBalance,
|
|
g_dailySession.startingEquity,
|
|
g_dailySession.balanceConfirmed ? 1 : 0,
|
|
g_dailySession.latestBalance,
|
|
g_dailySession.latestEquity,
|
|
g_dailySession.dailyLoss,
|
|
g_dailySession.maximumDailyLossReached,
|
|
g_dailySession.targetProgress,
|
|
g_dailySession.sessionStatus,
|
|
(long)g_dailySession.createdAt,
|
|
(long)g_dailySession.updatedAt);
|
|
|
|
if(request == INVALID_HANDLE)
|
|
{
|
|
Print("Prop Firm Guard: Could not prepare daily session save request. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Execute and finalize the prepared write request
|
|
return(ExecuteDatabaseRequest(request,
|
|
"saving daily session"));
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Load daily session |
|
|
//+------------------------------------------------------------------+
|
|
bool LoadDailySession()
|
|
{
|
|
//--- Select the session belonging to the current account and date
|
|
string sql =
|
|
"SELECT "
|
|
"account_login,"
|
|
"account_server,"
|
|
"trading_date,"
|
|
"starting_balance,"
|
|
"starting_equity,"
|
|
"balance_confirmed,"
|
|
"latest_balance,"
|
|
"latest_equity,"
|
|
"daily_loss,"
|
|
"maximum_daily_loss_reached,"
|
|
"target_progress,"
|
|
"session_status,"
|
|
"created_at,"
|
|
"updated_at "
|
|
"FROM daily_sessions "
|
|
"WHERE account_login=?1 "
|
|
"AND account_server=?2 "
|
|
"AND trading_date=?3;";
|
|
|
|
string tradingDate = GetTradingDate();
|
|
string accountServer = AccountInfoString(ACCOUNT_SERVER);
|
|
|
|
ResetLastError();
|
|
|
|
int request = DatabasePrepare(g_database,
|
|
sql,
|
|
g_accountState.login,
|
|
accountServer,
|
|
tradingDate);
|
|
|
|
if(request == INVALID_HANDLE)
|
|
{
|
|
Print("Prop Firm Guard: Could not prepare daily session load request. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Read the matching record
|
|
ResetLastError();
|
|
|
|
if(!DatabaseRead(request))
|
|
{
|
|
int errorCode = GetLastError();
|
|
|
|
if(errorCode != ERR_DATABASE_NO_MORE_DATA)
|
|
{
|
|
Print("Prop Firm Guard: Could not load daily session. Error: ",
|
|
errorCode);
|
|
}
|
|
|
|
FinalizeDatabaseRequest(request);
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Read all stored values before updating the in-memory session
|
|
long accountLogin;
|
|
string loadedServer;
|
|
string loadedDate;
|
|
double startingBalance;
|
|
double startingEquity;
|
|
int balanceConfirmed;
|
|
double latestBalance;
|
|
double latestEquity;
|
|
double dailyLoss;
|
|
double maximumDailyLossReached;
|
|
double targetProgress;
|
|
string sessionStatus;
|
|
long createdAt;
|
|
long updatedAt;
|
|
|
|
bool loaded =
|
|
DatabaseColumnLong(request, 0, accountLogin) &&
|
|
DatabaseColumnText(request, 1, loadedServer) &&
|
|
DatabaseColumnText(request, 2, loadedDate) &&
|
|
DatabaseColumnDouble(request, 3, startingBalance) &&
|
|
DatabaseColumnDouble(request, 4, startingEquity) &&
|
|
DatabaseColumnInteger(request, 5, balanceConfirmed) &&
|
|
DatabaseColumnDouble(request, 6, latestBalance) &&
|
|
DatabaseColumnDouble(request, 7, latestEquity) &&
|
|
DatabaseColumnDouble(request, 8, dailyLoss) &&
|
|
DatabaseColumnDouble(request, 9, maximumDailyLossReached) &&
|
|
DatabaseColumnDouble(request, 10, targetProgress) &&
|
|
DatabaseColumnText(request, 11, sessionStatus) &&
|
|
DatabaseColumnLong(request, 12, createdAt) &&
|
|
DatabaseColumnLong(request, 13, updatedAt);
|
|
|
|
if(!loaded)
|
|
{
|
|
Print("Prop Firm Guard: Could not read daily session columns. Error: ",
|
|
GetLastError());
|
|
|
|
FinalizeDatabaseRequest(request);
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Restore the complete daily-session state
|
|
g_dailySession.accountLogin = accountLogin;
|
|
g_dailySession.accountServer = loadedServer;
|
|
g_dailySession.tradingDate = loadedDate;
|
|
g_dailySession.startingBalance = startingBalance;
|
|
g_dailySession.startingEquity = startingEquity;
|
|
g_dailySession.balanceConfirmed = (balanceConfirmed != 0);
|
|
g_dailySession.latestBalance = latestBalance;
|
|
g_dailySession.latestEquity = latestEquity;
|
|
g_dailySession.dailyLoss = dailyLoss;
|
|
g_dailySession.maximumDailyLossReached = maximumDailyLossReached;
|
|
g_dailySession.targetProgress = targetProgress;
|
|
g_dailySession.sessionStatus = sessionStatus;
|
|
g_dailySession.createdAt = (datetime)createdAt;
|
|
g_dailySession.updatedAt = (datetime)updatedAt;
|
|
|
|
//--- Release the completed read request
|
|
FinalizeDatabaseRequest(request);
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Check daily session existence |
|
|
//+------------------------------------------------------------------+
|
|
bool DailySessionExists(const string tradingDate)
|
|
{
|
|
//--- Build the session identity for the requested trading date
|
|
string accountServer = AccountInfoString(ACCOUNT_SERVER);
|
|
|
|
string sql =
|
|
"SELECT 1 "
|
|
"FROM daily_sessions "
|
|
"WHERE account_login = ?1 "
|
|
"AND account_server = ?2 "
|
|
"AND trading_date = ?3 "
|
|
"LIMIT 1;";
|
|
|
|
int request = DatabasePrepare(g_database, sql);
|
|
|
|
if(request == INVALID_HANDLE)
|
|
{
|
|
Print("Prop Firm Guard: Could not prepare session existence request. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Bind the current account, server, and requested date
|
|
if(!DatabaseBind(request, 0, g_accountState.login) ||
|
|
!DatabaseBind(request, 1, accountServer) ||
|
|
!DatabaseBind(request, 2, tradingDate))
|
|
{
|
|
Print("Prop Firm Guard: Could not bind session existence values. Error: ",
|
|
GetLastError());
|
|
|
|
FinalizeDatabaseRequest(request);
|
|
return(false);
|
|
}
|
|
|
|
//--- Check whether one matching row exists
|
|
ResetLastError();
|
|
|
|
bool exists = DatabaseRead(request);
|
|
|
|
int errorCode = GetLastError();
|
|
|
|
FinalizeDatabaseRequest(request);
|
|
|
|
if(!exists && errorCode != ERR_DATABASE_NO_MORE_DATA)
|
|
{
|
|
Print("Prop Firm Guard: Could not check daily session existence. Error: ",
|
|
errorCode);
|
|
}
|
|
|
|
return(exists);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Create starting balance edit |
|
|
//+------------------------------------------------------------------+
|
|
bool CreateStartingBalanceEdit(const int x,
|
|
const int y,
|
|
const string suggestedBalance)
|
|
{
|
|
//--- Create the editable starting-balance field
|
|
if(!ObjectCreate(0,
|
|
g_startBalanceEdit,
|
|
OBJ_EDIT,
|
|
0,
|
|
0,
|
|
0))
|
|
{
|
|
Print("Prop Firm Guard: Could not create starting balance field. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Configure the field position and appearance
|
|
if(!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_CORNER,
|
|
CORNER_LEFT_UPPER) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_XDISTANCE,
|
|
x) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_YDISTANCE,
|
|
y) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_XSIZE,
|
|
120) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_YSIZE,
|
|
20) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_FONTSIZE,
|
|
9) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_COLOR,
|
|
clrBlack) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_BGCOLOR,
|
|
clrWhite) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_BORDER_COLOR,
|
|
clrSilver) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_ALIGN,
|
|
ALIGN_RIGHT) ||
|
|
!ObjectSetInteger(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_HIDDEN,
|
|
true))
|
|
{
|
|
Print("Prop Firm Guard: Could not configure starting balance field. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Apply the suggested balance and text properties
|
|
if(!ObjectSetString(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_FONT,
|
|
"Tahoma") ||
|
|
!ObjectSetString(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_TEXT,
|
|
suggestedBalance))
|
|
{
|
|
Print("Prop Firm Guard: Could not initialize starting balance field. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Create confirm balance button |
|
|
//+------------------------------------------------------------------+
|
|
bool CreateConfirmBalanceButton(const int x,
|
|
const int y)
|
|
{
|
|
//--- Create the daily-balance confirmation button
|
|
if(!ObjectCreate(0,
|
|
g_confirmButton,
|
|
OBJ_BUTTON,
|
|
0,
|
|
0,
|
|
0))
|
|
{
|
|
Print("Prop Firm Guard: Could not create confirmation button. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Configure the button position and appearance
|
|
if(!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_CORNER,
|
|
CORNER_LEFT_UPPER) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_XDISTANCE,
|
|
x) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_YDISTANCE,
|
|
y) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_XSIZE,
|
|
100) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_YSIZE,
|
|
20) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_FONTSIZE,
|
|
9) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_COLOR,
|
|
clrBlack) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_BGCOLOR,
|
|
clrWhite) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_BORDER_COLOR,
|
|
clrSilver) ||
|
|
!ObjectSetInteger(0,
|
|
g_confirmButton,
|
|
OBJPROP_HIDDEN,
|
|
true))
|
|
{
|
|
Print("Prop Firm Guard: Could not configure confirmation button. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Apply the button text and font
|
|
if(!ObjectSetString(0,
|
|
g_confirmButton,
|
|
OBJPROP_FONT,
|
|
"Tahoma") ||
|
|
!ObjectSetString(0,
|
|
g_confirmButton,
|
|
OBJPROP_TEXT,
|
|
"Confirm"))
|
|
{
|
|
Print("Prop Firm Guard: Could not initialize confirmation button. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Create daily session controls |
|
|
//+------------------------------------------------------------------+
|
|
bool CreateDailySessionControls()
|
|
{
|
|
//--- Skip the controls when today's balance is already confirmed
|
|
if(g_dailySession.balanceConfirmed)
|
|
return(true);
|
|
|
|
int controlX = InpDashboardX + 18;
|
|
int controlY = InpDashboardY + 120;
|
|
|
|
//--- Suggest the current balance without confirming it
|
|
string suggestedBalance =
|
|
DoubleToString(g_accountState.balance, 2);
|
|
|
|
//--- Create the editable starting-balance field
|
|
if(!CreateStartingBalanceEdit(controlX,
|
|
controlY,
|
|
suggestedBalance))
|
|
return(false);
|
|
|
|
//--- Create the confirmation button beside the edit field
|
|
if(!CreateConfirmBalanceButton(controlX + 130,
|
|
controlY))
|
|
return(false);
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Delete daily session controls |
|
|
//+------------------------------------------------------------------+
|
|
void DeleteDailySessionControls()
|
|
{
|
|
//--- Remove the starting-balance field when present
|
|
if(ObjectFind(0, g_startBalanceEdit) >= 0)
|
|
{
|
|
if(!ObjectDelete(0, g_startBalanceEdit))
|
|
{
|
|
Print("Prop Firm Guard: Could not delete starting balance field. Error: ",
|
|
GetLastError());
|
|
}
|
|
}
|
|
|
|
//--- Remove the confirmation button when present
|
|
if(ObjectFind(0, g_confirmButton) >= 0)
|
|
{
|
|
if(!ObjectDelete(0, g_confirmButton))
|
|
{
|
|
Print("Prop Firm Guard: Could not delete confirmation button. Error: ",
|
|
GetLastError());
|
|
}
|
|
}
|
|
|
|
ChartRedraw();
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Confirm daily starting balance |
|
|
//+------------------------------------------------------------------+
|
|
bool ConfirmDailyStartingBalance()
|
|
{
|
|
//--- Do not overwrite an already confirmed daily baseline
|
|
if(g_dailySession.balanceConfirmed)
|
|
{
|
|
Print("Prop Firm Guard: Today's starting balance is already confirmed.");
|
|
|
|
return(true);
|
|
}
|
|
|
|
string balanceText;
|
|
|
|
ResetLastError();
|
|
|
|
//--- Read the value entered in the starting-balance field
|
|
if(!ObjectGetString(0,
|
|
g_startBalanceEdit,
|
|
OBJPROP_TEXT,
|
|
0,
|
|
balanceText))
|
|
{
|
|
Print("Prop Firm Guard: Could not read starting balance field. Error: ",
|
|
GetLastError());
|
|
|
|
return(false);
|
|
}
|
|
|
|
double startingBalance = StringToDouble(balanceText);
|
|
|
|
//--- Reject an invalid daily starting balance
|
|
if(startingBalance <= 0.0)
|
|
{
|
|
Alert("Prop Firm Guard: Enter a valid starting balance greater than zero.");
|
|
|
|
return(false);
|
|
}
|
|
|
|
//--- Store the confirmed daily reference
|
|
g_dailySession.startingBalance = startingBalance;
|
|
g_dailySession.startingEquity = g_accountState.equity;
|
|
g_dailySession.balanceConfirmed = true;
|
|
g_dailySession.updatedAt = TimeCurrent();
|
|
|
|
//--- Persist the confirmed session immediately
|
|
if(!SaveDailySession())
|
|
{
|
|
Print("Prop Firm Guard: Could not save confirmed daily session.");
|
|
|
|
//--- Do not report a confirmed state that SQLite failed to preserve
|
|
g_dailySession.balanceConfirmed = false;
|
|
|
|
return(false);
|
|
}
|
|
|
|
Print("Prop Firm Guard: Daily starting balance confirmed at ",
|
|
DoubleToString(g_dailySession.startingBalance, 2),
|
|
" for ",
|
|
g_dailySession.tradingDate,
|
|
".");
|
|
|
|
//--- Remove controls after the confirmed value has been stored
|
|
DeleteDailySessionControls();
|
|
|
|
return(true);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Expert initialization function |
|
|
//+------------------------------------------------------------------+
|
|
int OnInit()
|
|
{
|
|
//--- Validate the monitoring interval
|
|
if(InpTimerSeconds < 1)
|
|
{
|
|
Print("Prop Firm Guard: Timer interval must be at least 1 second.");
|
|
|
|
return(INIT_PARAMETERS_INCORRECT);
|
|
}
|
|
|
|
//--- Validate the configured prop-firm rules
|
|
if(!ValidateComplianceInputs())
|
|
return(INIT_PARAMETERS_INCORRECT);
|
|
|
|
//--- Read the current account state
|
|
UpdateAccountState();
|
|
|
|
//--- Open the persistence layer
|
|
if(!OpenDatabase())
|
|
{
|
|
Print("Prop Firm Guard: Database initialization failed.");
|
|
|
|
return(INIT_FAILED);
|
|
}
|
|
|
|
//--- Ensure the required database schema exists
|
|
if(!EnsureDatabaseTables())
|
|
{
|
|
Print("Prop Firm Guard: Could not initialize database tables.");
|
|
|
|
CloseDatabase();
|
|
|
|
return(INIT_FAILED);
|
|
}
|
|
|
|
//--- Initialize the current account settings
|
|
if(!InitializeAccountSettings())
|
|
{
|
|
Print("Prop Firm Guard: Could not initialize account settings.");
|
|
|
|
CloseDatabase();
|
|
|
|
return(INIT_FAILED);
|
|
}
|
|
|
|
//--- Restore or create today's daily session
|
|
if(!InitializeDailySession())
|
|
{
|
|
Print("Prop Firm Guard: Could not initialize daily session.");
|
|
|
|
CloseDatabase();
|
|
|
|
return(INIT_FAILED);
|
|
}
|
|
|
|
//--- Create confirmation controls when required
|
|
if(!CreateDailySessionControls())
|
|
{
|
|
Print("Prop Firm Guard: Could not create daily session controls.");
|
|
|
|
DeleteDailySessionControls();
|
|
CloseDatabase();
|
|
|
|
return(INIT_FAILED);
|
|
}
|
|
|
|
//--- Start periodic session monitoring
|
|
if(!EventSetTimer(InpTimerSeconds))
|
|
{
|
|
Print("Prop Firm Guard: Failed to start the timer. Error: ",
|
|
GetLastError());
|
|
|
|
DeleteDailySessionControls();
|
|
CloseDatabase();
|
|
|
|
return(INIT_FAILED);
|
|
}
|
|
|
|
Print("Prop Firm Guard initialized successfully.");
|
|
|
|
return(INIT_SUCCEEDED);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Expert deinitialization function |
|
|
//+------------------------------------------------------------------+
|
|
void OnDeinit(const int reason)
|
|
{
|
|
//--- Stop periodic events
|
|
EventKillTimer();
|
|
|
|
//--- Remove daily-session controls
|
|
DeleteDailySessionControls();
|
|
|
|
//--- Close the SQLite connection
|
|
CloseDatabase();
|
|
|
|
Print("Prop Firm Guard removed. Deinitialization reason: ", reason);
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Expert tick function |
|
|
//+------------------------------------------------------------------+
|
|
void OnTick()
|
|
{
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Timer function |
|
|
//+------------------------------------------------------------------+
|
|
void OnTimer()
|
|
{
|
|
//--- Refresh live account values
|
|
UpdateAccountState();
|
|
|
|
//--- Maintain the current trading-day session
|
|
CheckForNewTradingDay();
|
|
}
|
|
|
|
//+------------------------------------------------------------------+
|
|
//| Chart event function |
|
|
//+------------------------------------------------------------------+
|
|
void OnChartEvent(const int id,
|
|
const long &lparam,
|
|
const double &dparam,
|
|
const string &sparam)
|
|
{
|
|
//--- Process chart-object clicks only
|
|
if(id != CHARTEVENT_OBJECT_CLICK)
|
|
return;
|
|
|
|
//--- Confirm the entered balance when the confirmation button is clicked
|
|
if(sparam == g_confirmButton)
|
|
{
|
|
if(!ConfirmDailyStartingBalance())
|
|
Print("Prop Firm Guard: Starting balance confirmation failed.");
|
|
}
|
|
}
|
|
//+------------------------------------------------------------------+ |