Orders Execution
Miscellaneous
0
Views
0
Downloads
0
Favorites
Av02
// Òîðãîâàÿ ñèñòåìà: Av
// Âåðñèÿ: 0.2
// Äàòà ïîñëåäíåé ìîäèôèêàöèè: 25.08.2010
// Àâòîð: Ìóðàä Èñìàéëîâ
// Ïî÷òà: wmlab@hotmail.com
#property copyright "Copyright © 2010, Murad Ismayilov"
#property link "http://www.wmlab.org/"
#include <stdlib.mqh>
#include <stderror.mqh>
//
// Âíåøíèå ïåðåìåííûå (îïòèìèçèðóþòñÿ)
//
extern double Lots = 0.1; // Ñòàðòîâûé ëîò
extern int MaxLoss = 75; // Ìàêñèìàëüíî äîïóñòèìàÿ ïðîñàäêà â ïðîöåíòàõ îò áàëàíñà
extern int StopLossPips = 30; // Ñòîïëîññ â ïèïñàõ
extern int TakeProfitPips = 90; // Òåéêïðîôèò â ïèïñàõ
extern double KMartin = 0.02; // Êîýô. íàðàùèâàíèÿ ëîòà
// Ïîÿñíåíèå: ïðè KMartin = 0.01 ëîòû áóäóò 0.10, 0.11, 0.22, 0.44, 0.88
// ïðè KMartin = 0.02 ëîòû áóäóò 0.10, 0.12, 0.24, 0.48, 0.96
// ïðè KMartin = 0.05 ëîòû áóäóò 0.10, 0.15, 0.30, 0.60, 1.20
// ïðè KMartin = 0.10 ëîòû áóäóò 0.10, 0.20, 0.40, 0.80, 1.60
//
// Ãëîáàëüíûå ïåðåìåííûå
//
bool IsExpertFailed = false;
bool IsExpertStopped = false;
int MagicNumber = 171100;
int NumberOfTry = 5;
int SlipPips = 3;
bool UseSound = true;
color ColorBuy = Blue;
color ColorSell = Red;
//+------------------------------------------------------------------+
//| Ñòàðò ðîáîòà |
//+------------------------------------------------------------------+
int init()
{
IsExpertStopped = false;
if (!IsTradeAllowed())
{
Comment("Íåîáõîäèìî ðàçðåøèòü ñîâåòíèêó òîðãîâàòü");
IsExpertStopped = true;
return (0);
}
if (!IsTesting())
{
if (IsExpertEnabled())
{
Comment("Ñîâåòíèê áóäåò çàïóùåí ñëåäóþùèì òèêîì");
}
else
{
Comment("Îòæàòà êíîïêà \"Ðàçðåøèòü çàïóñê ñîâåòíèêîâ\"");
}
}
// Èíèöèàëèçèðóåì ãåíåðàòîð
MathSrand(TimeLocal());
// Ïåðåñ÷åòû ïóíêòîâ äëÿ ïÿòèçíà÷íîãî ÄÖ
if ((Digits == 3) || (Digits == 5))
{
SlipPips = SlipPips * 10;
StopLossPips = StopLossPips * 10;
TakeProfitPips = TakeProfitPips * 10;
}
return (0);
}
//+------------------------------------------------------------------+
//| Çàâåðøåíèå ðàáîòû ðîáîòà |
//+------------------------------------------------------------------+
int deinit()
{
return (0);
}
//+------------------------------------------------------------------+
//| Îáðàáîòêà ñèãíàëà |
//+------------------------------------------------------------------+
int start()
{
if (IsExpertStopped)
{
Comment("Íå óäàëîñü èíèöèàëèçèðîâàòü ñîâåòíèê!");
return (0);
}
if (IsExpertFailed)
{
Comment("Êðèòè÷åñêàÿ îøèáêà! Ñîâåòíèê îñòàíîâëåí.");
return (0);
}
// Èùåì íàø îðäåð
int orderType;
for (int orderIndex = (OrdersTotal() - 1); orderIndex >= 0; orderIndex--)
{
if (!OrderSelect(orderIndex, SELECT_BY_POS))
{
continue;
}
if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != MagicNumber))
{
continue;
}
orderType = OrderType();
if ((orderType != OP_BUY) && (orderType != OP_SELL))
{
continue;
}
double orderLots = OrderLots();
double orderProfit = OrderProfit() + OrderSwap();
// Ïðîâåðêà íà ïðåäåëüíóþ ïðîñàäêó
double loss = - ((orderProfit * 100.0) / AccountBalance());
if (loss > MaxLoss)
{
Print ("MaxLoss");
CloseAllOrders(MagicNumber);
IsExpertFailed = true;
return (0);
}
string messageLoss = "";
if (orderProfit < 0.0)
{
messageLoss = "Ïðîñàäêà = " + DoubleToStr(loss, 1) + "% (ìàêñ. " + MaxLoss + "%)";
}
// Âûâîä òåêóùåãî ñîñòîÿíèÿ
Comment("Ïðèáûëü = ", DoubleToStr(orderProfit, 1), " (ëîò ", orderLots, ") ", messageLoss);
return (0);
}
Comment ("");
// Ïîèñê ïîñëåäíåãî îòðàáîòàâøåãî îðäåðà
for (orderIndex = (OrdersHistoryTotal() - 1); orderIndex >= 0; orderIndex--)
{
if (!OrderSelect(orderIndex, SELECT_BY_POS, MODE_HISTORY))
{
continue;
}
if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != MagicNumber))
{
continue;
}
// Ïðèíèìàåì â ðàñ÷åò òîëüêî îðäåð, çàêðûòûé íåäàâíî
if (OrderCloseTime() >= iTime(NULL, 0, 1))
{
int lastType = OrderType();
double lastLots = OrderLots();
double lastProfit = OrderProfit() + OrderSwap();
Print ("lastProfit = ", NormalizeDouble(lastProfit, 1));
// Àíàëèç òîëüêî ÷òî çàêðûâøåãîñÿ îðäåðà
if (lastProfit > 0.0)
{
// Îðäåð çàêðûëñÿ ñ ïðèáûëüþ, îòêðûâàåìñÿ ñòàðòîâûì ëîòîì â ñëó÷àéíîì íàïðàâëåíèè
if (MathRand() > 16384)
{
WmOrderSend(Symbol(), OP_BUY, Lots, Ask, NormalizeDouble(Bid - (StopLossPips * Point), Digits), NormalizeDouble(Ask + (TakeProfitPips * Point), Digits), "", MagicNumber);
}
else
{
WmOrderSend(Symbol(), OP_SELL, Lots, Bid, NormalizeDouble(Ask + (StopLossPips * Point), Digits), NormalizeDouble(Bid - (TakeProfitPips * Point), Digits), "", MagicNumber);
}
}
else
{
// Îðäåð çàêðûëñÿ ñ óáûòêîì, ñ÷èòàåì íîâûé lots è îòêðûâàåìñÿ â ñëó÷àéíîì íàïðàâëåíèè
// TP = SL
double lots;
if (lastLots == Lots)
{
lots = Lots + KMartin;
}
else
{
lots = lastLots * 2.0;
}
// Îïðåäåëÿåì íîìåð ðàçâîðîòà
int iteration = 1;
double maxLots = MarketInfo(Symbol(), MODE_MAXLOT);
double testLots = Lots + KMartin;
while ((testLots < lots) && (testLots < maxLots))
{
iteration++;
testLots = testLots * 2.0;
}
lots = NormalizeLots(lots);
if (lastType == OP_BUY)
{
WmOrderSend(Symbol(), OP_SELL, lots, Bid, NormalizeDouble(Ask + (StopLossPips * Point), Digits), NormalizeDouble(Bid - (StopLossPips * Point), Digits), "Iter " + iteration, MagicNumber);
}
else if (lastType == OP_SELL)
{
WmOrderSend(Symbol(), OP_BUY, lots, Ask, NormalizeDouble(Bid - (StopLossPips * Point), Digits), NormalizeDouble(Ask + (StopLossPips * Point), Digits), "Iter " + iteration, MagicNumber);
}
}
return (0);
}
// Íàéäåí çàêðûòûé îðäåð, íî îí ñòàðûé
break;
}
// Ñâåæèõ çàêðûòûõ îðäåðîâ íå áûëî, îòêðûâàåìñÿ ñòàðòîâûì ëîòîì â ñëó÷àéíîì íàïðàâëåíèè
if (MathRand() > 16384)
{
WmOrderSend(Symbol(), OP_BUY, Lots, Ask, NormalizeDouble(Bid - (StopLossPips * Point), Digits), NormalizeDouble(Ask + (TakeProfitPips * Point), Digits), "", MagicNumber);
}
else
{
WmOrderSend(Symbol(), OP_SELL, Lots, Bid, NormalizeDouble(Ask + (StopLossPips * Point), Digits), NormalizeDouble(Bid - (TakeProfitPips * Point), Digits), "", MagicNumber);
}
return(0);
}
//+------------------------------------------------------------------+
//| Íîðìàëèçàöèÿ ëîòà |
//+------------------------------------------------------------------+
double NormalizeLots(double lot)
{
double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
double lots = NormalizeDouble(lot / lotStep, 0) * lotStep;
lots = MathMax(lots, MarketInfo(Symbol(), MODE_MINLOT));
lots = MathMin(lots, MarketInfo(Symbol(), MODE_MAXLOT));
return (lots);
}
//+------------------------------------------------------------------+
//| Óñòàíîâêà îðäåðà |
//+------------------------------------------------------------------+
void WmOrderSend(string symbol, int cmd, double volume, double price, double stoploss, double takeprofit, string comment, int magic, datetime expiration = 0)
{
color clr;
datetime opentime;
int ticket;
int error;
comment = WindowExpertName() + " " + GetNameTF(Period()) + " " + comment;
int msl = MarketInfo(symbol, MODE_STOPLEVEL);
clr = CLR_NONE;
if (cmd == OP_BUY)
{
clr = ColorBuy;
}
else if (cmd == OP_SELL)
{
clr = ColorSell;
}
if ((expiration > 0) && (expiration < TimeCurrent()))
{
expiration = 0;
}
for (int try = 1; try <= NumberOfTry; try++)
{
if (!IsTesting() && (!IsExpertEnabled() || IsStopped()))
{
break;
}
while (!IsTradeAllowed())
{
Sleep(5000);
}
RefreshRates();
opentime = TimeCurrent();
ticket = OrderSend(symbol, cmd, volume, price, SlipPips, stoploss, takeprofit, comment, magic, expiration, clr);
if (ticket > 0)
{
if (UseSound)
{
PlaySound("ok.wav");
break;
}
}
else
{
error = GetLastError();
if (error == ERR_TRADE_TIMEOUT)
{
Sleep(1000*66);
if (ExistOrders(symbol, cmd, magic, opentime))
{
if (UseSound)
{
PlaySound("ok.wav");
break;
}
}
}
Print("Error(", error, ") set order: ", ErrorDescription(error), ", try ", try);
continue;
}
Print("Error(", error, ") set order: ", ErrorDescription(error), ", try ", try);
Print("Ask=", Ask, " Bid=", Bid, " symbol=", symbol, " volume=", volume, " cmd=", GetNameOP(cmd), " price=", price, " stoploss=", stoploss, " takeprofit=", stoploss, " magic=", magic);
if ((error == ERR_COMMON_ERROR) || (error == ERR_ACCOUNT_DISABLED) || (error == ERR_INVALID_ACCOUNT) || (error == ERR_TRADE_DISABLED))
{
IsExpertFailed = true;
break;
}
if ((error == ERR_SERVER_BUSY) || (ERR_INVALID_TRADE_VOLUME) || (error == ERR_MARKET_CLOSED))
{
Sleep(1000*300);
break;
}
if ((error == ERR_TOO_FREQUENT_REQUESTS) || (error == ERR_TOO_MANY_REQUESTS))
{
Sleep(1000*100);
}
if ((error == ERR_ORDER_LOCKED) || (error == ERR_LONG_POSITIONS_ONLY_ALLOWED) || (error == ERR_TRADE_TOO_MANY_ORDERS))
{
break;
}
if (error == ERR_TRADE_CONTEXT_BUSY)
{
while (IsTradeContextBusy())
{
Sleep(1000*11);
}
}
if (error == ERR_TRADE_EXPIRATION_DENIED )
{
expiration = 0;
continue;
}
if ((error != ERR_PRICE_CHANGED) && (error != ERR_REQUOTE))
{
Sleep(1000*7.7);
}
}
}
//+------------------------------------------------------------------+
//| Ïðîâåðêà ñóùåñòâîâàíèÿ îðäåðà |
//+------------------------------------------------------------------+
bool ExistOrders(string symbol, int cmd, int magic, datetime opentime = 0)
{
int orderType;
for (int i = 0; i < OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
orderType = OrderType();
if ((orderType > 1) && (orderType < 6))
{
if (OrderSymbol() == symbol)
{
if (OrderMagicNumber() == magic)
{
if (opentime <= OrderOpenTime())
return (true);
}
}
}
}
}
return (false);
}
//+------------------------------------------------------------------+
//| Ñòðîêîâîå çíà÷åíèå òàéìôðåéìà |
//+------------------------------------------------------------------+
string GetNameTF(int timeFrame)
{
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 (DoubleToStr(timeFrame, 0));
}
}
//+------------------------------------------------------------------+
//| Ñòðîêîâîå çíà÷åíèå îïåðàöèè |
//+------------------------------------------------------------------+
string GetNameOP(int cmd)
{
switch (cmd)
{
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 (DoubleToStr(cmd, 0));
}
}
//+------------------------------------------------------------------+
//| Çàêðûòèå âûáðàííîé ïîçèöèè |
//+------------------------------------------------------------------+
void ClosePosBySelect(double volume = 0.0)
{
color clr;
double price;
bool result;
int error;
if ((OrderType() == OP_BUY) || (OrderType() == OP_SELL))
{
for (int try = 1; try <= NumberOfTry; try++)
{
if (!IsTesting() && (!IsExpertEnabled() || IsStopped()))
{
break;
}
while (!IsTradeAllowed())
{
Sleep(5000);
}
RefreshRates();
if (OrderType() == OP_BUY)
{
price = Bid;
clr = ColorBuy;
}
else
{
price = Ask;
clr = ColorSell;
}
if (volume == 0.0)
{
volume = OrderLots();
}
result = OrderClose(OrderTicket(), volume, price, SlipPips, clr);
if (result)
{
if (UseSound)
{
PlaySound("expert.wav");
break;
}
}
else
{
error = GetLastError();
if (error == ERR_TRADE_CONTEXT_BUSY)
{
while (IsTradeContextBusy())
{
Sleep(1000*11);
}
}
Print("Error(", error, ") Close ", GetNameOP(OrderType()), " ", ErrorDescription(error), ", try ", try);
Print(OrderTicket()," Ask=", Ask," Bid=", Bid, " price=", price);
Print("symbol=", OrderSymbol()," volume=", OrderLots()," stoploss=", OrderStopLoss(), " takeprofit=", OrderTakeProfit()," magic=", OrderMagicNumber());
Sleep(1000*5);
}
}
}
else
{
Print("Incorrect Close ", GetNameOP(OrderType()));
}
}
//+------------------------------------------------------------------+
//| Çàêðûòèå âñåõ ïîçèöèé |
//+------------------------------------------------------------------+
void CloseAllOrders(int magic)
{
for (int orderIndex = (OrdersTotal() - 1); orderIndex >= 0; orderIndex--)
{
if (OrderSelect(orderIndex, SELECT_BY_POS))
{
if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == magic))
{
if ((OrderType() != OP_BUY) && (OrderType() != OP_SELL))
{
OrderDelete(OrderTicket());
}
else
{
ClosePosBySelect();
}
}
}
}
}
Comments
Markdown Formatting Guide
# H1
## H2
### H3
**bold text**
*italicized text*
[title](https://www.example.com)

`code`
```
code block
```
> blockquote
- Item 1
- Item 2
1. First item
2. Second item
---