code_snippet_DelayTrading
Download scriptThis script is designed to manage automated trading on the MetaTrader platform by incorporating a specific safety mechanism: a mandatory "cooling-off" period following a losing trade. Its primary goal is to prevent the system from making repetitive, rapid trades immediately after a position has been closed unsuccessfully.
Core Logic Overview
The script monitors your trading activity and enforces a timed pause based on the following logic:
1. Trade Monitoring The system constantly scans your open positions. It identifies specific trades using a unique identification number (Magic Number), ensuring it only interacts with the trades intended for this specific strategy while ignoring other manual or automated trades you might have running.
2. The "Cooling-Off" Timer The most significant feature of this script is its ability to look back at your trading history. If a trade was recently closed, the script calculates how much time has passed since that closure. If that time is less than the user-defined delay (e.g., 30 minutes), the script will proactively block any new trades from opening.
3. Visual Status Indicators To keep the user informed of what the script is doing, it provides real-time visual feedback directly on the trading chart:
- Active Waiting: If the cooling-off period is currently active, the script displays a message on the chart showing exactly what time trading will resume.
- Ready Status: Once the required time has passed, the script updates the text on the chart to notify you that trading has resumed.
4. Stability and Connectivity The script includes automated "cleanup" routines. If your connection to the server is lost or if the software restarts, it automatically refreshes its visual labels and settings to ensure the information displayed on your screen remains accurate and consistent.
Summary of Operation
In simple terms, this acts as a safety buffer. It prevents "revenge trading" or rapid-fire execution by checking the history book before every move. If a trade was just lost, it puts the system in a "waiting room" for a set amount of time, updating your screen to show you exactly when the system is allowed to start trading again.
//+------------------------------------------------------------------+
//| steinitz_test.mq4 |
//| Copyright © 2007, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"
extern int MagicNumber = 30000;
extern string hd = " --Delay time after last trade--";
extern bool useDelayAfterTrade = true;
extern int MinutesToDelay = 30;
extern string to="---Text Object Settings---";
extern int CommentTxtSize = 10;
extern color CommentColor = White;
int Comment1Y;
string Comment1Label;
datetime StopTime; // Time to wait after a trade is stopped out
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
DeleteExistingLabels();
SetupLabels();
ClearLabels();
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
ClearLabels();
DeleteExistingLabels();
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
int NumOrders = 0;
// Reset labels in case of disconnect from server
if (Comment1Y < 10)
{
SetupLabels();
ClearLabels();
DeleteExistingLabels();
SetupLabels();// Make sure label settings are OK
}
NumOrders = CalculateCurrentOrders(MagicNumber);
if(NumOrders == 0)
{
// Check if last trade stopped out
if (useDelayAfterTrade == 1)
{
StopTime = LastTradeStoppedOut();
if (TimeCurrent() < StopTime)
{
OutputComment1ToChart("No Trades Until : " + TimeToStr(StopTime,TIME_DATE|TIME_MINUTES));
return(0);
}
OutputComment1ToChart("Trading Resumed ");
}
// Your code for placing trades
}
else
{
RefreshRates();
// Your code to handle open trades
}
return(0);
}
//+------------------------------------------------------------------+
//| LastTradeStoppedOut |
//| Check History to see if last trade stopped out |
//| Return Time for next trade |
//+------------------------------------------------------------------+
datetime LastTradeStoppedOut()
{
int cnt, total;
bool Stopped;
datetime NextTime;
NextTime = 0;
total = OrdersHistoryTotal();
for (cnt = total - 1; cnt >= 0; cnt--)
{
OrderSelect (cnt, SELECT_BY_POS, MODE_HISTORY);
if(OrderSymbol()!=Symbol()) continue;
if (OrderMagicNumber() != MagicNumber) continue;
if (TimeCurrent() - OrderCloseTime() > MinutesToDelay*60) continue;
Stopped = true;
}
if (Stopped)
{
NextTime = OrderCloseTime() + MinutesToDelay*60;
}
return (NextTime);
}
int CalculateCurrentOrders(int MagicNumber)
{
int buys = 0, sells = 0, num = 0;
for(int i=0;i<OrdersTotal();i++)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()!= Symbol()) continue;
if (OrderMagicNumber()!= MagicNumber) continue;
if(OrderType() == OP_BUY) buys++;
if(OrderType() == OP_SELL) sells++;
}
num = buys + sells;
return(num);
}
void ClearLabels()
{
string mComment = " ";
OutputLabelToChart(Comment1Label, Comment1Y, CommentTxtSize, CommentColor, mComment, " ");
}
void DeleteExistingLabels()
{
int objLabels = ObjectsTotal(OBJ_LABEL);
string objName;
if (objLabels > 0)
{
for (int i = objLabels; i >= 0;i--)
{
objName = ObjectName(i);
if (StringFind(objName,Symbol() + "Comment1", 0) >= 0) { ObjectDelete(objName); continue; }
}
}
}
void SetupLabels()
{
Comment1Y = 12;
Comment1Label = Symbol() + "Comment1";
}
void OutputLabelToChart(string LabelName, int LabelY, int LabelTxtSize, color LabelColor, string LabelStr, string MarkString)
{
// string mtime=Month()+"/"+Day()+" "+Hour()+":"+Minute()+":"+Seconds()+" ";
if(ObjectFind(LabelName) != 0)
{
ObjectCreate(LabelName, OBJ_LABEL, 0, 0, 0);
ObjectSet(LabelName, OBJPROP_CORNER, 0);
ObjectSet(LabelName, OBJPROP_XDISTANCE, 20);
ObjectSet(LabelName, OBJPROP_YDISTANCE, LabelY);
}
ObjectSetText(LabelName, LabelStr, LabelTxtSize, "Arial Bold", LabelColor);
}
void OutputComment1ToChart(string mComment)
{
OutputLabelToChart(Comment1Label, Comment1Y, CommentTxtSize, CommentColor, mComment, "*");
}
//+------------------------------------------------------------------+
Comments