ManageTPv2-4
Download scriptThis script is designed to automate the management of active trades on the MetaTrader 4 platform. It acts as a dynamic assistant that monitors your open positions in real-time, automatically adjusting risk parameters and closing trades based on pre-defined profit targets, stop-loss movements, and maximum loss limits.
Core Functionalities
1. Automated Profit Taking (Scaling) The script tracks the price movement of your trades and measures them in "pips." Once a trade reaches a specific profit milestone (the First Target), the script automatically closes that portion of the trade. A key feature here is the "Target Increment" logic; every time a target is hit and a trade is closed, the script automatically moves the goalpost for the next milestone further out. This allows for a progressive exit strategy where profits are locked in at intervals.
2. Dynamic Stop-Loss Management To protect your capital as a trade moves into profitability, the script includes a "Move Stops" feature. It monitors how far the price has traveled in your favor:
- First Stage: Once the price reaches a specific success threshold, the script can adjust your stop-loss to a predetermined value (like moving it to break-even or a small profit).
- Second Stage: As the price continues to move even further, the script can update the stop-loss again to a secondary position, ensuring that your realized gains are secured.
3. Risk Mitigation (Hard Stop) The script includes a safety net known as "Max Loss." If a trade moves against you and reaches a specific negative pip value, the script will automatically close the position immediately. This is designed to prevent a losing trade from spiraling out of control and exceeding your planned risk per trade.
4. Smart Filtering The tool does not interfere with every single trade on your account unless you want it to. It uses two main filters:
- Symbol Filtering: It only manages trades on the specific currency pair or asset you have the script running on.
- Magic Number Filtering: You can assign a unique ID (Magic Number) to specific trades. The script can be set to ignore all trades except those with that specific ID, allowing you to run different strategies simultaneously without interference.
Summary of Operation
Instead of requiring you to manually watch the charts to move your stop-loss or decide when to take profit, this script handles the "math" and execution. It constantly calculates the current pip distance, checks it against your target goals, and executes orders (closing for profit, moving stops to safety, or killing a losing trade) the moment those conditions are met.
//+------------------------------------------------------------------+
//| TakeProfit.mq4 |
//| Copyright © 2006, Taylor Stockwell |
//| stockwet@yahoo.com |
//| Version: 2.4 |
//+------------------------------------------------------------------+
#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 = 20;
extern int Target_Increment = 20;
extern double Close_Lots = 0.2;
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 = 20;
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
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("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