ManageTPv2-3

Author: Copyright � 2006, Taylor Stockwell
ManageTPv2-3

This script is designed to automate trade management by monitoring active positions and adjusting their profit targets and risk levels in real-time. It functions as an automated "guardian" for your trades, ensuring that as a position moves in your favor, the security and profit mechanics evolve accordingly.

Core Functionality

1. Dynamic Profit Taking The script monitors how many pips a trade has moved from its opening price. Instead of a single static target, it uses an incremental system. Once a trade reaches a specific profit milestone (the "First Target"), the script automatically closes that position and moves the goalpost for the next trade further out by a set increment. This allows for consistent, step-by-step profit realization.

2. Intelligent Stop-Loss Adjustment (Trailing Logic) The tool manages risk by moving your Stop-Loss orders based on the trade's performance:

  • Initial Phase: When a trade begins to move into profit but hasn't reached the second major milestone, the script can move the Stop-Loss to a predetermined point to "lock in" some gains.
  • Advanced Phase: As the price moves even further into profit, the script adjusts the Stop-Loss again to a second specific target. This creates a "trailing" effect where your risk is reduced as the trade becomes more successful.

3. Risk Protection (Hard Cut-offs) The script includes a safety mechanism to prevent significant losses. If a trade moves against your position and hits a maximum loss threshold (which you can define), the script will automatically close the trade. This acts as a final line of defense to preserve your account balance.

4. Market Awareness To ensure accuracy, the logic accounts for different currency types (such as JPY pairs versus standard pairs) and calculates values based on real-time market "spreads" (the difference between buy and sell prices). This ensures that the pip calculations remain precise regardless of which market you are trading.

Summary of Behavior

For a user, this means that once a trade is opened:

  • The script watches it constantly.
  • If it loses too much money quickly, it closes it to save your capital.
  • As it gains profit, it moves the "safety net" (Stop-Loss) up so you don't lose your gains.
  • When it hits a specific profit goal, it closes the trade and prepares the next target, allowing for a systematic approach to trading.
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategy
11 Views
0 Downloads
0 Favorites
ManageTPv2-3
//+------------------------------------------------------------------+
//|                                                   TakeProfit.mq4 |
//|                               Copyright © 2006, Taylor Stockwell |
//|                                               stockwet@yahoo.com |
//|                                                    Version: 2.3  |
//+------------------------------------------------------------------+
#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.
*/

//=============== VARS external
extern int First_Target = 20;
extern int Target_Increment = 20;
extern double Close_Lots = 1.0;
extern bool Move_Stops = true;
extern int First_Stop_Target = 10;
extern int First_Stop = 0;
extern int Second_Stop_Target = 30;
extern int Second_Stop = 10;
extern bool Use_Max_Loss = true;
extern int Max_Loss = 0;
extern int Magic_Number=0;

//=============== VARS internal
int nextTP;
bool sl;
int range = 5;
int multiplier;
// 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
int getPipValue(double ord,int dir)
{
   int val;
   RefreshRates();
   if(dir == 1) val=((ord - Ask)/Point);
   else val=(Bid - ord)/Point;
   return(val);   
}
//== end function

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


int getMaxLoss()
{
   int calcMaxLoss;
   if(Symbol()=="USDJPY" || Symbol()=="EURJPY") multiplier = 100;
   else multiplier = 10000;
   //if(Max_Loss == 0) calcMaxLoss = 2+15+getSpread();
   //if(Max_Loss == 0) calcMaxLoss = 30;
   //else calcMaxLoss = Max_Loss;
   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()))
         {
            int val=getPipValue(OrderOpenPrice(),OrderType());
            if(Use_Max_Loss && Max_Loss > 0) killTrade(val,OrderTicket());
            if(Move_Stops) checkStops(val,OrderTicket());
            takeProfit(val,OrderTicket());            
         }
         
         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 Open: ",OrderOpenPrice(), 
         "\nPip Count: ", val,
         "\nNext Stop Target: ",nsl,
         "\nNext Stop Differential: ", nsd,
         "\nNext TP: ", nextTP,
         "\nSL: ",sl,
         "\nMax Loss: ", getMaxLoss(),
         "\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);
      }
   }


}

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