managetpv34
Download scriptThis script is designed as an automated trade management tool for the MetaTrader 4 platform. Its primary purpose is to monitor active trades in real-time and automatically execute specific actions—such as closing positions, moving stop-loss levels, or hitting profit targets—based on pre-defined pip price movements.
Core Logic Overview
The script functions as a continuous monitoring system. Every time the market updates, it scans all open trading positions to calculate how many "pips" a trade is currently in profit or loss relative to its opening price. Based on this calculation, it applies three main types of logic:
1. Automated Profit Taking
The script tracks a progression of profit targets. Instead of closing every trade at a single fixed point, it uses an incremental system:
- It monitors the current profit and compares it against a "Next Target."
- When a trade reaches that target, the script automatically closes the position.
- Once a trade is closed this way, the script automatically increases the next target by a specific increment, allowing for a structured sequence of exits.
2. Dynamic Stop-Loss Management (Trailing Logic)
The script includes a mechanism to protect profits by moving stop-loss levels as the market moves in your favor. This is handled through several "Stop Targets":
- Initial Protection: Once a trade reaches a certain profit milestone, the script can move the stop-loss to a specific point to "lock in" some gains.
- Tiered Adjustments: As the trade continues to move significantly in the correct direction, the script identifies different profit milestones and adjusts the stop-loss further. This ensures that as your profit grows, the safety net moves with it to prevent a winning trade from turning into a loss.
3. Risk Management (Maximum Loss)
To protect your account balance from significant drawdowns, the script includes a "Kill Trade" feature:
- It constantly monitors the negative movement of a trade.
- If a trade drops below a user-defined maximum loss threshold (expressed in pips), the script will automatically close that position immediately to prevent further losses.
Summary of Operations
Essentially, this tool acts as an automated "trade guardian." It ensures that:
- Profits are secured by closing trades at specific milestones.
- Risk is capped by shutting down losing trades that hit a maximum limit.
- Winning trades are protected by dynamically shifting stop-loss orders forward as the price moves favorably.
//+------------------------------------------------------------------+
//| 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 int Third_Stop_Target = 50;
extern int Third_Stop = 40;
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);
}
}
else if(sl==1 || pips >= Third_Stop_Target)
{
if(pips >= Third_Stop_Target)
{
moveStops(ticket,Third_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