//+------------------------------------------------------------------+
//|                                     Cowboy Trader.mq5     |
//| CLEAN VERSION: Title + Interactive Auto SL/TP + Split Close Buttons |
//+------------------------------------------------------------------+
#property version   "4.20"
#property strict

#include <Trade/Trade.mqh>
CTrade trade;

// === INPUTS ===
input double FixedLot       = 0.01; // Lot size for Button Trades
input int    Input_SL_Pts   = 300;  // Default Stop Loss (Points)
input int    Input_TP_Pts   = 600;  // Default Take Profit (Points)

// === DASHBOARD SETTINGS ===
input ENUM_BASE_CORNER DashCorner  = CORNER_LEFT_UPPER; // Panel Location
input color          DashColor     = clrWhite;          // Text Color
input int            DashXOffset   = 20;                // Horizontal Margin
input int            DashYOffset   = 20;                // Vertical Margin

// === BUTTON SETTINGS ===
input color BtnBgColor   = clrDarkSlateGray;
input color BtnTxtColor  = clrWhite;
input color BtnBuyColor  = clrGreen;
input color BtnSellColor = clrRed;
input int   BtnWidth     = 170;
input int   BtnHeight    = 30;

// === LIVE VARIABLES (Editable on Chart) ===
int  Live_SL;      // Holds current SL value
int  Live_TP;      // Holds current TP value
bool SLTP_Enabled = true; // Master Switch

//+------------------------------------------------------------------+
//| INIT                                                             |
//+------------------------------------------------------------------+
int OnInit()
{
   Print("AutoSLTP Cowboy v4.2 started.");
   
   trade.SetDeviationInPoints(50);
   trade.SetTypeFilling(ORDER_FILLING_IOC);
   trade.SetExpertMagicNumber(0); 
   
   Live_SL = Input_SL_Pts;
   Live_TP = Input_TP_Pts;

   CreateDashboard();
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| DEINIT                                                           |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   ObjectsDeleteAll(0, "AutoSLTP_");
}

//+------------------------------------------------------------------+
//| TICK (CORE LOGIC)                                                |
//+------------------------------------------------------------------+
void OnTick()
{
   if(SLTP_Enabled)
   {
      ApplySLTP_Positions();
      ApplySLTP_Orders();
   }
}

//+------------------------------------------------------------------+
//| CHART EVENT (BUTTONS & EDIT BOXES)                               |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
   // --- A. CLICK EVENTS (Buttons) ---
   if(id == CHARTEVENT_OBJECT_CLICK)
   {
      // 1. Toggle ON/OFF
      if(sparam == "AutoSLTP_Btn_Toggle")
      {
         SLTP_Enabled = !SLTP_Enabled;
         UpdateToggleButton();
         ObjectSetInteger(0, "AutoSLTP_Btn_Toggle", OBJPROP_STATE, false);
         ChartRedraw();
      }

      // 2. Buy/Sell
      if(sparam == "AutoSLTP_Btn_Buy")
      {
         if(!trade.Buy(FixedLot)) Print("Buy Failed: ", GetLastError());
         ObjectSetInteger(0, "AutoSLTP_Btn_Buy", OBJPROP_STATE, false);
      }
      if(sparam == "AutoSLTP_Btn_Sell")
      {
         if(!trade.Sell(FixedLot)) Print("Sell Failed: ", GetLastError());
         ObjectSetInteger(0, "AutoSLTP_Btn_Sell", OBJPROP_STATE, false);
      }

      // 3. Close Positions (Market Trades Only)
      if(sparam == "AutoSLTP_Btn_CloseOpen")
      {
         CloseAllPositions();
         ObjectSetInteger(0, "AutoSLTP_Btn_CloseOpen", OBJPROP_STATE, false);
      }
      
      // 4. Close Pending Only (Limit/Stop Orders) [NEW]
      if(sparam == "AutoSLTP_Btn_ClosePending")
      {
         DeleteAllPending();
         ObjectSetInteger(0, "AutoSLTP_Btn_ClosePending", OBJPROP_STATE, false);
      }
      
      // 5. Close EVERYTHING
      if(sparam == "AutoSLTP_Btn_CloseAll")
      {
         CloseAllPositions();
         DeleteAllPending();
         ObjectSetInteger(0, "AutoSLTP_Btn_CloseAll", OBJPROP_STATE, false);
      }
      ChartRedraw();
   }
   
   // --- B. EDIT EVENTS (Text Boxes) ---
   if(id == CHARTEVENT_OBJECT_ENDEDIT)
   {
      if(sparam == "AutoSLTP_Edit_SL") {
         Live_SL = (int)StringToInteger(ObjectGetString(0, "AutoSLTP_Edit_SL", OBJPROP_TEXT));
      }
      if(sparam == "AutoSLTP_Edit_TP") {
         Live_TP = (int)StringToInteger(ObjectGetString(0, "AutoSLTP_Edit_TP", OBJPROP_TEXT));
      }
   }
}

//+------------------------------------------------------------------+
//| CORE LOGIC                                                       |
//+------------------------------------------------------------------+
void ApplySLTP_Positions()
{
   int total = PositionsTotal();
   for(int i = 0; i < total; i++)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket > 0 && PositionSelectByTicket(ticket))
      {
         if(PositionGetInteger(POSITION_MAGIC) == 0) 
         {
            double sl = PositionGetDouble(POSITION_SL);
            double tp = PositionGetDouble(POSITION_TP);
            
            if(sl == 0 || tp == 0)
            {
               double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
               string symbol    = PositionGetString(POSITION_SYMBOL);
               long   type      = PositionGetInteger(POSITION_TYPE);
               double point     = SymbolInfoDouble(symbol, SYMBOL_POINT);
               
               double newSL, newTP;
               if(type == POSITION_TYPE_BUY) {
                  newSL = openPrice - Live_SL * point;
                  newTP = openPrice + Live_TP * point;
               } else {
                  newSL = openPrice + Live_SL * point;
                  newTP = openPrice - Live_TP * point;
               }
               trade.PositionModify(ticket, newSL, newTP);
            }
         }
      }
   }
}

void ApplySLTP_Orders()
{
   int total = OrdersTotal();
   for(int i = 0; i < total; i++)
   {
      ulong ticket = OrderGetTicket(i);
      if(ticket > 0 && OrderSelect(ticket))
      {
         if(OrderGetInteger(ORDER_MAGIC) == 0)
         {
            double sl = OrderGetDouble(ORDER_SL);
            double tp = OrderGetDouble(ORDER_TP);
            if(sl == 0 || tp == 0)
            {
               double openPrice = OrderGetDouble(ORDER_PRICE_OPEN);
               string symbol    = OrderGetString(ORDER_SYMBOL);
               long   type      = OrderGetInteger(ORDER_TYPE);
               double point     = SymbolInfoDouble(symbol, SYMBOL_POINT);
               
               double newSL, newTP;
               bool isBuy = (type == ORDER_TYPE_BUY_LIMIT || type == ORDER_TYPE_BUY_STOP);
               if(isBuy) {
                  newSL = openPrice - Live_SL * point;
                  newTP = openPrice + Live_TP * point;
               } else {
                  newSL = openPrice + Live_SL * point;
                  newTP = openPrice - Live_TP * point;
               }
               trade.OrderModify(ticket, openPrice, newSL, newTP, 0, 0);
            }
         }
      }
   }
}

//+------------------------------------------------------------------+
//| VISUALS: Dashboard Construction                                  |
//+------------------------------------------------------------------+
void CreateDashboard()
{
   int y = DashYOffset;
   int gap = 2;
   
   // Title
   DrawLabel("AutoSLTP_Title", "::: Cowboy Trader :::", DashXOffset + 8, y, DashColor, 10);
   y += 20;
   
   // Toggle
   CreateOneButton("AutoSLTP_Btn_Toggle", "Initializing...", DashXOffset, y, BtnWidth, BtnHeight, clrGray);
   UpdateToggleButton(); 
   
   // Edit Boxes
   y += BtnHeight + 5;
   int boxW = 55;
   DrawLabel("AutoSLTP_Lbl_SL", "SL:", DashXOffset, y+5, DashColor, 10);
   CreateEditBox("AutoSLTP_Edit_SL", IntegerToString(Live_SL), DashXOffset + 25, y, boxW, BtnHeight);
   DrawLabel("AutoSLTP_Lbl_TP", "TP:", DashXOffset + 90, y+5, DashColor, 10);
   CreateEditBox("AutoSLTP_Edit_TP", IntegerToString(Live_TP), DashXOffset + 115, y, boxW, BtnHeight);

   // Buy/Sell
   y += BtnHeight + 5;
   int halfWidth = (BtnWidth - gap) / 2;
   CreateOneButton("AutoSLTP_Btn_Buy", "BUY", DashXOffset, y, halfWidth, BtnHeight, BtnBuyColor);
   CreateOneButton("AutoSLTP_Btn_Sell", "SELL", DashXOffset + halfWidth + gap, y, halfWidth, BtnHeight, BtnSellColor);
   
   // --- CLOSE BUTTONS SECTION ---
   y += BtnHeight + 5;
   // 1. Close Positions
   CreateOneButton("AutoSLTP_Btn_CloseOpen", "CLOSE OPEN", DashXOffset, y, BtnWidth, BtnHeight, BtnBgColor);
   
   y += BtnHeight + 5;
   // 2. Close Pending [NEW]
   CreateOneButton("AutoSLTP_Btn_ClosePending", "CLOSE PENDING", DashXOffset, y, BtnWidth, BtnHeight, BtnBgColor);
   
   y += BtnHeight + 5;
   // 3. Close All
   CreateOneButton("AutoSLTP_Btn_CloseAll", "CLOSE ALL TRADES", DashXOffset, y, BtnWidth, BtnHeight, clrMaroon); // Dark Red for caution
}

void UpdateToggleButton()
{
   if(SLTP_Enabled) {
      ObjectSetString(0, "AutoSLTP_Btn_Toggle", OBJPROP_TEXT, "Auto SL/TP: ON");
      ObjectSetInteger(0, "AutoSLTP_Btn_Toggle", OBJPROP_BGCOLOR, clrGreen);
   } else {
      ObjectSetString(0, "AutoSLTP_Btn_Toggle", OBJPROP_TEXT, "Auto SL/TP: OFF");
      ObjectSetInteger(0, "AutoSLTP_Btn_Toggle", OBJPROP_BGCOLOR, clrRed);
   }
}

//+------------------------------------------------------------------+
//| HELPER FUNCTIONS                                                 |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
   int total = PositionsTotal();
   for(int i = total - 1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket > 0 && PositionSelectByTicket(ticket))
         if(PositionGetInteger(POSITION_MAGIC) == 0) 
            trade.PositionClose(ticket);
   }
}

void DeleteAllPending()
{
   int total = OrdersTotal();
   for(int i = total - 1; i >= 0; i--)
   {
      ulong ticket = OrderGetTicket(i);
      if(ticket > 0 && OrderSelect(ticket))
         if(OrderGetInteger(ORDER_MAGIC) == 0) 
            trade.OrderDelete(ticket);
   }
}

void CreateOneButton(string name, string text, int x, int y, int w, int h, color bg)
{
   if(ObjectFind(0, name) < 0) ObjectCreate(0, name, OBJ_BUTTON, 0, 0, 0);
   ObjectSetInteger(0, name, OBJPROP_CORNER, DashCorner);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, name, OBJPROP_XSIZE, w);
   ObjectSetInteger(0, name, OBJPROP_YSIZE, h);
   ObjectSetString (0, name, OBJPROP_TEXT, text);
   ObjectSetInteger(0, name, OBJPROP_BGCOLOR, bg);
   ObjectSetInteger(0, name, OBJPROP_COLOR, BtnTxtColor);
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 8);
   ObjectSetString (0, name, OBJPROP_FONT, "Arial");
   ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
}

void CreateEditBox(string name, string text, int x, int y, int w, int h)
{
   if(ObjectFind(0, name) < 0) ObjectCreate(0, name, OBJ_EDIT, 0, 0, 0);
   ObjectSetInteger(0, name, OBJPROP_CORNER, DashCorner);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetInteger(0, name, OBJPROP_XSIZE, w);
   ObjectSetInteger(0, name, OBJPROP_YSIZE, h);
   ObjectSetString (0, name, OBJPROP_TEXT, text);
   ObjectSetInteger(0, name, OBJPROP_BGCOLOR, clrWhite);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clrBlack);
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 9);
   ObjectSetInteger(0, name, OBJPROP_ALIGN, ALIGN_CENTER);
   ObjectSetInteger(0, name, OBJPROP_READONLY, false); 
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
}

void DrawLabel(string name, string text, int x, int y, color col, int size)
{
   if(ObjectFind(0, name) < 0) ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
   ObjectSetInteger(0, name, OBJPROP_CORNER, DashCorner);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetString (0, name, OBJPROP_TEXT, text);
   ObjectSetInteger(0, name, OBJPROP_COLOR, col);
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, size);
   ObjectSetString (0, name, OBJPROP_FONT, "Arial");
   ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
}