Manage_TP v3.5
Download scriptThis script is designed to automate the management of active trades in MetaTrader 4. It functions as a dynamic oversight tool that monitors your open positions and automatically adjusts take-profit targets, moves stop-loss levels, and enforces maximum loss limits based on real-time price movement.
Core Logic Overview
The script works by constantly calculating the "Pip Count" (the distance between the current market price and your trade's entry price). Based on this distance, it executes three primary management tasks:
1. Dynamic Take-Profit Management Instead of a static exit point, the script uses an incremental approach to closing trades.
- It monitors how many pips your trade has moved in your favor.
- Once a trade reaches a specific "Target" milestone, the script automatically closes the position.
- After a successful closure, it automatically updates the target for the next trade by a pre-defined increment. This allows you to scale your exit goals systematically.
2. Automated Stop-Loss Trailing The script includes a multi-stage logic to "lock in" profits as the market moves in your favor.
- It tracks specific price milestones (First, Second, Third, and Fourth Stop Targets).
- As your trade reaches these milestones, the script modifies your Stop-Loss order to move to a safer position.
- This ensures that as a winning trade grows, your risk is reduced by moving the "safety net" closer to the current price, protecting your gains from sudden market reversals.
3. Risk Protection (Maximum Loss) To safeguard your account against significant sudden drops, the script features a "kill switch."
- It continuously monitors the negative movement of your trades.
- If a trade moves against you by a distance exceeding your specified "Max Loss" limit, the script will automatically close that trade immediately to prevent further capital erosion.
User Monitoring & Visibility
While the script performs these actions automatically in the background, it also provides a real-time information dashboard directly on your trading chart. This display includes:
- Live Status: Current broker time, current pip count, and active spread.
- Trade Details: The open price, swap rates, and specific comments for the trade.
- Management Metrics: It shows you exactly where your current Stop-Loss sits, what the next profit target is, how much distance remains until the next stop move, and confirms which trades are being managed by the script (either all trades or specific ones identified by a Magic Number).
Summary of Operations
In short, this tool acts as an automated trade manager that handles the "heavy lifting" of monitoring. It systematically moves your safety nets forward as you win, closes out positions at calculated milestones, and acts as a final barrier to prevent large losses from a single trade.
//+------------------------------------------------------------------+
//| 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.
*/
//=============== VARS external
extern int First_Target = 100;
extern int Target_Increment = 50;
extern double Close_Lots = 0.25;
extern bool Move_Stops = true;
extern int First_Stop_Target = 100;
extern int First_Stop = 50;
extern int Second_Stop_Target = 125;
extern int Second_Stop = 75;
extern int Third_Stop_Target = 150;
extern int Third_Stop = 100;
extern int Fourth_Stop_Target = 175;
extern int Fourth_Stop = 125;
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;
// 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());
}
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(
"Your Brokers Time is : ",TimeHour (CurTime ()),":",TimeMinute (CurTime ()),":",TimeSeconds (CurTime ()),
"\nOrder Open: ",OrderOpenPrice(), " || Order Swap: ", OrderSwap(), " || Order Comment is ", OrderComment() ,
"\nPip Count: ", val," || Pip Spread: ",(Ask - Bid) / Point," || SL: ",sl, " || Max Loss: ", getMaxLoss(),
"\nNext Stop Target: ",nsl, " || Next Stop Differential: ", nsd, " || Next TP: ", nextTP,
"\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 >= Fourth_Stop_Target)
{
moveStops(ticket,Fourth_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