Certainly! Below is the MQL4 code for an Expert Advisor (EA) that collects all available built-in account information (both static and dynamic) as well as information about open positions and active orders. It then sends this data via a WebRequest to your Supabase database.
Instructions:
-
Copy and Paste: Copy the code into the MetaEditor and save it as an EA (e.g., SendAccountInfoToSupabase.mq4).
-
Adjust Supabase Credentials: Update the SupabaseURL and SupabaseAPIKey input parameters with your Supabase project's URL and API key.
-
Compile: Compile the code. There should be no errors.
-
Allow WebRequest: In MetaTrader 4, go to Tools → Options → Expert Advisors tab. Check the option "Allow WebRequest for listed URL" and add your Supabase URL to the list.
-
Attach to Chart: Attach the EA to a chart. It will automatically send the account and orders data to your Supabase database at the specified UpdateInterval.
Note: Ensure that your Supabase table and REST API are configured to accept the incoming data.
//+------------------------------------------------------------------+
//| SendAccountInfoToSupabase |
//| Developed by OpenAI Assistant |
//+------------------------------------------------------------------+
#property copyright "Developed by OpenAI"
#property link "https://openai.com/"
#property version "1.00"
#property strict
// Input parameters for Supabase credentials
input string SupabaseURL = "https://your-supabase-project.supabase.co/rest/v1/your-table"; // Supabase REST API endpoint
input string SupabaseAPIKey = "your-supabase-api-key"; // Supabase API Key
// Input parameter for how often to send data (in seconds)
input int UpdateInterval = 60; // Update interval in seconds
// Global variable to keep track of last time data was sent
datetime LastUpdateTime = 0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Check if WebRequest is allowed for the given URL
if(!IsAllowedURL(SupabaseURL))
{
Print("ERROR: Supabase URL is not allowed. Please add it to the list of allowed URLs in Tools -> Options -> Expert Advisors tab.");
return(INIT_FAILED);
}
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if it's time to send data
if(TimeCurrent() - LastUpdateTime >= UpdateInterval)
{
// Collect data and send to Supabase
SendAccountData();
LastUpdateTime = TimeCurrent();
}
}
//+------------------------------------------------------------------+
//| Function to send account data to Supabase |
//+------------------------------------------------------------------+
void SendAccountData()
{
// Collect account info
string account_data = GetAccountInfoJSON();
// Collect positions and orders info
string positions_data = GetPositionsInfoJSON();
// Combine data into one JSON string
string json_data = "{";
json_data += "\"account_info\":" + account_data + ",";
json_data += "\"positions_info\":" + positions_data;
json_data += "}";
// Send data via WebRequest
int res = SendJSONToSupabase(json_data);
if(res == 200 || res == 201)
Print("Data sent successfully to Supabase.");
else
Print("Failed to send data to Supabase. HTTP status code: ", res);
}
//+------------------------------------------------------------------+
//| Function to collect account info and return as JSON string |
//+------------------------------------------------------------------+
string GetAccountInfoJSON()
{
string json = "{";
json += "\"Balance\":" + DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2) + ",";
json += "\"Credit\":" + DoubleToString(AccountInfoDouble(ACCOUNT_CREDIT), 2) + ",";
json += "\"Company\":\"" + AccountInfoString(ACCOUNT_COMPANY) + "\",";
json += "\"Currency\":\"" + AccountInfoString(ACCOUNT_CURRENCY) + "\",";
json += "\"Equity\":" + DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY), 2) + ",";
json += "\"FreeMargin\":" + DoubleToString(AccountInfoDouble(ACCOUNT_FREEMARGIN), 2) + ",";
json += "\"Leverage\":" + IntegerToString(AccountInfoInteger(ACCOUNT_LEVERAGE)) + ",";
json += "\"Margin\":" + DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN), 2) + ",";
json += "\"Name\":\"" + AccountInfoString(ACCOUNT_NAME) + "\",";
json += "\"Number\":" + IntegerToString((int)AccountInfoInteger(ACCOUNT_LOGIN)) + ",";
json += "\"Profit\":" + DoubleToString(AccountInfoDouble(ACCOUNT_PROFIT), 2) + ",";
json += "\"Server\":\"" + AccountInfoString(ACCOUNT_SERVER) + "\"";
json += "}";
return(json);
}
//+------------------------------------------------------------------+
//| Function to collect positions and orders info as JSON array |
//+------------------------------------------------------------------+
string GetPositionsInfoJSON()
{
string json = "[";
bool first = true;
// Loop through all existing orders
int total = OrdersTotal();
for(int i = 0; i < total; i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(!first) json += ",";
json += "{";
json += "\"Ticket\":" + IntegerToString(OrderTicket()) + ",";
json += "\"Symbol\":\"" + OrderSymbol() + "\",";
json += "\"Type\":" + IntegerToString(OrderType()) + ",";
json += "\"Lots\":" + DoubleToString(OrderLots(), 2) + ",";
json += "\"OpenPrice\":" + DoubleToString(OrderOpenPrice(), _Digits) + ",";
json += "\"OpenTime\":\""+ TimeToString(OrderOpenTime(), TIME_DATE|TIME_MINUTES|TIME_SECONDS) + "\",";
json += "\"StopLoss\":" + DoubleToString(OrderStopLoss(), _Digits) + ",";
json += "\"TakeProfit\":"+ DoubleToString(OrderTakeProfit(), _Digits) + ",";
json += "\"Commission\":" + DoubleToString(OrderCommission(), 2) + ",";
json += "\"Swap\":" + DoubleToString(OrderSwap(), 2) + ",";
json += "\"Comment\":\"" + OrderComment() + "\",";
json += "\"Profit\":" + DoubleToString(OrderProfit(), 2);
json += "}";
first = false;
}
}
json += "]";
return(json);
}
//+------------------------------------------------------------------+
//| Function to send JSON data to Supabase via WebRequest |
//+------------------------------------------------------------------+
int SendJSONToSupabase(string json_data)
{
char post_data[];
StringToCharArray(json_data, post_data);
string headers;
headers = "Content-Type: application/json\r\n";
headers += "apikey: " + SupabaseAPIKey + "\r\n";
headers += "Authorization: Bearer " + SupabaseAPIKey + "\r\n";
headers += "Prefer: return=representation\r\n";
char response[];
string result;
ResetLastError();
int res = WebRequest("POST", SupabaseURL, headers, 10000, post_data, response, result);
if(res == -1)
{
Print("WebRequest failed. Error code: ", GetLastError());
ResetLastError();
return(-1);
}
else
{
// Successfully sent request
return(res);
}
}
//+------------------------------------------------------------------+
//| Function to check if URL is in the list of allowed URLs |
//+------------------------------------------------------------------+
bool IsAllowedURL(string url)
{
string allowed_urls[];
int url_count = 0;
if(!TerminalInfoString(TERMINAL_WEBREQUEST_URLS, allowed_urls, url_count))
{
Print("Error getting allowed URLs. Error code: ", GetLastError());
return(false);
}
for(int i = 0; i < url_count; i++)
{
if(StringFind(url, allowed_urls[i]) != -1)
return(true);
}
return(false);
}
//+------------------------------------------------------------------+
Additional Notes:
-
Supabase Table Setup: Ensure that your Supabase table (your-table in SupabaseURL) is set up to accept the JSON data structure as defined in the code. The table columns should match the JSON keys.
-
Data Privacy: Be cautious with sensitive information (e.g., account balance, equity). Ensure that your data transmission and storage comply with your broker's policies and any relevant laws/regulations.
-
WebRequest Timeouts: The WebRequest function has a timeout parameter (set to 10000 milliseconds or 10 seconds in the code). Adjust it if necessary based on your network conditions.
-
Error Handling: The code includes basic error handling. You can expand on this by parsing the result from the WebRequest to get more detailed error messages from Supabase.
-
Update Interval: The UpdateInterval controls how often the data is sent to Supabase. Setting it too low might cause performance issues or exceed API rate limits.
-
Order Types: The OrderType() function returns an integer representing the order type (e.g., buy, sell, pending). You might want to map these integers to their string representations for clarity.
Example Mapping for Order Types:
string OrderTypeToString(int type)
{
switch(type)
{
case OP_BUY: return "Buy";
case OP_SELL: return "Sell";
case OP_BUYLIMIT: return "Buy Limit";
case OP_SELLLIMIT: return "Sell Limit";
case OP_BUYSTOP: return "Buy Stop";
case OP_SELLSTOP: return "Sell Stop";
default: return "Unknown";
}
}
You can incorporate this function to convert the order type integer to a string before adding it to the JSON.
Security Reminder:
-
Secure Transmission: Supabase endpoints use HTTPS. Ensure that the SupabaseURL starts with https:// to encrypt data in transit.
-
API Key Protection: Keep your SupabaseAPIKey confidential. Do not share it or expose it in unsecured locations.
Feel free to adjust the code to suit your specific needs. If you encounter any issues or need further assistance, please let me know!