Author: Copyright � 2006, Taylor Stockwell
ManageTPv2

This automated trading script is designed to manage and execute trades based on specific price movements and technical indicators. Its primary goal is to handle the lifecycle of a trade—from entry logic to profit-taking and risk management—automatically.

Entry Logic

The system determines whether to enter a trade by comparing the current market price against a 30-minute Weighted Moving Average (WMA) over 200 periods.

  • Sell Orders: If the price is currently trading below the WMA, the script identifies this as a signal to open a sell position.
  • Buy Orders: If the price is trading above the WMA, the script identifies this as a signal to open a buy position.

Profit Management (Take Profit)

The script features a sophisticated multi-stage exit strategy. Instead of closing a full position at a single target, it can be configured to manage profit in increments:

  • Partial Closing: It can automatically close a specified portion of your total trade size when the price reaches an initial target.
  • Sequential Targets: Once the first target is met, the script adjusts its internal logic to look for a second, higher target to close the remaining portion of the position.
  • Dynamic Tracking: The system keeps track of these "pips" in real-time to ensure that as soon as the price hits the predefined threshold, the closing action is triggered.

Risk Management & Stop Losses

To protect capital, the script includes several safety layers:

  • Break-Even and Trail Logic: Once the first profit target is reached, the script can automatically move your "Stop Loss" to a safer point (such as the break-even price). It can then adjust this stop further as the trade moves in your favor.
  • Maximum Loss Protection: You can set a hard limit on how much of a loss you are willing to tolerate. If a trade moves against you by this specific amount, the script will automatically "kill" (close) the trade to prevent further capital depletion.
  • Automatic Adjustment: The system is intelligent enough to adjust these calculations based on the specific currency pair being traded (e.g., applying different multipliers for JPY pairs versus others).

Monitoring and Visibility

While the script works in the background, it provides a real-time status update on your trading screen. This display shows:

  • The current open price of your trades.
  • The current distance moved in pips.
  • The next target the system is watching for.
  • The current Stop Loss status and the maximum loss threshold.
  • Information on which specific trades are being managed (based on "Magic Numbers" or all active trades).
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategy
15 Views
0 Downloads
0 Favorites
ManageTPv2
//+------------------------------------------------------------------+
//|                                                   TakeProfit.mq4 |
//|                               Copyright © 2006, Taylor Stockwell |
//|                                               stockwet@yahoo.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2006, Taylor Stockwell"
#property link      "stockwet@yahoo.com"


/*
This is a simple expert that opens an order at a given time depending on the 30m 
WMA 200 value. If price is below the WMA value, it opens a sell order. If price is 
above the WMA, it opens a buy order.

Modified: 
7/14/2006: 
   Added take profit and max stop code. 
   Added wma distance parameter.
   Cleaned code up a bit.
7/18/2006:
   Added feature to specify the overall position size. If you want to trade 2 lots, put 2 in the
      Position_Size field.
   Added feature to take 1/2 of position out at one target and the second half at a second target.
      The feature accounts for odd sizes and mini lots, but not micro (.01) lots.         
   Added feature to move stops at B/E after first target is reached.
   Display whether the WMA-Price distance is within range.        

*/

//=============== 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 calcMaxLoss;
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()
{
   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;
   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(OrderSymbol() == Symbol()&&(Magic_Number==0 || Magic_Number == OrderMagicNumber()))
         {
            int val=getPipValue(OrderOpenPrice(),OrderType());
            if(Use_Max_Loss) 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)
   {
      if(pips >= First_Stop_Target && pips < (Second_Stop_Target))
      {
         moveStops(ticket, First_Stop);
      }
   }
   else if(sl==1)
   {
      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