//+------------------------------------------------------------------+
//|                                           Critter_MACD(crab).mq5 |
//|         Standalone MQL5 MACD Indicator — GG-Framework Pixel Crab |
//|    Converted from KenKaiii/gg-framework (AGPL-3.0-only) to MQL5. |
//|     Scuttles sideways along the bottom of the main MT5 chart and |
//|    speaks live MACD(4,10,5) values in a pixel-art speech bubble. |
//+------------------------------------------------------------------+
#property copyright "© c. 2026, Forex-Station"
#property version   "1.00"
#property description "Animated 18x18 pixel-art Crab MACD(4,10,5) indicator scuttling sideways along the bottom of the main chart. Speaks live MACD randomly & when clicked!"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   0

//--- MACD Indicator Inputs
input int                InpFastEma       = 4;           // Fast EMA Period
input int                InpSlowEma       = 10;          // Slow EMA Period
input int                InpSignalSma     = 5;           // Signal SMA Period
input ENUM_APPLIED_PRICE InpAppliedPrice  = PRICE_CLOSE; // Applied Price
input int                InpDecimals      = -1;          // Decimals (-1 = auto symbol _Digits)

//--- Speech & Appearance Inputs
input double             InpSpeakMinSec   = 4.5;         // Min seconds between random MACD speech
input double             InpSpeakMaxSec   = 10.0;        // Max seconds between random MACD speech
input double             InpSpeakDuration = 3.5;         // Speech bubble duration (sec)
input int                InpScale         = 2;           // Pixel scale (2 = 36x36 px Crab)
input int                InpBottomMargin  = 2;           // Distance above main chart bottom (px)
input int                InpSideMargin    = 8;           // Left/Right patrol margin (px)
input double             InpScuttleSpeed  = 38.0;        // Scuttle speed (px / sec, matches scuttle.speed)
input bool               InpShowShadow    = true;        // Show ground shadow beneath Crab
input bool               InpMixEmotes     = false;       // Occasionally show pixel icon emotes too
input bool               InpClickToSpook  = true;        // Click Crab to spook & speak live MACD
input bool               InpChartBack     = false;       // Draw behind candlesticks (false = front)

//--- Sprite & canvas geometry (art cells)
#define CRAB_CELLS      18
#define CANVAS_W_CELLS  114
#define CANVAS_H_CELLS  38
#define SCUTTLE_MS      110   // Fast sideways scuttle cadence (from critter-floor.ts scuttle.frameMs)
#define TIMER_MS        33    // ~30 FPS animation tick

//--- Emote IDs (used only when InpMixEmotes = true)
#define EMOTE_NONE  0
#define EMOTE_HEART 1
#define EMOTE_NOTE  2
#define EMOTE_STAR  3

//--- Indicator calculation buffers & MACD handle
double g_macdMainBuf[];
double g_macdSigBuf[];
int    g_macdHandle = INVALID_HANDLE;
double g_macdMain   = EMPTY_VALUE;
double g_macdSig    = EMPTY_VALUE;
bool   g_macdValid  = false;
int    g_lastSign   = 0;       // -1 = below zero, 0 = unset/zero, +1 = above zero

//--- Exact shaded palette from critter-sprites.ts ("crab") + critter-shade.ts (0xAARRGGBB)
const uint g_crabPalette[26] =
{
   0x00000000, 0xFFBC674A, 0xFFFEF9F0, 0xFF693733, 0xFF971D11, 0xFFFFFFFF,
   0xFFFFF1E6, 0xFF581418, 0xFFECA887, 0xFFC5230D, 0xFFF08162, 0xFF1B0A0A,
   0xFFFFC29E, 0xFFF04A3A, 0xFFEB8E67, 0xFFF22A0B, 0xFFD5856F, 0xFFB8282A,
   0xFFD25443, 0xFFA0261E, 0xFFFFB3A6, 0xFF5A1418, 0xFF671F1B, 0xFF41151D,
   0xFF83251C, 0xFFFFF6EB
};

//--- Frame 0: scuttle stance A, eyes open (18x18)
const uchar g_crabF0[324] =
{
    0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0,
    0, 4, 4, 4, 1, 2, 5, 6, 1, 1, 2, 5, 6, 1, 4, 4, 7, 0,
    4, 8, 9,10, 9, 6,11,12, 3, 3, 6,11,12, 9, 8, 9,10, 7,
    8, 8,10,13,13,14, 9, 3, 0, 0, 1, 9,14,10, 8, 8,13,13,
   13,13,13,15, 9, 9,15, 7, 0, 0, 4,15, 9, 9,10,13,13,15,
    7,13,15,15, 9, 9, 9, 9, 4, 4, 9, 9, 9, 9,13,15,15, 7,
    0, 7, 9, 9, 9, 8,10, 8, 8, 8, 8,13,13, 9, 9, 9, 7, 0,
    0, 0, 4,10, 8, 8,10, 8, 8,16,10,13,10,13,15, 7, 0, 0,
    0, 4, 8,10, 8,16, 8, 8,10,10,10,10,10,17,15,13, 7, 0,
    4, 8, 8, 8, 8, 8,10,18,10,10,10,18,13,13,13,13,13, 7,
    4,10,10,18,10,10,13,13,13,13,13,13,13,13,13,19,15, 7,
    4,13,13,20,20,13,13,13,21,21,13,13,15,20,20,15,15, 7,
    7,13,13,15,15,15,13,15,15,15,15,15,15,15,15,15,13, 7,
    0, 4,13,13,13,15,15,15,15,15,15,15,15,13,13,13, 7, 0,
    0,22, 9, 9, 9,13,13,13,13,13,13,13,13, 9, 9, 9,23, 0,
   22,17,24,19,24, 7, 7, 7, 7, 7, 7, 7, 7,24,19,24,17,23,
   23,17,23,19,23, 0, 0, 0, 0, 0, 0, 0, 0,23,19,23,17,23,
    0,23, 0,23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,23, 0,23, 0
};

//--- Frame 1: scuttle stance B, eyes open (18x18)
const uchar g_crabF1[324] =
{
    0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 2, 5, 6, 1, 1, 2, 5, 6, 3, 0, 0, 0, 0,
    0, 4, 4, 4,14, 6,11,12, 3, 3, 6,11,12,14, 4, 4, 7, 0,
    4, 8, 9,10, 9,14, 9, 3, 0, 0, 1, 9,14, 9, 8, 9,10, 7,
    8, 8,10,13,13, 9,15, 7, 0, 0, 4,15, 9,10,10, 8,13,13,
   13,13,13,15, 9, 9, 9, 9, 4, 4, 9, 9, 9, 9,13,13,13,15,
    7,13,15, 9, 9, 8,10, 8, 8, 8, 8,13,13, 9, 9,13,15, 7,
    0, 4, 9,10, 8, 8,10, 8, 8,16,10,13,10,13,15, 9, 7, 0,
    0, 4,10,10, 8,16, 8, 8,10,10,10,10,10,17,15,15, 7, 0,
    4, 8,10, 8, 8, 8,10,18,10,10,10,18,13,13,13,15,13, 7,
    4,10,10,18,10,10,13,13,13,13,13,13,13,13,13,19,15, 7,
    4,13,13,20,20,13,13,13,21,21,13,13,15,20,20,15,15, 7,
    7,13,13,15,15,15,13,15,15,15,15,15,15,15,15,15,13, 7,
    0, 7,13,13,13,15,15,15,15,15,15,15,15,13,13,13, 7, 0,
    0, 0, 4, 9, 9,13,13,13,13,13,13,13,13, 9, 9, 7, 0, 0,
    0,22,19,24,19, 9, 7, 7, 7, 7, 7, 7, 9,19,24,19,23, 0,
    0,23,19,23,19,23, 0, 0, 0, 0, 0, 0,23,19,23,19,23, 0,
    0, 0,23, 0,23, 0, 0, 0, 0, 0, 0, 0, 0,23, 0,23, 0, 0
};

//--- Blink Frame 0: scuttle stance A, eyes closed (18x18)
const uchar g_crabB0[324] =
{
    0, 0, 0, 0, 0, 1,25, 3, 0, 0, 1,25, 3, 0, 0, 0, 0, 0,
    0, 4, 4, 4, 1, 2, 6, 6, 1, 1, 2, 6, 6, 1, 4, 4, 7, 0,
    4, 8, 9,10, 9, 6,14, 6, 3, 3, 6,14, 6, 9, 8, 9,10, 7,
    8, 8,10,13,13,14, 9, 3, 0, 0, 1, 9,14,10, 8, 8,13,13,
   13,13,13,15, 9, 9,13, 7, 0, 0, 4,13, 9, 9,10,13,13,15,
    7,13,15,15, 9, 9, 9, 9, 4, 4, 9, 9, 9, 9,13,15,15, 7,
    0, 7, 9, 9, 9, 8,10, 8, 8, 8, 8,13,13, 9, 9, 9, 7, 0,
    0, 0, 4,10, 8, 8,10, 8, 8,16,10,13,10,13,15, 7, 0, 0,
    0, 4, 8,10, 8,16, 8, 8,10,10,10,10,10,17,15,13, 7, 0,
    4, 8, 8, 8, 8, 8,10,18,10,10,10,18,13,13,13,13,13, 7,
    4,10,10,18,10,10,13,13,13,13,13,13,13,13,13,19,15, 7,
    4,13,13,20,20,13,13,13,21,21,13,13,15,20,20,15,15, 7,
    7,13,13,15,15,15,13,15,15,15,15,15,15,15,15,15,13, 7,
    0, 4,13,13,13,15,15,15,15,15,15,15,15,13,13,13, 7, 0,
    0,22, 9, 9, 9,13,13,13,13,13,13,13,13, 9, 9, 9,23, 0,
   22,17,24,19,24, 7, 7, 7, 7, 7, 7, 7, 7,24,19,24,17,23,
   23,17,23,19,23, 0, 0, 0, 0, 0, 0, 0, 0,23,19,23,17,23,
    0,23, 0,23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,23, 0,23, 0
};

//--- Blink Frame 1: scuttle stance B, eyes closed (18x18)
const uchar g_crabB1[324] =
{
    0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 2, 5, 6, 1, 1, 2, 5, 6, 3, 0, 0, 0, 0,
    0, 4, 4, 4,14, 6,11,12, 3, 3, 6,11,12,14, 4, 4, 7, 0,
    4, 8, 9,10, 9,14, 9, 3, 0, 0, 1, 9,14, 9, 8, 9,10, 7,
    8, 8,10,13,13, 9,15, 7, 0, 0, 4,15, 9,10,10, 8,13,13,
   13,13,13,15, 9, 9, 9, 9, 4, 4, 9, 9, 9, 9,13,13,13,15,
    7,13,15, 9, 9, 8,10, 8, 8, 8, 8,13,13, 9, 9,13,15, 7,
    0, 4, 9,10, 8, 8,10, 8, 8,16,10,13,10,13,15, 9, 7, 0,
    0, 4,10,10, 8,16, 8, 8,10,10,10,10,10,17,15,15, 7, 0,
    4, 8,10, 8, 8, 8,10,18,10,10,10,18,13,13,13,15,13, 7,
    4,10,10,18,10,10,13,13,13,13,13,13,13,13,13,19,15, 7,
    4,13,13,20,20,13,13,13,21,21,13,13,15,20,20,15,15, 7,
    7,13,13,15,15,15,13,15,15,15,15,15,15,15,15,15,13, 7,
    0, 7,13,13,13,15,15,15,15,15,15,15,15,13,13,13, 7, 0,
    0, 0, 4, 9, 9,13,13,13,13,13,13,13,13, 9, 9, 7, 0, 0,
    0,22,19,24,19, 9, 7, 7, 7, 7, 7, 7, 9,19,24,19,23, 0,
    0,23,19,23,19,23, 0, 0, 0, 0, 0, 0,23,19,23,19,23, 0,
    0, 0,23, 0,23, 0, 0, 0, 0, 0, 0, 0, 0,23, 0,23, 0, 0
};

//--- Runtime canvas state
string g_objName = "";
string g_resName = "";
int    g_scale   = 2;
int    g_bmpW    = 228;
int    g_bmpH    = 76;
uint   g_buf[];

//--- Crab physics & AI state (scuttles sideways without flipping horizontally!)
double g_x            = 240.0;
double g_targetX      = 440.0;
double g_vx           = 0.0;
double g_stepAccMs    = 0.0;
int    g_scuttleFrame = 0;

//--- Blink state
bool   g_blinking     = false;
double g_blinkTimer   = 3.0;

//--- Idle / Patrol state
bool   g_idling       = false;
double g_stateTimer   = 3.0;

//--- Spook / Jump state
double g_spookTimer   = 0.0;
double g_jumpOffset   = 0.0;
double g_jumpVel      = 0.0;

//--- Speech bubble state (single-line "MACD(4,10,5)=..." readout or optional emote)
string g_speechText   = "";
uint   g_speechColor  = 0xFF1E0C1F;
int    g_emote        = EMOTE_NONE;
double g_bubbleTimer  = 0.0;
double g_nextSpeak    = 1.2;

//--- Timing & cached screen bounds
ulong  g_lastTickMs   = 0;
int    g_lastDrawX    = -9999;
int    g_lastDrawY    = -9999;
double g_pollAcc      = 0.0;

//+------------------------------------------------------------------+
//| Helper: random double in [lo, hi]                                |
//+------------------------------------------------------------------+
double RandRange(const double lo, const double hi)
{
   double a = MathMin(lo, hi);
   double b = MathMax(lo, hi);
   return a + ((double)MathRand() / 32767.0) * (b - a);
}

//+------------------------------------------------------------------+
//| Read latest live MACD main & signal values from bar 0            |
//+------------------------------------------------------------------+
bool RefreshMacdValue()
{
   if(g_macdHandle == INVALID_HANDLE)
      return false;

   double mTmp[1], sTmp[1];
   bool okM = (CopyBuffer(g_macdHandle, MAIN_LINE,   0, 1, mTmp) == 1 && MathIsValidNumber(mTmp[0]) && mTmp[0] != EMPTY_VALUE);
   bool okS = (CopyBuffer(g_macdHandle, SIGNAL_LINE, 0, 1, sTmp) == 1 && MathIsValidNumber(sTmp[0]) && sTmp[0] != EMPTY_VALUE);

   if(okM)
   {
      g_macdMain  = mTmp[0];
      g_macdSig   = okS ? sTmp[0] : 0.0;
      g_macdValid = true;
      return true;
   }
   return g_macdValid;
}

//+------------------------------------------------------------------+
//| Color for MACD reading (positive green, negative red, zero ink)  |
//+------------------------------------------------------------------+
uint MacdTextColor(const double val)
{
   if(val > 0.0) return 0xFF1B7F42;
   if(val < 0.0) return 0xFFC82834;
   return 0xFF1E0C1F;
}

//+------------------------------------------------------------------+
//| Format "MACD(4,10,5)=0.00042"                                    |
//+------------------------------------------------------------------+
string FormatMacdSpeech(const bool exclaimed)
{
   int f = MathMax(1, InpFastEma);
   int s = MathMax(1, InpSlowEma);
   int g = MathMax(1, InpSignalSma);
   int digits = (InpDecimals >= 0) ? MathMin(8, InpDecimals) : MathMax(0, MathMin(6, _Digits));
   if(g_macdValid)
      return StringFormat("MACD(%d,%d,%d)=%s%s", f, s, g, DoubleToString(g_macdMain, digits), exclaimed ? "!" : "");
   return StringFormat("MACD(%d,%d,%d)=--", f, s, g);
}

//+------------------------------------------------------------------+
//| Trigger a live single-line "MACD(4,10,5)=..." speech bubble      |
//+------------------------------------------------------------------+
void SpeakMacd(const bool exclaimed = false)
{
   RefreshMacdValue();
   g_emote       = EMOTE_NONE;
   g_speechText  = FormatMacdSpeech(exclaimed);
   g_speechColor = g_macdValid ? MacdTextColor(g_macdMain) : 0xFF1E0C1F;
   ObjectSetString(0, g_objName, OBJPROP_TOOLTIP, StringFormat("Crab %s (click to poke)", g_speechText));
   g_bubbleTimer = MathMax(1.0, InpSpeakDuration);
}

//+------------------------------------------------------------------+
//| Helper: draw one scaled art pixel (with alpha compositing)       |
//+------------------------------------------------------------------+
void PutArtPixel(const int ax, const int ay, const uint argb)
{
   uint a = (argb >> 24) & 0xFF;
   if(a == 0)
      return;
   if(ax < 0 || ax >= CANVAS_W_CELLS || ay < 0 || ay >= CANVAS_H_CELLS)
      return;

   int px0 = ax * g_scale;
   int py0 = ay * g_scale;

   for(int dy = 0; dy < g_scale; dy++)
   {
      int rowOff = (py0 + dy) * g_bmpW + px0;
      for(int dx = 0; dx < g_scale; dx++)
      {
         if(a == 255)
         {
            g_buf[rowOff + dx] = argb;
         }
         else
         {
            uint dst = g_buf[rowOff + dx];
            uint da  = (dst >> 24) & 0xFF;
            if(da == 0)
            {
               g_buf[rowOff + dx] = argb;
            }
            else
            {
               uint sr = (argb >> 16) & 0xFF;
               uint sg = (argb >> 8)  & 0xFF;
               uint sb =  argb        & 0xFF;
               uint dr = (dst >> 16)  & 0xFF;
               uint dg = (dst >> 8)   & 0xFF;
               uint db =  dst         & 0xFF;
               uint invA = 255 - a;
               uint outA = a + ((da * invA) / 255);
               if(outA > 255) outA = 255;
               uint outR = (sr * a + dr * invA) / 255;
               uint outG = (sg * a + dg * invA) / 255;
               uint outB = (sb * a + db * invA) / 255;
               g_buf[rowOff + dx] = (outA << 24) | (outR << 16) | (outG << 8) | outB;
            }
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Crisp 7-row pixel font for MACD speech bubbles ("MACD(...)=...") |
//+------------------------------------------------------------------+
void GetPixelGlyph(const ushort ch, string &rows[])
{
   ArrayResize(rows, 7);
   switch(ch)
   {
      case 'M':
         rows[0]="#...#"; rows[1]="##.##"; rows[2]="#.#.#"; rows[3]="#...#";
         rows[4]="#...#"; rows[5]="#...#"; rows[6]="#...#"; break;
      case 'A':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="#..#"; rows[3]="####";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]="#..#"; break;
      case 'C':
         rows[0]=".###"; rows[1]="#..."; rows[2]="#..."; rows[3]="#...";
         rows[4]="#..."; rows[5]="#..."; rows[6]=".###"; break;
      case 'D':
         rows[0]="###."; rows[1]="#..#"; rows[2]="#..#"; rows[3]="#..#";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]="###."; break;
      case '(':
         rows[0]="..#";  rows[1]=".#.";  rows[2]="#..";  rows[3]="#..";
         rows[4]="#..";  rows[5]=".#.";  rows[6]="..#";  break;
      case ')':
         rows[0]="#..";  rows[1]=".#.";  rows[2]="..#";  rows[3]="..#";
         rows[4]="..#";  rows[5]=".#.";  rows[6]="#..";  break;
      case ',':
         rows[0]="..";   rows[1]="..";   rows[2]="..";   rows[3]="..";
         rows[4]="..";   rows[5]=".#";   rows[6]="#.";   break;
      case '=':
         rows[0]="...."; rows[1]="...."; rows[2]="####"; rows[3]="....";
         rows[4]="####"; rows[5]="...."; rows[6]="...."; break;
      case '.':
         rows[0]="..";   rows[1]="..";   rows[2]="..";   rows[3]="..";
         rows[4]="..";   rows[5]="##";   rows[6]="##";   break;
      case '-':
         rows[0]="...."; rows[1]="...."; rows[2]="...."; rows[3]="####";
         rows[4]="...."; rows[5]="...."; rows[6]="...."; break;
      case '!':
         rows[0]="##";   rows[1]="##";   rows[2]="##";   rows[3]="##";
         rows[4]="..";   rows[5]="##";   rows[6]="##";   break;
      case '0':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="#..#"; rows[3]="#..#";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]=".##."; break;
      case '1':
         rows[0]=".#.";  rows[1]="##.";  rows[2]=".#.";  rows[3]=".#.";
         rows[4]=".#.";  rows[5]=".#.";  rows[6]="###";  break;
      case '2':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="...#"; rows[3]="..#.";
         rows[4]=".#.."; rows[5]="#..."; rows[6]="####"; break;
      case '3':
         rows[0]="###."; rows[1]="...#"; rows[2]="...#"; rows[3]=".##.";
         rows[4]="...#"; rows[5]="...#"; rows[6]="###."; break;
      case '4':
         rows[0]="#..#"; rows[1]="#..#"; rows[2]="#..#"; rows[3]="####";
         rows[4]="...#"; rows[5]="...#"; rows[6]="...#"; break;
      case '5':
         rows[0]="####"; rows[1]="#..."; rows[2]="###."; rows[3]="...#";
         rows[4]="...#"; rows[5]="#..#"; rows[6]=".##."; break;
      case '6':
         rows[0]=".##."; rows[1]="#..."; rows[2]="###."; rows[3]="#..#";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]=".##."; break;
      case '7':
         rows[0]="####"; rows[1]="...#"; rows[2]="..#."; rows[3]="..#.";
         rows[4]=".#.."; rows[5]=".#.."; rows[6]=".#.."; break;
      case '8':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="#..#"; rows[3]=".##.";
         rows[4]="#..#"; rows[5]="#..#"; rows[6]=".##."; break;
      case '9':
         rows[0]=".##."; rows[1]="#..#"; rows[2]="#..#"; rows[3]=".###";
         rows[4]="...#"; rows[5]="..#."; rows[6]="##.."; break;
      case ' ':
      default:
         rows[0]="...";  rows[1]="...";  rows[2]="...";  rows[3]="...";
         rows[4]="...";  rows[5]="...";  rows[6]="...";  break;
   }
}

//+------------------------------------------------------------------+
//| Measure pixel text width in art cells                            |
//+------------------------------------------------------------------+
int MeasurePixelText(const string text)
{
   int n = StringLen(text);
   if(n <= 0) return 0;
   int total = 0;
   string rows[];
   for(int i = 0; i < n; i++)
   {
      GetPixelGlyph(StringGetCharacter(text, i), rows);
      total += StringLen(rows[0]);
      if(i < n - 1) total += 1;
   }
   return total;
}

//+------------------------------------------------------------------+
//| Draw a single line of crisp pixel text at (x0, y0)               |
//+------------------------------------------------------------------+
void DrawPixelText(const int x0, const int y0, const string text, const uint col)
{
   int curX = x0;
   int n    = StringLen(text);
   string rows[];
   for(int i = 0; i < n; i++)
   {
      GetPixelGlyph(StringGetCharacter(text, i), rows);
      int gw = StringLen(rows[0]);
      for(int y = 0; y < 7; y++)
      {
         for(int x = 0; x < gw; x++)
         {
            if(StringGetCharacter(rows[y], x) == '#')
               PutArtPixel(curX + x, y0 + y, col);
         }
      }
      curX += gw + 1;
   }
}

//+------------------------------------------------------------------+
//| Draw shared chamfered pixel-art paper bubble shell & tail        |
//+------------------------------------------------------------------+
void DrawBubbleShell(const int bx, const int by, const int bw, const int bh)
{
   const uint INK   = 0xFF1E0C1F;
   const uint PAPER = 0xFFF4F8FC;
   const uint SHADE = 0xFFD2DDEA;

   for(int y = 0; y < bh; y++)
   {
      for(int x = 0; x < bw; x++)
      {
         bool corner = ((x == 0 || x == bw - 1) && (y == 0 || y == bh - 1));
         if(corner)
            continue;
         bool border = (x == 0 || x == bw - 1 || y == 0 || y == bh - 1);
         if(border)
            PutArtPixel(bx + x, by + y, INK);
         else if(y == bh - 2)
            PutArtPixel(bx + x, by + y, SHADE);
         else
            PutArtPixel(bx + x, by + y, PAPER);
      }
   }

   // Stepped pixel tail centered over the Crab
   int tx = CANVAS_W_CELLS / 2;
   int ty = by + bh - 1;
   PutArtPixel(tx - 1, ty,     SHADE);
   PutArtPixel(tx,     ty,     SHADE);
   PutArtPixel(tx - 2, ty + 1, INK);
   PutArtPixel(tx - 1, ty + 1, SHADE);
   PutArtPixel(tx,     ty + 1, INK);
   PutArtPixel(tx - 1, ty + 2, INK);
}

//+------------------------------------------------------------------+
//| Draw single-line "MACD(4,10,5)=..." speech bubble above Crab     |
//+------------------------------------------------------------------+
void DrawMacdBubble(const int crabTopY, const string text, const uint valueColor)
{
   int tw = MeasurePixelText(text);
   if(tw <= 0) return;

   int bw = MathMin(CANVAS_W_CELLS, tw + 6);
   int bh = 7 + 5; // 12 cells: border + pad + 7px font + shade + border
   int bx = (CANVAS_W_CELLS - bw) / 2;
   int by = crabTopY - bh - 2;
   if(by < 0) by = 0;

   DrawBubbleShell(bx, by, bw, bh);
   DrawPixelText(bx + (bw - tw) / 2, by + 2, text, valueColor);
}

//+------------------------------------------------------------------+
//| Draw optional pixel icon emote bubble above the Crab             |
//+------------------------------------------------------------------+
void DrawEmoteBubble(const int crabTopY, const int emote)
{
   if(emote == EMOTE_NONE)
      return;

   string glyph[];
   uint glyphCol = 0xFF1E0C1F;

   switch(emote)
   {
      case EMOTE_HEART:
         ArrayResize(glyph, 5);
         glyph[0] = ".#.#."; glyph[1] = "#####"; glyph[2] = "#####";
         glyph[3] = ".###."; glyph[4] = "..#..";
         glyphCol = 0xFFE0364F;
         break;
      case EMOTE_NOTE:
         ArrayResize(glyph, 5);
         glyph[0] = "..###"; glyph[1] = "..#.#"; glyph[2] = "..#..";
         glyph[3] = "###.."; glyph[4] = "###..";
         glyphCol = 0xFF6A3FC0;
         break;
      case EMOTE_STAR:
         ArrayResize(glyph, 5);
         glyph[0] = "..#.."; glyph[1] = "#####"; glyph[2] = ".###.";
         glyph[3] = ".#.#."; glyph[4] = "#...#";
         glyphCol = 0xFFC98A10;
         break;
      default:
         return;
   }

   int gh = ArraySize(glyph);
   int gw = StringLen(glyph[0]);
   int bw = gw + 6;
   int bh = gh + 5;
   int bx = (CANVAS_W_CELLS - bw) / 2;
   int by = crabTopY - bh - 2;
   if(by < 0) by = 0;

   DrawBubbleShell(bx, by, bw, bh);

   int gx0 = bx + 3;
   int gy0 = by + 2;
   for(int y = 0; y < gh; y++)
   {
      for(int x = 0; x < gw; x++)
      {
         if(StringGetCharacter(glyph[y], x) == '#')
            PutArtPixel(gx0 + x, gy0 + y, glyphCol);
      }
   }
}

//+------------------------------------------------------------------+
//| Draw ground shadow directly under the Crab                       |
//+------------------------------------------------------------------+
void DrawShadow(const double liftCells)
{
   if(!InpShowShadow)
      return;

   int halfW = (liftCells > 3.0) ? 4 : ((liftCells > 1.0) ? 6 : 7);
   int cx    = CANVAS_W_CELLS / 2;
   int sy    = CANVAS_H_CELLS - 2;

   for(int x = cx - halfW; x < cx + halfW; x++)
   {
      bool edge = (x == cx - halfW || x == cx + halfW - 1);
      PutArtPixel(x, sy,     edge ? 0x44140A18 : 0x88140A18);
      if(!edge)
         PutArtPixel(x, sy + 1, 0x55140A18);
   }
}

//+------------------------------------------------------------------+
//| Draw the 18x18 shaded Crab sprite (never flips horizontally!)    |
//+------------------------------------------------------------------+
void DrawCrab(const int ox, const int oy)
{
   for(int y = 0; y < CRAB_CELLS; y++)
   {
      int rowBase = y * CRAB_CELLS;
      for(int x = 0; x < CRAB_CELLS; x++)
      {
         uchar idx = 0;
         if(g_blinking)
            idx = (g_scuttleFrame == 0) ? g_crabB0[rowBase + x] : g_crabB1[rowBase + x];
         else
            idx = (g_scuttleFrame == 0) ? g_crabF0[rowBase + x] : g_crabF1[rowBase + x];

         if(idx != 0)
            PutArtPixel(ox + x, oy + y, g_crabPalette[idx]);
      }
   }
}

//+------------------------------------------------------------------+
//| Trigger click-to-spook hop + instant live MACD speech            |
//+------------------------------------------------------------------+
void SpookCrab()
{
   g_spookTimer = 1.6;
   g_idling     = false;
   g_jumpVel    = 40.0;
   SpeakMacd(true);

   int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0);
   int minX   = MathMax(0, InpSideMargin);
   int maxX   = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);

   double dist = RandRange(110.0, 240.0);
   if(g_x > (minX + maxX) * 0.5)
      g_targetX = MathMax((double)minX, g_x - dist);
   else
      g_targetX = MathMin((double)maxX, g_x + dist);
}

//+------------------------------------------------------------------+
//| Pick a new patrol destination along the bottom of the main chart |
//+------------------------------------------------------------------+
void PickNextTarget(const int chartW)
{
   int minX = MathMax(0, InpSideMargin);
   int maxX = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);
   double candidate = RandRange((double)minX, (double)maxX);
   if(MathAbs(candidate - g_x) < 60.0)
      candidate = (g_x > (minX + maxX) * 0.5) ? (double)minX + 16.0 : (double)maxX - 16.0;
   g_targetX = MathMax((double)minX, MathMin((double)maxX, candidate));
}

//+------------------------------------------------------------------+
//| Render current frame to the dynamic MT5 resource                 |
//+------------------------------------------------------------------+
void RenderFrame(const int chartW, const int chartH)
{
   ArrayInitialize(g_buf, 0x00000000);

   // Scuttles sideways right along the bottom floor (1px crisp scuttle bounce + spook jump)
   bool scuttling = (!g_idling && MathAbs(g_vx) > 2.0);
   double liftCells = (scuttling && g_scuttleFrame == 1 ? 1.0 : 0.0) + g_jumpOffset;
   if(liftCells > 6.0) liftCells = 6.0;

   int crabOx  = (CANVAS_W_CELLS - CRAB_CELLS) / 2;
   int groundY = CANVAS_H_CELLS - 1;
   int crabOy  = groundY - CRAB_CELLS - (int)MathRound(liftCells);
   if(crabOy < 0) crabOy = 0;

   DrawShadow(liftCells);
   DrawCrab(crabOx, crabOy);

   if(g_bubbleTimer > 0.0)
   {
      if(g_speechText != "")
         DrawMacdBubble(crabOy, g_speechText, g_speechColor);
      else if(g_emote != EMOTE_NONE)
         DrawEmoteBubble(crabOy, g_emote);
   }

   if(ResourceCreate(g_resName, g_buf, g_bmpW, g_bmpH, 0, 0, g_bmpW, COLOR_FORMAT_ARGB_NORMALIZE))
   {
      int drawX = (int)MathRound(g_x);
      int drawY = MathMax(0, chartH - MathMax(0, InpBottomMargin) - g_bmpH);

      if(drawX != g_lastDrawX)
      {
         ObjectSetInteger(0, g_objName, OBJPROP_XDISTANCE, drawX);
         g_lastDrawX = drawX;
      }
      if(drawY != g_lastDrawY)
      {
         ObjectSetInteger(0, g_objName, OBJPROP_YDISTANCE, drawY);
         g_lastDrawY = drawY;
      }
      ChartRedraw(0);
   }
}

//+------------------------------------------------------------------+
//| Custom indicator initialization                                  |
//+------------------------------------------------------------------+
int OnInit()
{
   MathSrand((uint)(GetTickCount64() ^ (ulong)ChartID() ^ 0xC4AB4105));

   int f = MathMax(1, InpFastEma);
   int s = MathMax(1, InpSlowEma);
   int g = MathMax(1, InpSignalSma);

   SetIndexBuffer(0, g_macdMainBuf, INDICATOR_CALCULATIONS);
   SetIndexBuffer(1, g_macdSigBuf,  INDICATOR_CALCULATIONS);
   IndicatorSetString(INDICATOR_SHORTNAME, StringFormat("CrabMACD(%d,%d,%d)", f, s, g));
   IndicatorSetInteger(INDICATOR_DIGITS, (InpDecimals >= 0) ? MathMin(8, InpDecimals) : _Digits);

   g_macdHandle = iMACD(_Symbol, _Period, f, s, g, InpAppliedPrice);
   if(g_macdHandle == INVALID_HANDLE)
   {
      Print("CrabMACDCritter: iMACD failed, err=", GetLastError());
      return INIT_FAILED;
   }

   g_scale = MathMax(1, MathMin(5, InpScale));
   g_bmpW  = CANVAS_W_CELLS * g_scale;
   g_bmpH  = CANVAS_H_CELLS * g_scale;
   ArrayResize(g_buf, g_bmpW * g_bmpH);
   ArrayInitialize(g_buf, 0x00000000);

   string uid = IntegerToString((long)ChartID()) + "_" + IntegerToString((long)(GetTickCount64() % 100000));
   g_objName  = "CrabMACD_" + uid;
   g_resName  = "::" + g_objName;

   int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0);
   int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
   if(chartW < 100) chartW = 800;
   if(chartH < 100) chartH = 400;

   int minX = MathMax(0, InpSideMargin);
   int maxX = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);
   g_x = RandRange((double)minX, (double)maxX);
   PickNextTarget(chartW);
   g_lastTickMs = GetTickCount64();

   RefreshMacdValue();

   if(!ResourceCreate(g_resName, g_buf, g_bmpW, g_bmpH, 0, 0, g_bmpW, COLOR_FORMAT_ARGB_NORMALIZE))
   {
      Print("CrabMACDCritter: ResourceCreate failed, err=", GetLastError());
      IndicatorRelease(g_macdHandle);
      g_macdHandle = INVALID_HANDLE;
      return INIT_FAILED;
   }

   if(!ObjectCreate(0, g_objName, OBJ_BITMAP_LABEL, 0, 0, 0))
   {
      Print("CrabMACDCritter: ObjectCreate failed, err=", GetLastError());
      ResourceFree(g_resName);
      IndicatorRelease(g_macdHandle);
      g_macdHandle = INVALID_HANDLE;
      return INIT_FAILED;
   }

   ObjectSetInteger(0, g_objName, OBJPROP_CORNER,     CORNER_LEFT_UPPER);
   ObjectSetInteger(0, g_objName, OBJPROP_ANCHOR,     ANCHOR_LEFT_UPPER);
   ObjectSetInteger(0, g_objName, OBJPROP_XDISTANCE,  (int)MathRound(g_x));
   ObjectSetInteger(0, g_objName, OBJPROP_YDISTANCE,  MathMax(0, chartH - MathMax(0, InpBottomMargin) - g_bmpH));
   ObjectSetInteger(0, g_objName, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, g_objName, OBJPROP_SELECTED,   false);
   ObjectSetInteger(0, g_objName, OBJPROP_HIDDEN,     true);
   ObjectSetInteger(0, g_objName, OBJPROP_BACK,       InpChartBack);
   ObjectSetInteger(0, g_objName, OBJPROP_ZORDER,     106);
   ObjectSetString(0,  g_objName, OBJPROP_TOOLTIP,    StringFormat("Crab MACD(%d,%d,%d) — click to poke!", f, s, g));
   ObjectSetString(0,  g_objName, OBJPROP_BMPFILE,    g_resName);

   RenderFrame(chartW, chartH);
   EventSetMillisecondTimer(TIMER_MS);
   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Custom indicator deinitialization                                |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   EventKillTimer();
   if(g_objName != "")
      ObjectDelete(0, g_objName);
   if(g_resName != "")
      ResourceFree(g_resName);
   if(g_macdHandle != INVALID_HANDLE)
   {
      IndicatorRelease(g_macdHandle);
      g_macdHandle = INVALID_HANDLE;
   }
   ChartRedraw(0);
}

//+------------------------------------------------------------------+
//| Indicator calculation: populate MACD buffers & zero-cross alert  |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   int minBars = MathMax(InpFastEma, InpSlowEma) + MathMax(1, InpSignalSma);
   if(g_macdHandle == INVALID_HANDLE || rates_total <= minBars)
      return 0;

   int toCopy = (prev_calculated <= 0 || prev_calculated > rates_total)
                ? rates_total
                : (rates_total - prev_calculated + 1);
   if(toCopy > rates_total) toCopy = rates_total;

   if(CopyBuffer(g_macdHandle, MAIN_LINE,   0, toCopy, g_macdMainBuf) <= 0) return prev_calculated;
   if(CopyBuffer(g_macdHandle, SIGNAL_LINE, 0, toCopy, g_macdSigBuf)  <= 0) return prev_calculated;

   if(RefreshMacdValue())
   {
      int sgn = (g_macdMain > 0.0) ? 1 : ((g_macdMain < 0.0) ? -1 : 0);
      if(g_lastSign != 0 && sgn != 0 && sgn != g_lastSign)
         SpeakMacd(true);
      if(sgn != 0)
         g_lastSign = sgn;
   }

   return rates_total;
}

//+------------------------------------------------------------------+
//| Animation, MACD speech & scuttle AI tick (~30 FPS, runs 24/7)    |
//+------------------------------------------------------------------+
void OnTimer()
{
   ulong nowMs = GetTickCount64();
   double dtMs = (double)(nowMs - g_lastTickMs);
   g_lastTickMs = nowMs;
   if(dtMs < 1.0)   dtMs = TIMER_MS;
   if(dtMs > 120.0) dtMs = 120.0;
   double dt = dtMs * 0.001;

   int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0);
   int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
   if(chartW < 80 || chartH < 80)
      return;

   // Poll live MACD every 0.5s so visible speech stays current
   g_pollAcc += dt;
   if(g_pollAcc >= 0.5)
   {
      g_pollAcc = 0.0;
      RefreshMacdValue();
      if(g_bubbleTimer > 0.0 && g_speechText != "" && g_macdValid)
      {
         bool bang = (StringFind(g_speechText, "!") >= 0);
         g_speechText  = FormatMacdSpeech(bang);
         g_speechColor = MacdTextColor(g_macdMain);
      }
   }

   // 1. Spook jump arc
   if(g_jumpOffset > 0.0 || g_jumpVel > 0.0)
   {
      g_jumpOffset += g_jumpVel * dt;
      g_jumpVel    -= 210.0 * dt;
      if(g_jumpOffset <= 0.0)
      {
         g_jumpOffset = 0.0;
         g_jumpVel    = 0.0;
      }
   }
   if(g_spookTimer > 0.0)
      g_spookTimer = MathMax(0.0, g_spookTimer - dt);

   // 2. Blinking timer
   g_blinkTimer -= dt;
   if(g_blinkTimer <= 0.0)
   {
      if(!g_blinking)
      {
         g_blinking   = true;
         g_blinkTimer = 0.14;
      }
      else
      {
         g_blinking   = false;
         g_blinkTimer = RandRange(2.5, 6.0);
      }
   }

   // 3. Random MACD speech timer
   if(g_bubbleTimer > 0.0)
   {
      g_bubbleTimer -= dt;
      if(g_bubbleTimer <= 0.0)
      {
         g_speechText = "";
         g_emote      = EMOTE_NONE;
      }
   }
   else if(g_spookTimer <= 0.0)
   {
      g_nextSpeak -= dt;
      if(g_nextSpeak <= 0.0)
      {
         if(InpMixEmotes && (MathRand() % 4) == 0)
         {
            int picks[3] = { EMOTE_HEART, EMOTE_NOTE, EMOTE_STAR };
            g_speechText  = "";
            g_emote       = picks[MathRand() % 3];
            g_bubbleTimer = 2.0;
         }
         else
         {
            SpeakMacd(false);
         }
         g_nextSpeak = RandRange(MathMax(1.0, InpSpeakMinSec), MathMax(2.0, InpSpeakMaxSec));
      }
   }

   // 4. Sideways scuttle patrol & idle state machine along the bottom of the main chart
   int minX = MathMax(0, InpSideMargin);
   int maxX = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);
   if(g_x < minX) g_x = minX;
   if(g_x > maxX) g_x = maxX;

   if(g_idling)
   {
      g_vx *= MathMax(0.0, 1.0 - dt * 10.0);
      g_x  += g_vx * dt;
      g_scuttleFrame = 0;
      g_stepAccMs    = 0.0;
      g_stateTimer  -= dt;
      if(g_stateTimer <= 0.0)
      {
         g_idling = false;
         PickNextTarget(chartW);
      }
   }
   else
   {
      double dx    = g_targetX - g_x;
      double dist  = MathAbs(dx);
      double speed = MathMax(10.0, InpScuttleSpeed) * ((g_spookTimer > 0.0) ? 2.4 : 1.0);

      if(dist <= 4.0)
      {
         g_vx = 0.0;
         g_scuttleFrame = 0;
         if(g_spookTimer > 0.0)
         {
            PickNextTarget(chartW);
         }
         else
         {
            g_idling     = true;
            g_stateTimer = RandRange(1.5, 4.2);
         }
      }
      else
      {
         double dir      = (dx > 0.0) ? 1.0 : -1.0;
         double desiredV = dir * speed * MathMin(1.0, dist / 24.0 + 0.35);
         g_vx += (desiredV - g_vx) * MathMin(1.0, dt * 8.0);
         g_x  += g_vx * dt;

         double stepMs = (g_spookTimer > 0.0) ? (SCUTTLE_MS * 0.55) : (double)SCUTTLE_MS;
         g_stepAccMs += dtMs;
         if(g_stepAccMs >= stepMs)
         {
            g_stepAccMs    = MathMod(g_stepAccMs, stepMs);
            g_scuttleFrame = 1 - g_scuttleFrame;
         }
      }
   }

   g_x = MathMax((double)minX, MathMin((double)maxX, g_x));
   RenderFrame(chartW, chartH);
}

//+------------------------------------------------------------------+
//| Chart events: click to spook/speak MACD & chart resize           |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
   if(id == CHARTEVENT_OBJECT_CLICK && InpClickToSpook && sparam == g_objName)
   {
      SpookCrab();
      return;
   }

   if(id == CHARTEVENT_CLICK && InpClickToSpook)
   {
      int mx = (int)lparam;
      int my = (int)dparam;
      int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
      int bx = (int)MathRound(g_x);
      int by = MathMax(0, chartH - MathMax(0, InpBottomMargin) - g_bmpH);
      if(mx >= bx && mx <= bx + g_bmpW && my >= by && my <= by + g_bmpH)
         SpookCrab();
      return;
   }

   if(id == CHARTEVENT_CHART_CHANGE)
   {
      int chartW = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS, 0);
      int chartH = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
      if(chartW >= 80 && chartH >= 80)
      {
         int minX = MathMax(0, InpSideMargin);
         int maxX = MathMax(minX + 10, chartW - g_bmpW - InpSideMargin);
         g_x       = MathMax((double)minX, MathMin((double)maxX, g_x));
         g_targetX = MathMax((double)minX, MathMin((double)maxX, g_targetX));
         RenderFrame(chartW, chartH);
      }
   }
}
//+------------------------------------------------------------------+
