//+------------------------------------------------------------------+ //| StateManager.mqh | //| Copyright 2025, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2025, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #include "IState.mqh" #include //+------------------------------------------------------------------+ //| State manager – holds named states and can save/load all | //+------------------------------------------------------------------+ class StateManager { private: struct StateEntry { string name; IState* state; }; StateEntry m_entries[]; int m_count; public: StateManager() : m_count(0) {} ~StateManager() { // States are owned externally, do not delete here. } // Register a state object under a unique name void AddState(string name, IState* state) { int size = ArraySize(m_entries); ArrayResize(m_entries, size + 1); m_entries[size].name = name; m_entries[size].state = state; m_count = size + 1; } // Save all states into a single JSON object JSON::Object* SaveAll() { JSON::Object* root = new JSON::Object(); for(int i = 0; i < m_count; i++) { JSON::Object* stateObj = m_entries[i].state.Save(); if(stateObj != NULL) root.setProperty(m_entries[i].name, stateObj); } return root; } // Load all states from a JSON object bool LoadAll(const JSON::Object* root) { if(root == NULL) return false; for(int i = 0; i < m_count; i++) { JSON::Object* stateObj = root.getObject(m_entries[i].name); if(stateObj == NULL) continue; // skip missing m_entries[i].state.Load(stateObj); } return true; } // Write the JSON representation to a file bool SaveToFile(string filename) { JSON::Object* root = SaveAll(); if(root == NULL) return false; string jsonStr = root.toString(); delete root; int handle = FileOpen(filename, FILE_WRITE|FILE_TXT|FILE_ANSI); if(handle == INVALID_HANDLE) return false; FileWriteString(handle, jsonStr); FileClose(handle); return true; } // Read JSON from file and load states bool LoadFromFile(string filename) { int handle = FileOpen(filename, FILE_READ|FILE_TXT|FILE_ANSI); if(handle == INVALID_HANDLE) return false; string jsonStr = ""; while(!FileIsEnding(handle)) jsonStr += FileReadString(handle, 0); FileClose(handle); JSON::Object* root = new JSON::Object(jsonStr); bool result = LoadAll(root); delete root; return result; } }; //+------------------------------------------------------------------+