//+------------------------------------------------------------------+
//| VSA MTF Vertical Histogram - Corpo + Pavios (3 Cores)           |
//| Baseado no VSA Full Overlay Wicks                              |
//| Histograma único com 3 cores: Superior=Pavio INF (invertido),  |
//| Meio=Corpo, Inferior=Pavio SUP (invertido)                    |
//| Com números fixos nas posições indicadas                      |
//| VERSÃO MULTI-INSTÂNCIA                                       |
//+------------------------------------------------------------------+
#property copyright "Rafael Viana Moreira Estrela  (Jovem Praga)"
#property indicator_chart_window
#property indicator_buffers 0
#property strict

 
// --- INPUTS ---
extern ENUM_TIMEFRAMES MTF_Period = PERIOD_CURRENT;
extern int HistoryBars = 200;
extern double MultiplicadorManual = 1.0;

extern int AlturaLinhas = 7;
extern int ComprimentoMaximo = 30;

// --- INPUTS PARA POSICIONAMENTO DO HISTOGRAMA ---
extern int MoverHistogramaHorizontal = 130;    // ←   - move o histograma para esquerda/direita
extern int MoverHistogramaVertical = -67;      // ←   - move o histograma para cima/baixo
extern int MoverHistogramaVertical2 = 250;     // ←   - ajuste extra vertical

extern bool Enable_MTF = false;
extern ENUM_TIMEFRAMES MTF_Period_Histo = PERIOD_D1;

extern color CorFundo = clrBlack;

// --- NOVO INPUT PARA IDENTIFICADOR ÚNICO ---
extern int InstanceID = 1;  // Cada instância deve ter um ID diferente (1, 2, 3...)

// ============================================================
// NOVO INPUT PARA COLORIR CORPO EM RED QUANDO COBRIR OS PAVIOS
// ============================================================
extern bool ColorBodyRedWhenFull = true;  // true = ativado, false = desativado

 

 

// --- VARIÁVEIS GLOBAIS ---
string indicatorName = "VSA_3Colors_Histo_";
double MultiplicadorAtivo;

int X_DISTANCE = 70;
int Y_DISTANCE = 200;
int currentWidth = 0;
int currentHeight = 0;

int lastAlturaTotal = -1;

// Posições FIXAS dos números (espaçadas igualmente)
int NUM_X_OFFSET = -25;
int NUM_Y_SUP = 0;
int NUM_Y_MEIO = 0;
int NUM_Y_INF = 0;

// ✅ TABELA DE 49 CORES (mesma do VSA Full Overlay Wicks)
color ColorTable[49] = {
   clrMediumAquamarine, clrOrchid, clrGreen, clrDodgerBlue, clrLavender,
   clrLime, clrYellow, clrOrange, clrGreenYellow, clrGray,
   clrGold, clrRed, clrAqua, clrPaleGreen, clrGray,
   clrFireBrick, clrDeepPink, clrPink, clrOlive, clrTomato,
   clrSpringGreen, clrIndigo, clrDarkGreen, clrDarkTurquoise, clrPaleGreen,
   clrPeru, clrSaddleBrown, clrSeashell, clrTomato, clrAqua,
   clrCadetBlue, clrDeepPink, clrHotPink, clrOrangeRed, clrGreenYellow,
   clrTan, clrAquamarine, C'0,155,78', C'94,0,94', C'0,73,147',
   C'255,255,85', C'0,73,147', C'0,64,64', C'128,128,255',
   C'64,0,128', C'128,128,64', C'128,64,64', C'255,255,66',
   clrLime
};

// ============================================================
// VARIÁVEIS ADICIONAIS (NÃO DUPLICAR AS QUE JÁ EXISTEM)
// ============================================================
// Variáveis para MAX e MIN acumulados
int acumuladoMaxIndex = -1;
int acumuladoMinIndex = 999;
bool acumuladoIsBearish = false;
datetime lastCandleTime = 0;

// Cores dos textos comp e venda
color CorTextoComp = clrAqua;
color CorTextoVenda = clrAqua;

//+------------------------------------------------------------------+
//| FUNÇÕES AUXILIARES DE COR                                        |
//+------------------------------------------------------------------+
int GetRed(color c) { return c & 0xFF; }
int GetGreen(color c) { return (c >> 8) & 0xFF; }
int GetBlue(color c) { return (c >> 16) & 0xFF; }
color RGB(int r, int g, int b) { return ((b & 0xFF) << 16) | ((g & 0xFF) << 8) | (r & 0xFF); }

color MixColor(color c1, color c2, double factor)
{
   int r = (int)(GetRed(c1)*(1-factor) + GetRed(c2)*factor);
   int g = (int)(GetGreen(c1)*(1-factor) + GetGreen(c2)*factor);
   int b = (int)(GetBlue(c1)*(1-factor) + GetBlue(c2)*factor);
   return RGB(r,g,b);
}

//+------------------------------------------------------------------+
//| FUNÇÃO PARA OBTER NÚMERO DA COR                                  |
//+------------------------------------------------------------------+
int GetColorNumberFromValue(double value)
{
   if(value < 6000) return 0;
   else if(value < 8000) return 1;
   else if(value < 10000) return 2;
   else if(value < 12000) return 3;
   else if(value < 14000) return 4;
   else if(value < 16000) return 5;
   else if(value < 18000) return 6;
   else if(value < 20000) return 7;
   else if(value < 22000) return 8;
   else if(value < 24000) return 9;
   else if(value < 26000) return 10;
   else if(value < 28000) return 11;
   else if(value < 30000) return 12;
   else if(value < 32000) return 13;
   else if(value < 34000) return 14;
   else if(value < 36000) return 15;
   else if(value < 38000) return 16;
   else if(value < 40000) return 17;
   else if(value < 50000) return 18;
   else if(value < 60000) return 19;
   else if(value < 70000) return 20;
   else if(value < 80000) return 21;
   else if(value < 90000) return 22;
   else if(value < 100000) return 23;
   else if(value < 110000) return 24;
   else if(value < 120000) return 25;
   else if(value < 130000) return 26;
   else if(value < 140000) return 27;
   else if(value < 150000) return 28;
   else if(value < 160000) return 29;
   else if(value < 170000) return 30;
   else if(value < 180000) return 31;
   else if(value < 190000) return 32;
   else if(value < 200000) return 33;
   else if(value < 210000) return 34;
   else if(value < 220000) return 35;
   else if(value < 230000) return 36;
   else if(value < 240000) return 37;
   else if(value < 250000) return 38;
   else if(value < 260000) return 39;
   else if(value < 270000) return 40;
   else if(value < 280000) return 41;
   else if(value < 290000) return 42;
   else if(value < 300000) return 43;
   else if(value < 310000) return 44;
   else if(value < 320000) return 45;
   else if(value < 330000) return 46;
   else if(value < 340000) return 47;
   else return 48;
}

//+------------------------------------------------------------------+
//| CALCULAR CORES DO CANDLE ATUAL                                  |
//+------------------------------------------------------------------+
void CalculateCandleColors(double &bodyPts, double &upperPts, double &lowerPts, 
                           int &bodyIndex, int &upperIndex, int &lowerIndex, 
                           bool &isBearish)
{
   ENUM_TIMEFRAMES tf;
   if(Enable_MTF) tf = MTF_Period_Histo;
   else tf = MTF_Period;
   
   double open = iOpen(NULL, tf, 0);
   double close = iClose(NULL, tf, 0);
   double high = iHigh(NULL, tf, 0);
   double low = iLow(NULL, tf, 0);
   
   isBearish = !(close > open);
   
   double bodySize = MathAbs(close - open);
   double upperWick = high - MathMax(open, close);
   double lowerWick = MathMin(open, close) - low;
   
   bodyPts = (bodySize / _Point) * MultiplicadorAtivo;
   upperPts = (upperWick / _Point) * MultiplicadorAtivo;
   lowerPts = (lowerWick / _Point) * MultiplicadorAtivo;
   
   bodyIndex = GetColorNumberFromValue(bodyPts);
   upperIndex = GetColorNumberFromValue(upperPts);
   lowerIndex = GetColorNumberFromValue(lowerPts);
}

//+------------------------------------------------------------------+
//| CALCULAR PONTOS REAIS PARA SINAIS                               |
//+------------------------------------------------------------------+
void CalculateRealPoints(double &bodyPts, double &upperPts, double &lowerPts, bool &isBearish)
{
   double open, close, high, low;
   ENUM_TIMEFRAMES tf;
   
   if(Enable_MTF) tf = MTF_Period_Histo;
   else tf = MTF_Period;
   
   open = iOpen(NULL, tf, 0);
   close = iClose(NULL, tf, 0);
   high = iHigh(NULL, tf, 0);
   low = iLow(NULL, tf, 0);
   
   isBearish = !(close > open);
   
   double bodySize = MathAbs(close - open);
   double upperWick = high - MathMax(open, close);
   double lowerWick = MathMin(open, close) - low;
   
   bodyPts = (bodySize / _Point) * MultiplicadorAtivo;
   upperPts = (upperWick / _Point) * MultiplicadorAtivo;
   lowerPts = (lowerWick / _Point) * MultiplicadorAtivo;
}
//+------------------------------------------------------------------+
//| ATUALIZA ACUMULADOR DE CORES MÁXIMA E MÍNIMA                    |
//+------------------------------------------------------------------+
void UpdateAccumulatedColors(int bodyIndex, int upperIndex, int lowerIndex, bool isBearish)
{
   ENUM_TIMEFRAMES tf;
   if(Enable_MTF) tf = MTF_Period_Histo;
   else tf = MTF_Period;
   
   datetime currentCandleTime = iTime(NULL, tf, 0);
    
   if(currentCandleTime != lastCandleTime) {
      acumuladoMaxIndex = -1;
      acumuladoMinIndex = -1;
      lastCandleTime = currentCandleTime;
      acumuladoIsBearish = isBearish;
   }
   
   int currentMax = MathMax(bodyIndex, MathMax(upperIndex, lowerIndex));
   int currentMin = MathMin(bodyIndex, MathMin(upperIndex, lowerIndex));
   
   if(!isBearish) {
      if(acumuladoMaxIndex == -1) acumuladoMaxIndex = currentMax;
      else if(currentMax > acumuladoMaxIndex) acumuladoMaxIndex = currentMax;
   }
   
   if(isBearish) {
      if(acumuladoMinIndex == -1) acumuladoMinIndex = bodyIndex;
      else if(bodyIndex > acumuladoMinIndex) acumuladoMinIndex = bodyIndex;
   }
   
   acumuladoIsBearish = isBearish;
}
//+------------------------------------------------------------------+
//| FUNÇÃO PARA OBTER COR COM REGRA ESPECIAL                         |
//+------------------------------------------------------------------+
color GetColorWithSpecialRule(int index, bool isBearish)
{
   if(isBearish && index == 0) return clrSlateBlue;
   if(index >= 0 && index < 49) return ColorTable[index];
   return clrWhite;
}

//+------------------------------------------------------------------+
//| CALCULAR VOLUME VSA                                              |
//+------------------------------------------------------------------+
void CalculateVSAVolume(int shift, double &buyVol, double &sellVol)
{
   ENUM_TIMEFRAMES tf;
   if(Enable_MTF) tf = MTF_Period_Histo;
   else tf = MTF_Period;
   
   double h = iHigh(NULL, tf, shift);
   double l = iLow(NULL, tf, shift);
   double c = iClose(NULL, tf, shift);
   double o = iOpen(NULL, tf, shift);

   double buyers = 0, sellers = 0;
   if(c > o) { 
      buyers = (c - o) * 10000; 
      sellers = (h - c) * 5000; 
   }
   else if(c < o) { 
      sellers = (o - c) * 10000; 
      buyers = (c - l) * 5000; 
   }
   else { 
      buyers = (h - c) * 3000; 
      sellers = (c - l) * 3000; 
   }

   buyVol = MathMax(buyers, 10) / 2000.0;
   sellVol = MathMax(sellers, 10) / 2000.0;
   
   buyVol *= MultiplicadorAtivo;
   sellVol *= MultiplicadorAtivo;
}

//+------------------------------------------------------------------+
//| CALCULA POSIÇÕES ADAPTATIVAS                                     |
//+------------------------------------------------------------------+
void CalculateAdaptivePositions()
{
   int chartWidth = (int)ChartGetInteger(0, CHART_WIDTH_IN_PIXELS);
   int chartHeight = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS);
   
   // Adiciona deslocamento baseado no InstanceID para permitir múltiplas instâncias
   int instanceOffset = (InstanceID - 1) * 200; // 200 pixels de deslocamento horizontal
   
   if(chartWidth != currentWidth || chartHeight != currentHeight) {
      currentWidth = chartWidth;
      currentHeight = chartHeight;
      
            int baseX = chartWidth - ComprimentoMaximo - 80 + instanceOffset;
      X_DISTANCE = baseX + MoverHistogramaHorizontal;  // Move para DIREITA (+) ou ESQUERDA (-)
      X_DISTANCE = MathMax(10 + instanceOffset, MathMin(chartWidth - ComprimentoMaximo - 20, X_DISTANCE));
      
      Y_DISTANCE = (int)(chartHeight * 0.30) + MoverHistogramaVertical + MoverHistogramaVertical2;  // Move para BAIXO (+) ou CIMA (-)
      Y_DISTANCE = MathMax(50, MathMin(chartHeight - 150, Y_DISTANCE));
      
      // ============================================================
      // POSIÇÕES FIXAS DOS NÚMEROS (espaçadas igualmente)
      // ============================================================
      int espacamento = 18;  // Espaçamento fixo entre os números
      int centro = Y_DISTANCE - 30;  // Centro do histograma
      
      NUM_Y_SUP = centro - espacamento;      // Superior
      NUM_Y_MEIO = centro;                   // Meio
      NUM_Y_INF = centro + espacamento;      // Inferior
      
      lastAlturaTotal = -1;
   }
}

//+------------------------------------------------------------------+
//| CRIA OU ATUALIZA UMA LINHA DO HISTOGRAMA                         |
//+------------------------------------------------------------------+
void UpdateHistoLine(string name, int x, int y, color clr, int size)
{
   if(ObjectFind(0, name) == -1) {
      ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
   }
   ObjectSetText(name, "—", size, "Arial", clr);
   ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
}

//+------------------------------------------------------------------+
//| CRIA OU ATUALIZA UM TEXTO (NÚMERO DA COR) - POSIÇÃO FIXA       |
//+------------------------------------------------------------------+
void UpdateNumberText(string name, int x, int y, string text, color clr, int size)
{
   if(ObjectFind(0, name) == -1) {
      ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
   }
   ObjectSetText(name, text, size, "DS-Digital Bold", clr);
   ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
}

//+------------------------------------------------------------------+
//| DESENHA HISTOGRAMA VERTICAL COM 3 CORES                         |
//| SUPERIOR = Pavio INFERIOR (INVERTIDO)                          |
//| MEIO = Corpo - CRESCE PARA BAIXO EM VENDA, PARA CIMA EM COMPRA |
//| INFERIOR = Pavio SUPERIOR (INVERTIDO)                         |
//| COM NÚMEROS FIXOS AO LADO                                     |
//+------------------------------------------------------------------+
void DrawVerticalHistogram(double buyVol, double sellVol, 
                           int bodyIndex, int upperIndex, int lowerIndex, 
                           bool isBearish)
{
   int spacing = 2;
   int Y_base = Y_DISTANCE;
   
   // Volume total para altura do histograma
   double totalVol = buyVol + sellVol;
   if(totalVol <= 0) totalVol = 1.0;
   
   int alturaMaxima = ComprimentoMaximo;
   int alturaTotal = MathMax(3, MathMin((int)((totalVol / totalVol) * alturaMaxima), alturaMaxima));
   
 
   // ============================================================
   // CALCULA ALTURA DE CADA SEÇÃO (proporcional ao tamanho real)
   // ============================================================
   double bodyPts, upperPts, lowerPts;
   int tempBodyIdx, tempUpperIdx, tempLowerIdx;
   bool tempBearish;
   CalculateCandleColors(bodyPts, upperPts, lowerPts, tempBodyIdx, tempUpperIdx, tempLowerIdx, tempBearish);
   
   double totalPts = bodyPts + upperPts + lowerPts;
   if(totalPts <= 0) totalPts = 1.0;
   
   // Calcula altura de cada seção baseada nas proporções reais
   int alturaSuperior = (int)((upperPts / totalPts) * alturaTotal);
   int alturaMeio = (int)((bodyPts / totalPts) * alturaTotal);
   int alturaInferior = (int)((lowerPts / totalPts) * alturaTotal);
   
   // Garante que cada seção tenha pelo menos 1 linha APENAS se o valor for > 0
   if(alturaSuperior <= 0 && upperPts > 0) alturaSuperior = 1;
   if(alturaMeio <= 0 && bodyPts > 0) alturaMeio = 1;
   if(alturaInferior <= 0 && lowerPts > 0) alturaInferior = 1;
   // ============================================================
   // DETERMINA CORES (DEPOIS do cálculo das alturas)
   // ============================================================
color bodyColor = ColorTable[bodyIndex];
color upperWickColor = ColorTable[lowerIndex];
color lowerWickColor = ColorTable[upperIndex];

// ============================================================
// ÍNDICE 0 — VENDA
// ============================================================
if(isBearish && bodyIndex == 0)
{
   bodyColor = clrSlateBlue;

   // Só substitui o pavio se ELE também estiver no índice 0
   if(lowerIndex == 0)
      upperWickColor = clrDarkViolet;

   if(upperIndex == 0)
      lowerWickColor = clrDarkViolet;
}

// ============================================================
// ÍNDICE 0 — COMPRA
// ============================================================
if(!isBearish && bodyIndex == 0)
{
   bodyColor = clrMediumAquamarine;

   // Só substitui o pavio se ELE também estiver no índice 0
   if(lowerIndex == 0)
      upperWickColor = clrPaleGreen;

   if(upperIndex == 0)
      lowerWickColor = clrPaleGreen;
}

// ============================================================
// REGRA 3: RED somente enquanto NÃO existir nenhuma linha
// visível de um dos pavios.
//
// COMPRA:
//   sem pavio = RED
//   apareceu 1 pontinha = MediumAquamarine
//
// VENDA:
//   sem pavio = RED
//   apareceu 1 pontinha = SlateBlue
// ============================================================
if(ColorBodyRedWhenFull)
{
   if(upperPts <= 0 || lowerPts <= 0)
   {
      bodyColor = clrRed;
   }
   else
   {
      if(isBearish && bodyIndex == 0)
         bodyColor = clrSlateBlue;
      else if(!isBearish && bodyIndex == 0)
         bodyColor = clrMediumAquamarine;
      else
         bodyColor = ColorTable[bodyIndex];
   }
}
   // Ajusta para caber exatamente no alturaTotal
   int soma = alturaSuperior + alturaMeio + alturaInferior;
   if(soma < alturaTotal && soma > 0) {
      int diff = alturaTotal - soma;
      if(alturaSuperior > 0 && upperPts > 0) 
         alturaSuperior += (int)(diff * (upperPts / totalPts));
      if(alturaMeio > 0 && bodyPts > 0) 
         alturaMeio += (int)(diff * (bodyPts / totalPts));
      if(alturaInferior > 0 && lowerPts > 0) 
         alturaInferior += (int)(diff * (lowerPts / totalPts));
      
      soma = alturaSuperior + alturaMeio + alturaInferior;
      if(soma < alturaTotal && alturaInferior > 0) alturaInferior += (alturaTotal - soma);
      if(soma < alturaTotal && alturaMeio > 0) alturaMeio += (alturaTotal - soma);
      if(soma < alturaTotal && alturaSuperior > 0) alturaSuperior += (alturaTotal - soma);
   } else if(soma > alturaTotal) {
      double fator = (double)alturaTotal / soma;
      if(alturaSuperior > 0) alturaSuperior = MathMax(1, (int)(alturaSuperior * fator));
      if(alturaMeio > 0) alturaMeio = MathMax(1, (int)(alturaMeio * fator));
      if(alturaInferior > 0) alturaInferior = MathMax(1, (int)(alturaInferior * fator));
      
      soma = alturaSuperior + alturaMeio + alturaInferior;
      if(soma > alturaTotal && alturaInferior > 1) alturaInferior--;
      if(soma > alturaTotal && alturaMeio > 1) alturaMeio--;
      if(soma > alturaTotal && alturaSuperior > 1) alturaSuperior--;
   }
   
   // ============================================================
   // INVERTE OS PAVIOS: 
   // - O que era PAVIO SUPERIOR (alturaSuperior) vai para BAIXO
   // - O que era PAVIO INFERIOR (alturaInferior) vai para CIMA
   // ============================================================
   int alturaPavioTopo = alturaInferior;     // Pavio INFERIOR vai para o TOPO
   int alturaPavioBase = alturaSuperior;     // Pavio SUPERIOR vai para a BASE
   
   // ============================================================
   // DESENHA AS 3 SEÇÕES DO HISTOGRAMA
   // ============================================================
   int linhaAtual = 0;
   
   // Limpa objetos antigos
   int maxLinhas = MathMax(alturaTotal, lastAlturaTotal);
   for(int i = 0; i < maxLinhas + 10; i++) {
      string name = indicatorName + "HISTO_" + IntegerToString(InstanceID) + "_" + IntegerToString(i);
      ObjectDelete(name);
   }
   
   // ============================================================
   // SEÇÃO SUPERIOR - PAVIO INFERIOR (AGORA NO TOPO)
   // Usa a cor upperWickColor (que já é a cor do pavio inferior)
   // ============================================================
   if(alturaPavioTopo > 0 && lowerPts > 0) {
      for(int i = 0; i < alturaPavioTopo; i++) {
         string name = indicatorName + "HISTO_" + IntegerToString(InstanceID) + "_" + IntegerToString(linhaAtual);
         int yPos = Y_base - (linhaAtual * spacing) - spacing;
         double factor = (alturaPavioTopo > 1) ? 1.0 - ((double)i / (double)(alturaPavioTopo - 1)) : 0.0;
         color corLinha = MixColor(upperWickColor, CorFundo, factor * 0.5);
         UpdateHistoLine(name, X_DISTANCE, yPos, corLinha, AlturaLinhas);
         linhaAtual++;
      }
   }
   
   // ============================================================
   // SEÇÃO MEIO - CORPO (mantido)
   // ============================================================
   if(alturaMeio > 0 && bodyPts > 0) {
      for(int i = 0; i < alturaMeio; i++) {
         string name = indicatorName + "HISTO_" + IntegerToString(InstanceID) + "_" + IntegerToString(linhaAtual);
         int yPos = Y_base - (linhaAtual * spacing) - spacing;
         double factor = (alturaMeio > 1) ? 1.0 - ((double)i / (double)(alturaMeio - 1)) : 0.0;
         color corLinha = MixColor(bodyColor, CorFundo, factor * 0.5);
         UpdateHistoLine(name, X_DISTANCE, yPos, corLinha, AlturaLinhas);
         linhaAtual++;
      }
   }
   
   // ============================================================
   // SEÇÃO INFERIOR - PAVIO SUPERIOR (AGORA NA BASE)
   // Usa a cor lowerWickColor (que já é a cor do pavio superior)
   // ============================================================
   if(alturaPavioBase > 0 && upperPts > 0) {
      for(int i = 0; i < alturaPavioBase; i++) {
         string name = indicatorName + "HISTO_" + IntegerToString(InstanceID) + "_" + IntegerToString(linhaAtual);
         int yPos = Y_base - (linhaAtual * spacing) - spacing;
         double factor = (alturaPavioBase > 1) ? 1.0 - ((double)i / (double)(alturaPavioBase - 1)) : 0.0;
         color corLinha = MixColor(lowerWickColor, CorFundo, factor * 0.5);
         UpdateHistoLine(name, X_DISTANCE, yPos, corLinha, AlturaLinhas);
         linhaAtual++;
      }
   }
   
   // Remove linhas excedentes
   for(int i = linhaAtual; i < maxLinhas; i++) {
      string name = indicatorName + "HISTO_" + IntegerToString(InstanceID) + "_" + IntegerToString(i);
      ObjectDelete(name);
   }
   
   // ============================================================
   // NÚMEROS FIXOS AO LADO DO HISTOGRAMA (NUNCA SE MOVEM)
   // ============================================================
   // Número SUPERIOR - upperIndex (cor do pavio SUPERIOR) - MANTIDO
   string numSupName = indicatorName + "NUM_SUP_" + IntegerToString(InstanceID);
   UpdateNumberText(numSupName, X_DISTANCE + NUM_X_OFFSET, NUM_Y_SUP, 
                    IntegerToString(upperIndex), ColorTable[upperIndex], 14);
   
    // Número MEIO - bodyIndex (cor do corpo) - MANTIDO
   string numMeioName = indicatorName + "NUM_MEIO_" + IntegerToString(InstanceID);
   color numBodyColor = bodyColor;
   // Se o corpo está RED, o número também fica RED
   if(ColorBodyRedWhenFull && bodyColor == clrRed) numBodyColor = clrRed;
   UpdateNumberText(numMeioName, X_DISTANCE + NUM_X_OFFSET, NUM_Y_MEIO, 
                    IntegerToString(bodyIndex), numBodyColor, 14);
   
   // Número INFERIOR - lowerIndex (cor do pavio INFERIOR) - MANTIDO
   string numInfName = indicatorName + "NUM_INF_" + IntegerToString(InstanceID);
   UpdateNumberText(numInfName, X_DISTANCE + NUM_X_OFFSET, NUM_Y_INF, 
                    IntegerToString(lowerIndex), ColorTable[lowerIndex], 14);
   
   // ============================================================
// MAX - agora na posição do MIN (NUM_Y_SUP)
// ============================================================
string maxStr;
color maxCor;
if(acumuladoMaxIndex == -1) {
   maxStr = "---";
   maxCor = clrGray;
} else {
   maxStr = IntegerToString(acumuladoMaxIndex);
   maxCor = GetColorWithSpecialRule(acumuladoMaxIndex, acumuladoIsBearish);
}

string maxName = indicatorName + "MAX_" + IntegerToString(InstanceID);
UpdateNumberText(maxName, X_DISTANCE + NUM_X_OFFSET + 45, NUM_Y_SUP-13,   // ← AGORA EM NUM_Y_SUP
                 "MAX:" + maxStr, maxCor, 19);

// ============================================================
// MIN - agora na posição do MAX (NUM_Y_INF)
// ============================================================
string minStr;
color minCor;
if(acumuladoMinIndex == -1) {
   minStr = "---";
   minCor = clrGray;
} else {
   minStr = IntegerToString(acumuladoMinIndex);
   minCor = GetColorWithSpecialRule(acumuladoMinIndex, acumuladoIsBearish);
}

string minName = indicatorName + "MIN_" + IntegerToString(InstanceID);
UpdateNumberText(minName, X_DISTANCE + NUM_X_OFFSET + 45, NUM_Y_INF,   // ← AGORA EM NUM_Y_INF
                 "MIN:" + minStr, minCor, 19);
   
   // ============================================================
   // TEXTOS "comp" e "venda" - do lado direito, no meio (abaixo do MIN e acima do MAX)
   // ============================================================
   double bodyPtsSig, upperPtsSig, lowerPtsSig;
   bool isBearishSig;
   CalculateRealPoints(bodyPtsSig, upperPtsSig, lowerPtsSig, isBearishSig);
   
   // Posição Y no meio entre NUM_SUP e NUM_INF
   int yMeio = (NUM_Y_SUP + NUM_Y_INF) / 2-4;
   
   // "comp" - fica no meio
   if(isBearishSig && (lowerPtsSig > bodyPtsSig)) {
      string compName = indicatorName + "COMP_" + IntegerToString(InstanceID);
      UpdateNumberText(compName, X_DISTANCE + NUM_X_OFFSET + 38, yMeio, 
                       "comp", CorTextoComp, 14);
      // Deleta "venda" se existir
      ObjectDelete(indicatorName + "VENDA_" + IntegerToString(InstanceID));
   }
   // "venda" - fica no meio (usando else if)
   else if(!isBearishSig && (upperPtsSig > bodyPtsSig)) {
      string vendaName = indicatorName + "VENDA_" + IntegerToString(InstanceID);
      UpdateNumberText(vendaName, X_DISTANCE + NUM_X_OFFSET + 35, yMeio, 
                       "venda", CorTextoVenda, 14);
      // Deleta "comp" se existir
      ObjectDelete(indicatorName + "COMP_" + IntegerToString(InstanceID));
   } else {
      // Nenhuma condição: deleta ambos
      ObjectDelete(indicatorName + "COMP_" + IntegerToString(InstanceID));
      ObjectDelete(indicatorName + "VENDA_" + IntegerToString(InstanceID));
   }
   
   lastAlturaTotal = alturaTotal;
}
//+------------------------------------------------------------------+
//| INICIALIZAÇÃO                                                    |
//+------------------------------------------------------------------+
int init()
{
   if(MultiplicadorManual != 0) MultiplicadorAtivo = MathAbs(MultiplicadorManual);
   else MultiplicadorAtivo = 1.0;
   
   IndicatorShortName("VSA 3 Cores Histogram (ID " + IntegerToString(InstanceID) + ")");
   CalculateAdaptivePositions();
   return(0);
}

//+------------------------------------------------------------------+
//| DESINICIALIZAÇÃO                                                 |
//+------------------------------------------------------------------+
int deinit()
{
   for(int i = ObjectsTotal() - 1; i >= 0; i--) {
      string name = ObjectName(i);
      if(StringFind(name, indicatorName) == 0 && StringFind(name, IntegerToString(InstanceID)) >= 0)
         ObjectDelete(name);
   }
   Comment("");
   return(0);
}

//+------------------------------------------------------------------+
//| PRINCIPAL                                                        |
//+------------------------------------------------------------------+
int start()
{
   CalculateAdaptivePositions();
   
   double bodyPts, upperPts, lowerPts;
   int bodyIndex, upperIndex, lowerIndex;
   bool isBearish;
   
   CalculateCandleColors(bodyPts, upperPts, lowerPts, bodyIndex, upperIndex, lowerIndex, isBearish);
   
    
   UpdateAccumulatedColors(bodyIndex, upperIndex, lowerIndex, isBearish);
   
   double buyVol, sellVol;
   CalculateVSAVolume(0, buyVol, sellVol);
   
   DrawVerticalHistogram(buyVol, sellVol, bodyIndex, upperIndex, lowerIndex, isBearish);
   
   WindowRedraw();
   return(0);
}
//+------------------------------------------------------------------+   
   