// FXMacroDataReleaseGuard.cpp (self-contained ACSIL source)
// Download and setup: https://fxmacrodata.com/documentation/sierra-chart

#include <cmath>
#include <cstring>
#include <ctime>
#include <limits>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include "sierrachart.h"

// FXMacroData Release Guard for Sierra Chart (ACSIL, C++17).
//
// Loads the FXMacroData release calendar for the currencies that matter to
// the chart, marks every scheduled release on the chart, shades a blackout
// window around each one, shows the next release in the corner, raises an
// alert ahead of it, and publishes two subgraphs that trading systems and
// Spreadsheet Studies can reference:
//
//   Subgraph 0 "Blackout"                 1 inside a release window, else 0
//   Subgraph 1 "Minutes to next release"  minutes until the next release,
//                                         NaN when nothing is scheduled
//
// Build: copy this file into ACS_Source, then in Analysis >> Build Custom
// Studies DLL use File >> Select Files to select it, then Build >> Remote
// Build. The fxmd headers are already inlined; no additional source files
// are needed.
//
// Standard headers sit above sierrachart.h, as the ACSIL documentation
// requires for additional headers.
//
// Data access: USD works without an API key. Other currencies need a key,
// which is sent in the X-API-Key header and never in the URL or the log.

// ---- begin fxmd_calendar.h ----
// fxmd_calendar.h
//
// Calendar rows, filtering and time helpers for the FXMacroData Sierra Chart
// study. Everything here is plain C++17 with no Sierra Chart dependency, so
// the same code is exercised by the test harness in tests/.
//
// Filtering rules match the FXMacroData TradingView relay:
//   - a row needs announcement_datetime (UNIX seconds, UTC);
//   - rows with time_announced false are date-only markers stamped at
//     00:00 publisher-local and are skipped;
//   - rows with release_time_assumed true carry a time estimated from past
//     lag and are skipped;
//   - importance High keeps market_tier 1 or top_tier_for_currency,
//     Medium keeps market_tier 1 or 2 or top_tier_for_currency, All keeps
//     everything. When market_tier is missing the event_importance label is
//     used instead.

#ifndef FXMD_CALENDAR_H
#define FXMD_CALENDAR_H


// ---- begin fxmd_json.h ----
// fxmd_json.h
//
// A small, self-contained JSON reader for the FXMacroData Sierra Chart study.
// It has no dependencies beyond the C++ standard library and is written to
// compile cleanly as C++17 under MSVC, GCC and Clang.
//
// Scope: it parses one complete JSON document into a tree of JsonValue nodes.
// Strings are decoded (including \uXXXX escapes and surrogate pairs) into
// UTF-8. Numbers are read as doubles. It does not write JSON and it does not
// validate every corner of the grammar with the strictness of a conformance
// suite; it accepts well-formed API responses and rejects clearly broken ones
// with a position in the error message.

#ifndef FXMD_JSON_H
#define FXMD_JSON_H


namespace fxmd {

class JsonValue {
public:
    enum Type { TypeNull = 0, TypeBool, TypeNumber, TypeString, TypeArray, TypeObject };

    Type type;
    bool boolValue;
    double numberValue;
    std::string stringValue;
    // For arrays: the elements, in order. For objects: the member values, in
    // document order, with the matching member names in `keys`.
    std::vector<JsonValue> items;
    std::vector<std::string> keys;

    JsonValue() : type(TypeNull), boolValue(false), numberValue(0.0) {}

    bool IsNull() const { return type == TypeNull; }
    bool IsBool() const { return type == TypeBool; }
    bool IsNumber() const { return type == TypeNumber; }
    bool IsString() const { return type == TypeString; }
    bool IsArray() const { return type == TypeArray; }
    bool IsObject() const { return type == TypeObject; }

    // Number of elements (array) or members (object); 0 for anything else.
    size_t Size() const {
        return (type == TypeArray || type == TypeObject) ? items.size() : 0;
    }

    const JsonValue& At(size_t index) const {
        static const JsonValue nullValue;
        if (index >= items.size())
            return nullValue;
        return items[index];
    }

    // Object member lookup. Returns nullptr when this is not an object or the
    // member is absent.
    const JsonValue* Get(const char* key) const {
        if (type != TypeObject || key == nullptr)
            return nullptr;
        for (size_t i = 0; i < keys.size() && i < items.size(); ++i) {
            if (keys[i] == key)
                return &items[i];
        }
        return nullptr;
    }

    bool Has(const char* key) const { return Get(key) != nullptr; }

    // Loose readers that mirror how the TradingView relay treats the same
    // fields: booleans may arrive as true/false, as the strings "true", "1",
    // "yes", or as numbers.
    bool AsBool(bool fallback) const {
        switch (type) {
        case TypeBool:
            return boolValue;
        case TypeNumber:
            return numberValue != 0.0;
        case TypeString: {
            std::string lowered = stringValue;
            for (size_t i = 0; i < lowered.size(); ++i)
                lowered[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(lowered[i])));
            if (lowered == "true" || lowered == "1" || lowered == "yes")
                return true;
            if (lowered == "false" || lowered == "0" || lowered == "no" || lowered.empty())
                return false;
            return fallback;
        }
        default:
            return fallback;
        }
    }

    // Returns the number, or a numeric string converted, or fallback.
    double AsNumber(double fallback) const {
        if (type == TypeNumber)
            return numberValue;
        if (type == TypeString && !stringValue.empty()) {
            char* end = nullptr;
            double parsed = std::strtod(stringValue.c_str(), &end);
            if (end != nullptr && *end == '\0')
                return parsed;
        }
        return fallback;
    }

    std::string AsString(const std::string& fallback) const {
        if (type == TypeString)
            return stringValue;
        return fallback;
    }

    bool GetBool(const char* key, bool fallback) const {
        const JsonValue* v = Get(key);
        return v ? v->AsBool(fallback) : fallback;
    }

    double GetNumber(const char* key, double fallback) const {
        const JsonValue* v = Get(key);
        return v ? v->AsNumber(fallback) : fallback;
    }

    std::string GetString(const char* key, const std::string& fallback) const {
        const JsonValue* v = Get(key);
        return v ? v->AsString(fallback) : fallback;
    }
};

class JsonParser {
public:
    // Parse `text` into `out`. Returns true on success. On failure `error`
    // holds a short message with the byte offset of the problem.
    static bool Parse(const std::string& text, JsonValue& out, std::string& error) {
        JsonParser parser(text);
        out = JsonValue();
        error.clear();
        parser.SkipWhitespace();
        if (!parser.ParseValue(out, 0)) {
            error = parser.m_error;
            return false;
        }
        parser.SkipWhitespace();
        if (parser.m_pos != parser.m_text.size()) {
            parser.Fail("trailing characters after the JSON document");
            error = parser.m_error;
            return false;
        }
        return true;
    }

private:
    static const int kMaxDepth = 64;

    const std::string& m_text;
    size_t m_pos;
    std::string m_error;

    explicit JsonParser(const std::string& text) : m_text(text), m_pos(0) {}

    void Fail(const char* message) {
        if (!m_error.empty())
            return;
        char buffer[64];
        std::snprintf(buffer, sizeof(buffer), " at offset %u", static_cast<unsigned>(m_pos));
        m_error = std::string(message) + buffer;
    }

    bool AtEnd() const { return m_pos >= m_text.size(); }
    char Peek() const { return AtEnd() ? '\0' : m_text[m_pos]; }

    void SkipWhitespace() {
        while (!AtEnd()) {
            char c = m_text[m_pos];
            if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
                ++m_pos;
            else
                break;
        }
    }

    bool Consume(const char* literal) {
        size_t len = std::strlen(literal);
        if (m_text.compare(m_pos, len, literal) == 0) {
            m_pos += len;
            return true;
        }
        return false;
    }

    bool ParseValue(JsonValue& out, int depth) {
        if (depth > kMaxDepth) {
            Fail("nesting too deep");
            return false;
        }
        if (AtEnd()) {
            Fail("unexpected end of input");
            return false;
        }
        char c = Peek();
        switch (c) {
        case '{':
            return ParseObject(out, depth);
        case '[':
            return ParseArray(out, depth);
        case '"':
            out.type = JsonValue::TypeString;
            return ParseString(out.stringValue);
        case 't':
            if (Consume("true")) {
                out.type = JsonValue::TypeBool;
                out.boolValue = true;
                return true;
            }
            break;
        case 'f':
            if (Consume("false")) {
                out.type = JsonValue::TypeBool;
                out.boolValue = false;
                return true;
            }
            break;
        case 'n':
            if (Consume("null")) {
                out.type = JsonValue::TypeNull;
                return true;
            }
            break;
        default:
            if (c == '-' || (c >= '0' && c <= '9'))
                return ParseNumber(out);
            break;
        }
        Fail("unexpected character");
        return false;
    }

    bool ParseNumber(JsonValue& out) {
        size_t start = m_pos;
        if (Peek() == '-')
            ++m_pos;
        if (AtEnd() || !(Peek() >= '0' && Peek() <= '9')) {
            Fail("malformed number");
            return false;
        }
        while (!AtEnd() && Peek() >= '0' && Peek() <= '9')
            ++m_pos;
        if (Peek() == '.') {
            ++m_pos;
            if (!(Peek() >= '0' && Peek() <= '9')) {
                Fail("malformed number fraction");
                return false;
            }
            while (!AtEnd() && Peek() >= '0' && Peek() <= '9')
                ++m_pos;
        }
        if (Peek() == 'e' || Peek() == 'E') {
            ++m_pos;
            if (Peek() == '+' || Peek() == '-')
                ++m_pos;
            if (!(Peek() >= '0' && Peek() <= '9')) {
                Fail("malformed number exponent");
                return false;
            }
            while (!AtEnd() && Peek() >= '0' && Peek() <= '9')
                ++m_pos;
        }
        std::string span = m_text.substr(start, m_pos - start);
        out.type = JsonValue::TypeNumber;
        out.numberValue = std::strtod(span.c_str(), nullptr);
        return true;
    }

    static int HexValue(char c) {
        if (c >= '0' && c <= '9') return c - '0';
        if (c >= 'a' && c <= 'f') return c - 'a' + 10;
        if (c >= 'A' && c <= 'F') return c - 'A' + 10;
        return -1;
    }

    bool ParseHex4(unsigned& code) {
        if (m_pos + 4 > m_text.size()) {
            Fail("truncated \\u escape");
            return false;
        }
        code = 0;
        for (int i = 0; i < 4; ++i) {
            int h = HexValue(m_text[m_pos + i]);
            if (h < 0) {
                Fail("bad hex digit in \\u escape");
                return false;
            }
            code = (code << 4) | static_cast<unsigned>(h);
        }
        m_pos += 4;
        return true;
    }

    static void AppendUtf8(std::string& out, unsigned code) {
        if (code < 0x80) {
            out.push_back(static_cast<char>(code));
        } else if (code < 0x800) {
            out.push_back(static_cast<char>(0xC0 | (code >> 6)));
            out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
        } else if (code < 0x10000) {
            out.push_back(static_cast<char>(0xE0 | (code >> 12)));
            out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));
            out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
        } else {
            out.push_back(static_cast<char>(0xF0 | (code >> 18)));
            out.push_back(static_cast<char>(0x80 | ((code >> 12) & 0x3F)));
            out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));
            out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
        }
    }

    bool ParseString(std::string& out) {
        out.clear();
        if (Peek() != '"') {
            Fail("expected string");
            return false;
        }
        ++m_pos;
        while (true) {
            if (AtEnd()) {
                Fail("unterminated string");
                return false;
            }
            char c = m_text[m_pos++];
            if (c == '"')
                return true;
            if (c != '\\') {
                out.push_back(c);
                continue;
            }
            if (AtEnd()) {
                Fail("unterminated escape");
                return false;
            }
            char e = m_text[m_pos++];
            switch (e) {
            case '"': out.push_back('"'); break;
            case '\\': out.push_back('\\'); break;
            case '/': out.push_back('/'); break;
            case 'b': out.push_back('\b'); break;
            case 'f': out.push_back('\f'); break;
            case 'n': out.push_back('\n'); break;
            case 'r': out.push_back('\r'); break;
            case 't': out.push_back('\t'); break;
            case 'u': {
                unsigned code = 0;
                if (!ParseHex4(code))
                    return false;
                if (code >= 0xD800 && code <= 0xDBFF) {
                    // High surrogate: a low surrogate must follow.
                    if (m_pos + 6 <= m_text.size() && m_text[m_pos] == '\\' && m_text[m_pos + 1] == 'u') {
                        m_pos += 2;
                        unsigned low = 0;
                        if (!ParseHex4(low))
                            return false;
                        if (low >= 0xDC00 && low <= 0xDFFF) {
                            code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00);
                        } else {
                            code = 0xFFFD;
                        }
                    } else {
                        code = 0xFFFD;
                    }
                } else if (code >= 0xDC00 && code <= 0xDFFF) {
                    code = 0xFFFD;
                }
                AppendUtf8(out, code);
                break;
            }
            default:
                Fail("unknown escape sequence");
                return false;
            }
        }
    }

    bool ParseArray(JsonValue& out, int depth) {
        ++m_pos; // '['
        out.type = JsonValue::TypeArray;
        out.items.clear();
        SkipWhitespace();
        if (Peek() == ']') {
            ++m_pos;
            return true;
        }
        while (true) {
            SkipWhitespace();
            JsonValue element;
            if (!ParseValue(element, depth + 1))
                return false;
            out.items.push_back(element);
            SkipWhitespace();
            char c = Peek();
            if (c == ',') {
                ++m_pos;
                continue;
            }
            if (c == ']') {
                ++m_pos;
                return true;
            }
            Fail("expected ',' or ']' in array");
            return false;
        }
    }

    bool ParseObject(JsonValue& out, int depth) {
        ++m_pos; // '{'
        out.type = JsonValue::TypeObject;
        out.items.clear();
        out.keys.clear();
        SkipWhitespace();
        if (Peek() == '}') {
            ++m_pos;
            return true;
        }
        while (true) {
            SkipWhitespace();
            std::string key;
            if (!ParseString(key))
                return false;
            SkipWhitespace();
            if (Peek() != ':') {
                Fail("expected ':' after object key");
                return false;
            }
            ++m_pos;
            SkipWhitespace();
            JsonValue value;
            if (!ParseValue(value, depth + 1))
                return false;
            out.keys.push_back(key);
            out.items.push_back(value);
            SkipWhitespace();
            char c = Peek();
            if (c == ',') {
                ++m_pos;
                continue;
            }
            if (c == '}') {
                ++m_pos;
                return true;
            }
            Fail("expected ',' or '}' in object");
            return false;
        }
    }
};

} // namespace fxmd

#endif // FXMD_JSON_H
// ---- end fxmd_json.h ----

namespace fxmd {

enum Importance { ImportanceHigh = 0, ImportanceMedium = 1, ImportanceAll = 2 };

struct CalendarEvent {
    std::string currency;   // upper-case ISO code
    std::string release;    // API slug, e.g. "inflation"
    std::string name;       // display name, e.g. "Consumer Price Index (CPI)"
    long long releaseEpoch; // UNIX seconds, UTC
    int marketTier;         // 1, 2, 3 or 0 when absent
    bool topTier;           // top_tier_for_currency

    CalendarEvent() : releaseEpoch(0), marketTier(0), topTier(false) {}
};

inline bool EventBefore(const CalendarEvent& a, const CalendarEvent& b) {
    if (a.releaseEpoch != b.releaseEpoch)
        return a.releaseEpoch < b.releaseEpoch;
    if (a.currency != b.currency)
        return a.currency < b.currency;
    return a.release < b.release;
}

// ---------------------------------------------------------------------------
// Dates. The proleptic Gregorian algorithms below avoid gmtime and its
// platform-specific thread-safe variants.

struct CivilDate {
    int year;
    int month; // 1..12
    int day;   // 1..31
};

inline CivilDate CivilFromDays(long long daysSinceEpoch) {
    // Howard Hinnant's days-to-civil algorithm, public domain.
    long long z = daysSinceEpoch + 719468;
    long long era = (z >= 0 ? z : z - 146096) / 146097;
    long long doe = z - era * 146097;
    long long yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    long long y = yoe + era * 400;
    long long doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    long long mp = (5 * doy + 2) / 153;
    long long d = doy - (153 * mp + 2) / 5 + 1;
    long long m = mp < 10 ? mp + 3 : mp - 9;
    CivilDate out;
    out.year = static_cast<int>(m <= 2 ? y + 1 : y);
    out.month = static_cast<int>(m);
    out.day = static_cast<int>(d);
    return out;
}

inline long long FloorDiv(long long a, long long b) {
    long long q = a / b;
    if ((a % b != 0) && ((a < 0) != (b < 0)))
        --q;
    return q;
}

// "YYYY-MM-DD" for the UTC date `dayOffset` days away from `epochSeconds`.
inline std::string FormatIsoDate(long long epochSeconds, int dayOffset) {
    long long days = FloorDiv(epochSeconds, 86400) + dayOffset;
    CivilDate c = CivilFromDays(days);
    char buffer[16];
    std::snprintf(buffer, sizeof(buffer), "%04d-%02d-%02d", c.year, c.month, c.day);
    return std::string(buffer);
}

// "YYYY-MM-DD HH:MM UTC"
inline std::string FormatUtcMinutes(long long epochSeconds) {
    long long days = FloorDiv(epochSeconds, 86400);
    long long secs = epochSeconds - days * 86400;
    CivilDate c = CivilFromDays(days);
    char buffer[32];
    std::snprintf(buffer, sizeof(buffer), "%04d-%02d-%02d %02d:%02d UTC", c.year, c.month, c.day,
                  static_cast<int>(secs / 3600), static_cast<int>((secs % 3600) / 60));
    return std::string(buffer);
}

// "HH:MM UTC"
inline std::string FormatUtcClock(long long epochSeconds) {
    long long days = FloorDiv(epochSeconds, 86400);
    long long secs = epochSeconds - days * 86400;
    char buffer[16];
    std::snprintf(buffer, sizeof(buffer), "%02d:%02d UTC", static_cast<int>(secs / 3600),
                  static_cast<int>((secs % 3600) / 60));
    return std::string(buffer);
}

// ---------------------------------------------------------------------------
// Currency lists.

inline std::string UpperTrim(const std::string& text) {
    std::string out;
    for (size_t i = 0; i < text.size(); ++i) {
        unsigned char c = static_cast<unsigned char>(text[i]);
        if (std::isspace(c))
            continue;
        out.push_back(static_cast<char>(std::toupper(c)));
    }
    return out;
}

inline bool IsCurrencyCode(const std::string& code) {
    if (code.size() != 3)
        return false;
    for (size_t i = 0; i < 3; ++i) {
        if (!std::isalpha(static_cast<unsigned char>(code[i])))
            return false;
    }
    return true;
}

// "usd, eur;GBP" -> {"EUR", "GBP", "USD"}. Invalid tokens are dropped.
inline std::vector<std::string> ParseCurrencyList(const std::string& text) {
    std::vector<std::string> out;
    std::string current;
    for (size_t i = 0; i <= text.size(); ++i) {
        char c = i < text.size() ? text[i] : ',';
        if (c == ',' || c == ';' || c == '|' || c == ' ' || c == '/') {
            std::string code = UpperTrim(current);
            if (IsCurrencyCode(code))
                out.push_back(code);
            current.clear();
        } else {
            current.push_back(c);
        }
    }
    std::sort(out.begin(), out.end());
    out.erase(std::unique(out.begin(), out.end()), out.end());
    return out;
}

inline std::vector<std::string> IntersectCurrencies(const std::vector<std::string>& a,
                                                    const std::vector<std::string>& b) {
    std::vector<std::string> out;
    for (size_t i = 0; i < a.size(); ++i) {
        if (std::find(b.begin(), b.end(), a[i]) != b.end())
            out.push_back(a[i]);
    }
    return out;
}

inline std::string JoinCurrencies(const std::vector<std::string>& list, const char* separator) {
    std::string out;
    for (size_t i = 0; i < list.size(); ++i) {
        if (i > 0)
            out += separator;
        out += list[i];
    }
    return out;
}

inline std::string LowerAscii(const std::string& text) {
    std::string out = text;
    for (size_t i = 0; i < out.size(); ++i)
        out[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(out[i])));
    return out;
}

// ---------------------------------------------------------------------------
// Request URL.

static const char* const kApiBase = "https://fxmacrodata.com/api/v1";

// GET /api/v1/calendar/{currency}?start_date=<yesterday>&end_date=<today+lookahead>
// The API key never goes in this URL; it travels in the X-API-Key header.
inline std::string BuildCalendarUrl(const std::string& currency, long long nowEpoch, int lookbackDays,
                                    int lookaheadDays) {
    std::string url = kApiBase;
    url += "/calendar/";
    url += LowerAscii(currency);
    url += "?start_date=";
    url += FormatIsoDate(nowEpoch, -lookbackDays);
    url += "&end_date=";
    url += FormatIsoDate(nowEpoch, lookaheadDays);
    return url;
}

// ---------------------------------------------------------------------------
// Row filtering.

inline bool RowIsTimed(const JsonValue& row) {
    const JsonValue* when = row.Get("announcement_datetime");
    if (when == nullptr || when->IsNull())
        return false;
    if (row.Has("time_announced") && !row.GetBool("time_announced", true))
        return false;
    if (row.GetBool("release_time_assumed", false))
        return false;
    return true;
}

inline bool RowPassesImportance(const JsonValue& row, int importance) {
    if (importance == ImportanceAll)
        return true;
    const JsonValue* tierValue = row.Get("market_tier");
    bool hasTier = tierValue != nullptr && !tierValue->IsNull() && !tierValue->IsBool();
    int tier = hasTier ? static_cast<int>(tierValue->AsNumber(0)) : 0;
    if (hasTier && tier <= 0)
        hasTier = false;
    bool topTier = row.GetBool("top_tier_for_currency", false);
    std::string label = LowerAscii(row.GetString("event_importance", ""));
    if (importance == ImportanceHigh) {
        if (hasTier)
            return tier == 1 || topTier;
        return topTier || label == "high";
    }
    // Medium
    if (hasTier)
        return tier <= 2 || topTier;
    return topTier || label == "high" || label == "medium";
}

// Parse one calendar response body. Events that pass the filters are
// appended to `out`. Returns false, with a message in `error`, when the body
// is not a calendar response (bad JSON, an API error object, no data list).
// Error messages never include the request URL or any credential.
inline bool ParseCalendarResponse(const std::string& body, const std::string& currency, int importance,
                                  std::vector<CalendarEvent>& out, std::string& error) {
    JsonValue root;
    if (!JsonParser::Parse(body, root, error)) {
        error = "response is not valid JSON (" + error + ")";
        return false;
    }
    if (!root.IsObject()) {
        error = "response is not a JSON object";
        return false;
    }
    const JsonValue* data = root.Get("data");
    if (data == nullptr || !data->IsArray()) {
        // FastAPI style errors carry "detail"; other shapes carry "error" or
        // "message". Surface whichever is present.
        std::string detail = root.GetString("detail", "");
        if (detail.empty()) {
            const JsonValue* d = root.Get("detail");
            if (d != nullptr && d->IsObject())
                detail = d->GetString("message", d->GetString("error", ""));
        }
        if (detail.empty())
            detail = root.GetString("error", root.GetString("message", ""));
        if (detail.empty())
            detail = "response has no data list";
        error = detail;
        return false;
    }
    std::string code = UpperTrim(currency);
    for (size_t i = 0; i < data->Size(); ++i) {
        const JsonValue& row = data->At(i);
        if (!row.IsObject())
            continue;
        if (!RowIsTimed(row))
            continue;
        if (!RowPassesImportance(row, importance))
            continue;
        double epoch = row.GetNumber("announcement_datetime", -1.0);
        if (!(epoch > 0.0) || std::isnan(epoch) || epoch > 4102444800.0)
            continue;
        CalendarEvent event;
        event.currency = code;
        event.release = row.GetString("release", "");
        event.name = row.GetString("name", event.release);
        if (event.name.empty())
            event.name = event.release;
        event.releaseEpoch = static_cast<long long>(epoch);
        event.marketTier = static_cast<int>(row.GetNumber("market_tier", 0.0));
        event.topTier = row.GetBool("top_tier_for_currency", false);
        out.push_back(event);
    }
    return true;
}

// ---------------------------------------------------------------------------
// Live status.

struct LiveStatus {
    bool inBlackout;          // now is inside [release - before, release + after)
    int activeIndex;          // event whose window contains now, or -1
    int nextIndex;            // first event with release >= now, or -1
    double minutesToNext;     // NaN when nextIndex < 0
    double minutesToWindowEnd;// valid when inBlackout

    LiveStatus() : inBlackout(false), activeIndex(-1), nextIndex(-1),
                   minutesToNext(std::nan("")), minutesToWindowEnd(0.0) {}
};

// `events` must be sorted with EventBefore.
inline LiveStatus ComputeLiveStatus(const std::vector<CalendarEvent>& events, long long nowEpoch,
                                    int beforeMinutes, int afterMinutes) {
    LiveStatus status;
    long long before = static_cast<long long>(beforeMinutes) * 60;
    long long after = static_cast<long long>(afterMinutes) * 60;
    for (size_t i = 0; i < events.size(); ++i) {
        long long start = events[i].releaseEpoch - before;
        long long end = events[i].releaseEpoch + after;
        if (nowEpoch >= start && nowEpoch < end) {
            if (!status.inBlackout) {
                status.inBlackout = true;
                status.activeIndex = static_cast<int>(i);
                status.minutesToWindowEnd = static_cast<double>(end - nowEpoch) / 60.0;
            } else {
                // Overlapping windows: the blackout lasts until the latest end.
                double remaining = static_cast<double>(end - nowEpoch) / 60.0;
                if (remaining > status.minutesToWindowEnd)
                    status.minutesToWindowEnd = remaining;
            }
        }
        if (status.nextIndex < 0 && events[i].releaseEpoch >= nowEpoch) {
            status.nextIndex = static_cast<int>(i);
            status.minutesToNext = static_cast<double>(events[i].releaseEpoch - nowEpoch) / 60.0;
        }
    }
    return status;
}

// True when the half-open interval [intervalStart, intervalEnd) overlaps any
// release window. Used for historical bars.
inline bool IntervalTouchesWindow(const std::vector<CalendarEvent>& events, long long intervalStart,
                                  long long intervalEnd, int beforeMinutes, int afterMinutes) {
    long long before = static_cast<long long>(beforeMinutes) * 60;
    long long after = static_cast<long long>(afterMinutes) * 60;
    for (size_t i = 0; i < events.size(); ++i) {
        long long start = events[i].releaseEpoch - before;
        long long end = events[i].releaseEpoch + after;
        if (start < intervalEnd && end > intervalStart)
            return true;
        if (start >= intervalEnd)
            break; // sorted: nothing later can overlap
    }
    return false;
}

// Minutes from `fromEpoch` to the first release at or after it; NaN if none.
inline double MinutesToNextRelease(const std::vector<CalendarEvent>& events, long long fromEpoch) {
    for (size_t i = 0; i < events.size(); ++i) {
        if (events[i].releaseEpoch >= fromEpoch)
            return static_cast<double>(events[i].releaseEpoch - fromEpoch) / 60.0;
    }
    return std::nan("");
}

// Shorten a display name so a chart label stays readable.
inline std::string ShortLabel(const CalendarEvent& event, size_t maxChars) {
    std::string label = event.currency + " " + event.name;
    if (label.size() > maxChars && maxChars > 3)
        label = label.substr(0, maxChars - 3) + "...";
    return label;
}

} // namespace fxmd

#endif // FXMD_CALENDAR_H
// ---- end fxmd_calendar.h ----
// ---- begin fxmd_symbols.h ----
// fxmd_symbols.h
//
// Maps a Sierra Chart symbol to the currencies whose scheduled releases can
// move it. The rules follow the FXMacroData TradingView relay: EURUSD is EUR
// and USD, US500 is USD, XAUUSD is USD, BTCUSDT is USD, and so on. On top of
// those rules this file understands futures contract codes such as ESZ6,
// 6EH26, GCG6 or CLF26, and the exchange prefixes and suffixes Sierra Chart
// data feeds attach to them (ESZ6-CME, F.US.EPZ26, ESZ26_FUT_CME).
//
// Unknown symbols return an empty list so the caller can decide whether to
// fall back to its configured currency list.

#ifndef FXMD_SYMBOLS_H
#define FXMD_SYMBOLS_H


namespace fxmd {

typedef std::vector<std::string> CurrencyList;

namespace symbols_detail {

inline bool InList(const char* const* list, size_t count, const std::string& value) {
    for (size_t i = 0; i < count; ++i) {
        if (value == list[i])
            return true;
    }
    return false;
}

// ISO codes treated as fiat currencies when splitting a pair. The list is
// wider than the FXMacroData catalogue on purpose: the caller intersects the
// result with the currencies it actually wants.
static const char* const kFiat[] = {
    "AUD", "BRL", "CAD", "CHF", "CNH", "CNY", "CZK", "DKK", "EUR", "GBP",
    "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NGN",
    "NOK", "NZD", "PEN", "PHP", "PLN", "RUB", "SEK", "SGD", "THB", "TRY",
    "TWD", "USD", "ZAR",
};

static const char* const kMetals[] = { "XAU", "XAG", "XPT", "XPD" };

static const char* const kExchangeSuffixes[] = {
    "CME", "CBOT", "CBT", "NYMEX", "NYM", "COMEX", "CMX", "EUREX", "ICE", "ICEUS",
    "ICEEU", "IFEU", "IFUS", "SGX", "OSE", "JPX", "CFE", "TSE", "HKEX", "HKFE",
    "MX", "NYBOT", "KCBT", "MGEX", "BMF", "B3", "ASX", "SFE", "LIFFE", "EEX",
    "FUT", "SPOT", "FX", "FOREX", "FXCM", "OANDA", "LMAX", "IB", "RITHMIC", "TETON",
};

inline bool IsFiat(const std::string& code) {
    return InList(kFiat, sizeof(kFiat) / sizeof(kFiat[0]), code);
}

inline bool IsMetal(const std::string& code) {
    return InList(kMetals, sizeof(kMetals) / sizeof(kMetals[0]), code);
}

inline bool IsExchangeSuffix(const std::string& text) {
    return InList(kExchangeSuffixes, sizeof(kExchangeSuffixes) / sizeof(kExchangeSuffixes[0]), text);
}

struct SymbolEntry {
    const char* symbol;
    const char* currencies; // comma separated, may be empty
};

// Indices, energy, dollar index and other cash/CFD names. An empty currency
// string means "known, but no currency calendar applies".
static const SymbolEntry kCashSymbols[] = {
    // US equity indices
    { "US500", "USD" }, { "SPX", "USD" }, { "SPX500", "USD" }, { "SPX500USD", "USD" },
    { "SP500", "USD" }, { "ES1!", "USD" }, { "NAS100", "USD" }, { "US100", "USD" },
    { "NDX", "USD" }, { "NQ1!", "USD" }, { "US30", "USD" }, { "DJI", "USD" },
    { "DJIA", "USD" }, { "YM1!", "USD" }, { "US2000", "USD" }, { "RTY1!", "USD" },
    { "RUT", "USD" }, { "VIX", "USD" },
    // European indices
    { "DE40", "EUR" }, { "GER40", "EUR" }, { "GER30", "EUR" }, { "DAX", "EUR" },
    { "EU50", "EUR" }, { "STOXX50", "EUR" }, { "SX5E", "EUR" }, { "FR40", "EUR" },
    { "CAC40", "EUR" }, { "UK100", "GBP" }, { "FTSE", "GBP" }, { "FTSE100", "GBP" },
    { "UKX", "GBP" }, { "SMI", "CHF" }, { "SWI20", "CHF" },
    // Asia-Pacific indices
    { "JP225", "JPY" }, { "NI225", "JPY" }, { "JPN225", "JPY" }, { "N225", "JPY" },
    { "NKY", "JPY" }, { "AUS200", "AUD" }, { "AU200", "AUD" }, { "XJO", "AUD" },
    { "HK50", "" }, { "HSI", "" }, { "SPTSX", "CAD" }, { "CA60", "CAD" },
    // Energy
    { "USOIL", "USD" }, { "UKOIL", "USD" }, { "WTI", "USD" }, { "BRENT", "USD" },
    { "NATGAS", "USD" }, { "CL1!", "USD" }, { "NG1!", "USD" },
    // Dollar index
    { "DXY", "USD" }, { "USDX", "USD" }, { "DX1!", "USD" },
};

// Futures roots. Month codes and year digits are stripped before lookup, so
// ESZ6, ESZ26 and ESZ2026 all resolve to ES. Where a data feed uses its own
// root (for example CQG uses EP for the E-mini S&P 500) that root is listed
// as well.
static const SymbolEntry kFuturesRoots[] = {
    // US equity index futures
    { "ES", "USD" }, { "MES", "USD" }, { "EP", "USD" }, { "NQ", "USD" }, { "MNQ", "USD" },
    { "ENQ", "USD" }, { "YM", "USD" }, { "MYM", "USD" }, { "RTY", "USD" }, { "M2K", "USD" },
    { "EMD", "USD" }, { "VX", "USD" }, { "VXM", "USD" },
    // US rates
    { "ZB", "USD" }, { "ZN", "USD" }, { "ZF", "USD" }, { "ZT", "USD" }, { "UB", "USD" },
    { "TN", "USD" }, { "SR3", "USD" }, { "SR1", "USD" }, { "ZQ", "USD" }, { "GE", "USD" },
    { "US", "USD" }, { "TY", "USD" }, { "FV", "USD" }, { "TU", "USD" },
    // Energy (CME codes and CQG codes)
    { "CL", "USD" }, { "MCL", "USD" }, { "QM", "USD" }, { "CLE", "USD" }, { "NG", "USD" },
    { "QG", "USD" }, { "NGE", "USD" }, { "HO", "USD" }, { "HOE", "USD" }, { "RB", "USD" },
    { "RBE", "USD" }, { "BZ", "USD" }, { "BRN", "USD" },
    // Metals (CME codes and CQG codes)
    { "GC", "USD" }, { "MGC", "USD" }, { "GCE", "USD" }, { "SI", "USD" }, { "SIL", "USD" },
    { "SIE", "USD" }, { "HG", "USD" }, { "HGE", "USD" }, { "PL", "USD" }, { "PA", "USD" },
    // Grains and softs are priced in USD
    { "ZC", "USD" }, { "ZS", "USD" }, { "ZW", "USD" }, { "ZM", "USD" }, { "ZL", "USD" },
    { "KC", "USD" }, { "SB", "USD" }, { "CC", "USD" }, { "CT", "USD" },
    // Dollar index
    { "DX", "USD" },
    // CME FX futures (full size, E-mini and micro) plus legacy floor codes
    { "6E", "EUR,USD" }, { "E7", "EUR,USD" }, { "M6E", "EUR,USD" }, { "EC", "EUR,USD" }, { "EU6", "EUR,USD" },
    { "6J", "JPY,USD" }, { "J7", "JPY,USD" }, { "MJY", "JPY,USD" }, { "JY", "JPY,USD" }, { "JY6", "JPY,USD" },
    { "6B", "GBP,USD" }, { "M6B", "GBP,USD" }, { "BP", "GBP,USD" }, { "BP6", "GBP,USD" },
    { "6A", "AUD,USD" }, { "M6A", "AUD,USD" }, { "AD", "AUD,USD" }, { "AD6", "AUD,USD" },
    { "6C", "CAD,USD" }, { "MCD", "CAD,USD" }, { "CD", "CAD,USD" }, { "CA6", "CAD,USD" },
    { "6S", "CHF,USD" }, { "MSF", "CHF,USD" }, { "SF", "CHF,USD" }, { "SF6", "CHF,USD" },
    { "6N", "NZD,USD" }, { "NE", "NZD,USD" }, { "NE6", "NZD,USD" },
    { "6M", "MXN,USD" }, { "MP", "MXN,USD" },
    { "6L", "BRL,USD" }, { "6Z", "ZAR,USD" }, { "6R", "RUB,USD" },
    { "RMB", "CNH,USD" }, { "CNH", "CNH,USD" },
    // Europe
    { "FDAX", "EUR" }, { "FDXM", "EUR" }, { "FDXS", "EUR" }, { "FESX", "EUR" }, { "FSXE", "EUR" },
    { "FGBL", "EUR" }, { "FGBM", "EUR" }, { "FGBS", "EUR" }, { "FGBX", "EUR" }, { "FOAT", "EUR" },
    { "FBTP", "EUR" }, { "FCE", "EUR" }, { "FESB", "EUR" }, { "FSTX", "EUR" },
    { "FSMI", "CHF" },
    { "Z", "GBP" }, { "R", "GBP" }, { "L", "GBP" },
    // Asia-Pacific
    { "NK", "JPY" }, { "NIY", "JPY" }, { "NKD", "JPY,USD" }, { "JGB", "JPY" },
    { "AP", "AUD" }, { "XT", "AUD" }, { "YT", "AUD" }, { "IR", "AUD" },
    { "SXF", "CAD" }, { "CGB", "CAD" }, { "BAX", "CAD" },
};

inline const SymbolEntry* FindEntry(const SymbolEntry* table, size_t count, const std::string& key) {
    for (size_t i = 0; i < count; ++i) {
        if (key == table[i].symbol)
            return &table[i];
    }
    return nullptr;
}

inline void SplitCommaList(const std::string& text, CurrencyList& out) {
    std::string current;
    for (size_t i = 0; i <= text.size(); ++i) {
        if (i == text.size() || text[i] == ',') {
            if (!current.empty())
                out.push_back(current);
            current.clear();
        } else {
            current.push_back(text[i]);
        }
    }
}

inline CurrencyList FromEntry(const SymbolEntry* entry) {
    CurrencyList out;
    if (entry != nullptr)
        SplitCommaList(entry->currencies, out);
    return out;
}

inline bool IsMonthCode(char c) {
    return std::strchr("FGHJKMNQUVXZ", c) != nullptr && c != '\0';
}

inline bool IsAllAlpha(const std::string& s) {
    if (s.empty())
        return false;
    for (size_t i = 0; i < s.size(); ++i) {
        if (!std::isalpha(static_cast<unsigned char>(s[i])))
            return false;
    }
    return true;
}

// Strip a futures month code plus one to four year digits from the end of a
// symbol: ESZ6 -> ES, 6EH26 -> 6E, GCG2026 -> GC. Returns false when the
// symbol does not look like a contract code.
inline bool StripContractCode(const std::string& symbol, std::string& root) {
    size_t end = symbol.size();
    size_t digits = 0;
    while (end > 0 && std::isdigit(static_cast<unsigned char>(symbol[end - 1])) && digits < 4) {
        --end;
        ++digits;
    }
    if (digits == 0 || end == 0)
        return false;
    if (!IsMonthCode(symbol[end - 1]))
        return false;
    root = symbol.substr(0, end - 1);
    return !root.empty() && root.size() <= 4;
}

} // namespace symbols_detail

inline void SortUnique(CurrencyList& list) {
    std::sort(list.begin(), list.end());
    list.erase(std::unique(list.begin(), list.end()), list.end());
}

// Upper-case the symbol and strip feed decorations.
//   "OANDA:EURUSD"  -> "EURUSD"      exchange prefix
//   "EURUSD.P"      -> "EURUSD"      broker suffix after a dot
//   "EUR/USD"       -> "EURUSD"      pair separator
//   "ESZ6-CME"      -> "ESZ6"        Sierra Chart exchange suffix
//   "ESZ26_FUT_CME" -> "ESZ26"       Denali style suffix
//   "F.US.EPZ26"    -> "EPZ26"       CQG style prefix
// A "!" continuous-contract suffix (ES1!) is kept because the cash table
// lists it that way.
inline std::string NormalizeSymbol(const std::string& raw) {
    std::string text;
    for (size_t i = 0; i < raw.size(); ++i) {
        unsigned char c = static_cast<unsigned char>(raw[i]);
        if (c == ' ' || c == '\t')
            continue;
        text.push_back(static_cast<char>(std::toupper(c)));
    }
    if (text.empty())
        return text;

    // Exchange prefix: "OANDA:EURUSD".
    size_t colon = text.find(':');
    if (colon != std::string::npos)
        text = text.substr(colon + 1);

    // Dotted names. CQG style prefixes ("F.US.EPZ26", "I.US.SPX") keep the
    // last segment; broker suffixes ("EURUSD.P", "ESZ6.CME") keep the first.
    size_t dot = text.find('.');
    if (dot != std::string::npos) {
        if (dot <= 2 && text.size() > dot + 1) {
            size_t lastDot = text.rfind('.');
            text = text.substr(lastDot + 1);
        } else {
            text = text.substr(0, dot);
        }
    }

    // Underscore suffixes: "ESZ26_FUT_CME", "EURUSD_FXCM".
    size_t underscore = text.find('_');
    if (underscore != std::string::npos) {
        std::string head = text.substr(0, underscore);
        std::string tail = text.substr(underscore + 1);
        size_t tailSep = tail.find('_');
        std::string tailFirst = tailSep == std::string::npos ? tail : tail.substr(0, tailSep);
        if (symbols_detail::IsExchangeSuffix(tailFirst) || head.size() >= 5) {
            text = head;
        } else {
            // Treat as a pair separator: EUR_USD.
            std::string joined;
            for (size_t i = 0; i < text.size(); ++i) {
                if (text[i] != '_')
                    joined.push_back(text[i]);
            }
            text = joined;
        }
    }

    // Hyphen: an exchange suffix ("ESZ6-CME") is dropped; a pair separator
    // ("EUR-USD") is removed.
    size_t hyphen = text.find('-');
    if (hyphen != std::string::npos) {
        std::string head = text.substr(0, hyphen);
        std::string tail = text.substr(hyphen + 1);
        if (symbols_detail::IsExchangeSuffix(tail) || (!head.empty() && head.size() <= 5 && tail.size() >= 2 && tail.size() <= 6 && !symbols_detail::IsFiat(tail))) {
            text = head;
        } else {
            std::string joined;
            for (size_t i = 0; i < text.size(); ++i) {
                if (text[i] != '-')
                    joined.push_back(text[i]);
            }
            text = joined;
        }
    }

    // Any remaining slashes are pair separators.
    std::string result;
    for (size_t i = 0; i < text.size(); ++i) {
        if (text[i] != '/')
            result.push_back(text[i]);
    }
    return result;
}

// Return the currency codes whose calendars apply to `rawSymbol`, sorted and
// de-duplicated. An empty list means the symbol is unknown or has no
// currency calendar (for example HSI).
inline CurrencyList CurrenciesForSymbol(const std::string& rawSymbol) {
    using namespace symbols_detail;
    CurrencyList out;
    std::string symbol = NormalizeSymbol(rawSymbol);
    if (symbol.empty())
        return out;

    const size_t cashCount = sizeof(kCashSymbols) / sizeof(kCashSymbols[0]);
    const size_t rootCount = sizeof(kFuturesRoots) / sizeof(kFuturesRoots[0]);

    if (const SymbolEntry* entry = FindEntry(kCashSymbols, cashCount, symbol)) {
        out = FromEntry(entry);
        SortUnique(out);
        return out;
    }

    // Plain six-letter FX pair.
    if (symbol.size() == 6 && IsFiat(symbol.substr(0, 3)) && IsFiat(symbol.substr(3, 3))) {
        out.push_back(symbol.substr(0, 3));
        out.push_back(symbol.substr(3, 3));
        SortUnique(out);
        return out;
    }

    // Futures: a bare root (ES) or a dated contract (ESZ6, ESZ26).
    if (const SymbolEntry* entry = FindEntry(kFuturesRoots, rootCount, symbol)) {
        out = FromEntry(entry);
        SortUnique(out);
        return out;
    }
    std::string root;
    if (StripContractCode(symbol, root)) {
        if (const SymbolEntry* entry = FindEntry(kFuturesRoots, rootCount, root)) {
            out = FromEntry(entry);
            SortUnique(out);
            return out;
        }
    }

    // Something quoted in a fiat currency or a USD stablecoin.
    static const size_t quoteLengths[] = { 4, 3 };
    for (size_t q = 0; q < 2; ++q) {
        size_t quoteLen = quoteLengths[q];
        if (symbol.size() <= quoteLen)
            continue;
        std::string base = symbol.substr(0, symbol.size() - quoteLen);
        std::string quote = symbol.substr(symbol.size() - quoteLen);
        std::string quoteFiat;
        if (quoteLen == 4 && (quote == "USDT" || quote == "USDC"))
            quoteFiat = "USD";
        else if (quoteLen == 3 && IsFiat(quote))
            quoteFiat = quote;
        if (quoteFiat.empty())
            continue;
        if (IsMetal(base)) {
            out.push_back("USD");
            out.push_back(quoteFiat);
        } else if (IsFiat(base)) {
            out.push_back(base);
            out.push_back(quoteFiat);
        } else if (IsAllAlpha(base) && base.size() >= 2 && base.size() <= 6) {
            // Crypto or another asset quoted in a fiat currency.
            out.push_back(quoteFiat);
        } else {
            continue;
        }
        SortUnique(out);
        return out;
    }

    // Broker suffix glued on without a separator: EURUSDM, GBPUSDPRO, XAUUSDM.
    if (symbol.size() > 6 && IsFiat(symbol.substr(0, 3)) && IsFiat(symbol.substr(3, 3))) {
        out.push_back(symbol.substr(0, 3));
        out.push_back(symbol.substr(3, 3));
        SortUnique(out);
        return out;
    }
    if (symbol.size() > 6 && IsMetal(symbol.substr(0, 3)) && IsFiat(symbol.substr(3, 3))) {
        out.push_back("USD");
        out.push_back(symbol.substr(3, 3));
        SortUnique(out);
        return out;
    }

    return out;
}

} // namespace fxmd

#endif // FXMD_SYMBOLS_H
// ---- end fxmd_symbols.h ----

SCDLLName("FXMacroData Release Guard")

namespace {

// ---------------------------------------------------------------------------
// Persistent storage keys. Integers, doubles and the pointer each have their
// own key space in ACSIL, so overlapping numbers are fine, but they are kept
// distinct here for readability.

const int PK_STATE = 1;            // int: request state machine
const int PK_CURRENCY_INDEX = 2;   // int: which currency is being fetched
const int PK_FAILED_REFRESHES = 3; // int: consecutive refresh cycles with a failure
const int PK_DRAWN_MARKERS = 4;    // int: release markers currently on the chart
const int PK_DRAWN_RECTS = 5;      // int: blackout rectangles currently on the chart
const int PK_CALENDAR_VERSION = 6; // int: version of the calendar the subgraphs reflect
const int PK_STATUS_LOGGED = 7;    // int: 1 once the USD-only notice has been logged
const int PK_STALE_LOGGED = 8;     // int: 1 once the stale notice has been logged
const int PK_HAVE_LOADED_ONCE = 9; // int: 1 after the first successful refresh

const int PK_LAST_REFRESH_EPOCH = 1;  // double: when the last refresh cycle started
const int PK_LAST_GOOD_EPOCH = 2;     // double: when the last full refresh succeeded
const int PK_LAST_ALERT_EPOCH = 3;    // double: release epoch the last alert was for
const int PK_REQUEST_STARTED_EPOCH = 4; // double: when the in-flight request was issued

const int kRequestTimeoutSeconds = 120;

const int PK_STATE_POINTER = 1;        // void*: StudyState

enum RequestState { STATE_IDLE = 0, STATE_WAITING = 1 };

// Input indices.
enum {
    IN_CURRENCIES = 0,
    IN_API_KEY,
    IN_MINUTES_BEFORE,
    IN_MINUTES_AFTER,
    IN_IMPORTANCE,
    IN_REFRESH_MINUTES,
    IN_DRAW_MARKERS,
    IN_DRAW_SHADING,
    IN_SHOW_STATUS_TEXT,
    IN_ALERT_MINUTES,
    IN_ALERT_SOUND,
    IN_USE_SYMBOL_CURRENCIES,
    IN_COUNT
};

// Subgraph indices. Subgraphs 2 to 4 are never plotted; their colours are
// the user-editable colours for the chart drawings.
enum {
    SG_BLACKOUT = 0,
    SG_MINUTES_TO_NEXT,
    SG_COLOR_TOP_TIER,
    SG_COLOR_OTHER,
    SG_COLOR_SHADING,
    SG_COUNT
};

const int kLookbackDays = 1;
const int kLookaheadDays = 7;
const int kMaxDrawnEvents = 250;

// Everything that lives across study calls and is not a plain number.
struct StudyState {
    std::vector<fxmd::CalendarEvent> live;     // the calendar in use
    std::vector<fxmd::CalendarEvent> staging;  // the calendar being fetched
    std::vector<std::string> currencies;       // currencies for the current cycle
    std::string lastError;                     // last fetch error, for the status text
    bool cycleHadFailure;
    int calendarVersion;                       // bumps whenever `live` changes
    std::string lastDrawnText;
    std::string fetchSignature;                // inputs that require a new fetch
    std::string fetchApiKey;                   // compared in memory only, never logged

    // Each live event's window in the chart's time zone, as SCDateTime
    // doubles (days). Rebuilt when the calendar or the window inputs change.
    std::vector<double> chartRelease;
    std::vector<double> chartStart;
    std::vector<double> chartEnd;
    int windowBeforeMinutes;
    int windowAfterMinutes;
    int windowVersion;                         // calendarVersion the windows reflect

    StudyState() : cycleHadFailure(false), calendarVersion(0), windowBeforeMinutes(-1),
                   windowAfterMinutes(-1), windowVersion(-1) {}
};

long long NowEpochUtc() {
    return static_cast<long long>(std::time(nullptr));
}

// UNIX seconds -> SCDateTime in UTC. SCDateTime dates count days since
// 1899-12-30, so 1970-01-01 is day 25569.
SCDateTime EpochToSCDateTimeUtc(long long epochSeconds) {
    long long days = fxmd::FloorDiv(epochSeconds, 86400);
    int timeOfDay = static_cast<int>(epochSeconds - days * 86400);
    return SCDateTime(static_cast<int>(days + 25569), timeOfDay);
}

// UNIX seconds -> SCDateTime in the chart's time zone.
SCDateTime EpochToChartTime(SCStudyInterfaceRef sc, long long epochSeconds) {
    return sc.ConvertDateTimeToChartTimeZone(EpochToSCDateTimeUtc(epochSeconds), TIMEZONE_UTC);
}

// Rebuild the chart-time copies of every live window. Converting each release
// individually keeps daylight-saving changes inside the loaded range correct.
void RebuildChartWindows(SCStudyInterfaceRef sc, StudyState& state, int beforeMinutes, int afterMinutes) {
    const size_t count = state.live.size();
    state.chartRelease.resize(count);
    state.chartStart.resize(count);
    state.chartEnd.resize(count);
    const long long before = static_cast<long long>(beforeMinutes) * 60;
    const long long after = static_cast<long long>(afterMinutes) * 60;
    for (size_t i = 0; i < count; ++i) {
        const long long release = state.live[i].releaseEpoch;
        state.chartRelease[i] = EpochToChartTime(sc, release).GetAsDouble();
        state.chartStart[i] = EpochToChartTime(sc, release - before).GetAsDouble();
        state.chartEnd[i] = EpochToChartTime(sc, release + after).GetAsDouble();
    }
    state.windowBeforeMinutes = beforeMinutes;
    state.windowAfterMinutes = afterMinutes;
    state.windowVersion = state.calendarVersion;
}

// True when the bar [barStart, barEnd) overlaps any window. Times are
// SCDateTime doubles in the chart's time zone; windows are sorted by start.
bool BarTouchesWindow(const StudyState& state, double barStart, double barEnd) {
    for (size_t i = 0; i < state.chartStart.size(); ++i) {
        if (state.chartStart[i] < barEnd && state.chartEnd[i] > barStart)
            return true;
        if (state.chartStart[i] >= barEnd)
            break;
    }
    return false;
}

// Minutes from a bar's start to the first release at or after it; NaN if none.
double BarMinutesToNextRelease(const StudyState& state, double barStart) {
    for (size_t i = 0; i < state.chartRelease.size(); ++i) {
        if (state.chartRelease[i] >= barStart)
            return (state.chartRelease[i] - barStart) * 1440.0;
    }
    return std::nan("");
}

void Log(SCStudyInterfaceRef sc, const std::string& text) {
    SCString line;
    line.Format("FXMacroData Release Guard: %s", text.c_str());
    sc.AddMessageToLog(line, 0);
}

int BaseLineNumber(SCStudyInterfaceRef sc) {
    // Keep the drawing identifiers of two instances of this study on the
    // same chart apart. StudyGraphInstanceID is unique per study on a chart.
    return 740000 + (sc.StudyGraphInstanceID % 200) * 1000;
}

// Resolve which currencies this chart should load. Returns the list and
// fills `note` with anything worth showing in the status text.
std::vector<std::string> ResolveCurrencies(SCStudyInterfaceRef sc, bool haveKey, std::string& note) {
    std::vector<std::string> configured = fxmd::ParseCurrencyList(sc.Input[IN_CURRENCIES].GetString());
    std::vector<std::string> chosen = configured;
    note.clear();

    if (sc.Input[IN_USE_SYMBOL_CURRENCIES].GetYesNo()) {
        std::string symbol = sc.Symbol.GetChars();
        fxmd::CurrencyList fromSymbol = fxmd::CurrenciesForSymbol(symbol);
        if (fromSymbol.empty()) {
            note = "symbol not recognised, using the Currencies input";
        } else {
            chosen = fxmd::IntersectCurrencies(fromSymbol, configured);
            if (chosen.empty())
                note = "no overlap between the symbol's currencies (" + fxmd::JoinCurrencies(fromSymbol, " ") +
                       ") and the Currencies input";
        }
    }

    if (!haveKey) {
        std::vector<std::string> usdOnly;
        for (size_t i = 0; i < chosen.size(); ++i) {
            if (chosen[i] == "USD")
                usdOnly.push_back(chosen[i]);
        }
        if (usdOnly.size() != chosen.size()) {
            if (!note.empty())
                note += "; ";
            note += "no API key, USD only";
        }
        chosen = usdOnly;
    }
    return chosen;
}

// Issue the calendar request for one currency. Returns false when ACSIL
// refused to start the request.
//
// Without a key: sc.MakeHTTPRequest (GET).
// With a key:    sc.MakeHTTPPOSTRequest with the X-API-Key header and an
//                empty body. It is the only ACSIL HTTP call that accepts
//                custom headers, and the key must not travel in the URL.
bool IssueCalendarRequest(SCStudyInterfaceRef sc, const std::string& currency, const char* apiKey,
                          long long nowEpoch) {
    std::string url = fxmd::BuildCalendarUrl(currency, nowEpoch, kLookbackDays, kLookaheadDays);
    SCString requestUrl;
    requestUrl = url.c_str();

    if (apiKey != nullptr && apiKey[0] != '\0') {
        n_ACSIL::s_HTTPHeader headers[2];
        headers[0].Name = "X-API-Key";
        headers[0].Value = apiKey;
        headers[1].Name = "Accept";
        headers[1].Value = "application/json";
        SCString emptyBody;
        emptyBody = "";
        return sc.MakeHTTPPOSTRequest(requestUrl, emptyBody, headers, 2) != 0;
    }
    return sc.MakeHTTPRequest(requestUrl) != 0;
}

void DeleteDrawingRange(SCStudyInterfaceRef sc, int firstLineNumber, int count) {
    for (int i = 0; i < count; ++i)
        sc.DeleteACSChartDrawing(sc.ChartNumber, TOOL_DELETE_CHARTDRAWING, firstLineNumber + i);
}

void UpdateReleaseDrawings(SCStudyInterfaceRef sc, StudyState& state, int beforeMinutes, int afterMinutes) {
    const int base = BaseLineNumber(sc);
    const int markerBase = base + 100;   // vertical line i  -> base + 100 + i
    const int labelBase = base + 400;    // text label i     -> base + 400 + i
    const int rectBase = base + 700;     // rectangle i      -> base + 700 + i

    int& drawnMarkers = sc.GetPersistentInt(PK_DRAWN_MARKERS);
    int& drawnRects = sc.GetPersistentInt(PK_DRAWN_RECTS);

    const bool drawMarkers = sc.Input[IN_DRAW_MARKERS].GetYesNo() != 0;
    const bool drawShading = sc.Input[IN_DRAW_SHADING].GetYesNo() != 0;

    int wanted = static_cast<int>(state.live.size());
    if (wanted > kMaxDrawnEvents)
        wanted = kMaxDrawnEvents;

    int markersToDraw = drawMarkers ? wanted : 0;
    int rectsToDraw = drawShading ? wanted : 0;

    // Remove drawings that no longer have an event.
    if (drawnMarkers > markersToDraw) {
        DeleteDrawingRange(sc, markerBase + markersToDraw, drawnMarkers - markersToDraw);
        DeleteDrawingRange(sc, labelBase + markersToDraw, drawnMarkers - markersToDraw);
    }
    if (drawnRects > rectsToDraw)
        DeleteDrawingRange(sc, rectBase + rectsToDraw, drawnRects - rectsToDraw);

    const COLORREF topTierColor = sc.Subgraph[SG_COLOR_TOP_TIER].PrimaryColor;
    const COLORREF otherColor = sc.Subgraph[SG_COLOR_OTHER].PrimaryColor;
    const COLORREF shadeColor = sc.Subgraph[SG_COLOR_SHADING].PrimaryColor;

    for (int i = 0; i < wanted; ++i) {
        const fxmd::CalendarEvent& event = state.live[static_cast<size_t>(i)];
        SCDateTime releaseChart = EpochToChartTime(sc, event.releaseEpoch);
        const bool important = event.marketTier == 1 || event.topTier;

        if (drawMarkers) {
            s_UseTool line;
            line.Clear();
            line.ChartNumber = sc.ChartNumber;
            line.DrawingType = DRAWING_VERTICALLINE;
            line.LineNumber = markerBase + i;
            line.AddMethod = UTAM_ADD_OR_ADJUST;
            line.BeginDateTime = releaseChart;
            line.Color = important ? topTierColor : otherColor;
            line.LineWidth = important ? 2 : 1;
            line.LineStyle = important ? LINESTYLE_SOLID : LINESTYLE_DASH;
            line.Region = 0;
            line.DrawUnderneathMainGraph = 1;
            line.AddAsUserDrawnDrawing = 0;
            sc.UseTool(line);

            s_UseTool label;
            label.Clear();
            label.ChartNumber = sc.ChartNumber;
            label.DrawingType = DRAWING_TEXT;
            label.LineNumber = labelBase + i;
            label.AddMethod = UTAM_ADD_OR_ADJUST;
            label.BeginDateTime = releaseChart;
            label.UseRelativeVerticalValues = 1;
            label.BeginValue = 96.0f;
            label.Color = important ? topTierColor : otherColor;
            label.FontSize = important ? 9 : 8;
            label.FontBold = important ? 1 : 0;
            label.TextAlignment = DT_TOP | DT_LEFT;
            label.Region = 0;
            label.AddAsUserDrawnDrawing = 0;
            std::string text = fxmd::ShortLabel(event, 36);
            label.Text = text.c_str();
            sc.UseTool(label);
        }

        if (drawShading) {
            s_UseTool rect;
            rect.Clear();
            rect.ChartNumber = sc.ChartNumber;
            rect.DrawingType = DRAWING_RECTANGLEHIGHLIGHT;
            rect.LineNumber = rectBase + i;
            rect.AddMethod = UTAM_ADD_OR_ADJUST;
            rect.BeginDateTime = EpochToChartTime(sc, event.releaseEpoch - static_cast<long long>(beforeMinutes) * 60);
            rect.EndDateTime = EpochToChartTime(sc, event.releaseEpoch + static_cast<long long>(afterMinutes) * 60);
            rect.UseRelativeVerticalValues = 1;
            rect.BeginValue = 0.0f;
            rect.EndValue = 100.0f;
            rect.Color = shadeColor;
            rect.SecondaryColor = shadeColor;
            rect.TransparencyLevel = 80;
            rect.LineWidth = 1;
            rect.NoVerticalOutline = 1;
            rect.Region = 0;
            rect.DrawUnderneathMainGraph = 1;
            rect.AddAsUserDrawnDrawing = 0;
            sc.UseTool(rect);
        }
    }

    drawnMarkers = markersToDraw;
    drawnRects = rectsToDraw;
}

void UpdateStatusText(SCStudyInterfaceRef sc, StudyState& state, const std::string& text) {
    const int lineNumber = BaseLineNumber(sc) + 1;
    if (text.empty()) {
        if (!state.lastDrawnText.empty()) {
            sc.DeleteACSChartDrawing(sc.ChartNumber, TOOL_DELETE_CHARTDRAWING, lineNumber);
            state.lastDrawnText.clear();
        }
        return;
    }
    if (!sc.IsFullRecalculation && text == state.lastDrawnText)
        return;

    s_UseTool tool;
    tool.Clear();
    tool.ChartNumber = sc.ChartNumber;
    tool.DrawingType = DRAWING_TEXT;
    tool.LineNumber = lineNumber;
    tool.AddMethod = UTAM_ADD_OR_ADJUST;
    // Horizontal placement: an integer from 1 to 150 is a position across the
    // chart width; 149 sits at the right edge. Vertical: percent of region.
    tool.BeginDateTime = SCDateTime(149.0);
    tool.UseRelativeVerticalValues = 1;
    tool.BeginValue = 99.0f;
    tool.Color = sc.Subgraph[SG_COLOR_TOP_TIER].PrimaryColor;
    tool.FontSize = 9;
    tool.FontBold = 0;
    tool.MultiLineLabel = 1;
    tool.TextAlignment = DT_TOP | DT_RIGHT;
    tool.Region = 0;
    tool.AddAsUserDrawnDrawing = 0;
    tool.Text = text.c_str();
    sc.UseTool(tool);
    state.lastDrawnText = text;
}

std::string FormatMinutes(double minutes) {
    char buffer[32];
    if (minutes >= 1440.0)
        std::snprintf(buffer, sizeof(buffer), "%.1f d", minutes / 1440.0);
    else if (minutes >= 90.0)
        std::snprintf(buffer, sizeof(buffer), "%.1f h", minutes / 60.0);
    else
        std::snprintf(buffer, sizeof(buffer), "%d min", static_cast<int>(minutes + 0.5));
    return std::string(buffer);
}

std::string ChartClock(SCStudyInterfaceRef sc, long long epochSeconds) {
    SCDateTime chartTime = EpochToChartTime(sc, epochSeconds);
    SCString text = sc.DateTimeToString(chartTime.GetAsDouble(), FLAG_DT_HOUR | FLAG_DT_MINUTE);
    return std::string(text.GetChars());
}

} // namespace

SCSFExport scsf_FXMacroDataReleaseGuard(SCStudyInterfaceRef sc) {
    SCSubgraphRef Blackout = sc.Subgraph[SG_BLACKOUT];
    SCSubgraphRef MinutesToNext = sc.Subgraph[SG_MINUTES_TO_NEXT];
    SCSubgraphRef ColorTopTier = sc.Subgraph[SG_COLOR_TOP_TIER];
    SCSubgraphRef ColorOther = sc.Subgraph[SG_COLOR_OTHER];
    SCSubgraphRef ColorShading = sc.Subgraph[SG_COLOR_SHADING];

    if (sc.SetDefaults) {
        sc.GraphName = "FXMacroData Release Guard";
        sc.StudyDescription = "Marks scheduled macro releases from the FXMacroData calendar, shades a blackout "
                              "window around each one and exposes a Blackout subgraph for trading systems. "
                              "USD works without an API key; other currencies need one.";
        sc.AutoLoop = 0;
        sc.UpdateAlways = 1;
        sc.GraphRegion = 1;
        sc.ValueFormat = 1;
        sc.CalculationPrecedence = LOW_PREC_LEVEL;

        Blackout.Name = "Blackout";
        Blackout.DrawStyle = DRAWSTYLE_BAR;
        Blackout.PrimaryColor = RGB(220, 70, 70);
        Blackout.LineWidth = 2;
        Blackout.DrawZeros = 0;

        MinutesToNext.Name = "Minutes to next release";
        MinutesToNext.DrawStyle = DRAWSTYLE_IGNORE;
        MinutesToNext.PrimaryColor = RGB(120, 160, 255);
        MinutesToNext.DrawZeros = 0;

        ColorTopTier.Name = "Marker colour: top tier";
        ColorTopTier.DrawStyle = DRAWSTYLE_IGNORE;
        ColorTopTier.PrimaryColor = RGB(255, 140, 0);

        ColorOther.Name = "Marker colour: other";
        ColorOther.DrawStyle = DRAWSTYLE_IGNORE;
        ColorOther.PrimaryColor = RGB(160, 160, 160);

        ColorShading.Name = "Blackout shading colour";
        ColorShading.DrawStyle = DRAWSTYLE_IGNORE;
        ColorShading.PrimaryColor = RGB(255, 140, 0);

        sc.Input[IN_CURRENCIES].Name = "Currencies (comma separated)";
        sc.Input[IN_CURRENCIES].SetString("USD");
        sc.Input[IN_CURRENCIES].SetDescription("Currencies whose calendars to load. USD is free; others need an API key.");

        sc.Input[IN_API_KEY].Name = "FXMacroData API key";
        sc.Input[IN_API_KEY].SetString("");
        sc.Input[IN_API_KEY].SetDescription("Optional. Sent in the X-API-Key header, never in the URL or the log.");

        sc.Input[IN_MINUTES_BEFORE].Name = "Minutes before release";
        sc.Input[IN_MINUTES_BEFORE].SetInt(10);
        sc.Input[IN_MINUTES_BEFORE].SetIntLimits(0, 1440);

        sc.Input[IN_MINUTES_AFTER].Name = "Minutes after release";
        sc.Input[IN_MINUTES_AFTER].SetInt(10);
        sc.Input[IN_MINUTES_AFTER].SetIntLimits(0, 1440);

        sc.Input[IN_IMPORTANCE].Name = "Importance";
        sc.Input[IN_IMPORTANCE].SetCustomInputStrings("High;Medium;All");
        sc.Input[IN_IMPORTANCE].SetCustomInputIndex(0);
        sc.Input[IN_IMPORTANCE].SetDescription("High: market tier 1 or top tier for the currency. Medium: tier 1 or 2. All: every timed release.");

        sc.Input[IN_REFRESH_MINUTES].Name = "Refresh minutes";
        sc.Input[IN_REFRESH_MINUTES].SetInt(60);
        sc.Input[IN_REFRESH_MINUTES].SetIntLimits(5, 1440);

        sc.Input[IN_DRAW_MARKERS].Name = "Draw release markers";
        sc.Input[IN_DRAW_MARKERS].SetYesNo(1);

        sc.Input[IN_DRAW_SHADING].Name = "Draw blackout shading";
        sc.Input[IN_DRAW_SHADING].SetYesNo(1);

        sc.Input[IN_SHOW_STATUS_TEXT].Name = "Show next-release text";
        sc.Input[IN_SHOW_STATUS_TEXT].SetYesNo(1);

        sc.Input[IN_ALERT_MINUTES].Name = "Alert at T-minus minutes (0 = off)";
        sc.Input[IN_ALERT_MINUTES].SetInt(0);
        sc.Input[IN_ALERT_MINUTES].SetIntLimits(0, 1440);

        sc.Input[IN_ALERT_SOUND].Name = "Alert sound number";
        sc.Input[IN_ALERT_SOUND].SetInt(1);
        sc.Input[IN_ALERT_SOUND].SetIntLimits(0, 150);

        sc.Input[IN_USE_SYMBOL_CURRENCIES].Name = "Use chart symbol currencies";
        sc.Input[IN_USE_SYMBOL_CURRENCIES].SetYesNo(1);
        sc.Input[IN_USE_SYMBOL_CURRENCIES].SetDescription("Derive currencies from the chart symbol (EURUSD, ES, 6E, GC, CL, ...) and keep only those also listed in Currencies.");
        return;
    }

    // ----------------------------------------------------------------------
    // Persistent state.
    StudyState* state = static_cast<StudyState*>(sc.GetPersistentPointer(PK_STATE_POINTER));

    if (sc.LastCallToFunction) {
        if (state != nullptr) {
            delete state;
            sc.SetPersistentPointer(PK_STATE_POINTER, nullptr);
        }
        return;
    }

    int& requestState = sc.GetPersistentInt(PK_STATE);

    if (state == nullptr) {
        // First call, or the DLL was reloaded and the calendar is gone while
        // the persistent numbers survived. Start a fresh fetch straight away
        // and forget any request that was in flight.
        state = new StudyState();
        sc.SetPersistentPointer(PK_STATE_POINTER, state);
        sc.GetPersistentDouble(PK_LAST_REFRESH_EPOCH) = 0.0;
        requestState = STATE_IDLE;
    }
    int& currencyIndex = sc.GetPersistentInt(PK_CURRENCY_INDEX);
    int& failedRefreshes = sc.GetPersistentInt(PK_FAILED_REFRESHES);
    int& subgraphVersion = sc.GetPersistentInt(PK_CALENDAR_VERSION);
    int& haveLoadedOnce = sc.GetPersistentInt(PK_HAVE_LOADED_ONCE);
    double& lastRefreshEpoch = sc.GetPersistentDouble(PK_LAST_REFRESH_EPOCH);
    double& lastGoodEpoch = sc.GetPersistentDouble(PK_LAST_GOOD_EPOCH);
    double& lastAlertEpoch = sc.GetPersistentDouble(PK_LAST_ALERT_EPOCH);
    double& requestStartedEpoch = sc.GetPersistentDouble(PK_REQUEST_STARTED_EPOCH);

    const long long now = NowEpochUtc();
    const int beforeMinutes = sc.Input[IN_MINUTES_BEFORE].GetInt();
    const int afterMinutes = sc.Input[IN_MINUTES_AFTER].GetInt();
    const int importance = static_cast<int>(sc.Input[IN_IMPORTANCE].GetIndex());
    const int refreshMinutes = sc.Input[IN_REFRESH_MINUTES].GetInt();
    const char* apiKey = sc.Input[IN_API_KEY].GetString();
    const bool haveKey = apiKey != nullptr && apiKey[0] != '\0';

    std::string currencyNote;
    std::vector<std::string> wantedCurrencies = ResolveCurrencies(sc, haveKey, currencyNote);

    if (!haveKey && sc.GetPersistentInt(PK_STATUS_LOGGED) == 0) {
        sc.GetPersistentInt(PK_STATUS_LOGGED) = 1;
        if (currencyNote.find("USD only") != std::string::npos)
            Log(sc, "no API key configured, loading the USD calendar only.");
    }

    // A change to the currencies, the importance filter or the key means the
    // loaded calendar no longer matches the inputs: refresh on the next idle
    // call instead of waiting for the timer.
    {
        char signature[256];
        std::snprintf(signature, sizeof(signature), "%s|%d|%d", fxmd::JoinCurrencies(wantedCurrencies, ",").c_str(),
                      importance, haveKey ? 1 : 0);
        const std::string currentApiKey = apiKey != nullptr ? apiKey : "";
        if (state->fetchSignature != signature || state->fetchApiKey != currentApiKey) {
            if (!state->fetchSignature.empty())
                lastRefreshEpoch = 0.0;
            state->fetchSignature = signature;
            state->fetchApiKey = currentApiKey;
        }
    }

    // ----------------------------------------------------------------------
    // Request state machine. Only one HTTP request may be in flight per
    // chart, so currencies are fetched one after another.
    bool calendarChanged = false;

    if (requestState == STATE_WAITING) {
        const bool timedOut = requestStartedEpoch > 0.0 &&
                              static_cast<double>(now) - requestStartedEpoch > static_cast<double>(kRequestTimeoutSeconds);
        if (sc.HTTPResponse == "" && !timedOut) {
            // Still pending; fall through and keep displaying the last calendar.
        } else {
            std::string body = timedOut && sc.HTTPResponse == "" ? std::string("ERROR") : std::string(sc.HTTPResponse.GetChars());
            std::string currency = currencyIndex >= 0 && currencyIndex < static_cast<int>(state->currencies.size())
                                       ? state->currencies[static_cast<size_t>(currencyIndex)]
                                       : std::string("?");
            if (body == "ERROR" || body == "HTTP_REQUEST_ERROR") {
                state->cycleHadFailure = true;
                state->lastError = currency + (timedOut ? ": no response within the timeout" : ": request failed");
                Log(sc, state->lastError);
            } else {
                std::string error;
                size_t beforeCount = state->staging.size();
                if (!fxmd::ParseCalendarResponse(body, currency, importance, state->staging, error)) {
                    state->cycleHadFailure = true;
                    state->lastError = currency + ": " + error;
                    Log(sc, state->lastError);
                } else {
                    char counted[64];
                    std::snprintf(counted, sizeof(counted), "%s: %u timed release(s) loaded", currency.c_str(),
                                  static_cast<unsigned>(state->staging.size() - beforeCount));
                    Log(sc, counted);
                }
            }

            ++currencyIndex;
            if (currencyIndex < static_cast<int>(state->currencies.size())) {
                requestStartedEpoch = static_cast<double>(now);
                if (!IssueCalendarRequest(sc, state->currencies[static_cast<size_t>(currencyIndex)], apiKey, now)) {
                    state->cycleHadFailure = true;
                    state->lastError = state->currencies[static_cast<size_t>(currencyIndex)] + ": could not start the request";
                    Log(sc, state->lastError);
                    requestState = STATE_IDLE;
                }
            } else {
                requestState = STATE_IDLE;
            }

            if (requestState == STATE_IDLE) {
                // Cycle finished. Keep the last good calendar when anything
                // failed; otherwise adopt the staged one.
                if (state->cycleHadFailure) {
                    ++failedRefreshes;
                    if (!haveLoadedOnce && !state->staging.empty()) {
                        // Partial first load is better than nothing.
                        std::sort(state->staging.begin(), state->staging.end(), fxmd::EventBefore);
                        state->live = state->staging;
                        ++state->calendarVersion;
                        calendarChanged = true;
                    }
                } else {
                    std::sort(state->staging.begin(), state->staging.end(), fxmd::EventBefore);
                    state->live = state->staging;
                    ++state->calendarVersion;
                    calendarChanged = true;
                    failedRefreshes = 0;
                    haveLoadedOnce = 1;
                    lastGoodEpoch = static_cast<double>(now);
                    state->lastError.clear();
                    sc.GetPersistentInt(PK_STALE_LOGGED) = 0;
                }
                state->staging.clear();
            }
        }
    }

    if (requestState == STATE_IDLE) {
        const bool due = lastRefreshEpoch <= 0.0 ||
                         (static_cast<double>(now) - lastRefreshEpoch) >= static_cast<double>(refreshMinutes) * 60.0;
        if (due) {
            lastRefreshEpoch = static_cast<double>(now);
            state->currencies = wantedCurrencies;
            state->staging.clear();
            state->cycleHadFailure = false;
            currencyIndex = 0;
            if (state->currencies.empty()) {
                // Nothing to fetch. An empty calendar is the correct result.
                if (!state->live.empty()) {
                    state->live.clear();
                    ++state->calendarVersion;
                    calendarChanged = true;
                }
            } else if (IssueCalendarRequest(sc, state->currencies[0], apiKey, now)) {
                requestState = STATE_WAITING;
                requestStartedEpoch = static_cast<double>(now);
            } else {
                state->cycleHadFailure = true;
                state->lastError = state->currencies[0] + ": could not start the request";
                ++failedRefreshes;
                Log(sc, state->lastError);
            }
        }
    }

    // ----------------------------------------------------------------------
    // Subgraphs. Historical bars use bar times; the last bar uses the clock.
    const bool windowsChanged = sc.IsFullRecalculation || state->windowVersion != state->calendarVersion ||
                                state->windowBeforeMinutes != beforeMinutes ||
                                state->windowAfterMinutes != afterMinutes;
    if (windowsChanged)
        RebuildChartWindows(sc, *state, beforeMinutes, afterMinutes);

    const float nanValue = std::numeric_limits<float>::quiet_NaN();
    const bool fullPass = calendarChanged || windowsChanged || sc.IsFullRecalculation ||
                          subgraphVersion != state->calendarVersion;
    int startIndex = fullPass ? 0 : sc.UpdateStartIndex;
    if (startIndex < 0)
        startIndex = 0;
    if (!sc.IsFullRecalculation && startIndex < sc.UpdateStartIndex)
        sc.EarliestUpdateSubgraphDataArrayIndex = startIndex;

    const double oneMinuteDays = 1.0 / 1440.0;
    for (int index = startIndex; index < sc.ArraySize; ++index) {
        const double barStart = sc.BaseDateTimeIn[index].GetAsDouble();
        double barEnd;
        if (index + 1 < sc.ArraySize)
            barEnd = sc.BaseDateTimeIn[index + 1].GetAsDouble();
        else if (index > 0)
            barEnd = barStart + (barStart - sc.BaseDateTimeIn[index - 1].GetAsDouble());
        else
            barEnd = barStart + oneMinuteDays;
        if (barEnd <= barStart)
            barEnd = barStart + oneMinuteDays / 60.0;

        const bool blackout = BarTouchesWindow(*state, barStart, barEnd);
        const double minutes = BarMinutesToNextRelease(*state, barStart);
        Blackout[index] = blackout ? 1.0f : 0.0f;
        MinutesToNext[index] = std::isnan(minutes) ? nanValue : static_cast<float>(minutes);
    }
    subgraphVersion = state->calendarVersion;

    fxmd::LiveStatus live = fxmd::ComputeLiveStatus(state->live, now, beforeMinutes, afterMinutes);
    if (sc.ArraySize > 0) {
        const int last = sc.ArraySize - 1;
        Blackout[last] = live.inBlackout ? 1.0f : 0.0f;
        MinutesToNext[last] = live.nextIndex >= 0 ? static_cast<float>(live.minutesToNext) : nanValue;
    }

    // ----------------------------------------------------------------------
    // Drawings.
    if (fullPass)
        UpdateReleaseDrawings(sc, *state, beforeMinutes, afterMinutes);

    const bool stale = failedRefreshes >= 2;
    if (stale && sc.GetPersistentInt(PK_STALE_LOGGED) == 0) {
        sc.GetPersistentInt(PK_STALE_LOGGED) = 1;
        Log(sc, "two refreshes in a row failed; the calendar is stale. Last error: " + state->lastError);
    }

    if (sc.Input[IN_SHOW_STATUS_TEXT].GetYesNo()) {
        std::string text = "FXMacroData Release Guard\n";
        if (live.inBlackout && live.activeIndex >= 0) {
            const fxmd::CalendarEvent& active = state->live[static_cast<size_t>(live.activeIndex)];
            text += "BLACKOUT: " + fxmd::ShortLabel(active, 40) + "\n";
            text += "window ends in " + FormatMinutes(live.minutesToWindowEnd) + "\n";
        } else {
            text += "Status: clear\n";
        }
        if (live.nextIndex >= 0) {
            const fxmd::CalendarEvent& next = state->live[static_cast<size_t>(live.nextIndex)];
            text += "Next: " + fxmd::ShortLabel(next, 40) + "\n";
            text += fxmd::FormatUtcMinutes(next.releaseEpoch) + " / " + ChartClock(sc, next.releaseEpoch) +
                    " chart, in " + FormatMinutes(live.minutesToNext) + "\n";
        } else if (!state->live.empty()) {
            text += "No further releases in the loaded window\n";
        } else if (requestState == STATE_WAITING) {
            text += "Loading calendar...\n";
        } else {
            text += "No timed releases loaded\n";
        }
        {
            char summary[96];
            std::snprintf(summary, sizeof(summary), "%u release(s), %s", static_cast<unsigned>(state->live.size()),
                          wantedCurrencies.empty() ? "no currencies" : fxmd::JoinCurrencies(wantedCurrencies, " ").c_str());
            text += summary;
            if (lastGoodEpoch > 0.0)
                text += ", refreshed " + fxmd::FormatUtcClock(static_cast<long long>(lastGoodEpoch));
            text += "\n";
        }
        if (!currencyNote.empty())
            text += currencyNote + "\n";
        if (stale) {
            if (lastGoodEpoch > 0.0)
                text += "calendar stale since " + fxmd::FormatUtcMinutes(static_cast<long long>(lastGoodEpoch)) + "\n";
            else
                text += "calendar unavailable: " + state->lastError + "\n";
        }
        UpdateStatusText(sc, *state, text);
    } else {
        UpdateStatusText(sc, *state, std::string());
    }

    // ----------------------------------------------------------------------
    // Alert ahead of the next release.
    const int alertMinutes = sc.Input[IN_ALERT_MINUTES].GetInt();
    if (alertMinutes > 0 && live.nextIndex >= 0 && sc.ArraySize > 0) {
        const fxmd::CalendarEvent& next = state->live[static_cast<size_t>(live.nextIndex)];
        const double releaseEpoch = static_cast<double>(next.releaseEpoch);
        if (live.minutesToNext <= static_cast<double>(alertMinutes) && lastAlertEpoch != releaseEpoch) {
            lastAlertEpoch = releaseEpoch;
            SCString message;
            message.Format("FXMacroData: %s in %d min (%s)", fxmd::ShortLabel(next, 40).c_str(),
                           static_cast<int>(live.minutesToNext + 0.5), fxmd::FormatUtcClock(next.releaseEpoch).c_str());
            sc.AddAlertLine(message, 0);
            const int sound = sc.Input[IN_ALERT_SOUND].GetInt();
            if (sound > 0)
                sc.SetAlert(sound, sc.ArraySize - 1, message);
        }
    }
}
