This script is an automated trading robot designed to execute specific buy and sell orders based on a strict time-based schedule. Rather than analyzing complex market trends or technical indicators, the logic operates as a "set-and-forget" system that triggers trades at predetermined hours and minutes during the trading day.
Core Operational Logic
The script monitors the current time and manages two distinct sets of trading rules (identified by unique internal markers):
1. The Sell Sequence:
- Entry Trigger: The robot looks for a specific moment early in the day (at 04:00). If no position is currently open, it automatically initiates a Sell order. This order includes built-in safety nets: a "Stop Loss" to limit potential losses and a "Take Profit" to secure gains.
- Exit Trigger: The robot monitors the open position and will automatically close it at a specific late-night time (between 05:55 and 06:00).
2. The Buy Sequence:
- Entry Trigger: The robot looks for a specific moment later in the day (at 10:00). If no position is currently open, it automatically initiates a Buy order with its own set of Stop Loss and Take Profit parameters.
- Exit Trigger: The robot monitors this position and will automatically close it at a specific midday time (between 12:55 and 13:00).
Key Functional Features
- Automated Order Management: The script handles the heavy lifting of opening and closing trades. It calculates the correct pricing for your "Stop Loss" and "Take Profit" levels automatically, ensuring they meet the minimum requirements set by your broker.
- Smart Error Handling: One of the script's primary features is its ability to deal with common trading obstacles. If an order fails to open due to temporary issues (such as a price change or a busy server), the robot will automatically retry the action several times before giving up. It also provides specific alerts to notify you if there are critical issues, such as a locked account or disabled trading permissions.
- Position Monitoring: The script is designed to be "aware" of what it is doing. It constantly checks your current open positions to ensure it doesn't create duplicate trades or try to close orders that aren't currently active.
- Safety Constraints: It includes a built-in safety check to ensure that the distance between your entry price and your stop-loss/take-profit levels is never smaller than what your broker allows, preventing the order from being rejected by the server.
Summary for the User
Essentially, this tool acts as a scheduled executor. You provide the lot size (trade volume), and the script follows a rigid timeline: it sells at 4:00 AM, buys at 10:00 AM, and closes those respective positions at their designated times. It is built to handle the technical "noise" of the market—like price fluctuations and server delays—so that your trades are executed as planned without manual intervention.
//+------------------------------------------------------------------+
//| jpytest.mq4 |
//| Copyright © 2009, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"
extern double LotSize=0.1; //Ðàçìåð ëîòà äëÿ òîðãîâëè
int MagicNumber;
int OpenedOrder;
double ExtendPoint=1; //äëÿ ÄÖ ñ äîïîëíèòåëüíûì çíàêîì ExtendPoint=10
int init()
{
return(0);
}
int deinit()
{
return(0);
}
int start()
{
MagicNumber=900;
datetime curtime=iTime(NULL,PERIOD_M1,0);
if (ExistPositions(Symbol(),-1 , MagicNumber)) {
if ((TimeHour(curtime)==5 && TimeMinute(curtime)==55) || (TimeHour(curtime)==6 && TimeMinute(curtime)==0))
OrderClose(OpenedOrder,LotSize,Ask,3);
}
else {
if (TimeHour(curtime)==4 && TimeMinute(curtime)==0)
iSetOrder(Symbol(), OP_SELL, 20*ExtendPoint,10000);
}
MagicNumber=901;
if (ExistPositions(Symbol(),-1 , MagicNumber)) {
if ((TimeHour(curtime)==12 && TimeMinute(curtime)==55) || (TimeHour(curtime)==13 && TimeMinute(curtime)==0))
OrderClose(OpenedOrder,LotSize,Bid,3);
}
else {
if (TimeHour(curtime)==10 && TimeMinute(curtime)==0)
iSetOrder(Symbol(), OP_BUY, 15*ExtendPoint,10000);
}
return(0);
}
bool iSetOrder(string symbol, int cmd, double stoploss, double takeprofit, string comment=""){
int Dist_SL =stoploss; // Çàäàííûé SL (pt)
int Dist_TP =takeprofit; // Çàäàííûé TP (pt)
double Prots=0.10; // Ïðîöåíò ñâîá. ñð.
string Symb=symbol; // Ôèíàíñ. èíñòðóìåíò
double i=0;
double SL;
double TP;
color arr;
double price;
//--------------------------------------------------------------- 2 --
while(i<5) // Öèêë îòêðûòèÿ îðä.
{
if (cmd==OP_BUY) {
SL=Bid - New_Stop(stoploss)*Point; // Âû÷èñëåíèå SL îòêð.
TP=Bid + New_Stop(takeprofit)*Point; // Âû÷èñëåíèå TP îòêð.
Alert("Ïîïûòêà îòêðûòü Buy. Îæèäàíèå îòâåòà..");
price=Ask;
arr=Maroon;
} else
{
SL=Ask + New_Stop(stoploss)*Point; // Âû÷èñëåíèå SL îòêð.
TP=Ask - New_Stop(takeprofit)*Point; // Âû÷èñëåíèå TP îòêð.
price=Bid;
arr=Green;
}//if else
if (stoploss==0) SL=0;
if (takeprofit==0) TP=0;
int ticket=OrderSend(symbol,cmd,LotSize,price,3,SL,TP,comment,MagicNumber,0,arr);//Îòêðûòèå Buy
//--------------------------------------------------------- 7 --
if (ticket>0) // Ïîëó÷èëîñü :)
{
Alert ("Îòêðûò îðäåð Buy ",ticket);
OpenedOrder=ticket;
return(True);
break; // Âûõîä èç öèêëà
}
//--------------------------------------------------------- 8 --
int Error=GetLastError(); // Íå ïîëó÷èëîñü :(
switch(Error) // Ïðåîäîëèìûå îøèáêè
{
case 135:Alert("Öåíà èçìåíèëàñü. Ïðîáóåì åù¸ ðàç..");
RefreshRates(); // Îáíîâèì äàííûå
i=i+1;
continue; // Íà ñëåä. èòåðàöèþ
case 136:Alert("Íåò öåí. Æä¸ì íîâûé òèê..");
while(RefreshRates()==false) // Äî íîâîãî òèêà
Sleep(1); // Çàäåðæêà â öèêëå
continue; // Íà ñëåä. èòåðàöèþ
case 146:Alert("Ïîäñèñòåìà òîðãîâëè çàíÿòà. Ïðîáóåì åù¸..");
Sleep(500); // Ïðîñòîå ðåøåíèå
i=i+0.3;
RefreshRates(); // Îáíîâèì äàííûå
continue; // Íà ñëåä. èòåðàöèþ
}
switch(Error) // Êðèòè÷åñêèå îøèáêè
{
case 2 : Alert("Îáùàÿ îøèáêà.");
break; // Âûõîä èç switch
case 5 : Alert("Ñòàðàÿ âåðñèÿ êëèåíòñêîãî òåðìèíàëà.");
break; // Âûõîä èç switch
case 64: Alert("Ñ÷åò çàáëîêèðîâàí.");
break; // Âûõîä èç switch
case 133:Alert("Òîðãîâëÿ çàïðåùåíà");
break; // Âûõîä èç switch
default: Alert("Âîçíèêëà îøèáêà ",Error);// Äðóãèå âàðèàíòû
}
break; // Âûõîä èç öèêëà
}
//--------------------------------------------------------------- 9 --
return(False);
}
int New_Stop(int Parametr) // Ïðîâåðêà ñòîï-ïðèê.
{
int Min_Dist=MarketInfo(Symbol(),MODE_STOPLEVEL);// Ìèíèì. äèñòàíöèÿ
if (Parametr < Min_Dist) // Åñëè ìåíüøå äîïóñò.
{
Parametr=Min_Dist; // Óñòàíîâèì äîïóñò.
Alert("Óâåëè÷åíà äèñòàíöèÿ ñòîï-ïðèêàçà.");
}
return(Parametr); // Âîçâðàò çíà÷åíèÿ
}
bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=0) {
int i, k=OrdersTotal();
if (sy=="0") sy=Symbol();
for (i=0; i<k; i++) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderSymbol()==sy || sy=="") {
if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
if (op<0 || OrderType()==op) {
if (mn<0 || OrderMagicNumber()==mn) {
if (ot<=OrderOpenTime()) return(True);
}
}
}
}
}
}
return(False);
}
Comments