Manage_TP v3.5 bis comment
Download scriptThis script is designed to automate the management of active trades in MetaTrader 4 by dynamically adjusting profit targets, moving stop-loss levels, and enforcing risk limits. Instead of leaving a trade static, the logic monitors price movement in real-time and adjusts the trade parameters based on specific milestones (measured in "pips").
Core Functionalities
1. Dynamic Profit Taking The script manages how profits are realized by monitoring the distance between the current market price and your entry price. It uses a multi-stage approach:
- It identifies a "First Target" for profit.
- Once the price reaches this target, the script automatically closes a specific percentage of the trade volume (configurable by the user).
- After closing that portion, it automatically moves the target forward by a set increment, allowing you to "scale out" of a position while keeping the remainder of the trade open to capture further gains.
2. Automated Stop-Loss Management (Trailing Logic) The script includes a tiered system to protect your capital as a trade becomes profitable:
- As the price moves in your favor and hits specific milestones, the script automatically moves the Stop Loss to a safer level.
- It follows a ladder of targets (e.g., Second Stop Target, Third Stop Target, etc.). As each milestone is crossed, the stop loss is moved to a predefined distance to lock in gains.
- This ensures that if the market reverses suddenly, you have already secured a portion of your profit rather than letting the trade return to a break-even or losing point.
3. Risk Mitigation (Maximum Loss) To prevent significant account drawdown from a single bad trade, the script monitors the current "unrealized" loss of open positions:
- It constantly calculates the distance of the price from your entry.
- If the trade moves against you by a user-defined maximum number of pips, the script will automatically trigger a market order to close the position immediately.
4. Real-Time Monitoring and Feedback The script provides a continuous visual update on your screen. It calculates and displays several pieces of information simultaneously for the user:
- Current pip count (profit/loss distance).
- Current Spread and Broker time.
- Live status of Stop Loss and Take Profit levels.
- The "Next Target" milestone the trade is currently approaching.
- The calculated amount of lots to be closed at the next step.
Summary of Workflow
When a trade is opened with the designated comment, the script takes over management. It watches the price: if it goes up (for buys) or down (for sells), it checks if you have hit a milestone. If you have, it either locks in profit by moving your stop loss, secures some capital by closing a percentage of the trade, or cuts the loss if the market moves too far against you.
//+------------------------------------------------------------------+
//| 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()))
{
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