// Profitabul Levels for Sierra Chart (ACSIL)
//
// Draws your Profitabul key levels (call wall, put wall, zero gamma, max gamma strike,
// key gamma level) as horizontal lines and refreshes them every minute.
//
// Install: copy this file to your Sierra Chart ACS_Source folder, then
// Analysis > Build Custom Studies DLL > Remote Build (or Build with Visual C++).
// Add "Profitabul Levels" to a chart and set the "API key" input to a key from
// Profitabul, Settings > Integrations (a read-only key is enough). Leave
// "Symbol" empty to use the chart's root symbol (ES, NQ, RTY, GC ...).
//
// Uses POST https://compute.profitabul.ai/v1/plugin/levels?symbol=<root>,
// which answers one "label,price" line per level.

#include "sierrachart.h"

SCDLLName("Profitabul Levels")

namespace
{
    const char* const kLabels[] = { "Call wall", "Put wall", "Zero gamma", "Max gamma strike", "Key gamma level" };
    const int kLevelCount = 5;

    SCString RootSymbol(SCStudyInterfaceRef sc, const SCString& overrideSymbol)
    {
        SCString symbol = overrideSymbol;
        if (symbol.GetLength() == 0)
        {
            // "NQZ26_FUT_CME" or "NQZ6" -> "NQ"
            const char* s = sc.Symbol.GetChars();
            char root[8] = { 0 };
            int n = 0;
            while (s[n] != 0 && n < 7 && s[n] >= 'A' && s[n] <= 'Z')
            {
                root[n] = s[n];
                ++n;
            }
            // Drop a trailing month code letter when the next character is a year digit.
            if (n >= 3 && s[n] >= '0' && s[n] <= '9')
                root[n - 1] = 0;
            symbol = root;
        }
        if (symbol == "MNQ") return "NQ";
        if (symbol == "MES") return "ES";
        if (symbol == "M2K") return "RTY";
        if (symbol == "MGC") return "GC";
        return symbol;
    }
}

SCSFExport scsf_ProfitabulLevels(SCStudyInterfaceRef sc)
{
    SCInputRef ApiKey = sc.Input[0];
    SCInputRef SymbolOverride = sc.Input[1];
    SCInputRef RefreshSeconds = sc.Input[2];

    if (sc.SetDefaults)
    {
        sc.GraphName = "Profitabul Levels";
        sc.StudyDescription = "Profitabul key levels: call wall, put wall, zero gamma, max gamma strike and key gamma level.";
        sc.GraphRegion = 0;
        sc.AutoLoop = 0;
        sc.UpdateAlways = 1;

        ApiKey.Name = "API key (Settings > Integrations)";
        ApiKey.SetString("");
        SymbolOverride.Name = "Symbol (empty = chart symbol)";
        SymbolOverride.SetString("");
        RefreshSeconds.Name = "Refresh (seconds)";
        RefreshSeconds.SetInt(60);
        RefreshSeconds.SetIntLimits(30, 3600);

        const COLORREF colors[kLevelCount] = { RGB(50, 205, 50), RGB(220, 20, 60), RGB(255, 215, 0), RGB(255, 215, 0), RGB(255, 215, 0) };
        for (int i = 0; i < kLevelCount; ++i)
        {
            sc.Subgraph[i].Name = kLabels[i];
            sc.Subgraph[i].DrawStyle = DRAWSTYLE_DASH;
            sc.Subgraph[i].PrimaryColor = colors[i];
            sc.Subgraph[i].LineWidth = 2;
            sc.Subgraph[i].DrawZeros = 0;
            sc.Subgraph[i].LineLabel = LL_DISPLAY_NAME | LL_DISPLAY_VALUE | LL_NAME_ALIGN_RIGHT | LL_VALUE_ALIGN_RIGHT;
        }
        return;
    }

    double& lastRequestTime = sc.GetPersistentDouble(1);
    int& requestPending = sc.GetPersistentInt(1);

    // A response arrived: parse "label,price" lines into the persistent levels.
    if (requestPending && sc.HTTPResponse.GetLength() > 0)
    {
        requestPending = 0;
        const char* body = sc.HTTPResponse.GetChars();
        for (int i = 0; i < kLevelCount; ++i)
            sc.GetPersistentFloat(100 + i) = 0.0f;
        const char* line = body;
        while (*line)
        {
            const char* end = line;
            while (*end && *end != '\n') ++end;
            if (*line != '#')
            {
                for (int i = 0; i < kLevelCount; ++i)
                {
                    size_t len = strlen(kLabels[i]);
                    if (strncmp(line, kLabels[i], len) == 0 && line[len] == ',')
                        sc.GetPersistentFloat(100 + i) = static_cast<float>(atof(line + len + 1));
                }
            }
            line = *end ? end + 1 : end;
        }
        sc.HTTPResponse = "";
    }

    // Time to refresh.
    const double now = sc.CurrentSystemDateTime.GetAsDouble();
    const double refreshDays = RefreshSeconds.GetInt() / 86400.0;
    if (!requestPending && ApiKey.GetString()[0] != 0 && now - lastRequestTime >= refreshDays)
    {
        SCString url;
        url.Format("https://compute.profitabul.ai/v1/plugin/levels?symbol=%s", RootSymbol(sc, SymbolOverride.GetString()).GetChars());
        SCString auth;
        auth.Format("Bearer %s", ApiKey.GetString());
        n_ACSIL::s_HTTPHeader headers[1];
        headers[0].Name = "Authorization";
        headers[0].Value = auth;
        if (sc.MakeHTTPPOSTRequest(url, "", headers, 1))
            requestPending = 1;
        lastRequestTime = now;
    }

    // Draw each level across the loaded bars.
    for (int i = 0; i < kLevelCount; ++i)
    {
        const float price = sc.GetPersistentFloat(100 + i);
        for (int bar = sc.UpdateStartIndex; bar < sc.ArraySize; ++bar)
            sc.Subgraph[i][bar] = price;
        if (sc.UpdateStartIndex > 0)
        {
            // Keep the whole line when a level changes.
            for (int bar = 0; bar < sc.UpdateStartIndex; ++bar)
                sc.Subgraph[i][bar] = price;
        }
    }
}
