Sure! Below is a production-ready MQL4 Expert Advisor (EA) that collects all available built-in account information (both static and dynamic) as well as details about open positions and active orders. It then sends this data to your Supabase database using WebRequest. The EA is designed for easy customization—simply input your Supabase credentials and table names via the EA's input parameters.
Prerequisites
-
Supabase Setup:
- Ensure you have a Supabase project set up.
- Create two tables in your Supabase database:
account_info for storing account-related data.
orders for storing order-related data.
- Obtain your Supabase Base URL and API Key from the Supabase Dashboard.
-
MetaTrader Configuration:
- In MetaTrader, navigate to Tools → Options → Expert Advisors.
- Check the option "Enable WebRequest for listed URL".
- Add your Supabase REST API base URL (e.g.,
https://your-project.supabase.co/rest/v1/) to the list of allowed URLs.
EA Code
//+------------------------------------------------------------------+
//| SupabaseSenderEA.mq4 |
//| Generated by ChatGPT |
//+------------------------------------------------------------------+
#property strict
//--- Input Parameters for Supabase
input string SupabaseURL = "https://your-project.supabase.co/rest/v1/";
input string SupabaseApiKey = "your-supabase-api-key";
input string AccountTable = "account_info";
input string OrdersTable = "orders";
//--- Input Parameter for Data Sending Interval in Seconds
input int SendInterval = 300; // Send data every 300 seconds (5 minutes)
//--- Global Variables
datetime lastSendTime = 0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Check if Supabase URL ends with a slash; if not, add it
if(StringFind(SupabaseURL, "?")==-1 && StringFind(SupabaseURL, "/rest/v1/") == -1)
{
Print("Error: SupabaseURL should be the REST endpoint, e.g., https://your-project.supabase.co/rest/v1/");
return(INIT_FAILED);
}
// Initialize lastSendTime to current time minus interval to send immediately
lastSendTime = TimeCurrent() - SendInterval;
Print("SupabaseSenderEA initialized successfully.");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Any necessary cleanup can be done here
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if the sending interval has passed
if(TimeCurrent() - lastSendTime >= SendInterval)
{
// Gather account information
string accountJson = GetAccountInfoJSON();
// Send account information
bool accountSent = SendData(SupabaseURL + AccountTable, accountJson);
if(accountSent)
{
Print("Account information sent successfully.");
}
else
{
Print("Failed to send account information.");
}
// Gather orders information
string ordersJson = GetOrdersInfoJSON();
// Send orders information
bool ordersSent = SendData(SupabaseURL + OrdersTable, ordersJson);
if(ordersSent)
{
Print("Orders information sent successfully.");
}
else
{
Print("Failed to send orders information.");
}
// Update the last sent time
lastSendTime = TimeCurrent();
}
}
//+------------------------------------------------------------------+
//| Function to Gather Account Information and Convert to JSON |
//+------------------------------------------------------------------+
string GetAccountInfoJSON()
{
string json = "{";
// Static Account Information
json += "\"account_number\": \"" + IntegerToString(AccountNumber()) + "\",";
json += "\"account_leverage\": " + DoubleToString(AccountLeverage(), 2) + ",";
json += "\"account_currency\": \"" + AccountCurrency() + "\",";
// Dynamic Account Information
json += "\"balance\": " + DoubleToString(AccountBalance(), 2) + ",";
json += "\"credit\": " + DoubleToString(AccountCredit(), 2) + ",";
json += "\"equity\": " + DoubleToString(AccountEquity(), 2) + ",";
json += "\"free_margin\": " + DoubleToString(AccountFreeMargin(), 2) + ",";
json += "\"margin\": " + DoubleToString(AccountMargin(), 2) + ",";
json += "\"margin_level\": " + DoubleToString(AccountMarginLevel(), 2) + ",";
// Add more account-related fields as needed
// Remove the last comma if necessary
if(StringSubstr(json, StringLen(json)-1, 1) == ",")
json = StringSubstr(json, 0, StringLen(json)-1);
json += "}";
return(json);
}
//+------------------------------------------------------------------+
//| Function to Gather Orders Information and Convert to JSON |
//+------------------------------------------------------------------+
string GetOrdersInfoJSON()
{
string json = "[";
for(int i=0; i<OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
json += "{";
json += "\"ticket\": " + IntegerToString(OrderTicket()) + ",";
json += "\"symbol\": \"" + OrderSymbol() + "\",";
json += "\"type\": " + IntegerToString(OrderType()) + ",";
json += "\"volume\": " + DoubleToString(OrderLots(), 2) + ",";
json += "\"open_price\": " + DoubleToString(OrderOpenPrice(), 5) + ",";
json += "\"stop_loss\": " + DoubleToString(OrderStopLoss(), 5) + ",";
json += "\"take_profit\": " + DoubleToString(OrderTakeProfit(), 5) + ",";
json += "\"magic_number\": " + IntegerToString(OrderMagicNumber()) + ",";
json += "\"comment\": \"" + StringReplace(OrderComment(), "\"", "\\\"") + "\",";
json += "\"close_time\": \"" + TimeToString(OrderCloseTime(), TIME_SECONDS) + "\",";
json += "\"profit\": " + DoubleToString(OrderProfit(), 2);
// Add more order-related fields as needed
json += "},";
}
}
// Remove the last comma if necessary
if(StringFind(json, "},", StringLen(json)-2) != -1)
json = StringSubstr(json, 0, StringLen(json)-1);
json += "]";
return(json);
}
//+------------------------------------------------------------------+
//| Function to Send Data via WebRequest to Supabase |
//+------------------------------------------------------------------+
bool SendData(string url, string jsonData)
{
char post[];
StringToCharArray(jsonData, post);
string headers = "Content-Type: application/json\r\n" +
"apikey: " + SupabaseApiKey + "\r\n" +
"Authorization: Bearer " + SupabaseApiKey;
string result;
int res_timeout = 5000; // Timeout in milliseconds
int statusCode;
string response_headers;
// Perform the WebRequest
int res = WebRequest("POST", url, headers, res_timeout, post, result, statusCode, response_headers);
if(res == -1)
{
Print("WebRequest error: ", GetLastError());
ResetLastError();
return(false);
}
if(statusCode >= 200 && statusCode < 300)
{
// Success
return(true);
}
else
{
// Handle HTTP errors
Print("HTTP Error: ", statusCode, " Response: ", result);
return(false);
}
}
//+------------------------------------------------------------------+
Explanation of the Code
-
Input Parameters:
- SupabaseURL: Your Supabase REST API base URL.
- SupabaseApiKey: Your Supabase API key.
- AccountTable: Name of the table in Supabase to store account information.
- OrdersTable: Name of the table in Supabase to store orders information.
- SendInterval: Interval in seconds between consecutive data sends (default is 300 seconds or 5 minutes).
-
Initialization (OnInit):
- Verifies that the
SupabaseURL is correctly formatted.
- Initializes the
lastSendTime to ensure data is sent immediately upon starting the EA.
-
Tick Function (OnTick):
- Checks if the defined interval has passed since the last data send.
- Gathers account information and sends it to the
AccountTable.
- Gathers all open orders and sends them to the
OrdersTable.
- Updates the
lastSendTime after successful sends.
-
Data Gathering Functions:
GetAccountInfoJSON: Collects static and dynamic account information and formats it as a JSON object.
GetOrdersInfoJSON: Iterates through all open orders, collects their details, and formats them as a JSON array of objects.
-
Data Sending Function (SendData):
- Prepares the HTTP headers required by Supabase, including
Content-Type, apikey, and Authorization.
- Uses
WebRequest to send a POST request with the JSON data to the specified Supabase table.
- Handles errors and prints relevant messages to the Experts log.
Additional Notes
-
Error Handling: The EA includes basic error handling. It prints error messages to the Experts log if the WebRequest fails or if the HTTP response indicates an error.
-
JSON Formatting: The JSON is manually constructed. For more complex scenarios or additional data fields, consider implementing a more robust JSON serialization method or using a JSON library compatible with MQL4.
-
Security: Ensure that your Supabase API Key is kept secure. Avoid hardcoding sensitive information in scripts that might be shared or exposed.
-
Customization: You can expand the GetAccountInfoJSON and GetOrdersInfoJSON functions to include more fields as needed based on your Supabase table schemas.
Final Steps
-
Customize the EA:
- Replace
"https://your-project.supabase.co/rest/v1/" with your actual Supabase REST API base URL.
- Replace
"your-supabase-api-key" with your actual Supabase API key.
- Ensure that the table names (
account_info and orders) match the table names in your Supabase database.
-
Compile and Attach the EA:
- Open the MetaEditor in MetaTrader.
- Create a new EA and paste the above code.
- Compile the EA ensuring there are no errors.
- Attach the EA to a chart in MetaTrader.
-
Monitor:
- Check the Experts log in MetaTrader to ensure that data is being sent successfully.
- Verify in your Supabase database that the
account_info and orders tables are receiving data as expected.
Feel free to further enhance the EA based on your specific requirements. If you encounter any issues or have further questions, don't hesitate to ask!