Useful features from KimIV - page 49

 
KimIV писал (а) >>

Examples of how to use the ExistOrders() function.

5. Check for any order with a setting time of 2 hours or more ago

ExistOrders("", -1, -1, TimeCurrent()-2*60*60);

Good evening, I'm a bit confused by this comment. I'm sitting here figuring it out ! Can't figure out how to formulate my condition correctly - "not earlier than 5 min" or "not later than 5 min" ! (It was clear to me before I started thinking about it!)

I need to delete a pending order if it has not triggered within a given time. For example, within 5 min after setting !

I have done so:

if (ExistOrders(NULL, OP_BUYSTOP, Magic,TimeCurrent()-5*60) >0) //ЕСЛИ ЕСТЬ ОРДЕР BUYSTOP > 5 min 
                 DeleteOrders(NULL, OP_BUYSTOP, Magic);
if (ExistOrders(NULL, OP_SELLSTOP, Magic,TimeCurrent()-5*60) >0) //ЕСЛИ ЕСТЬ ОРДЕР SELLSTOP > 5 min  
                 DeleteOrders(NULL, OP_SELLSTOP, Magic);

Is this correct? But it does not work in the tester. Orders are placed and immediately deleted.

Please advise how to write ExistOrders() function correctly ?

 
rid писал (а) >>
I'm a bit confused...

I seem to be confused as well. Let's get it together... :-)

The ot parameter (order placing time) has been introduced into the ExistOrders function to correctly handle errors 128, 142 and 143. The purpose of error handling is to exclude double (in practical cases, even triple) settings of the same order. To do this, the time of order sending is memorized and trading attempts are paused. After the pause, presence of the order with the set time after the memorized one is checked. If there is an order, the conclusion is made that the target has been reached (the order has been set) and the trading attempts are terminated. In other words, the time after which the order setting is checked for is passed to the ot parameter. Later = not earlier.

rid wrote (a) >>
I need to delete a pending order if it hasn't triggered within a given time. For example, within 5 minutes of setting !

The ot parameter of the ExistOrders function is not helpful here. It works in the opposite direction. It works in the direction of closer to the present. What you need to do is to move into the past. The expiration parameter of the OrderSend function (or the ex parameter of the SetOrder function) is great for this.

 

The ClosePosBySelect() function for the tester.

Executes the closure of one pre-selected position. This is a light version of the function of the same name, previously posted on page 13. Nothing extra. No extra features. In my practice, I have never had a position that was not closed in the tester. That is why there are no checks in this function. They are unnecessary in the tester.

//+----------------------------------------------------------------------------+
//|  Автор   : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                    |
//+----------------------------------------------------------------------------+
//|  Версия  : 13.06.2007                                                      |
//|  Описание: Закрытие одной предварительно выбранной позиции                 |
//+----------------------------------------------------------------------------+
void ClosePosBySelect() {
  double pp;

  if (OrderType()==OP_BUY) {
    pp=MarketInfo(OrderSymbol(), MODE_BID);
    OrderClose(OrderTicket(), OrderLots(), pp, Slippage, clCloseBuy);
  }
  if (OrderType()==OP_SELL) {
    pp=MarketInfo(OrderSymbol(), MODE_ASK);
    OrderClose(OrderTicket(), OrderLots(), pp, Slippage, clCloseSell);
  }
}

SZY. Example of use of function ClosePosBySelect() I will give later, together with function OpenPosition() for tester.

 

Hi all. To avoid having to dig through pages every time, I had to make the content branch by branch.

I've consolidated the functions of similar themes. Contents from 1 to 40 pages.

Those who wish may continue and add other pages and put them here.

Files:
 

Hello Igor, I need your help. I have decided to implement closing function in e-CloseByProfit EA similar to e-CloseByPercentProfit.

Everything works fine, expert advisor works properly and terminal closes. But when I reopen the terminal, it closes it right away.

Please help me to change the code to correct this problem.

//+----------------------------------------------------------------------------+
//| e-CloseByProfit.mq4 |
//| Kim Igor V. aka KimIV |
//| http://www.kimiv.ru |
//| |
//| 22.10.2006 The Expert Advisor closes all positions as soon as the specified |
//| profit level.
//| 20.06.2008 Fixed error in calculation of profit in points. |
//+----------------------------------------------------------------------------+
#property copyright "Kim Igor V. aka KimIV"
#property link "http://www.kimiv.ru"
#define MAGIC 20061022

//------- External parameters of the Expert Advisor ------------------------------------------
extern string _P_Expert = "---------- EA parameters";
extern bool CurSymbolOnly = false; // Only the current symbol
extern intProfit = 100; // TakeProfit
extern bool CloseTerminal = False; // Close terminal
extern bool ShowComment = True; // Show comment
extern int NumberAccount = 0; // Number of trading account
extern bool UseSound = True; // Use sound signal
extern string NameFileSound = "manycoin.wav"; // Name of sound file
extern int Slippage = 3; // Price slippage
extern inttern NumberOfTry = 5; // Number of attempts

//------- Global variables of the Expert Advisor --------------------------------------
color clCloseBuy = Blue; // colour clCloseSell = Red; // colour of the buy close symbol
color clCloseSell = Red; // colour of the Sell close flag
int CurProfit;

//------- Connection of external modules -------------------------------------------
#include <stdlib.mqh>.
#include <WinUser32.mqh>

//+----------------------------------------------------------------------------+
//| expert initialization function |
//+----------------------------------------------------------------------------+
void init() { if (!IsTesting()) Comment(""); }

//+----------------------------------------------------------------------------+
//| expert deinitialization function |
//+----------------------------------------------------------------------------+
void deinit() { if (!IsTesting()) Comment("); }

//+----------------------------------------------------------------------------+
//| expert start function |
//+----------------------------------------------------------------------------+
void start() {
if (!IsTesting()) {
if (NumberAccount>0 && NumberAccount!=AccountNumber()) {
Message("Trading in the account is FORBIDDEN" +AccountNumber());
return;
} else Comment(");
}

CloseByProfit();
if (ShowComment) {
Comment(IIFs(CurSymbolOnly, "CurSymbolOnly ","),
"Current Profit=",CurProfit," p."
"Close Profit=",TakeProfit," p."
);
}
}


//+----------------------------------------------------------------------------+
//| Author : Kim Igor V. aka KimIV, http://www.kimiv.ru |
//+----------------------------------------------------------------------------+
//| Version : 19.02.2008 |
//| Description : Closing of one pre-selected position |
//+----------------------------------------------------------------------------+
void ClosePosBySelect() {
bool fc;
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=closeBuy;
} else {
pp=pa; clClose=closeSell;
}
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("Invalid trade operation. Close ",GetNameOP(OrderType()));
}

//+----------------------------------------------------------------------------+
//| Author : Kim Igor V. aka KimIV, http://www.kimiv.ru |
//+----------------------------------------------------------------------------+
//| Version : 19.02.2008 |
//| Description : Closing positions at market price first profitable |
//+----------------------------------------------------------------------------+
//| Parameters: |
//| sy - name of the instrument (" - any symbol, |
//| NULL - current symbol) |
| //| op - operation (-1 - any position) |
//| mn - MagicNumber (-1 - any magik) |
//+----------------------------------------------------------------------------+
void ClosePosFirstProfit(string sy="", int op=-1, int mn=-1) {
int i, k=OrdersTotal();
if (sy=="0") sy=Symbol();

// First close profitable positions
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) {
if (OrderProfit()+OrderSwap()>0) ClosePosBySelect();
}
}
}
}
}
// then all the rest
k=OrdersTotal();
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();
}
}
}
}
}

//+----------------------------------------------------------------------------+
//| Closing all positions on profit. |
//+----------------------------------------------------------------------------+
void CloseByProfit() {
double pa, pb, pp;
int i, k=OrdersTotal(), pr=0;

for (i=0; i<k; i++) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (!CurSymbolOnly || OrderSymbol()==Symbol()) {
pa=MarketInfo(OrderSymbol(), MODE_ASK);
pb=MarketInfo(OrderSymbol(), MODE_BID);
pp=MarketInfo(OrderSymbol(), MODE_POINT);
if (pp==0) if (StringFind(OrderSymbol(), "JPY")<0) pp=0.0001; else pp=0.01;
if (OrderType()==OP_BUY) {
pr+=NormalizeDouble((pb-OrderOpenPrice())/pp, 0);
}
if (OrderType()==OP_SELL) {
pr+=NormalizeDouble((OrderOpenPrice()-pa)/pp, 0);
}
}
}
}
CurProfit=pr;
if (CurProfit>=TakeProfit) ClosePosFirstProfit();
if (CloseTerminal && !ExistPositions()) CloseTerminal();
}
//+----------------------------------------------------------------------------+
//| Close the trading terminal. |
//+----------------------------------------------------------------------------+
void CloseTerminal() {
Print("CloseTerminal() has triggered;)
int hwnd=WindowHandle(Symbol(), Period());
int hwnd_parent=0;

while(!IsStopped()) {
hwnd=GetParent(hwnd);
if (hwnd==0) break;
hwnd_parent=hwnd;
}
if (hwnd_parent!=0) PostMessageA(hwnd_parent, WM_CLOSE, 0, 0);
}

//+----------------------------------------------------------------------------+
//| Returns flag of existence |
//| Parameters: |
//| sy - name of the instrument (" - any symbol, |
//| NULL - current symbol) |
| //| op - operation (-1 - any position) |
//| mn - MagicNumber (-1 - any magik) |
//+----------------------------------------------------------------------------+
bool ExistPositions(string sy="", int op=-1, int mn=-1) {
int i, k=OrdersTotal();

if (StringLen(sy)==1 && StringGetChar(sy, 0)==48) 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) return(True);
}
}
}
}
}
return(False);
}
//+----------------------------------------------------------------------------+
//| Author : Kim Igor V. aka KimIV, http://www.kimiv.ru |
//+----------------------------------------------------------------------------+
//| Version : 01.09.2005 |
//| Description : Returns the name of trade operation |
//+----------------------------------------------------------------------------+
//| Parameters: ||
//| op - identifier of trade operation |
//+----------------------------------------------------------------------------+
string GetNameOP(int op) {
switch (op) {
case OP_BUY : return("Buy");
case OP_SELL : return("Sell");
case OP_BUYLIMIT : return("BuyLimit");
case OP_SELLLIMIT : return("SellLimit");
case OP_BUYSTOP : return("BuyStop");
case OP_SELLSTOP : return("SellStop");
default : return("Unknown Operation");
}
}

//+----------------------------------------------------------------------------+
//| Author : Kim Igor V. aka KimIV, http://www.kimiv.ru |
//+----------------------------------------------------------------------------+
//| Version : 01.02.2008 |
//| Description : It returns one of two values depending on the condition. |
//+----------------------------------------------------------------------------+
string IIFs(bool condition, string ifTrue, string ifFalse) {
if (condition) return(ifTrue); else return(ifFalse);
}

//+----------------------------------------------------------------------------+
//| Display a message in the comment and in the log file |
//+----------------------------------------------------------------------------+
void Message(string m) {
Comment(m);
if (StringLen(m)>0) Print(m);
}
//+----------------------------------------------------------------------------+

 
Vkorch писал (а) >>
Hello Igor, I need your help. I have decided to write the terminal close function in e-CloseByProfit EA similar to e-CloseByPercentProfit.

Everything works fine, the EA works, the terminal closes. But when I reopen the terminal, the Expert Advisor closes it immediately.
Help to change a code so, that to eliminate this lack.

Make it like this:

CurProfit=pr;
if (CurProfit>=TakeProfit) {
  ClosePosFirstProfit();
  if (CloseTerminal && !ExistPositions()) CloseTerminal();
}
 
KimIV писал(а) >>

Make it like this:

Thank you, Igor. Fixed it. But when compiling, I have an error

'(' - function definition unexpected C:\Program Files\MetaTrader - Alpari\experts\e-CloseByProfit.mq4 (180, 19)

What should I do?

 

Igor, could you please make a library of functions for working with orders and positions? The library has been developed and tested for more than 2 years, I attached the files, maybe some ideas will come in handy.

As for

OpenPosition("GBPJPY", OP_SELL, 0.1, pb+23*po, pb-44*po);

Maybe it would be better to call OpenPosition("GBPJPY", OP_SELL, 0.1, 23, 44);

а

double pa=MarketInfo("USDCAD", MODE_ASK);
double pb=MarketInfo("USDCAD", MODE_BID);
double po=MarketInfo(
"USDCAD", MODE_POINT);
and this insert 
  
 
double lot_min =MarketInfo(Symbol(),MODE_MINLOT)
; 
if(Lots<lot_min) return;

calculate inside the function, i.e. pass the sl value to and tp, and calculate and normalize everything correctly inside the function.


	          
 

Hello Igor!

If I have a 0.3 lot position open, I need to:

1.Close part of a 0.1 lot position.

Modify (move stop loss to another level)

2.1 More close part of the position 0.1 lot.

Modify (set stop loss to another level).

3.Close position.

One more question? When partial position is closed.

OrderClose(OrderTicket(),NormalizeDouble(OrderLots()/3,2),Ask,3,Violet);

I get error 131 (wrong volume). how can i correct it ?

Answer please for a newbie. can be in words.

.

 
Prival писал (а) >>
Igor, could you please make the functions work with orders and positions into a library?

No, it's not... In principle, it's already arranged as it should be... I'm not posting it because not all functions from this library have been published yet... there are a couple or three left that have appeared since this thread was started.

And I will think over the rest...