Orders Execution
0
Views
0
Downloads
0
Favorites
Trend_your_friend
#property version "1.00"
#property strict
// inputs
input double i_fLot = 0.01; // Lot Size
input uint i_nGridStep = 100; // Grid Step
input uint i_nOrdersNumber = 20; // Orders Number
input double i_fSL = 0; // Stop Loss, $ (0 - not used)
input double i_fTP = 1; // Take Profit, $ (0 - not used)
sinput uint i_nMagic = 10; // Magic Number
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
DrawStats(i_nMagic);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
string sName;
for(int i = ObjectsTotal(0, 0)-1; i >= 0; i--)
{
sName = ObjectName(0, i, 0);
if(StringFind(sName, "Grid") == 0)
ObjectDelete(0, sName);
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// new bar flag
static datetime s_dtLastBarTime = 0;
bool bNewBar = false;
if(Time[0] > s_dtLastBarTime)
{
if(s_dtLastBarTime != 0)
bNewBar = true;
s_dtLastBarTime = Time[0];
}
// look for pending and market orders
int nTotalOrders = 0;
double fTotalProfit = 0;
CheckGrid(nTotalOrders, fTotalProfit);
// place orders
if(bNewBar && nTotalOrders == 0)
{
double fAsk = Ask;
double fBid = Bid;
double fLot = RoundLot(_Symbol, i_fLot);
for(uint i = 0; i < i_nOrdersNumber; i++)
{
PendingOrder(_Symbol, OP_BUYSTOP, fLot, NormalizeDouble(fAsk + (i+1) * i_nGridStep * _Point, _Digits), 1000, 0, 0, NULL, 0, i_nMagic, clrGreen);
PendingOrder(_Symbol, OP_SELLSTOP, fLot, NormalizeDouble(fBid - (i+1) * i_nGridStep * _Point, _Digits), 1000, 0, 0, NULL, 0, i_nMagic, clrGreen);
}
}
// close all
if((i_fTP > 0 && fTotalProfit >= i_fTP) || (i_fSL > 0 && fTotalProfit <= -i_fSL))
{
while(IsTesting() || IsOptimization() || IsVisualMode() || (!IsStopped() && IsExpertEnabled() && IsTradeAllowed()))
{
CheckGrid(nTotalOrders, fTotalProfit);
if(nTotalOrders == 0)
break;
// delete pending orders
for(int i = OrdersTotal()-1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS) == true)
{
if(OrderSymbol() == _Symbol && OrderMagicNumber() == i_nMagic)
{
if(OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP)
{
DeletePendingOrder(OrderTicket());
}
}
}
}
// close market orders
for(int i = OrdersTotal()-1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS) == true)
{
if(OrderSymbol() == _Symbol && OrderMagicNumber() == i_nMagic)
{
if(OrderType() == OP_BUY || OrderType() == OP_SELL)
{
ClosePosition(OrderTicket(), 0, 1000, clrRed);
}
}
}
}
}
}
// draw SL and TP level in visual mode
if(!IsOptimization() && !(IsTesting() && !IsVisualMode()))
{
CalculateSLTPLevels();
DrawStats(i_nMagic);
}
}
//+------------------------------------------------------------------+
void CheckGrid(int & nTotalOrders, double & fTotalProfit)
{
nTotalOrders = 0;
fTotalProfit = 0;
for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS) == true)
{
if(OrderSymbol() == _Symbol && OrderMagicNumber() == i_nMagic)
{
nTotalOrders++;
if(OrderType() == OP_BUY || OrderType() == OP_SELL)
{
fTotalProfit += (OrderProfit() + OrderCommission() + OrderSwap());
}
}
}
}
}
//+------------------------------------------------------------------+
void CalculateSLTPLevels()
{
double fTPPrice = 0, fSLPrice = 0;
double fTotalLot = 0;
double fTotalProfit = 0;
for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS) == true)
{
if(OrderSymbol() == _Symbol && OrderMagicNumber() == i_nMagic)
{
if(OrderType() == OP_BUY)
{
fTotalLot += OrderLots();
fTotalProfit += (OrderProfit() + OrderCommission() + OrderSwap());
}
if(OrderType() == OP_SELL)
{
fTotalLot -= OrderLots();
fTotalProfit += (OrderProfit() + OrderCommission() + OrderSwap());
}
}
}
}
if(fTotalLot != 0)
{
double fPointPrice = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE) * MathAbs(fTotalLot);
if(fPointPrice > 0)
{
int nTotalPipsProfit = (int) MathRound(fTotalProfit / fPointPrice);
int nTPPoints = (int) MathRound(i_fTP / fPointPrice);
int nSLPoints = (int) MathRound(i_fSL / fPointPrice);
if(fTotalLot > 0)
{
double fAvgOpenPrice = Bid - nTotalPipsProfit * _Point;
fTPPrice = fAvgOpenPrice + nTPPoints * _Point;
fSLPrice = fAvgOpenPrice - nSLPoints * _Point;
}
if(fTotalLot < 0)
{
double fAvgOpenPrice = Ask + nTotalPipsProfit * _Point;
fTPPrice = fAvgOpenPrice - nTPPoints * _Point;
fSLPrice = fAvgOpenPrice + nSLPoints * _Point;
}
}
}
DrawHLine(0, "Grid SL", 0, Time[0], fSLPrice, STYLE_DOT, 1, clrRed, false, false,false, true, 0);
DrawHLine(0, "Grid TP", 0, Time[0], fTPPrice, STYLE_DOT, 1, clrGreen, false, false,false, true, 0);
}
//+------------------------------------------------------------------+
void DrawStats(const int nMagic = 0)
{
int nTitlesX = 100;
int nTitlesY = 20;
int nLineDelta = 20;
color cLineColor = clrLimeGreen;
DrawLabel(0, "Grid Buy Lots", 0, nTitlesX, nTitlesY + 0 * nLineDelta, CORNER_RIGHT_UPPER, "Buy Lots:", "Arial", 10, cLineColor, 0, ANCHOR_RIGHT_UPPER);
DrawLabel(0, "Grid Sell Lots", 0, nTitlesX, nTitlesY + 1 * nLineDelta, CORNER_RIGHT_UPPER, "Sell Lots:", "Arial", 10, cLineColor, 0, ANCHOR_RIGHT_UPPER);
DrawLabel(0, "Grid Buy Proifit", 0, nTitlesX, nTitlesY + 2 * nLineDelta, CORNER_RIGHT_UPPER, "Buy Proifit:", "Arial", 10, cLineColor, 0, ANCHOR_RIGHT_UPPER);
DrawLabel(0, "Grid Sell Profit", 0, nTitlesX, nTitlesY + 3 * nLineDelta, CORNER_RIGHT_UPPER, "Sell Profit:", "Arial", 10, cLineColor, 0, ANCHOR_RIGHT_UPPER);
DrawLabel(0, "Grid Total Profit", 0, nTitlesX, nTitlesY + 4 * nLineDelta, CORNER_RIGHT_UPPER, "Total Profit:", "Arial", 10, cLineColor, 0, ANCHOR_RIGHT_UPPER);
double fBuyLots = 0;
double fSellLots = 0;
double fBuyProfit = 0;
double fSellProfit = 0;
double fTotalProfit = 0;
for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS) == true)
{
if(OrderSymbol() == _Symbol && OrderMagicNumber() == nMagic)
{
if(OrderType() == OP_BUY)
{
fBuyLots += OrderLots();
fBuyProfit += (OrderProfit() + OrderCommission() + OrderSwap());
}
if(OrderType() == OP_SELL)
{
fSellLots += OrderLots();
fSellProfit += (OrderProfit() + OrderCommission() + OrderSwap());
}
}
}
}
fTotalProfit = fBuyProfit + fSellProfit;
int nValuesX = 90;
int nValuesY = 20;
DrawLabel(0, "Grid Buy Lots Value", 0, nValuesX, nValuesY + 0 * nLineDelta, CORNER_RIGHT_UPPER, DoubleToString(fBuyLots, 3), "Arial", 10, clrLimeGreen, 0, ANCHOR_LEFT_UPPER);
DrawLabel(0, "Grid Sell Lots Value", 0, nValuesX, nValuesY + 1 * nLineDelta, CORNER_RIGHT_UPPER, DoubleToString(fSellLots, 3), "Arial", 10, clrLimeGreen, 0, ANCHOR_LEFT_UPPER);
DrawLabel(0, "Grid Buy Profit Value", 0, nValuesX, nValuesY + 2 * nLineDelta, CORNER_RIGHT_UPPER, DoubleToString(fBuyProfit, 2), "Arial", 10, fBuyProfit >= 0 ? clrLimeGreen : clrRed, 0, ANCHOR_LEFT_UPPER);
DrawLabel(0, "Grid Sell Profit Value", 0, nValuesX, nValuesY + 3 * nLineDelta, CORNER_RIGHT_UPPER, DoubleToString(fSellProfit, 2), "Arial", 10, fSellProfit >= 0 ? clrLimeGreen : clrRed, 0, ANCHOR_LEFT_UPPER);
DrawLabel(0, "Grid Total Profit Value",0, nValuesX, nValuesY + 4 * nLineDelta, CORNER_RIGHT_UPPER, DoubleToString(fTotalProfit, 2), "Arial", 10, fTotalProfit >= 0 ? clrLimeGreen : clrRed, 0, ANCHOR_LEFT_UPPER);
ChartRedraw();
}
//+------------------------------------------------------------------+
// ôóíêöèÿ îêðóãëåíèÿ ëîòà
double RoundLot(const string sSymbol, const double fLot)
{
double fMinLot = SymbolInfoDouble(sSymbol, SYMBOL_VOLUME_MIN);
double fMaxLot = SymbolInfoDouble(sSymbol, SYMBOL_VOLUME_MAX);
double fLotStep = SymbolInfoDouble(sSymbol, SYMBOL_VOLUME_STEP);
// error check
if(fMinLot <= 0 || fMaxLot <= 0 || fLotStep <= 0)
return 0;
int nLotDigits = 0;
if(fLotStep < 1)
nLotDigits = (int) MathCeil(-MathLog10(fLotStep));
double fRoundedLot = MathRound(fLot/fLotStep) * fLotStep;
if(fRoundedLot < fMinLot)
fRoundedLot = fMinLot;
if(fRoundedLot > fMaxLot)
fRoundedLot = fMaxLot;
fRoundedLot = NormalizeDouble(fRoundedLot, nLotDigits);
return(fRoundedLot);
}
//+------------------------------------------------------------------+
int PendingOrder( const string sSymbol,
const int cmd,
const double fLot,
const double fPrice,
const int nSlippage = 1000,
const int nSL = 0,
const int nTP = 0,
const string sComment = NULL,
const datetime dtExpiration = 0,
const int nMagic = 0,
const color cColor = clrNONE)
{
// check type
if(cmd != OP_BUYSTOP && cmd != OP_SELLSTOP && cmd != OP_BUYLIMIT && cmd != OP_SELLLIMIT)
return (-1);
// find symbol
if(sSymbol != _Symbol && SymbolSelect(sSymbol, true) == false)
{
Print("Peinding order failed: symbol " + sSymbol + " is not found. \r\n");
return (-1);
}
// symbol spec
int nDigits = (int) SymbolInfoInteger(sSymbol, SYMBOL_DIGITS);
double fPoint = SymbolInfoDouble(sSymbol, SYMBOL_POINT);
double fOpenPrice = NormalizeDouble(fPrice, nDigits);
double fSLPrice = 0;
double fTPPrice = 0;
// stoplevel flag
bool bStopLevelAllows = false;
int nTicket = 0;
// 5 tries to send the order
int nMaxTries = 5;
for(int k = 0; k < nMaxTries && IsTradeAllowed() && !IsStopped(); k++)
{
RefreshRates();
// current prices
double fBid = NormalizeDouble(SymbolInfoDouble(sSymbol, SYMBOL_BID), nDigits);
double fAsk = NormalizeDouble(SymbolInfoDouble(sSymbol, SYMBOL_ASK), nDigits);
// current stop level
double fStopLevel = NormalizeDouble(MarketInfo(sSymbol, MODE_STOPLEVEL) * fPoint, nDigits);
// order prices
switch(cmd)
{
case OP_BUYSTOP:
fSLPrice = NormalizeDouble(fOpenPrice - nSL * fPoint, nDigits) * (nSL > 0);
fTPPrice = NormalizeDouble(fOpenPrice + nTP * fPoint, nDigits) * (nTP > 0);
bStopLevelAllows = (fOpenPrice - fAsk) > fStopLevel;
break;
case OP_SELLSTOP:
fSLPrice = NormalizeDouble(fOpenPrice + nSL * fPoint, nDigits) * (nSL > 0);
fTPPrice = NormalizeDouble(fOpenPrice - nTP * fPoint, nDigits) * (nTP > 0);
bStopLevelAllows = (fBid - fOpenPrice) > fStopLevel;
break;
case OP_BUYLIMIT:
fSLPrice = NormalizeDouble(fOpenPrice - nSL * fPoint, nDigits) * (nSL > 0);
fTPPrice = NormalizeDouble(fOpenPrice + nTP * fPoint, nDigits) * (nTP > 0);
bStopLevelAllows = (fAsk - fOpenPrice) > fStopLevel;
break;
case OP_SELLLIMIT:
fSLPrice = NormalizeDouble(fOpenPrice + nSL * fPoint, nDigits) * (nSL > 0);
fTPPrice = NormalizeDouble(fOpenPrice - nTP * fPoint, nDigits) * (nTP > 0);
bStopLevelAllows = (fOpenPrice - fBid) > fStopLevel;
break;
}
ResetLastError();
if(bStopLevelAllows)
{
nTicket = OrderSend(sSymbol, cmd, fLot, fOpenPrice, nSlippage, fSLPrice, fTPPrice, sComment, nMagic, dtExpiration, cColor);
// success
if(nTicket > 0)
return(nTicket);
}
// error
if(k == nMaxTries - 1)
{
string sType = "";
switch(cmd)
{
case OP_BUYSTOP:
sType = "BuyStop";
break;
case OP_SELLSTOP:
sType = "SellStop";
break;
case OP_BUYLIMIT:
sType = "BuyLimit";
break;
case OP_SELLLIMIT:
sType = "SellLimit";
break;
}
string sError = IntegerToString(GetLastError());
if(!bStopLevelAllows)
sError = "Stop Level";
if(TerminalInfoString(TERMINAL_LANGUAGE) == "Russian")
Print("Íå óäàëîñü óñòàíîâèòü îòëîæåííûé îðäåð ", sType, " ïî öåíå ", DoubleToString(fOpenPrice, nDigits), ". Îøèáêà: " + sError);
else
Print("Pending order ", sType, " at ", DoubleToString(fOpenPrice, nDigits), "failed. Error: " + sError);
return(-1);
}
Sleep(250);
}
// if we are here, order failed
return (-1);
}
//+------------------------------------------------------------------+
bool ClosePosition(const int nTicket, const double fLot = 0, const int nSlippage = 1000, const color cColor = clrNONE)
{
if(OrderSelect(nTicket, SELECT_BY_TICKET))
{
int nDigits = (int) SymbolInfoInteger(OrderSymbol(), SYMBOL_DIGITS);
MqlTick oTick;
double fCloseLot = OrderLots();
if(fLot > 0)
fCloseLot = RoundLot(OrderSymbol(), fLot);
// 5 tries to close
int nMaxTries = 5;
for(int k = 0; k < nMaxTries; k++)
{
RefreshRates();
if(SymbolInfoTick(OrderSymbol(), oTick) == false)
{
Print("SymbloInfoTick failed");
return (false);
}
double fClosePrice = 0;
if(OrderType() == OP_BUY)
fClosePrice = NormalizeDouble(oTick.bid, nDigits);
if(OrderType() == OP_SELL)
fClosePrice = NormalizeDouble(oTick.ask, nDigits);
if(fClosePrice <= 0)
return(false);
ResetLastError();
if(OrderClose(nTicket, fCloseLot, fClosePrice, nSlippage, cColor) == true)
return(true);
if(k == nMaxTries - 1)
{
if(TerminalInfoString(TERMINAL_LANGUAGE) == "Russian")
Print("Íå óäàëîñü çàêðûòü ðûíî÷íûé îðäåð. Êîä îøèáêè: " + IntegerToString(GetLastError()));
else
Print("Market order close failed. Error code: " + IntegerToString(GetLastError()));
return(false);
}
Sleep(250);
}
}
return(false);
}
//+------------------------------------------------------------------+
bool DeletePendingOrder(const int nTicket, const color cColor = clrNONE)
{
if(OrderSelect(nTicket, SELECT_BY_TICKET) == true)
{
int nType = OrderType();
if((nType != OP_BUYLIMIT && nType != OP_BUYSTOP && nType != OP_SELLLIMIT && nType != OP_SELLSTOP) || OrderCloseTime() > 0)
{
if(TerminalInfoString(TERMINAL_LANGUAGE) == "Russian")
Print("Íå óäàëîñü óäàëèòü îðäåð #" + IntegerToString(nTicket) + ". Îðäåð íå ÿâëÿåòñÿ îòëîæåííûì, èëè óæå óäàë¸í. \r\n");
else
Print("Order #" + IntegerToString(nTicket) + " was not deleted. The order is not pending or is already deleted. \r\n");
return(false);
}
int nMaxTries = 3;
for(int k = 0; k < nMaxTries; k++)
{
ResetLastError();
if(OrderDelete(nTicket, cColor) == true)
return(true);
if(k == nMaxTries - 1)
{
if(TerminalInfoString(TERMINAL_LANGUAGE) == "Russian")
Print("Íå óäàëîñü óäàëèòü îòëîæåííûé îðäåð #" + IntegerToString(nTicket) + ". Êîä îøèáêè: " + IntegerToString(GetLastError()));
else
Print("Pending order #" + IntegerToString(nTicket) + " is not deleted. Error code: " + IntegerToString(GetLastError()));
return(false);
}
}
}
return(false);
}
//+------------------------------------------------------------------+
bool DrawLabel(const long nChartID = 0,
const string sName = "Label",
const int nSubWindow = 0,
const int nX = 0,
const int nY = 0,
const ENUM_BASE_CORNER nCorner = CORNER_LEFT_UPPER,
const string sText = "Label",
const string sFontFace = "Arial",
const int nFontSize = 10,
const color cColor = clrRed,
const double fAngle = 0,
const ENUM_ANCHOR_POINT eAnchor = ANCHOR_LEFT_UPPER,
const bool bInBackground = false,
const bool bSelectable = false,
const bool bSelected = false,
const bool bHidden = true,
const long nZOrder = 0)
{
if(ObjectFind(nChartID, sName) != nSubWindow)
{
if(!ObjectCreate(nChartID, sName, OBJ_LABEL, nSubWindow, 0, 0))
return(false);
}
ObjectSetInteger(nChartID, sName, OBJPROP_XDISTANCE, nX);
ObjectSetInteger(nChartID, sName, OBJPROP_YDISTANCE, nY);
ObjectSetInteger(nChartID, sName, OBJPROP_CORNER, nCorner);
ObjectSetString (nChartID, sName, OBJPROP_TEXT, sText);
ObjectSetString (nChartID, sName, OBJPROP_FONT, sFontFace);
ObjectSetInteger(nChartID, sName, OBJPROP_FONTSIZE, nFontSize);
ObjectSetDouble (nChartID, sName, OBJPROP_ANGLE, fAngle);
ObjectSetInteger(nChartID, sName, OBJPROP_ANCHOR, eAnchor);
ObjectSetInteger(nChartID, sName, OBJPROP_COLOR, cColor);
ObjectSetInteger(nChartID, sName, OBJPROP_BACK, bInBackground);
ObjectSetInteger(nChartID, sName, OBJPROP_SELECTABLE, bSelectable);
ObjectSetInteger(nChartID, sName, OBJPROP_SELECTED, bSelectable && bSelected);
ObjectSetInteger(nChartID, sName, OBJPROP_HIDDEN, bHidden);
ObjectSetInteger(nChartID, sName, OBJPROP_ZORDER, nZOrder);
return(true);
}
//+------------------------------------------------------------------+
bool DrawHLine(const long nChartID = 0,
const string sName = "HLine",
const int nSubWindow = 0,
const datetime dtTime1 = 0,
const double fPrice1 = 0,
const ENUM_LINE_STYLE eStyle = STYLE_SOLID,
const int nWidth = 1,
const color cColor = clrRed,
const bool bInBackGround = false,
const bool bSelectable = false,
const bool bSelected = false,
const bool bHidden = true,
const long nZOrder = 0)
{
if(ObjectFind(nChartID, sName) != nSubWindow)
{
if(ObjectCreate(nChartID, sName, OBJ_HLINE, nSubWindow, dtTime1, fPrice1) == false)
return (false);
}
else
{
ObjectMove(nChartID, sName, 0, dtTime1, fPrice1);
}
ObjectSetInteger(nChartID, sName, OBJPROP_COLOR, cColor);
ObjectSetInteger(nChartID, sName, OBJPROP_WIDTH, nWidth);
ObjectSetInteger(nChartID, sName, OBJPROP_STYLE, eStyle);
ObjectSetInteger(nChartID, sName, OBJPROP_BACK, bInBackGround);
ObjectSetInteger(nChartID, sName, OBJPROP_SELECTABLE, bSelectable);
ObjectSetInteger(nChartID, sName, OBJPROP_SELECTED, bSelectable && bSelected);
ObjectSetInteger(nChartID, sName, OBJPROP_HIDDEN, bHidden);
ObjectSetInteger(nChartID, sName, OBJPROP_ZORDER, nZOrder);
return(true);
}
//+------------------------------------------------------------------+
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
---