Download MetaTrader 5

Experts: OpenTime

To add comments, please log in or register
Need mobile version of MetaTrader 5? Download it and trade!
MetaQuotes Software Corp.
Moderator
181341
MetaQuotes Software Corp. 2009.05.18 06:04 

OpenTime:

The adviser in the time, given by the user, opens a market position, Buy, Sell or lock. As, it is possible to set closing of positions in the certain time, and Trailing of positions.

Author: IURII TOKMAN

MQL4 Comments
16319
MQL4 Comments 2009.06.29 18:14  

Satop,

attached this indicator to my chart, but it does not seem to work. I want to use it only to close out all open positions at a specific time. How do i do that?

Iurii Tokman
31200
Iurii Tokman 2009.06.29 20:17  
maurice2trade:

Satop,

attached this indicator to my chart, but it does not seem to work. I want to use it only to close out all open positions at a specific time. How do i do that?

To change a code and to make the new adviser.

MQL4 Comments
16319
MQL4 Comments 2009.11.07 10:29  

The original code has a lot of Russian language throughout. I used an online translator to create an English only code. You can replace the original with the following code to be more understandable.

//+------------------------------------------------------------------+

//| OpenTime.mq4 |

//| Yuriy Tokman |

//| yuriytokman@gmail.com |

//+------------------------------------------------------------------+

#property copyright "Yuriy Tokman"

#property link "yuriytokman@gmail.com"


extern string _____1_____ = "Adjustments of closing of a position";

extern bool TimeClose = True; // True allows Time of closing of a position

extern string CloseTime = "22:59"; // Time of closing of a position

extern bool Trailing = False; // True allows Trailing Stop operation

extern double TrailingStop = 30; // The pip size of the trail

extern int TrailingStep = 3; // Pip movement for resetting of a trail


extern string _____2_____ = "Adjustments of opening of a position";

extern string TimeTrade = "10:00"; // Time of opening of a position

extern int Duration = 0; // Duration in seconds. Used to add seconds to time closing/opening

extern bool Sell = True; // True-Sell

extern bool Buy = False; // True-Buy

extern double Lots = 0.1; // The Lot size

extern int StopLoss = 500; // The size of stop in pips

extern int TakeProfit = 100; // The size of profit in pips


extern string _____3_____ = "Parameters of the adviser";

extern int MagicNumber = 89888; //Magic number used by advisor

int NumberAccount = 0; // Number of the trading account

bool UseSound = True; // True uses a sound signal, False doesn't

string NameFileSound = "expert.wav"; // The name of a sound file

bool ShowComment = True; // at the top of charts

bool MarketWatch = False; // False uses StopLoss and TakeProfit values, True the values = 0

extern int Slippage = 0; // number of pips from the price to allow a trade

extern int NumberOfTry = 5; // number of trading attempts

//------- Global variables of the adviser -------------------------------------+

bool gbDisabled = False; // True blocks operation of the adviser, False allows operation

bool gbNoInit = False; // True blocks initialization, False allows operation

color clOpenBuy = LightBlue; // Color of "marker line" of opening of purchase

color clOpenSell = LightCoral; // Color of "marker line" of opening of sale


//------- Connection of external modules --------------------------------------+

#include <stdlib.mqh> // Standard library of MT4



//+----------------------------------------------------------------------------+

//| |

//| THE PRE-ASSIGNED FUNCTIONS |

//| |

//+----------------------------------------------------------------------------+

//| Function of initialization |

//+----------------------------------------------------------------------------+

void init() {

gbNoInit=False;

if (!IsTradeAllowed()) {

Message("For normal work of the adviser it is necessary \n"+

"To allow to trade to the adviser");

gbNoInit=True; return;

}

if (!IsLibrariesAllowed()) {

Message("For normal work of the adviser it is necessary \n"+

"To resolve import external experts");

gbNoInit=True; return;

}

if (!IsTesting()) {

if (IsExpertEnabled()) Message("The adviser will be started by a following tic");

else Message("The button is wrung out \"To resolve start of advisers\"");

}

}


//+----------------------------------------------------------------------------+

//| Function of expert operation |

//+----------------------------------------------------------------------------+

void deinit() { if (!IsTesting()) Comment(""); }


//+----------------------------------------------------------------------------+

//| expert start function |

//+----------------------------------------------------------------------------+

void start() {

double sl=0, tp=0;

if (gbDisabled) {

Message("Critical error! The adviser is stopped!"); return;

}

if (gbNoInit) {

Message("The adviser was not possible to initialize!"); return;

}

if (!IsTesting()) {

if (NumberAccount>0 && NumberAccount!=AccountNumber()) {

Comment("Trade on the account: "+AccountNumber()+" IT IS FORBIDDEN!");

return;

} else Comment("");

if (ShowComment) {

string st="CurrentTime="+TimeToStr(TimeCurrent(), TIME_MINUTES)

+" TimeTrade="+TimeTrade

+IIFs(TimeClose," CloseTime="+CloseTime, "")

+" Trade="

+IIFs(Sell," Sell", "")

+IIFs(Buy," Buy", "")

+" Lots="+DoubleToStr(Lots, 1)

+IIFs(MarketWatch, " MarketWatch", "")

;

Comment(st);

} else Comment("");

}

//----------------------------------------------------------------------------------+

if(TimeClose)

{

if (TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+CloseTime)

&& TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+CloseTime)+Duration)

ClosePositions(NULL,-1,MagicNumber);

}

//----------------------------------------------------------------------------------+

if(Trailing)SimpleTrailing(NULL, -1,MagicNumber);

//----------------------------------------------------------------------------------+

if (TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTrade)

&& TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTrade)+Duration)

{

if (!ExistPositions("", OP_BUY, MagicNumber)&&Buy)

{

if (StopLoss >0) sl=Ask-StopLoss*Point; else sl=0;

if (TakeProfit>0) tp=Ask+TakeProfit*Point; else tp=0;

OpenPosition(NULL, OP_BUY, Lots, sl, tp, MagicNumber);

}

if (!ExistPositions("", OP_SELL, MagicNumber)&&Sell)

{

if (StopLoss >0) sl=Bid+StopLoss*Point; else sl=0;

if (TakeProfit>0) tp=Bid-TakeProfit*Point; else tp=0;

OpenPosition(NULL, OP_SELL, Lots, sl, tp, MagicNumber);

}

}

}

//+----------------------------------------------------------------------------+

//| |

//| THE USER FUNCTIONS |

//| |

//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 06.03.2008 |

//| The description: Returns a flag of creation of a trade |

//+----------------------------------------------------------------------------+

//| Parameters: |

//| sy - The name of the tool ("" - Any symbol, |

//| NULL - Current symbol) |

//| op - Operation (-1 - Any buy or sell trade) |

//| mn - MagicNumber (-1 - Any assigned number) |

//| ot - Time of opening ( 0 - Any time of opening) |

//+----------------------------------------------------------------------------+

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);

}


//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 01.09.2005 |

//| The description : Returns the name of trading operation |

//+----------------------------------------------------------------------------+

//| Parameters: |

//| op - The trading operation |

//+----------------------------------------------------------------------------+

string GetNameOP(int op) {

switch (op) {

case OP_BUY : return("Buy");

case OP_SELL : return("Sell");

case OP_BUYLIMIT : return("Buy Limit");

case OP_SELLLIMIT: return("Sell Limit");

case OP_BUYSTOP : return("Buy Stop");

case OP_SELLSTOP : return("Sell Stop");

default : return("Unknown Operation");

}

}


//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 01.09.2005 |

//| The description: Returns the name for chart period |

//+----------------------------------------------------------------------------+

//| Parameters: |

//| TimeFrame - named period (0 - Current period) |

//+----------------------------------------------------------------------------+

string GetNameTF(int TimeFrame=0) {

if (TimeFrame==0) TimeFrame=Period();

switch (TimeFrame) {

case PERIOD_M1: return("M1");

case PERIOD_M5: return("M5");

case PERIOD_M15: return("M15");

case PERIOD_M30: return("M30");

case PERIOD_H1: return("H1");

case PERIOD_H4: return("H4");

case PERIOD_D1: return("Daily");

case PERIOD_W1: return("Weekly");

case PERIOD_MN1: return("Monthly");

default: return("UnknownPeriod");

}

}


//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 01.02.2008 |

//| The description: Returns one of two values from a condition. |

//+----------------------------------------------------------------------------+

string IIFs(bool condition, string ifTrue, string ifFalse) {

if (condition) return(ifTrue); else return(ifFalse);

}


//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 01.09.2005 |

//| The description: conclusion of the message displayed on chart and Print |

//+----------------------------------------------------------------------------+

//| Parameters: |

//| m - The text of the message |

//+----------------------------------------------------------------------------+

void Message(string m) {

Comment(m);

if (StringLen(m)>0) Print(m);

}


//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 28.11.2006 |

//| The description: modifying an open Order. |

//+----------------------------------------------------------------------------+

//| Parameters: |

//| pp - The price of the order |

//| sl - Price level of stop |

//| tp - price level of profit |

//| ex - Date of the expiration |

//+----------------------------------------------------------------------------+

void ModifyOrder(double pp=-1, double sl=0, double tp=0, datetime ex=0) {

bool fm;

color cl;

double op, pa, pb, os, ot;

int dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er, it;


if (pp<=0) pp=OrderOpenPrice();

if (sl<0 ) sl=OrderStopLoss();

if (tp<0 ) tp=OrderTakeProfit();

pp=NormalizeDouble(pp, dg);

sl=NormalizeDouble(sl, dg);

tp=NormalizeDouble(tp, dg);

op=NormalizeDouble(OrderOpenPrice(), dg);

os=NormalizeDouble(OrderStopLoss(), dg);

ot=NormalizeDouble(OrderTakeProfit(), dg);


if (pp!=op || sl!=os || tp!=ot) {

for (it=1; it<=NumberOfTry; it++) {

if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;

while (!IsTradeAllowed()) Sleep(5000);

RefreshRates();

fm=OrderModify(OrderTicket(), pp, sl, tp, ex, cl);

if (fm) {

if (UseSound) PlaySound(NameFileSound); break;

} else {

er=GetLastError();

pa=MarketInfo(OrderSymbol(), MODE_ASK);

pb=MarketInfo(OrderSymbol(), MODE_BID);

Print("Error(",er,") modifying order: ",ErrorDescription(er),", try ",it);

Print("Ask=",pa," Bid=",pb," sy=",OrderSymbol(),

" op="+GetNameOP(OrderType())," pp=",pp," sl=",sl," tp=",tp);

Sleep(1000*10);

}

}

}

}


//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 10.04.2008 |

//| The description: Opens a trade at the market pric |

//+----------------------------------------------------------------------------+

//| Parameters: |

//| sy - The name of the tool (NULL Or " " - a current symbol) |

//| op - Operation |

//| ll - lot |

//| sl - stop loss level |

//| tp - take profit target |

//| mn - MagicNumber |

//+----------------------------------------------------------------------------+

void OpenPosition(string sy, int op, double ll, double sl=0, double tp=0, int mn=0) {

color clOpen;

datetime ot;

double pp, pa, pb;

int dg, err, it, ticket=0;

string lsComm=WindowExpertName()+" "+GetNameTF(Period());


if (sy=="" || sy=="0") sy=Symbol();

if (op==OP_BUY) clOpen=clOpenBuy; else clOpen=clOpenSell;

for (it=1; it<=NumberOfTry; it++) {

if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) {

Print("OpenPosition(): Stop of work of function");

break;

}

while (!IsTradeAllowed()) Sleep(5000);

RefreshRates();

dg=MarketInfo(sy, MODE_DIGITS);

pa=MarketInfo(sy, MODE_ASK);

pb=MarketInfo(sy, MODE_BID);

if (op==OP_BUY) pp=pa; else pp=pb;

pp=NormalizeDouble(pp, dg);

ot=TimeCurrent();

if (MarketWatch)

ticket=OrderSend(sy, op, ll, pp, Slippage, 0, 0, lsComm, mn, 0, clOpen);

else

ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, lsComm, mn, 0, clOpen);

if (ticket>0) {

if (UseSound) PlaySound(NameFileSound); break;

} else {

err=GetLastError();

if (pa==0 && pb==0) Message("Check up in the Review of the market presence of a symbol "+sy);

// Conclusion of the message on an error

Print("Error(",err,") opening position: ",ErrorDescription(err),", try ",it);

Print("Ask=",pa," Bid=",pb," sy=",sy," ll=",ll," op=",GetNameOP(op),

" pp=",pp," sl=",sl," tp=",tp," mn=",mn);

// Blocking of work of the adviser

if (err==2 || err==64 || err==65 || err==133) {

gbDisabled=True; break;

}

// Length of pause

if (err==4 || err==131 || err==132) {

Sleep(1000*300); break;

}

if (err==128 || err==142 || err==143) {

Sleep(1000*66.666);

if (ExistPositions(sy, op, mn, ot)) {

if (UseSound) PlaySound(NameFileSound); break;

}

}

if (err==140 || err==148 || err==4110 || err==4111) break;

if (err==141) Sleep(1000*100);

if (err==145) Sleep(1000*17);

if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);

if (err!=135) Sleep(1000*7.7);

}

}

if (MarketWatch && ticket>0 && (sl>0 || tp>0)) {

if (OrderSelect(ticket, SELECT_BY_TICKET)) ModifyOrder(-1, sl, tp);

}

}

//+----------------------------------------------------------------------------+

//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 19.02.2008 |

//| The description: Closing of positions at the market price |

//+----------------------------------------------------------------------------+

//| Parameters: |

//| sy - The name of the tool ("" - Any symbol, |

//| NULL - Current symbol) |

//| op - Operation (-1 - Any position) |

//| mn - MagicNumber (-1 - any assigned number) |

//+----------------------------------------------------------------------------+

void ClosePositions(string sy="", int op=-1, int mn=-1) {//ClosePositions(NULL,-1,MagicNumber)

int i, k=OrdersTotal();


if (sy=="0") sy=Symbol();

for (i=k-1; i>=0; i--) {

if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {

if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {

if (OrderType()==OP_BUY || OrderType()==OP_SELL) {

if (mn<0 || OrderMagicNumber()==mn) ClosePosBySelect();

}

}

}

}

}

//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 19.02.2008 |

//| The description: Closing of one selected position |

//+----------------------------------------------------------------------------+

void ClosePosBySelect() {

bool fc;

color clClose;

double ll, pa, pb, pp;

int err, it;


if (OrderType()==OP_BUY || OrderType()==OP_SELL) {

for (it=1; it<=NumberOfTry; it++) {

if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;

while (!IsTradeAllowed()) Sleep(5000);

RefreshRates();

pa=MarketInfo(OrderSymbol(), MODE_ASK);

pb=MarketInfo(OrderSymbol(), MODE_BID);

if (OrderType()==OP_BUY) {

pp=pb; clClose=Green;

} else {

pp=pa; clClose=Red;

}

ll=OrderLots();

fc=OrderClose(OrderTicket(), ll, pp, Slippage, clClose);

if (fc) {

if (UseSound) PlaySound(NameFileSound); break;

} else {

err=GetLastError();

if (err==146) while (IsTradeContextBusy()) Sleep(1000*11);

Print("Error(",err,") Close ",GetNameOP(OrderType())," ",

ErrorDescription(err),", try ",it);

Print(OrderTicket()," Ask=",pa," Bid=",pb," pp=",pp);

Print("sy=",OrderSymbol()," ll=",ll," sl=",OrderStopLoss(),

" tp=",OrderTakeProfit()," mn=",OrderMagicNumber());

Sleep(1000*5);

}

}

} else Print("Incorrect trading operation. Close ",GetNameOP(OrderType()));

}

//+----------------------------------------------------------------------------+

//| The author : Kim Igor of Century aka KimIV, http://www.kimiv.ru |

//+----------------------------------------------------------------------------+

//| The version : 11.09.2008 |

//| The description: Support of positions by a simple trail |

//+----------------------------------------------------------------------------+

//| Parameters: |

//| sy - The name of the tool (" " - any symbol, |

//| NULL -Current symbol) |

//| op - operation ( -1 - Any position) |

//| mn - MagicNumber ( -1 - any assigned number) |

//+----------------------------------------------------------------------------+

void SimpleTrailing(string sy="", int op=-1, int mn=-1) {

double po, pp;

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=="") && (op<0 || OrderType()==op)) {

po=MarketInfo(OrderSymbol(), MODE_POINT);

if (mn<0 || OrderMagicNumber()==mn) {

if (OrderType()==OP_BUY) {

pp=MarketInfo(OrderSymbol(), MODE_BID);

if ( pp-OrderOpenPrice()>TrailingStop*po) {

if (OrderStopLoss()<pp-(TrailingStop+TrailingStep-1)*po) {

ModifyOrder(-1, pp-TrailingStop*po, -1);

}

}

}

if (OrderType()==OP_SELL) {

pp=MarketInfo(OrderSymbol(), MODE_ASK);

if ( OrderOpenPrice()-pp>TrailingStop*po) {

if (OrderStopLoss()>pp+(TrailingStop+TrailingStep-1)*po || OrderStopLoss()==0) {

ModifyOrder(-1, pp+TrailingStop*po, -1);

}

}

}

}

}

}

}

}


To add comments, please log in or register