Your code looks mostly fine but there are a few areas that might cause errors depending on the specifics of the CSV file and environment. The most common problems while reading UTF-16 CSV files in pandas are:
The file delimiter is not specified correctly.
Your data snippet uses tabs (\t) as delimiters, but read_csv by default expects commas.
The BOM (byte order mark) in UTF-16 files sometimes causes pandas to not interpret the first column header correctly.
The 'Volume' column might have integer values, but if there are missing or malformed values, astype(float) conversion can fail.
Sometimes, columns might contain extra whitespace or hidden characters.
Suggested fixes:
Specify the delimiter as tab (\t) explicitly in pd.read_csv.
Use encoding='utf-16' or utf-16-le/utf-16-be depending on your file. Usually utf-16 with the right BOM works fine.
Use pd.to_numeric(..., errors='coerce') for conversion to handle any bad numeric data safely.
Strip whitespace from all string columns (like 'Pair') to avoid subtle bugs.
which means the file is using ; (semicolon) as delimiter, not tab (\t).
What you should do:
Use delimiter=';' in pd.read_csv instead of delimiter='\t'.
Why this happens?
The line:
code
Time Open High Low Close Volume Pair Timeframe
may look tab-delimited to you, but your actual file probably uses semicolons ; as separators. Sometimes spreadsheet software or editors use ; instead of commas or tabs.
// Open file in overwrite mode to recreate it each time (optional: use append instead)
int fileHandle = FileOpen(FileName, FILE_WRITE | FILE_CSV | FILE_TXT | FILE_ANSI);
if (fileHandle == INVALID_HANDLE)
{
Print("Failed to open file: ", FileName);
return;
}
// Loop through each symbol
for (int i = 0; i < ArraySize(symbols); i++)
{
string symbol = symbols[i];
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
code
if (bid == 0 || ask == 0) // Check if data is valid
continue;
FileWrite(fileHandle, timeStr, DoubleToString(bid, _Digits), DoubleToString(ask, _Digits), symbol);
}
FileClose(fileHandle);
}
Assistant
The core issue here is that you are opening the file in FILE_WRITE mode every second, which overwrites the file and only saves the latest snapshot of data.
Why some pairs "do not update":
On each timer tick (OnTimer), you:
Open the file in overwrite mode (FILE_WRITE)
Write the header once
Write all pairs that have valid bid/ask at this particular moment
Close the file
If some symbols return bid/ask = 0 at that moment, you skip them.
This means the file never accumulates data, you only have the last successful poll.
Likely reasons why pairs are missing sometimes:
For pairs like "USDCHF.Z", "GBPUSD.Z", "EURUSD.Z", "AUDUSD.Z" the broker or terminal reports 0 bid or ask in some ticks (maybe due to market closed, symbol inactive, or delays).
Since you skip them, those pairs don't get written to that file update.
The file overwrites each time, so those pairs disappear from your CSV until the symbol has valid prices again.
How to fix your EA to handle this better:
Option 1: Use a persistent file in append mode, writing data continuously per symbol per line
Open the file once in FILE_WRITE | FILE_CSV | FILE_TXT | FILE_ANSI mode in OnInit().
Keep appending lines for all symbols whose data is valid on every timer event.
Flush and close the file gracefully on deinit.
If you want the entire dataset appended, each line is a new timestamp per symbol.
Option 2: Build a snapshot with all pairs, and write them all every tick, using previous known values or placeholders for missing data.
You’d need to:
Keep a cached copy of last known valid bid/ask per symbol.
Update cache only when new data is valid.
When writing the file, always write all symbols, using last known value if current is 0.
Here is a quick fix version of your existing code to append lines instead of overwrite:
FILE_APPEND does not exist as a predefined constant in MQL5. The MQL5 FileOpen function either overwrites the file (FILE_WRITE) or opens it for reading (FILE_READ). MQL5 does not have a direct "append mode" flag like Python or other languages.
How to append lines to a file in MQL5:
You open the file in FILE_READ|FILE_WRITE mode.
Then move the file pointer to the end using FileSeek.
Then write new data.
Your fix — appending lines correctly in MQL5
mql5
void OnTimer()
{
datetime time = TimeCurrent();
string timeStr = TimeToString(time, TIME_DATE|TIME_MINUTES|TIME_SECONDS);
// Open file for reading and writing
int fileHandle = FileOpen(FileName, FILE_READ|FILE_WRITE|FILE_CSV|FILE_TXT|FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Failed to open file: ", FileName);
return;
}
// Move pointer to the end of file before writing to append
FileSeek(fileHandle, 0, SEEK_END);
for(int i=0; i<ArraySize(symbols); i++)
{
string symbol = symbols[i];
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
if(bid == 0 || ask == 0)
continue;
FileWrite(fileHandle, timeStr, DoubleToString(bid, _Digits), DoubleToString(ask, _Digits), symbol);
}
FileClose(fileHandle);
}
Additional notes:
When you open a file with FILE_READ | FILE_WRITE, you must manually move to the end with FileSeek(fileHandle, 0, SEEK_END); to append.
Opening with just FILE_WRITE will always overwrite.
Make sure you create the file first (in OnInit) by writing your header once (using or ), then append data later using the method above.
User
kindly provide the full updated code
Assistant
Certainly! Here's the full updated MQL5 Expert Advisor code to export multiple symbols' BID and ASK prices every second into a CSV file, correctly appending lines (not overwriting), and writing the CSV header only once on initialization:
mql5
//+------------------------------------------------------------------+
//| Expert advisor: Export multiple symbols with BID/ASK to CSV |
//+------------------------------------------------------------------+
#property strict
input string FileName = "LiveData.csv";
string symbols[] = {
"AUDUSD.Z", "EURGBP.Z", "EURJPY.Z", "EURUSD.Z", "GBPJPY.Z",
"GBPUSD.Z", "USDCAD.Z", "USDCHF.Z", "USDJPY.Z"
};
int OnInit()
{
// Write header once (overwrite file)
int fileHandle = FileOpen(FileName, FILE_WRITE | FILE_CSV | FILE_TXT | FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Cannot create file ", FileName);
return(INIT_FAILED);
}
FileWrite(fileHandle, "Time", "BID", "ASK", "PAIR");
FileClose(fileHandle);
// Optionally select symbols so their quotes are available
for(int i = 0; i < ArraySize(symbols); i++)
SymbolSelect(symbols[i], true);
EventSetTimer(1); // Set timer to 1 second to write data every second
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
EventKillTimer();
}
void OnTimer()
{
datetime time = TimeCurrent();
string timeStr = TimeToString(time, TIME_DATE | TIME_MINUTES | TIME_SECONDS);
// Open file for read/write to append data
int fileHandle = FileOpen(FileName, FILE_READ | FILE_WRITE | FILE_CSV | FILE_TXT | FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Failed to open file: ", FileName);
return;
}
// Move pointer to end of file to append lines
FileSeek(fileHandle, 0, SEEK_END);
// Loop through each symbol and write bid/ask if valid
for(int i = 0; i < ArraySize(symbols); i++)
{
string symbol = symbols[i];
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
// Skip if no valid quotes
if(bid == 0 || ask == 0)
continue;
FileWrite(fileHandle, timeStr, DoubleToString(bid, _Digits), DoubleToString(ask, _Digits), symbol);
}
FileClose(fileHandle);
}
User
id prefer the data to have the 9 columns only . i suspect the broker is closed that is why its not updating
Assistant
Got it! You want the CSV to have the same 9 columns as your original data format, i.e.:
code
Time, Open, High, Low, Close, Volume, Pair, Timeframe
Currently, your script writes only 4 columns:
code
Time, BID, ASK, PAIR
Let's update your code to export all 9 columns for each symbol, using the latest data in the chart or from the market.
Key points to consider:
For each symbol, the EA will gather the current bar data (Open, High, Low, Close, Volume).
Timeframe can be set as a constant or from current chart timeframe.
We use CopyRates or iOpen, iHigh, etc. functions to get current bar's OHLCV.
We use SymbolInfoDouble for bid/ask if still needed alongside, but since you want data columns like in your example we'll read OHLCV.
We will write one line per symbol per second with all 9 columns.
For Volume, we get tick volume (iVolume).
For Timeframe, put something like "PERIOD_M1" as string or convert the period integer.
Full updated code to export 9-column data every second
mql5
User
meant 9 rows
Assistant
Thanks for the clarification — you want the file to contain exactly 9 lines per update, one line per each of the 9 symbols, even if some symbols are currently unavailable or have bid/ask=0 (for example, due to broker/server disconnection or market closed).
Problem recap:
Your previous code skips symbols with bid or ask = 0.
So sometimes fewer rows (less than 9) are written per update.
You want all 9 symbols always present in every single write, so the CSV has exactly 9 rows per update/tick.
How to do that?
We need to:
For all symbols in your list, write one line each per update.
If a symbol is missing or has no valid data, write a placeholder row (e.g., with zeros or empty strings).
This guarantees 9 rows per update.
Here is a ready-to-use fully updated MQL5 EA snippet to:
Export one line per symbol every second.
Write exactly 9 lines per update.
Use zeros or N/A where values are missing or zero.
Use these columns (4 columns as in your initial minimal example): Time, BID, ASK, PAIR.
You can easily extend this with more columns if you want.
Full code snippet (guaranteed 9 rows every second):
import pandas as pd
# Path to your UTF-16 encoded CSV file
csv_file = 'historical_data.csv' # Change this to your actual file path
try:
# Load the file using UTF-16 encoding and tab delimiter
df = pd.read_csv(csv_file, encoding='utf-16', delimiter='\t')
# Strip any whitespace from column names
df.columns = df.columns.str.strip()
# Print column names for verification
print(f"✅ Columns found: {df.columns.tolist()}")
# Ensure required numeric columns are present
required_columns = ['Open', 'High', 'Low', 'Close', 'Volume', 'Pair']
for col in required_columns:
if col not in df.columns:
raise ValueError(f"Missing column: {col}")
# Strip whitespace from the 'Pair' column (and any object dtype columns)
for col in df.select_dtypes(include=['object']).columns:
df[col] = df[col].str.strip()
# Convert numeric columns to float (handle errors gracefully)
numeric_cols = required_columns[:-1] # All except 'Pair'
for col in numeric_cols:
df[col] = pd.to_numeric(df[col], errors='coerce')
# Check for any NaNs after conversion
if df[numeric_cols].isna().any().any():
print("⚠️ Warning: Some numeric values could not be converted and are set as NaN.")
# Group by currency pair
grouped = df.groupby('Pair')
# Prepare summary list
summary = []
for pair, group in grouped:
# Drop rows with NaN in relevant columns to avoid calculation errors
group_clean = group.dropna(subset=['High', 'Low', 'Close'])
if group_clean.empty:
print(f"⚠️ Warning: No valid numeric data for pair {pair}, skipping.")
continue
high = group_clean['High'].max()
low = group_clean['Low'].min()
max_close = group_clean['Close'].max()
min_close = group_clean['Close'].min()
mode_close = group_clean['Close'].mode()
most_common_close = mode_close.iloc[0] if not mode_close.empty else None
frequency = group_clean['Close'].value_counts().get(most_common_close, 0)
count = len(group_clean)
summary.append({
'Pair': pair,
'Highest High': high,
'Lowest Low': low,
'Highest Close': max_close,
'Lowest Close': min_close,
'Most Frequent Close': most_common_close,
'Frequency of Most Frequent Close': frequency,
'Data Points': count
})
# Create summary DataFrame
summary_df = pd.DataFrame(summary)
# Print to console
print("\n📊 Forex Summary Statistics:\n")
print(summary_df)
# Save to CSV
output_file = 'forex_analysis_summary.csv'
summary_df.to_csv(output_file, index=False)
print(f"\n✅ Summary exported to '{output_file}'")
except Exception as e:
print(f"\n❌ Error: {e}")
Key Changes:
Added delimiter='\t' to pd.read_csv since your data is tab-delimited.
Stripping whitespaces from all object columns to avoid unexpected mismatches.
Used pd.to_numeric with errors='coerce' to safely convert numerical columns, replacing bad data with NaN instead of raising.
Added warnings if NaNs are detected after numeric conversion.
Dropped NaNs before computing max/min/mode for numeric columns.
Added skip logic if a group doesn't have any valid numeric data.
Try running this code and let me know if you get any further errors!
//+------------------------------------------------------------------+
//| Expert advisor: Export multiple symbols with BID/ASK to CSV |
//+------------------------------------------------------------------+
#property strict
input string FileName = "LiveData.csv";
string symbols[] = {"AUDUSD.Z", "EURGBP.Z", "EURJPY.Z", "EURUSD.Z", "GBPJPY.Z", "GBPUSD.Z",
"USDCAD.Z", "USDCHF.Z", "USDJPY.Z"};
int OnInit()
{
// Write header only once when EA starts
if (!FileIsExist(FileName))
{
int fileHandle = FileOpen(FileName, FILE_WRITE|FILE_CSV|FILE_TXT|FILE_ANSI);
if (fileHandle != INVALID_HANDLE)
{
FileWrite(fileHandle, "Time", "BID", "ASK", "PAIR");
FileClose(fileHandle);
}
else
Print("Failed to open file for writing header");
}
EventSetTimer(1); // Update every 1 second
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
EventKillTimer();
}
void OnTimer()
{
datetime time = TimeCurrent();
string timeStr = TimeToString(time, TIME_DATE|TIME_MINUTES|TIME_SECONDS);
// Open file in append mode to keep adding new lines
int fileHandle = FileOpen(FileName, FILE_WRITE|FILE_CSV|FILE_TXT|FILE_ANSI|FILE_READ|FILE_APPEND);
if (fileHandle == INVALID_HANDLE)
{
Print("Failed to open file: ", FileName);
return;
}
for(int i=0; i<ArraySize(symbols); i++)
{
string symbol = symbols[i];
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
if(bid == 0 || ask == 0)
continue;
FileWrite(fileHandle, timeStr, DoubleToString(bid, _Digits), DoubleToString(ask, _Digits), symbol);
}
FileClose(fileHandle);
}
What changed:
OnInit writes header only once at the first run.
OnTimer opens file in append mode (FILE_APPEND) instead of overwrite.
Each second, new rows are appended, preserving history.
This way, your CSV gradually fills with all valid rows as they come in.
If a symbol's bid/ask is 0 any tick, that tick is skipped (no entry for that pair that second), but previous data is still there.
Further tips:
If you want to guarantee no missing data for each tick for all pairs, you’ll need to cache last known values and fill missing values when bid or ask is zero, but that is more complex.
Also, check if your terminal/broker really provides live quotes for the pairs in your symbol list (SymbolSelect sometimes needed).
SymbolInfoDouble(...) returns 0 if symbol is not selected or not available — consider selecting symbols first:
Let me know if you want help implementing a caching solution or full snapshots!
FILE_WRITE
FILE_WRITE | FILE_CSV
Sample complete snippet for clarity:
mql5
#property strict
input string FileName = "LiveData.csv";
string symbols[] = {"AUDUSD.Z", "EURGBP.Z", "EURJPY.Z", "EURUSD.Z", "GBPJPY.Z", "GBPUSD.Z",
"USDCAD.Z", "USDCHF.Z", "USDJPY.Z"};
int OnInit()
{
// Write header once (overwrite file)
int fileHandle = FileOpen(FileName, FILE_WRITE|FILE_CSV|FILE_TXT|FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Cannot create file ", FileName);
return(INIT_FAILED);
}
FileWrite(fileHandle, "Time", "BID", "ASK", "PAIR");
FileClose(fileHandle);
EventSetTimer(1);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
EventKillTimer();
}
void OnTimer()
{
datetime time = TimeCurrent();
string timeStr = TimeToString(time, TIME_DATE|TIME_MINUTES|TIME_SECONDS);
// Open file for reading and writing
int fileHandle = FileOpen(FileName, FILE_READ|FILE_WRITE|FILE_CSV|FILE_TXT|FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Failed to open file: ", FileName);
return;
}
// Move pointer to end to append new lines
FileSeek(fileHandle, 0, SEEK_END);
for(int i=0; i<ArraySize(symbols); i++)
{
string symbol = symbols[i];
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
if(bid == 0 || ask == 0)
continue;
FileWrite(fileHandle, timeStr, DoubleToString(bid, _Digits), DoubleToString(ask, _Digits), symbol);
}
FileClose(fileHandle);
}
This will:
Create the file with a header once on OnInit.
Append new data lines every second on OnTimer.
If you want, I can also help you implement caching or filling missing data!
How this works:
OnInit:
Creates/overwrites the CSV file and writes header line exactly once.
Selects all symbols for receiving quotes.
Sets a 1-second timer.
OnTimer:
Every second, opens the file for read/write, seeks to its end (so not to overwrite), and appends new lines with current datetime, bid, ask, and symbol name.
Skips symbols whose bid or ask is 0 (often means no quotes available at the moment).
OnDeinit:
Kills the timer on EA removal.
Notes:
The output CSV LiveData.csv will grow by one line per symbol, per second (for those with valid quotes).
Make sure your terminal has these symbols available and that the quotes are live for them (no zeros).
You can customize symbols[] as needed.
If you want me to help with enhancements like caching the last known bid/ask or writing the data differently, just ask!
//+------------------------------------------------------------------+
//| Expert advisor: Export 9-column OHLCV data per symbol to CSV |
//+------------------------------------------------------------------+
#property strict
input string FileName = "LiveData.csv";
string symbols[] = {
"AUDUSD.Z", "EURGBP.Z", "EURJPY.Z", "EURUSD.Z", "GBPJPY.Z",
"GBPUSD.Z", "USDCAD.Z", "USDCHF.Z", "USDJPY.Z"
};
// Helper function to convert ENUM_TIMEFRAMES to string (common periods)
string TimeframeToString(ENUM_TIMEFRAMES timeframe)
{
switch(timeframe)
{
case PERIOD_M1: return "PERIOD_M1";
case PERIOD_M5: return "PERIOD_M5";
case PERIOD_M15: return "PERIOD_M15";
case PERIOD_M30: return "PERIOD_M30";
case PERIOD_H1: return "PERIOD_H1";
case PERIOD_H4: return "PERIOD_H4";
case PERIOD_D1: return "PERIOD_D1";
case PERIOD_W1: return "PERIOD_W1";
case PERIOD_MN1: return "PERIOD_MN1";
default: return "PERIOD_UNKNOWN";
}
}
int OnInit()
{
// Write header once (overwrite file)
int fileHandle = FileOpen(FileName, FILE_WRITE | FILE_CSV | FILE_TXT | FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Cannot create file ", FileName);
return(INIT_FAILED);
}
// Write exact 9-column header matching the data format
FileWrite(fileHandle, "Time", "Open", "High", "Low", "Close", "Volume", "Pair", "Timeframe");
FileClose(fileHandle);
// Select symbols
for(int i = 0; i < ArraySize(symbols); i++)
SymbolSelect(symbols[i], true);
EventSetTimer(1); // 1 second timer
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
EventKillTimer();
}
void OnTimer()
{
// Open file for read/write (append mode)
int fileHandle = FileOpen(FileName, FILE_READ | FILE_WRITE | FILE_CSV | FILE_TXT | FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Failed to open file: ", FileName);
return;
}
// Move pointer to end to append new data
FileSeek(fileHandle, 0, SEEK_END);
ENUM_TIMEFRAMES tf = PERIOD_M1; // set your preferred timeframe or get from chart
// loop symbols
for(int i = 0; i < ArraySize(symbols); i++)
{
string symbol = symbols[i];
// Check if symbol selected
if(!SymbolSelect(symbol, true))
{
Print("Failed to select symbol: ", symbol);
continue;
}
// Get the last (current) bar index 0 data
MqlRates rates[];
// Copy 1 bar of data from the given timeframe
if(CopyRates(symbol, tf, 0, 1, rates) <= 0)
{
Print("Failed to copy rates for ", symbol);
continue;
}
MqlRates current = rates[0];
// Sometimes volume or prices can be 0 - skip those
if(current.open == 0 || current.high == 0 || current.low == 0 || current.close == 0)
continue;
string timeStr = TimeToString(current.time, TIME_DATE|TIME_MINUTES|TIME_SECONDS);
// Write one CSV line for this symbol
FileWrite(fileHandle,
timeStr,
DoubleToString(current.open, _Digits),
DoubleToString(current.high, _Digits),
DoubleToString(current.low, _Digits),
DoubleToString(current.close, _Digits),
(long)current.tick_volume,
symbol,
TimeframeToString(tf)
);
}
FileClose(fileHandle);
}
Explanation and important notes:
Time: Time of the current bar start (the candle timestamp per symbol & timeframe).
Open / High / Low / Close: from MqlRates for the last complete or current bar depending on broker feed.
Volume: tick_volume (number of ticks in that bar).
Pair: Symbol name as is with .Z suffix as you had.
Timeframe: hardcoded to PERIOD_M1, but you can change to other periods or call ChartPeriod() if running on chart.
This exports 9 columns exactly as your data example.
About "broker closed" or "no updates"
If a symbol has no new data (closed market), the same bar data will repeat, so your CSV will have repeated identical rows.
If symbols are truly inactive, CopyRates could fail or return empty array, skipping that symbol.
This is normal behavior for stopped markets.
If you want, I can also help you:
Export data on bar close instead of every second
Append volume from tick counts or real volume
Handle multiple timeframes dynamically
Just ask!
//+------------------------------------------------------------------+
//| Expert Advisor: Write 9 symbols BID/ASK per second, fixed rows |
//+------------------------------------------------------------------+
#property strict
input string FileName = "LiveData.csv";
string symbols[] = {
"AUDUSD.Z", "EURGBP.Z", "EURJPY.Z", "EURUSD.Z", "GBPJPY.Z",
"GBPUSD.Z", "USDCAD.Z", "USDCHF.Z", "USDJPY.Z"
};
int OnInit()
{
// Write CSV header once (overwrite file)
int fileHandle = FileOpen(FileName, FILE_WRITE | FILE_CSV | FILE_TXT | FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Cannot create file ", FileName);
return(INIT_FAILED);
}
FileWrite(fileHandle, "Time", "BID", "ASK", "PAIR");
FileClose(fileHandle);
// Select symbols to ensure quotes available
for(int i = 0; i < ArraySize(symbols); i++)
SymbolSelect(symbols[i], true);
EventSetTimer(1);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
EventKillTimer();
}
void OnTimer()
{
datetime time = TimeCurrent();
string timeStr = TimeToString(time, TIME_DATE | TIME_MINUTES | TIME_SECONDS);
int fileHandle = FileOpen(FileName, FILE_READ | FILE_WRITE | FILE_CSV | FILE_TXT | FILE_ANSI);
if(fileHandle == INVALID_HANDLE)
{
Print("Failed to open file: ", FileName);
return;
}
// Append data: move to end of file
FileSeek(fileHandle, 0, SEEK_END);
for(int i = 0; i < ArraySize(symbols); i++)
{
string symbol = symbols[i];
double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
// If no valid bid or ask (e.g. 0), write placeholders
string bidStr = (bid > 0) ? DoubleToString(bid, _Digits) : "0";
string askStr = (ask > 0) ? DoubleToString(ask, _Digits) : "0";
FileWrite(fileHandle, timeStr, bidStr, askStr, symbol);
}
FileClose(fileHandle);
}
Explanation:
File is created with header once on OnInit.
On every OnTimer tick (~1s), appends exactly 9 rows, one per symbol.
If bid or ask is zero or missing, writes "0" instead of skipping.
This guarantees exactly 9 rows per update.
CSV content example snippet after a couple of ticks:
code
Time,BID,ASK,PAIR
2025.05.22 16:30:00,1.12956,1.12957,AUDUSD.Z
2025.05.22 16:30:00,0,0,EURGBP.Z
... (7 more rows)
2025.05.22 16:30:01,1.12954,1.12978,AUDUSD.Z
2025.05.22 16:30:01,1.14123,1.14130,EURGBP.Z
... etc.
If you want all 9 columns per line in your earlier data format (Time,Open,High,Low,Close,Volume,Pair,Timeframe), you can similarly get OHLCV for each symbol — and write zero/placeholder rows if data is missing.
Let me know if you want me to provide that version with full 9 columns per line and guaranteed 9 rows per update.