Encountering cryptic error messages is a common part of a developer’s journey. In the world of MQL5 development, one such message that occasionally puzzles even experienced programmers is “Only one character code expected”. This error directly relates to how MQL5 interprets and handles character literals within your source code.
Understanding the “Only One Character Code Expected” Error in MQL5
At its core, the “Only one character code expected” error signifies that the MQL5 compiler encountered a character literal declaration (using single quotes ') but found more than a single character or an invalid sequence within those quotes. Unlike string literals which use double quotes " and can contain sequences of characters, a character literal in MQL5 is strictly defined as a single character value.
This error indicates a fundamental misunderstanding or mistake in using the character data type char. The char type in MQL5 is designed to hold a single 8-bit character value, corresponding to its ASCII representation. When you enclose multiple characters or an incorrectly formatted escape sequence within single quotes, the compiler doesn’t know how to interpret the sequence as a single character and throws this error.
The Nature of the Error: Identifying the Root Cause
The error message points directly to the use of single quotes '. In C++ and languages influenced by it, including MQL5, single quotes are used for character literals, while double quotes are used for string literals. A character literal like 'A' represents the integer value of the ASCII character ‘A’ (which is 65). A string literal like "ABC" represents a sequence of characters stored as an array, null-terminated.
The error arises when you incorrectly use single quotes where double quotes are intended for a string, or when you attempt to place multiple characters inside single quotes, effectively trying to define something that is not a single char value using the char literal syntax. It’s a compile-time error, meaning the code fails to build before it can even be executed.
Common Scenarios Triggering the Error
Several typical coding mistakes can lead to this error:
-
Using Single Quotes for Strings: The most frequent cause is accidentally using single quotes for a text string, for example,
string name = 'MyEA';instead ofstring name = "MyEA";. -
Multiple Characters in a Character Literal: Trying to define a character literal with more than one character, such as
char initial = 'JD';. This is invalid syntax for a singlechar. -
Incorrect Escape Sequences: While single quotes can contain escape sequences representing a single character (like
\nfor newline or\tfor tab), an incorrectly formed or unknown escape sequence within single quotes can also trigger this error if the compiler cannot resolve it to a single character value. -
Confusing Character and String Operations: Attempting to apply operations meant for strings (like concatenation) to character literals using single quotes, or vice-versa, can sometimes manifest in ways that confuse the compiler, although direct type mismatches often result in different errors.
Character Encoding in MQL5: A Primer
Understanding character encoding is crucial when dealing with text, especially when working with files, external libraries (DLLs), or non-ASCII characters in your code or UI elements.
ASCII, Unicode, and UTF-8: Relevance to MQL5
-
ASCII: The American Standard Code for Information Interchange is a 7-bit character set, defining 128 characters, primarily English letters, numbers, and control characters. The
chartype in MQL5 fundamentally relates to an 8-bit interpretation, often extended to cover basic Western European character sets (like Latin-1) in older systems or specific contexts. -
Unicode: A much larger character set aiming to encode characters from virtually all writing systems. It uses code points (numbers) to uniquely identify each character.
-
UTF-8: A variable-width encoding for Unicode. It’s the most common encoding on the web and in modern systems. It can represent any Unicode character, with common ASCII characters using just one byte.
MQL5, particularly in MetaTrader 5, has significantly improved its handling of strings and character encoding compared to MQL4. MQL5 strings (string type) are Unicode-based, typically using UTF-8 internally or when interacting with the environment (like terminal messages, file operations). This means a single character displayed on the screen might require multiple bytes in a UTF-8 encoded string.
However, the char type remains an 8-bit integer type. While it can store any 8-bit value (0-255), its interpretation as a character is often context-dependent, especially when printing or converting to/from strings. The “Only one character code expected” error specifically relates to the literal syntax for the char type, expecting a single 8-bit value representation.
MQL5’s Handling of Character Sets
MQL5 strings (string) are handled as sequences of 16-bit ushort values internally (UTF-16), although UTF-8 is often the encoding used for external interaction (like file I/O, terminal output). The char type, conversely, is an 8-bit integer type. This distinction is key.
When you use a character literal like 'A', you are specifying a single 8-bit value (65). When you use a string literal "ABC", you are defining a sequence that MQL5 stores internally using UTF-16. The compiler expects the single quotes ' syntax to yield one 8-bit value, either directly from a single character that fits within 8 bits (like ASCII) or from a valid 8-bit escape sequence.
Troubleshooting and Resolving the Error
Resolving the “Only one character code expected” error usually involves a straightforward correction of syntax.
Inspecting the Source Code for Encoding Issues
The primary step is to locate the exact line indicated by the compiler error. Examine the usage of single quotes ' on that line.
-
Are you trying to define a string? If the intention was a string (a sequence of characters), change the single quotes
'to double quotes".string symbol = 'EURUSD';becomesstring symbol = "EURUSD";. -
Are you using multiple characters? If you have something like
char key = 'AltF4';, you need to rethink the logic. If you intended to capture a single special key press, you might need to use Windows API calls or handle specific terminal events, not define it as a simple character literal. If you needed the first character, usechar key = 'A';(though this specific example is unlikely). -
Is it an escape sequence? Verify that any escape sequence within single quotes is valid (e.g.,
\n,\t,\',\",\\,\xHHfor hex code). Invalid sequences like\zor incomplete ones like\xwill cause issues.
// Incorrect - trying to use single quotes for a string
// string error_msg = 'Order failed'; // Error: Only one character code expected
// Correct - using double quotes for a string
string correct_msg = "Order failed";
// Incorrect - multiple characters in char literal
// char my_initials = 'JD'; // Error: Only one character code expected
// Correct - single character
char my_initial = 'J';
// Correct - using escape sequence for a single character (newline)
char newline_char = '\n';
// Incorrect - invalid escape sequence
// char invalid_char = '\q'; // Error: Only one character code expected (or similar compiler error)
Using the MQL5 Editor’s Encoding Options
While the “Only one character code expected” error is fundamentally a syntax issue with character literals, file encoding can indirectly cause problems if your source file is saved in an unusual or mixed encoding that makes certain characters appear as multi-byte sequences where a single byte character is expected, or if it corrupts character escape sequences.
The MetaEditor allows you to specify the encoding when saving files (File -> Save As -> Encoding). For MQL5, UTF-8 is the recommended encoding for source files (.mq5, .mqh) as it supports the full range of Unicode characters that you might use in comments or string literals, and is generally compatible with how MQL5 handles text. Ensuring your file is saved with a consistent, standard encoding like UTF-8 helps prevent hidden issues.
Dealing with External Data and File Encoding
When reading text data from external files (using FileOpen, FileReadString, etc.), the encoding of the file is paramount. If you attempt to read a multi-byte character from a UTF-8 file byte by byte and assign it to a char, you might encounter issues, though this specific error is less likely here and more likely related to incorrect loop boundaries or type casting.
The “Only one character code expected” error is specifically about the source code literal syntax. However, if you are generating MQL5 source code programmatically (e.g., writing an MQL5 file from another script or program), ensuring that the generated string literals and character literals are correctly quoted and encoded is vital to avoid this error when that generated file is later compiled.
Best Practices to Avoid Encoding Problems
Adhering to simple best practices can save significant debugging time related to character and string handling.
Consistent Encoding Across Files
Always save your MQL5 source files (.mq5, .mqh) using UTF-8 encoding. This ensures that string literals and comments containing non-ASCII characters are handled correctly by the compiler and are displayed properly in the MetaEditor. Using a consistent encoding prevents subtle bugs related to character representation.
Validating Input Data Encoding
When your MQL5 program reads configuration files, data files, or interacts with external sources (like web requests or DLLs), be explicit about the expected character encoding of the data. Use MQL5 functions that allow specifying encoding where available (e.g., file functions) or perform manual conversion if necessary. Do not assume a default encoding.
Properly Handling Special Characters
- Use double quotes
"for all string literals, even if they contain only one character (e.g.,string s = "A";is a string of length 1,char c = 'A';is a single character value). - Use single quotes
'only for defining a singlecharvalue, often an ASCII character or a standard escape sequence. - When working with specific byte values (0-255), particularly when dealing with binary data or low-level protocols, use integer literals or hexadecimal escape sequences (
\xHH) within single quotes if you intend to assign them to achartype.
// Correct: String literal
string message = "Hello, world!";
// Correct: Character literal (ASCII 'A')
char char_A = 'A';
// Correct: Character literal (ASCII value 65)
char char_65 = 65; // Equivalent to 'A'
// Correct: Character literal (Hex escape for ASCII 65)
char char_hex_41 = '\x41'; // Equivalent to 'A'
// Correct: Character literal (newline)
char newline = '\n';
// Incorrect: Using single quotes for a string
// string bad_string = 'This is wrong'; // Error: Only one character code expected
Advanced Scenarios and Workarounds
While the basic fix for the “Only one character code expected” error is syntax correction, understanding encoding becomes more critical in advanced scenarios.
Working with DLLs and External Libraries
When passing strings to or receiving strings from external DLLs written in languages like C++ or C#, you must be acutely aware of the character encoding and string type conventions used by the DLL. MQL5’s internal string representation (UTF-16) might differ from the DLL’s expectation (often UTF-8 or ANSI/MBCS on Windows). You might need to perform explicit encoding conversions using Windows API functions or intermediary structures.
The “Only one character code expected” error is unlikely to originate directly from DLL interaction unless you are constructing arguments for DLL functions using incorrect character literals in your MQL5 code.
Encoding Conversion Techniques
If you need to convert strings between different encodings within MQL5 (e.g., before writing to a file or passing to a DLL), you might need to leverage Windows API functions like MultiByteToWideChar and WideCharToMultiByte. These functions allow converting between multi-byte character sets (like UTF-8 or ANSI) and wide character sets (like UTF-16, used internally by MQL5 strings). This requires using the import keyword to call functions from user32.dll or other relevant Windows libraries.
#import "kernel32.dll"
int MultiByteToWideChar(
uint CodePage,
uint dwFlags,
string lpMultiByteStr,
int cbMultiByte,
ushort& lpWideCharStr[],
int cchWideChar
);
int WideCharToMultiByte(
uint CodePage,
uint dwFlags,
ushort& lpWideCharStr[],
int cchWideChar,
string lpMultiByteStr,
int cbMultiByte,
string lpDefaultChar,
bool &lpUsedDefaultChar
);
#end import
// Code page identifiers (examples)
#define CP_UTF8 65001
#define CP_ACP 0 // ANSI code page
// Example (simplified): Converting MQL5 string (UTF-16) to UTF-8 byte array
bool StringToUTF8Bytes(string mql5_string, uchar& utf8_bytes[])
{
ushort wide_chars[];
int len = StringToShortArray(mql5_string, wide_chars);
if (len <= 0) { ArrayResize(utf8_bytes, 0); return true; }
// Get required buffer size for UTF-8
int utf8_len = WideCharToMultiByte(CP_UTF8, 0, wide_chars, len, NULL, 0, NULL, 0);
if (utf8_len <= 0) return false;
// Resize destination array and perform conversion
ArrayResize(utf8_bytes, utf8_len);
int converted_len = WideCharToMultiByte(CP_UTF8, 0, wide_chars, len, utf8_bytes, utf8_len, NULL, 0);
return converted_len == utf8_len;
}
// Note: Direct string variables cannot be passed as buffers to WideCharToMultiByte
// You would typically need to work with char[] or uchar[] arrays and pointers,
// which adds complexity and requires careful memory management.
// The example above uses a simplified approach for illustration.
This level of encoding manipulation is often necessary when interfacing with low-level libraries or APIs that don’t automatically handle Unicode conversions. The “Only one character code expected” error, while seemingly basic, serves as a reminder of the different ways characters and strings are represented and the compiler’s strict rules regarding character literals.