mql5/Experts/Recommended Project Knowledge Structure.md
2025-10-29 13:34:40 +00:00

13 Kio

Recommended Project Knowledge Structure 0.66 KB •13 lines • Formatting may be inconsistent from source Project Knowledge/ ├── MQL5_Compliance/ │ ├── STRICT_RULES.md (Critical syntax rules) │ ├── COMMON_FIXES.md (Error fix patterns) │ ├── MODULE_TEMPLATE.mqh (Standard module structure) │ └── TEST_TEMPLATE.mq5 (Module test template) ├── Development/ │ ├── CODING_STANDARDS.md (Naming conventions) │ ├── DEPENDENCY_GRAPH.md (Module dependencies) │ └── BUILD_CHECKLIST.md (Pre-release checks) └── Troubleshooting/ ├── COMPILATION_ERRORS.md (Common errors and fixes) └── MIGRATION_GUIDE.md (Structure update guide)

Critical Syntax Requirement 0.90 KB •23 lines • Formatting may be inconsistent from source

MQL5 CRITICAL SYNTAX REQUIREMENTS

MANDATORY RULES:

  1. NEVER use pointer syntax (->) - ALWAYS use dot operator (.)
  2. When using pointers to objects, declare with * but access with .
  3. Cannot use reference (&) for local simple type variables
  4. Must work directly with array elements: array[i].member = value
  5. All enums MUST be defined BEFORE structures that use them

COMMON ERROR FIXES:

  • Replace ALL m_utils-> with m_utils.
  • Replace ALL m_tech-> with m_tech.
  • Replace ALL m_risk-> with m_risk.
  • Change pointer member access from ptr->member to ptr.member

MODULE STRUCTURE:

  • DataTypes module: NO dependencies (base module)
  • All structures defined in DataTypes
  • All enums defined BEFORE structures
  • Include order: System → Library → DataTypes → Utils → Components

TESTING REQUIREMENT:

Every module must compile independently with zero errors and warnings

Compliance check script 0.43 KB •17 lines • Formatting may be inconsistent from source #!/bin/bash

MQL5 Compliance Quick Check

echo "Checking for non-compliant syntax..."

Check for pointer syntax

if grep -n "->" *.mqh *.mq5 2>/dev/null; then echo " Found pointer syntax (->)" else echo " No pointer syntax found" fi

Check for correct includes

if grep -l "DataTypes_PME.mqh" *.mqh *.mq5 2>/dev/null; then echo "⚠️ Check if should use DataTypes_PME_Fixed.mqh" fi

echo "Compliance check complete"

MQL coding guidelines for EA development 10.58 KB •503 lines • Formatting may be inconsistent from source

MQL5 Strict Compliance Guidelines for EA Development

1. FUNDAMENTAL MQL5 SYNTAX RULES

1.1 NO Pointer Syntax

NEVER USE:

CObject* obj;
obj->Method();      // WRONG - pointer syntax not supported

ALWAYS USE:

CObject* obj;       // Declaration with * is OK
obj.Method();       // Use dot operator for access

1.2 NO Reference Parameters for Local Variables

NEVER USE:

void Function(int &value) { }  // Reference parameters only for arrays/objects
int local = 5;
Function(local);               // WRONG for simple types

ALWAYS USE:

void Function(int value) { }   // Pass by value for simple types
void ArrayFunc(int &arr[]) { } // References OK for arrays

1.3 Array Element Direct Access

NEVER USE:

ManagedPosition* pos = &m_positions[i];
pos->member = value;           // WRONG - no pointer operations

ALWAYS USE:

m_positions[i].member = value; // Direct array element access
// Or work with index:
int index = FindPosition(ticket);
m_positions[index].member = value;

2. STRUCTURE AND CLASS DEFINITIONS

2.1 Structure Member Naming

  • Use consistent, descriptive names
  • Avoid abbreviations that might change (e.g., use magic not magic_number if shorter is standard)
  • Document any name changes in migration notes

2.2 Enum Definitions

// ALWAYS define enums BEFORE structures that use them
enum ENUM_EXIT_REASON
{
    EXIT_NONE = 0,
    EXIT_STOP_LOSS = 1,
    // ... more values
};

// THEN define structures
struct ManagedPosition
{
    ENUM_EXIT_REASON exit_signal;  // Can now use the enum
};

2.3 Structure Evolution

When modifying structures:

  1. ADD new fields at the end
  2. NEVER remove fields in production code
  3. DOCUMENT deprecated fields
  4. Use ZeroMemory() for initialization

3. MODULE ORGANIZATION

3.1 Include File Order

// CORRECT ORDER:
#include <Object.mqh>              // 1. System includes first
#include <Trade/Trade.mqh>         // 2. MQL5 standard library
#include "DataTypes_PME.mqh"        // 3. Project data types
#include "Utilities_PME.mqh"        // 4. Utilities
#include "RiskManager_PME.mqh"      // 5. Dependent modules
#include "TechnicalAnalysis_PME.mqh" // 6. Technical modules
#include "PositionManager_PME.mqh"  // 7. Main logic modules

3.2 Module Dependencies

  • DataTypes module should have NO dependencies (except system includes)
  • Utilities should only depend on DataTypes
  • Higher-level modules can depend on lower-level ones
  • AVOID circular dependencies

3.3 Header Guards

#ifndef MODULE_NAME_MQH
#define MODULE_NAME_MQH
// ... module content
#endif // MODULE_NAME_MQH

4. OBJECT AND MEMORY MANAGEMENT

4.1 Object Creation and Deletion

// ALWAYS check allocation
CObject* obj = new CObject();
if(obj == NULL)
{
    Print("ERROR: Failed to create object");
    return false;
}

// ALWAYS delete in destructor or cleanup
if(obj != NULL)
{
    delete obj;
    obj = NULL;  // Set to NULL after deletion
}

4.2 Array Management

// Dynamic arrays
ArrayResize(m_array, new_size);
ArrayFree(m_array);  // In destructor

// Check bounds
if(index >= 0 && index < ArraySize(m_array))
{
    m_array[index].member = value;
}

5. COMMON PITFALLS AND SOLUTIONS

5.1 Enum Value Changes

// PROBLEM: Enum values might not exist
case TRAIL_FIXED:  // Might not be defined

// SOLUTION: Use defines for compatibility
#define TRAIL_FIXED TRAIL_FIXED_POINTS

5.2 Method Return Types

// PROBLEM: Incorrect return type
ENUM_SIGNAL_TYPE CheckExitSignal();  // Returns wrong enum

// SOLUTION: Ensure return types match usage
ENUM_EXIT_REASON CheckExitSignal();  // Correct enum type

5.3 Null Pointer Checks

// ALWAYS check before use
if(m_utils != NULL)
    m_utils.Log("message", LOG_INFO);

6. COMPILATION AND TESTING

6.1 Compilation Checks

Before release, ensure:

  • ZERO warnings with strict compilation
  • All includes use correct paths
  • No undefined identifiers
  • All enums defined before use
  • All structure members exist

6.2 Test Module Pattern

// Create standalone test for each module
void TestModule()
{
    CModule* module = new CModule();
    if(module == NULL)
    {
        Print("FAILED: Module creation");
        return;
    }
    
    if(!module.Initialize())
    {
        Print("FAILED: Module initialization");
        delete module;
        return;
    }
    
    // Test specific functionality
    
    delete module;
    Print("Module test PASSED");
}

7. STRING AND TYPE HANDLING

7.1 String Operations

// Use StringFormat for complex strings
string message = StringFormat("Value: %d, Price: %.5f", value, price);

// String concatenation
string full = str1 + " " + str2;  // OK in MQL5

7.2 Type Casting

// Explicit casting when needed
int magic = (int)PositionGetInteger(POSITION_MAGIC);
datetime time = (datetime)PositionGetInteger(POSITION_TIME);
ENUM_ORDER_TYPE type = (ENUM_ORDER_TYPE)PositionGetInteger(POSITION_TYPE);

8. ERROR HANDLING

8.1 Function Return Checks

if(!FunctionCall())
{
    int error = GetLastError();
    Print(StringFormat("Error %d: %s", error, ErrorDescription(error)));
    return false;
}

8.2 Trade Operation Checks

CTrade trade;
if(!trade.PositionClose(ticket))
{
    Print("Failed to close position: ", trade.ResultRetcodeDescription());
    return false;
}

9. NAMING CONVENTIONS

9.1 Class Members

class CMyClass
{
private:
    int      m_member;      // m_ prefix for members
    static int s_static;    // s_ prefix for static
    
public:
    void     Method();      // PascalCase for methods
    int      GetValue();    // Get/Set for properties
};

9.2 Global Variables

CManager*  g_manager = NULL;  // g_ prefix for globals
int        g_counter = 0;

9.3 Constants and Enums

#define MAX_POSITIONS 100      // UPPER_CASE for defines
enum ENUM_MY_TYPE             // ENUM_ prefix
{
    TYPE_NONE = 0,            // UPPER_CASE with underscores
    TYPE_ACTIVE = 1
};

10. MODULAR DEVELOPMENT BEST PRACTICES

10.1 Module Structure Template

//+------------------------------------------------------------------+
//|                        ModuleName.mqh                            |
//|                     Brief Description                            |
//+------------------------------------------------------------------+
#ifndef MODULE_NAME_MQH
#define MODULE_NAME_MQH

#include "Dependencies.mqh"

class CModuleName : public CObject
{
private:
    // Private members
    
public:
    CModuleName();
    ~CModuleName();
    
    bool Initialize(/* parameters */);
    void Deinitialize();
    
    // Public methods
};

// Implementation
CModuleName::CModuleName()
{
    // Initialize members
}

CModuleName::~CModuleName()
{
    Deinitialize();
}

bool CModuleName::Initialize(/* parameters */)
{
    // Initialization logic
    return true;
}

void CModuleName::Deinitialize()
{
    // Cleanup
}

#endif // MODULE_NAME_MQH

10.2 Module Testing Template

//+------------------------------------------------------------------+
//|                    Test_ModuleName.mq5                           |
//+------------------------------------------------------------------+
#include "ModuleName.mqh"

void OnStart()
{
    Print("Testing ModuleName...");
    
    CModuleName* module = new CModuleName();
    if(module == NULL)
    {
        Print("FAILED: Creation");
        return;
    }
    
    if(!module.Initialize())
    {
        Print("FAILED: Initialization");
        delete module;
        return;
    }
    
    // Specific tests
    
    delete module;
    Print("SUCCESS: All tests passed");
}

11. VERSION CONTROL AND DOCUMENTATION

11.1 Version Headers

//+------------------------------------------------------------------+
//|                     ModuleName v1.0.0                            |
//|                   [FIXED VERSION - MQL5 Compliant]               |
//|                   Last Updated: 2024-01-01                       |
//+------------------------------------------------------------------+

11.2 Change Documentation

// CHANGELOG:
// v1.0.1 - Fixed pointer syntax for MQL5 compliance
// v1.0.0 - Initial release

11.3 Deprecation Notices

// DEPRECATED: Use NewMethod() instead
// Will be removed in v2.0.0
void OldMethod() { NewMethod(); }

12. CRITICAL REMINDERS

Always Remember:

  1. NO pointer operators (->) - use dot notation (.)
  2. Check NULL before using any object pointer
  3. Initialize structures with ZeroMemory()
  4. Free resources in destructors
  5. Check array bounds before access
  6. Define enums before use in structures
  7. Include files in correct order
  8. Test each module independently
  9. Document all changes in headers
  10. Compile with strict mode enabled

Common Error Fixes:

  • “undeclared identifier” → Check if defined in includes
  • “cannot convert enum” → Check enum type matches
  • “object pointer expected” → Change -> to .
  • “some operator expected” → Check syntax and types
  • “operand expected” → Check expression syntax

13. BUILD AND DEPLOYMENT CHECKLIST

Pre-Compilation:

  • All modules include correct dependencies
  • No circular dependencies
  • All enums defined before use
  • All structure members properly typed
  • No pointer syntax (->) used

Post-Compilation:

  • Zero errors
  • Zero warnings
  • All modules tested individually
  • Integration tests pass
  • Memory leaks checked
  • Performance benchmarked

Deployment:

  • Version number updated
  • Changelog updated
  • Backup created
  • Test on demo account
  • Document any breaking changes

Quick Reference Card

AVOID

  • obj->Method() - pointer syntax
  • int &local - local variable references
  • Undefined enums in structures
  • Circular dependencies
  • Memory leaks

ALWAYS

  • obj.Method() - dot notation
  • Check NULL pointers
  • Initialize with ZeroMemory()
  • Delete objects in cleanup
  • Define enums first
  • Test each module

🔧 FIX PATTERNS

Error Solution
-> Change to .
undeclared identifier Add to DataTypes or include
cannot convert enum Check/fix enum type
object pointer expected Remove ->, use .

This document should be included in project knowledge and referenced during all MQL5 EA development.