Manage_TP v3.5 bis

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

This script is an automated trade management tool designed to monitor active trading positions and execute specific actions based on price movement. It focuses on three core functionalities: progressive profit-taking, dynamic stop-loss management, and risk protection.

Core Logic Overview

1. Automated Partial Profit Taking The primary logic of this tool is to "scale out" of a position as it becomes profitable. Rather than waiting for the entire trade to hit a final target, the script monitors the price in real-time. Once the price reaches a specific profit milestone (defined by the user), the script automatically closes a predetermined percentage of that specific trade's volume. After this partial close is successful, the script automatically adjusts its next target forward, allowing for a multi-stage exit strategy on a single position.

2. Dynamic Stop-Loss Management The script includes logic to move "Stop Loss" orders based on how much profit has been secured. As the trade moves into positive territory and hits specific price targets, the tool can automatically shift the stop loss to a more favorable position. This is designed to lock in gains or protect the capital as the market moves in your favor. The script uses a tiered system to determine when these movements should occur based on the current pip count of the trade.

3. Hard Risk Protection (Max Loss) To prevent significant account drawdowns, the script monitors the floating loss of every open position. If a trade moves against your position and reaches a user-defined maximum loss threshold, the script will immediately trigger an emergency exit to close the trade. This acts as a safety net, ensuring that no single trade can exceed a specific level of risk.

4. Order Identification and Monitoring The tool is designed to be precise in what it manages. It scans your active trades and filters them based on two criteria:

  • Symbol Matching: It only interacts with trades on the specific currency pair or asset you are currently viewing.
  • Magic Number Filtering: It can be set to manage all trades, or only those assigned to a specific "Magic Number" (a unique ID used to distinguish between different automated systems).

User Interface Features

While the script runs in the background, it provides a real-time information dashboard on the trading chart. This display shows:

  • Current profit/loss in pips and spreads.
  • Broker time and order swap details.
  • The current status of your Stop Loss and Take Profit levels.
  • Detailed tracking of which profit targets have been hit and what the "Next Target" is.
  • Information on how many lots are currently being managed based on your percentage settings.
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategy
9 Views
0 Downloads
0 Favorites
Manage_TP v3.5 bis
//+------------------------------------------------------------------+
//|                                                   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.
               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;
extern int Magic_Number=500;

//=============== 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()&&(Magic_Number==0 || Magic_Number == OrderMagicNumber()))
         {     


            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(); double OSL=OrderStopLoss(); double OTP= OrderTakeProfit();
            
         }
         
         if(Magic_Number == 0)
         mngMagic = "All "+Symbol()+" trades.";
         else
         mngMagic = "Trades with 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,
         "\nManaging ",mngMagic 
          );

         
         

     }  
}

//========== 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