Manage_TP v3.5 bis comment2

Download script
Author: Copyright � 2006, Taylor Stockwell
Manage_TP v3.5 bis comment2

This script is designed to automate trade management for MetaTrader 4 by monitoring active positions and executing specific actions based on price movement. It functions as a systematic "safety net" and profit-taking tool, ensuring that trades are managed dynamically rather than being left static once opened.

The logic operates through four primary management layers:

1. Dynamic Profit Taking (Partial Closures)

Rather than closing an entire position at a single fixed price, the script monitors how many "pips" a trade has moved in your favor. Once a trade reaches a specific target, the script automatically closes a predetermined percentage of that position (e.g., 20%). After this partial close is successful, it automatically moves to the next profit milestone, repeating this process as the price continues to trend favorably.

2. Intelligent Stop-Loss Protection

The script features an automated "trailing" logic. As the market moves in your favor and hits specific milestones (targets), the script adjusts your Stop-Loss levels. This is designed to "lock in" gains by moving the stop-loss closer to the current price as the trade becomes more profitable, reducing the risk of a sudden market reversal turning a winning trade into a losing one.

3. Hard Risk Limits (Maximum Loss)

To protect your account from significant drawdowns, the script includes a "kill switch." If a trade moves against you by a pre-defined maximum amount of pips, the script will automatically close the position immediately. This acts as an automated emergency brake to ensure that no single trade exceeds a specific level of risk.

4. Real-Time Monitoring and Feedback

The script continuously scans all open orders on your platform. It identifies trades based on specific comments you provide and calculates the current performance in real-time. It then provides a visual dashboard on your trading chart, displaying critical data such as:

  • Current profit/loss in pips.
  • Current spread and swap values.
  • The next scheduled stop-loss target.
  • The next planned profit-taking milestone.
  • The exact lot size of the next partial closure.

In summary, this tool automates the "manual" work of a trader—constantly watching the charts to move stops, take profits at specific intervals, and cutting losses when they become too large—allowing for a more disciplined and consistent trading execution.

Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategy
13 Views
0 Downloads
0 Favorites
Manage_TP v3.5 bis comment2
//+------------------------------------------------------------------+
//|                                                   TakeProfit.mq4 |
//|                               Copyright © 2006, Taylor Stockwell |
//|                                               stockwet@yahoo.com |
//|                                                    Version: 3.5  |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2006, Taylor Stockwell"
#property link      "stockwet@yahoo.com"


/*
Updates:

   11/2/2006:: Fixed bug that caused the sl var to be set to 1 when a pending
               order was > than the First_Stop_Target value.
   1/23/2007:: Fixed pip calculation. The old way of calculating pips could be
               off by 1 pip, resulting in missed TP or move stops. The new
               calculation is more accurate.
               Trace by comment and close lots by percent
*/

//=============== VARS external
extern int First_Target = 20;
extern int Target_Increment = 30;
extern int Close_Lots_Percent = 20;
extern bool Move_Stops = true;
extern int First_Stop_Target = 20;
extern int First_Stop = 0;
extern int Second_Stop_Target = 60;
extern int Second_Stop = 30;
extern int Third_Stop_Target = 90;
extern int Third_Stop = 60;
extern int Fourth_Stop_Target = 120;
extern int Fourth_Stop = 90;
extern int Fifth_Stop_Target = 150;
extern int Fifth_Stop = 120;
extern bool Use_Max_Loss = true;
extern int Max_Loss = 100;
int Magic_Number=500;
extern string Order_Comment="Trade";

//=============== VARS internal
int nextTP;
bool sl;
int range = 5;
int multiplier;
double Close_Lots = 0;

// OrderType == 1 is OP_SELL




//=============== FUNCTION init
int init()
  {
   sl=0;
   nextTP = First_Target;
   getMaxLoss();
  }
//== end function


//=============== FUNCTION deinit
int deinit()
  {
//----
   sl=0;
   nextTP = First_Target;
//----
   return(0);
  }
//== end function

//========== FUNCTION Start
int start()
  {
//----
   getOpenOrders();
   getSpread();
   //Comment(sl);
//----
   return(0);
  }
//== end function

//========== FUNCTION getPipValue
double getPipValue(double ord,int dir)
{
   double val;
   RefreshRates();
   if(dir == 1) val=(NormalizeDouble(ord,Digits) - NormalizeDouble(Ask,Digits));
   else val=(NormalizeDouble(Bid,Digits) - NormalizeDouble(ord,Digits));
   val = val/Point;
   return(val);   
}

//== end function

int getSpread()
{
   int spread=MarketInfo(Symbol(),MODE_SPREAD);
   return(spread);
}


int getMaxLoss()
{
   int calcMaxLoss;
   calcMaxLoss = Max_Loss;
   return(calcMaxLoss);
}
//========== FUNCTION getOpenOrders
void getOpenOrders()
{

   int nsl, nsd;
   string mngMagic;
   int totalorders = OrdersTotal();
   for(int j=0; j<totalorders;j++)
     {  
         OrderSelect(j, SELECT_BY_POS, MODE_TRADES);
//         if((OrderType() == OP_BUY || OrderType() == OP_SELL) && OrderSymbol() == Symbol() && (Order_Comment == OrderComment()))
         if((OrderType() == OP_BUY || OrderType() == OP_SELL) && OrderSymbol() == Symbol() && (StringFind(OrderComment(), Order_Comment) >0))
         {     


            double val=getPipValue(OrderOpenPrice(),OrderType());
            //int val = OrderProfit()/(OrderLots()*10);
            if(Use_Max_Loss && Max_Loss > 0) killTrade(val,OrderTicket());
            if(Move_Stops) checkStops(val,OrderTicket());
            takeProfit(val,OrderTicket());
          	Close_Lots = NormalizeDouble(OrderLots() * Close_Lots_Percent * 0.01, 2);
            double Swap = OrderSwap(); string Order_comment = OrderComment(); double orderopen_price = OrderOpenPrice();
            string Order_Symbol = OrderSymbol(); Magic_Number=OrderMagicNumber(); double OSL=OrderStopLoss(); double OTP= OrderTakeProfit();
            
         }
         

         mngMagic = "Order Magic Number = "+Magic_Number;
         
         
         if(sl==0)
            {
               nsl = First_Stop_Target;
               nsd = First_Stop;
            }
          else
            {
               nsl = Second_Stop_Target;
               nsd = Second_Stop;
            }
         //RefreshRates();
         Comment(
         Order_Symbol,
         "\nYour Brokers Time is : ",TimeHour (CurTime ()),":",TimeMinute (CurTime ()),":",TimeSeconds (CurTime ()),
         "\nOrder Open: ",orderopen_price, " || Order Swap: ", Swap, " || Order SL: ", OSL, " || Order TP: ", OTP ,
         "\nPip Count: ", val," || Pip Spread: ",(Ask - Bid) / Point," || Max Loss: ", getMaxLoss()," ||Close lots percent is ",Close_Lots, 
         "\nNext Stop Target: ",nsl, " || Next Stop Differential: ", nsd, " || Next TP: ", nextTP, " || EA SL: ", sl,
         "\n",mngMagic, " || Trail by Order Comment: ", Order_comment  
         );

         
         

     }  
}

//========== FUNCTION takeProfit
void takeProfit(int pips, int ticket)
{
   if(OrderSelect(ticket, SELECT_BY_TICKET)==true)
   {

      if(pips >= nextTP && pips < (nextTP + Target_Increment))
      {
         if(OrderType()==1)
         {
            if(OrderClose(ticket, Close_Lots, Ask, 3, YellowGreen))
            nextTP+=Target_Increment;
            else
            Print("Error closing order : ",GetLastError()); 
         } 
         else
         {
            if(OrderClose(ticket, Close_Lots, Bid, 3, YellowGreen))
            nextTP+=Target_Increment;
            else
            Print("Error closing order : ",GetLastError()); 
         }
              
      }

   }
}

//== end function



//========== FUNCTION moveStops
void checkStops(int pips,int ticket)
{
   if(sl==0 && pips < Second_Stop_Target)
   {
      if(pips >= First_Stop_Target && pips < (Second_Stop_Target))
      {
         moveStops(ticket, First_Stop);
      }
   }
   
   else if(sl==1 || pips >= Second_Stop_Target)
   
   {
      if(pips >= Second_Stop_Target)
      {
         moveStops(ticket,Second_Stop);
      }
   }

   else if(sl==1 || pips >= Third_Stop_Target)
   
   {
      if(pips >= Third_Stop_Target)
      {
         moveStops(ticket,Third_Stop);
      }
   }
   
      else if(sl==1 || pips >= Third_Stop_Target)
   
   {
      if(pips >= Fifth_Stop_Target)
      {
         moveStops(ticket,Fifth_Stop);
      }
   }
   
   
}

//== end function

//========== FUNCTION moveStops
void moveStops(int ticket,int stopDiff)
{
   if(OrderSelect(ticket, SELECT_BY_TICKET)==true)
   {
      Print("moveStops called ",ticket, " ",stopDiff);
      if(OrderType()==1) 
      {
      OrderModify(ticket,OrderOpenPrice(),OrderOpenPrice()-stopDiff*Point, OrderTakeProfit(),0,Plum);
      sl=1;
      }
      else 
      {
      OrderModify(ticket,OrderOpenPrice(),OrderOpenPrice()+stopDiff*Point, OrderTakeProfit(),0,Plum);
      sl=1;
      }
   }
   

   
}

//== end function

//========== FUNCTION killTrades
void killTrade(int pips, int ticket)
{
   if(OrderSelect(ticket, SELECT_BY_TICKET)==true)
   {
      if(pips <= -1*getMaxLoss())
      {
         if(OrderType()==1) OrderClose(ticket,OrderLots(),Ask,3,Red);     
         else OrderClose(ticket,OrderLots(),Bid,3,Red); 
      }      
   }
}
//== end function

Comments