Professional Documents
Culture Documents
#include <stdlib.mqh>
enum styleType
{
Conservative = 0
,Moderate = 1
//,Agresive = 2
,Standard = 3
,SC = 4
,Agresive = 5
};
bool Trade=True;
int Slippage = 3;
double LevelDistance = 20;
double profitTarget;
double entryPrice = 0;
double lotQty;
int ticketB0,ticketS0;
double levelB1,levelB2,levelB3,levelS1,levelS2,levelS3;
bool FirstTickOfBar=false, isBarInitialized=false;
bool isNextLong = true, takeProfit=false;
double lowestSell, highestBuy;
int profitLabelSize=8;
double Total_Buy_Lots, Total_Sell_Lots, Total_Lots;
double bigestLotSize_Buy, bigestLotPrice_Buy, bigestLotSize_Sell,
bigestLotPrice_Sell;
bool isNeutralized = false, isNeutralizedSend=false;
int lastLevelBars=0;
double targetLevelMultiplier = 2.5;
bool alertInsideGridSent = false;
bool onExecutionNow;
string nextSize="";
double zoneSize;
double zoneLevels;
double PointValue;
bool FirstTime=true;
bool verbose = true;
int colorBit = 0;
double maxMoneyLoss;
double Net_Lots;
double Buy_Average, Sell_Average;
double Total_Buy_Size, Total_Sell_Size;
double currentProfit;
bool isTradingPaused;
double testingLoss;
double zoneTop, zoneBtn;
double insideLevels, counterLevels=10;
bool isInAccumulateMode;
int gridDirection;
double lastOrderQty=0; //to prevent duplicates
int ATRAvg=0; //day atr averahe in pips
int gridIncrements=10;
//+------------------------------------------------------------------+
int init()
{
//----
PointValue = Point;
if( Digits == 5 || Digits == 3 ) PointValue *= 10;
isBarInitialized=false;
lowestSell = 0;
highestBuy = 0;
isNeutralized = false;
Trade=True;
onExecutionNow = false;
FirstTime=true;
isNeutralizedSend=false;
isInAccumulateMode = Accumulate_Mode;
if (IsTesting())
{
verbose = false;
}
gridIncrements = Grid_Increments;
//EventSetMillisecondTimer(600);
EventSetTimer(1);
ticketB0 = 0;
ticketS0 = 0;
lotQty = Start_Lot_Qty;
if (lotQty < MarketInfo(Symbol(),MODE_MINLOT))
lotQty = MarketInfo(Symbol(),MODE_MINLOT);
//Print("Using Lot quantity of: "+lotQty);
lotQty = MarketInfo(Symbol(),MODE_MINLOT);
Print("Using Minimum Lot quantity of: "+lotQty+" Ignoring Start_Lot_Qty for
now...");
maxMoneyLoss = 1000000;
if (Max_Money_Loss>0)
{
maxMoneyLoss = Max_Money_Loss;
if(verbose) Print("Maximum Money Loss set to "+maxMoneyLoss);
}
isTradingPaused = Pause_Trading;
ObjectCreate("Rcvr_Hdg_Alert_"+Symbol(),OBJ_LABEL,0,0,0);
ObjectSet("Rcvr_Hdg_Alert_"+Symbol(),OBJPROP_XDISTANCE,0);
ObjectSet("Rcvr_Hdg_Alert_"+Symbol(),OBJPROP_ANCHOR,ANCHOR_LEFT_UPPER);
ObjectSetText("Rcvr_Hdg_Alert_"+Symbol(),"*** PLEASE WAIT ***" ,16,NULL,Yellow);
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
EventKillTimer();
deleteLines();
//ObjectDelete("Rcvr_Hdg_Information_"+Symbol());
ObjectDelete("rcvHdgBuy_Average_Line_"+Symbol());
ObjectDelete("rcvHdgSell_Average_Line_"+Symbol());
ObjectDelete("Rcvr_Hdg_Alert_"+Symbol());
ObjectDelete("Rcvr_Hdg_Counter_"+Symbol());
ObjectDelete("Epd_Grid_Pause_"+Symbol());
ObjectDelete("eGrid_levels_"+Symbol());
ObjectDelete("rcvHdgBuy_Neutral_Line_"+Symbol());
//ObjectDelete("targetBuy");
//ObjectDelete("targetSell");
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
int R1=0, R5=0, R10=0, R20=0;
//i do not recomend trading with thise lines. use it for emergencies only.
gridTradeManualLines();
//ChartSetInteger
LevelDistance = gridIncrements*PointValue;
profitTarget = 0.05;
//if (TradeStyle == Moderate)
{
if( Digits == 5 || Digits == 3 )
profitTarget =
gridIncrements*10*MarketInfo(Symbol(),MODE_TICKVALUE)*lotQty;
else
profitTarget = gridIncrements*MarketInfo(Symbol(),MODE_TICKVALUE)*lotQty;
}
updateLines();
if (FirstTime)
{
// Get the average daily range in pips
R1 = iATR(NULL,PERIOD_D1, 1,1) / PointValue;
R5 = iATR(NULL,PERIOD_D1, 5,1) / PointValue;
R10 = iATR(NULL,PERIOD_D1,10,1) / PointValue;
R20 = iATR(NULL,PERIOD_D1,20,1) / PointValue;
ATRAvg = (3*R1+2*R5+R10+R20) / 7;
if (counterLevels>3)
{
gridIncrements = ATRAvg/(counterLevels-1);
if (gridIncrements<10) gridIncrements=10;
}
Print("Daily ATR Average is "+ATRAvg+" Pips. Changing Grid Increments to
"+gridIncrements);
}
if (counterLevels>3)
{
gridIncrements = ATRAvg/(counterLevels-1);
if (gridIncrements<10) gridIncrements=10;
}
if (verbose) Print("Daily ATR Average is "+ATRAvg+" Pips. Changing Grid
Increments to "+gridIncrements);
isNeutralizedSend = false;
isInAccumulateMode = Accumulate_Mode;
if (FirstTime)
isNextLong = iClose(Symbol(),PERIOD_H4,1)>
iClose(Symbol(),PERIOD_H4,2);
if (isNextLong)
{
if(ticketB0==0)
{
ticketB0 = gridOpenOrder(OP_BUY, lotQty);
}
}
if (!isNextLong)
{
if(ticketS0==0)
{
ticketS0 = gridOpenOrder(OP_SELL, lotQty);
}
}
return 0;
}
zoneSize = MathAbs(bigestLotPrice_Buy-bigestLotPrice_Sell);
zoneLevels = NormalizeDouble(((zoneSize/LevelDistance)+2),1);
if (!alertInsideGridSent)
{
if (alert_Levels_Qty>0 && zoneLevels>=alert_Levels_Qty)
{
alertInsideGridSent = true;
SendMail(Symbol()+" Expand Grid Levels at "+zoneLevels+" Alert. This
magic is "+MagicNumber,"");
Print("***ALERT*** Expand Grid Levels at "+zoneLevels+" Alert. This
magic is "+MagicNumber);
}
}
if (FirstTime)
{
FirstTime=false;
int initialPips = zoneSize/PointValue;
Print("Initial ZoneSize: "+initialPips+" pips ("+zoneSize+"), ZoneLevels:
"+zoneLevels);
}
insideLevels = 0;
if (zoneTop-zoneBtn>0)
insideLevels = NormalizeDouble((zoneTop-zoneBtn)/LevelDistance,1);
isInAccumulateMode = insideLevels<counterLevels;
double oldZoneLevels=zoneLevels;
//if (zoneLevels>2 && TradeStyle != Standard && TradeStyle != SC) levelB1 =
levelB2;
if(ticketB0==0 && MarketInfo(Symbol(),MODE_BID) >= levelB1 && levelB1>0)
{
//accumulate
if (isInAccumulateMode && Total_Sell_Lots>0)
{
levelBuy = bigestLotSize_Sell+lotQty;
}
//reverse
if (!isInAccumulateMode && Total_Sell_Lots>0)
{
if (TradeStyle == Standard)
{
if (Total_Buy_Lots<Total_Sell_Lots)
levelBuy = (bigestLotSize_Sell*zoneLevels)+lotQty-Total_Buy_Lots;
}
}
levelB1 = 0;
isNextLong=true;
ticketB0 = gridOpenOrder(OP_BUY,levelBuy );
isBarInitialized=false;
}
}
//reverse
if (!isInAccumulateMode && Total_Buy_Lots>0)
{
if ( TradeStyle == Standard)
{
if (Total_Sell_Lots<bigestLotSize_Buy)
levelSell = (bigestLotSize_Buy*zoneLevels)+lotQty-
Total_Sell_Lots;
}
levelS1 = 0;
isNextLong=false;
isBarInitialized=false;
}
//---TAKE PROFIT
if(MoneyTakeProfit!=0 && currentProfit>=MoneyTakeProfit) takeProfit = true;
if (currentProfit>=profitTarget) takeProfit = true;
if (!isInAccumulateMode && TradeStyle == Conservative && currentProfit>0)
takeProfit = true;
if(takeProfit)
{
isNextLong = gridDirection==OP_BUY;
Trade = CONTINUE;
subCloseOrder();
subCloseAllOrder();
subCloseAllOrder();
subCloseAllPending();
subCloseAllPending();
ObjectDelete("targetBuy");
ObjectDelete("closeAll");
ObjectDelete("targetSell");
ObjectDelete("buyStop");
ObjectDelete("sellStop");
ObjectDelete("buyLimit");
ObjectDelete("sellLimit");
ObjectDelete("neutralize");
ObjectDelete("takeProfit");
Sleep(1000);
bigestLotSize_Buy = 0;
bigestLotSize_Sell = 0;
bigestLotPrice_Buy = 0;
bigestLotPrice_Sell = 0;
lowestSell = 0;
highestBuy = 0;
//myQty = 0;
if (Trade)
{
ticketB0 = 0;
ticketS0 = 0;
}
isBarInitialized = false;
deleteLines();
highestBuy=0;
lowestSell=0;
}
//------------------------------------------------------------------
void OnTimer()
{
if (colorBit==0)
colorBit = 1;
else
colorBit = 0;
ObjectDelete("rcvHdgBuy_Average_Line_"+Symbol());
ObjectDelete("rcvHdgSell_Average_Line_"+Symbol());
if (Total_Buy_Size>0)
{
ObjectCreate("rcvHdgBuy_Average_Line_"+Symbol(),OBJ_HLINE,0,0,Buy_Average/Total_Buy
_Size);
ObjectSet("rcvHdgBuy_Average_Line_"+Symbol(),OBJPROP_WIDTH,2);
ObjectSet("rcvHdgBuy_Average_Line_"+Symbol(),OBJPROP_COLOR,Blue);
}
if (Total_Sell_Size>0)
{
ObjectCreate("rcvHdgSell_Average_Line_"+Symbol(),OBJ_HLINE,0,0,Sell_Average/Total_S
ell_Size);
ObjectSet("rcvHdgSell_Average_Line_"+Symbol(),OBJPROP_WIDTH,2);
ObjectSet("rcvHdgSell_Average_Line_"+Symbol(),OBJPROP_COLOR,Red);
}
ObjectSetText("Rcvr_Hdg_Alert_"+Symbol(),DoubleToStr(Total_Buy_Lots,2)+"/"+DoubleTo
Str(Total_Sell_Lots,2)+
"("+DoubleToStr(currentProfit,2)+")"+nextSize ,14,NULL,Yellow);
ObjectSet("Rcvr_Hdg_Alert_"+Symbol(),OBJPROP_COLOR,Magenta);
}
ObjectDelete("eGrid_levels_"+Symbol());
if (alert_Levels_Qty>0 && zoneLevels>=alert_Levels_Qty && Total_Sell_Lots!
=Total_Buy_Lots)
{
ObjectCreate("eGrid_levels_"+Symbol(),OBJ_LABEL,0,0,0);
ObjectSet("eGrid_levels_"+Symbol(),OBJPROP_XDISTANCE,0);
ObjectSet("eGrid_levels_"+Symbol(),OBJPROP_YDISTANCE,65);
if (colorBit==0)
{
ObjectSetText("eGrid_levels_"+Symbol(),"LEVELS ALERT: "+zoneLevels ,
16,NULL,Red);
}
}
ObjectDelete("Epd_Grid_Pause_"+Symbol());
if (isTradingPaused)
{
ObjectCreate("Epd_Grid_Pause_"+Symbol(),OBJ_LABEL,0,0,0);
ObjectSet("Epd_Grid_Pause_"+Symbol(),OBJPROP_XDISTANCE,0);
ObjectSet("Epd_Grid_Pause_"+Symbol(),OBJPROP_YDISTANCE,65);
ObjectSetText("Epd_Grid_Pause_"+Symbol(),"** PAUSED **" ,20,NULL,Red);
}
}
//------------------------------------------------------------------
bool IsNewBar()
{
static datetime lastbar = 0;
//datetime curbar = Time[0];
datetime curbar = TimeMinute(TimeCurrent());
if(lastbar!=curbar)
{
lastbar=curbar;
return (true);
}
else
{
return(false);
}
}
//+------------------------------------------------------------------+
void updateLines()
{
deleteLines();
levelB1 = 0;
levelB2 = 0;
levelB3 = 0;
levelS1 = 0;
levelS2 = 0;
levelS3 = 0;
ticketB0 = 0;
ticketS0 = 0;
if (TradeStyle==Conservative)
gridTop == bigestLotPrice_Buy;
levelB1 = gridTop+(1*LevelDistance);
levelB2 = gridTop+(2*LevelDistance);
levelB3 = gridTop+(3*LevelDistance);
if (TradeStyle==Conservative)
gridBtn = bigestLotPrice_Sell;
levelS1 = gridBtn-(1*LevelDistance);
levelS2 = gridBtn-(2*LevelDistance);
levelS3 = gridBtn-(3*LevelDistance);
if (levelB1>0 ) {
ObjectCreate("hedgLineB1"+Symbol(),OBJ_HLINE,0,0,levelB1);
ObjectSet("hedgLineB1"+Symbol(),OBJPROP_COLOR,Blue);
ObjectSet("hedgLineB1"+Symbol(),OBJPROP_BACK,true);}
if (levelB2>0) {
ObjectCreate("hedgLineB2"+Symbol(),OBJ_HLINE,0,0,levelB2);
ObjectSet("hedgLineB2"+Symbol(),OBJPROP_COLOR,Blue);
ObjectSet("hedgLineB2"+Symbol(),OBJPROP_BACK,true); }
if (!IsTesting())
{
if (levelB3>0 ) {
ObjectCreate("hedgLineB3"+Symbol(),OBJ_HLINE,0,0,levelB3);
ObjectSet("hedgLineB3"+Symbol(),OBJPROP_COLOR,Blue);
ObjectSet("hedgLineB3"+Symbol(),OBJPROP_BACK,true); }
}
if (levelS1>0 ) {
ObjectCreate("hedgLineS1"+Symbol(),OBJ_HLINE,0,0,levelS1);
ObjectSet("hedgLineS1"+Symbol(),OBJPROP_COLOR,Red);
ObjectSet("hedgLineS1"+Symbol(),OBJPROP_BACK,true);}
if (levelS2>0 ) {
ObjectCreate("hedgLineS2"+Symbol(),OBJ_HLINE,0,0,levelS2);
ObjectSet("hedgLineS2"+Symbol(),OBJPROP_COLOR,Red);
ObjectSet("hedgLineS2"+Symbol(),OBJPROP_BACK,true); }
if (!IsTesting())
{
if (levelS3>0 ) {
ObjectCreate("hedgLineS3"+Symbol(),OBJ_HLINE,0,0,levelS3);
ObjectSet("hedgLineS3"+Symbol(),OBJPROP_COLOR,Red);
ObjectSet("hedgLineS3"+Symbol(),OBJPROP_BACK,true); }
}
void deleteLines()
{
ObjectDelete("hedgLineB1"+Symbol());
ObjectDelete("hedgLineB2"+Symbol());
ObjectDelete("hedgLineB3"+Symbol());
ObjectDelete("hedgLineS1"+Symbol());
ObjectDelete("hedgLineS2"+Symbol());
ObjectDelete("hedgLineS3"+Symbol());
//+------------------------------------------------------------------+
void subCloseAllPending()
{
int
NumberOfTries=10,
cnt,
total = 0,
ticket = 0,
err = 0,
c = 0;
total = OrdersTotal();
for(cnt=total-1;cnt>=0;cnt--)
{
if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
{
if(OrderMagicNumber()==MagicNumber)
{
if(OrderSymbol() == Symbol() )
{
switch(OrderType())
{
case OP_BUYLIMIT :
case OP_BUYSTOP :
case OP_SELLLIMIT:
case OP_SELLSTOP :
OrderDelete(OrderTicket());
}
}
}
}
}
}
int subTotalOrders()
{
int
cnt,
total = 0;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderMagicNumber()==MagicNumber)
{
if(OrderSymbol()==Symbol())
total++;
}
}
return(total);
}
int subTotalOpen()
{
int
cnt,
total = 0;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderMagicNumber()==MagicNumber)
{
if(OrderType()<=OP_SELL&&OrderSymbol()==Symbol())
total++;
}
}
return(total);
}
double subTotalProfit()
{
int
cnt,
total = 0;
int err = 0;
double Profit = 0;
Net_Lots = 0;
highestBuy = 0;
lowestSell = 0;
Total_Lots = 0;
bigestLotSize_Buy = 0;
bigestLotPrice_Buy = 0;
bigestLotSize_Sell = 0;
bigestLotPrice_Sell = 0;
Buy_Average =0; Sell_Average = 0;
Total_Buy_Size =0; Total_Sell_Size =0;
zoneTop = 0; zoneBtn = 0;
datetime startTime=TimeCurrent();
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderMagicNumber()==MagicNumber)
{
if(OrderType()==OP_BUY && OrderSymbol()==Symbol())
{
if(highestBuy<OrderOpenPrice()) highestBuy = OrderOpenPrice();
if (OrderLots()>bigestLotSize_Buy) {bigestLotSize_Buy = OrderLots();
bigestLotPrice_Buy = OrderOpenPrice();}
Net_Lots+=OrderLots();
Buy_Average+= OrderOpenPrice()*OrderLots();
Total_Buy_Size+=OrderLots();
if (zoneTop < OrderOpenPrice()) zoneTop =
OrderOpenPrice();
if (zoneBtn==0 || zoneBtn>OrderOpenPrice()) zoneBtn =
OrderOpenPrice();
if (OrderOpenTime() < startTime) {startTime=OrderOpenTime();
gridDirection = OP_BUY;}
Profit = Profit +OrderProfit()+OrderSwap()+OrderCommission();
}
if(OrderType()==OP_SELL && OrderSymbol()==Symbol())
{
if(lowestSell==0 || lowestSell>OrderOpenPrice()) lowestSell =
OrderOpenPrice();
if (OrderLots()>bigestLotSize_Sell) {bigestLotSize_Sell =
OrderLots(); bigestLotPrice_Sell = OrderOpenPrice();}
Net_Lots-=OrderLots();
Sell_Average+= OrderOpenPrice()*OrderLots();
Total_Sell_Size+=OrderLots();
if (zoneTop < OrderOpenPrice()) zoneTop =
OrderOpenPrice();
if (zoneBtn==0 || zoneBtn>OrderOpenPrice()) zoneBtn =
OrderOpenPrice();
if (OrderOpenTime() < startTime) {startTime=OrderOpenTime();
gridDirection = OP_SELL;}
Profit = Profit +OrderProfit()+OrderSwap()+OrderCommission();
}
}
}
Total_Buy_Lots = NormalizeDouble(Total_Buy_Size,2);
Total_Sell_Lots = NormalizeDouble(Total_Sell_Size,2);
Total_Lots = NormalizeDouble(Total_Buy_Lots+Total_Sell_Lots,2);
if (IsTesting())
{
if (testingLoss>Profit) testingLoss = Profit;
Comment(profitLabel+ " ("+contractsLabel+") -> "+MagicNumber
+"\nZone Levels: "+DoubleToStr(zoneLevels,1)
+"\nLog Lots: "+ DoubleToStr(Total_Buy_Lots,2)
+"\nShort Lots: "+ DoubleToStr(Total_Sell_Lots,2)
+"\nAcummulating: "+ isInAccumulateMode
+"\nInside Levels: "+ insideLevels
+"\nMaximun Loss: "+DoubleToStr(testingLoss,2)
+"\nOn Execution: "+ onExecutionNow
+"\nIsNextLong : "+ isNextLong
);
ObjectDelete("Rcvr_Hdg_Alert_"+Symbol());
//LOSS
if (-Profit>maxMoneyLoss)
{
Print("TRADE LOSS "+Profit);
subCloseOrder();
subCloseAllOrder();
return -1;
}
ObjectDelete("rcvHdgBuy_Neutral_Line_"+Symbol());
isNeutralized = false;
double neutralValue = 0;
if ((Maximum_Levels>0 && zoneLevels > Maximum_Levels) || AccountEquity()<50 /*||
-Profit>maxMoneyLoss*/)
{
//neutralValue = (bigestLotPrice_Buy+bigestLotPrice_Sell)/2;
if (NormalizeDouble(Total_Buy_Size,2)>NormalizeDouble(Total_Sell_Size,2))
{
neutralValue = bigestLotPrice_Buy-((bigestLotPrice_Buy-
bigestLotPrice_Sell)*0.63);
if (-Profit>maxMoneyLoss)
{
neutralValue = MarketInfo(Symbol(),MODE_ASK) + 1;
isTradingPaused = true;
}
ObjectCreate("rcvHdgBuy_Neutral_Line_"+Symbol(),OBJ_HLINE,0,0,neutralValue);
ObjectSet("rcvHdgBuy_Neutral_Line_"+Symbol(),OBJPROP_WIDTH,2);
ObjectSet("rcvHdgBuy_Neutral_Line_"+Symbol(),OBJPROP_COLOR,Yellow);
ObjectSet("rcvHdgBuy_Neutral_Line_"+Symbol(),OBJPROP_BACK,true);
}
if (NormalizeDouble(Total_Buy_Size,2)<NormalizeDouble(Total_Sell_Size,2))
{
neutralValue = Total_Sell_Size+((bigestLotPrice_Buy-
bigestLotPrice_Sell)*0.63);
if (-Profit>maxMoneyLoss)
{
neutralValue = MarketInfo(Symbol(),MODE_BID)-1;
isTradingPaused = true;
}
ObjectCreate("rcvHdgBuy_Neutral_Line_"+Symbol(),OBJ_HLINE,0,0,neutralValue);
ObjectSet("rcvHdgBuy_Neutral_Line_"+Symbol(),OBJPROP_WIDTH,2);
ObjectSet("rcvHdgBuy_Neutral_Line_"+Symbol(),OBJPROP_COLOR,Yellow);
ObjectSet("rcvHdgBuy_Neutral_Line_"+Symbol(),OBJPROP_BACK,true);
return(Profit);
}
//-------------------------------------------------------------------
//+------------------------------------------------------------------+
int gridOpenOrder(int orderType, double Lotz)
{
int NumberOfTries = 5;
//string TicketComment = MagicNumber+"-ExG";
string TicketComment = MagicNumber;
int
ticket = 0,
err = 0,
c = 0;
double
aStopLoss = 0,
aTakeProfit = 0,
bStopLoss = 0,
bTakeProfit = 0;
int type = orderType;
if (isInAccumulateMode)
{
if (type==OP_BUY) type = OP_SELL;
else if (type==OP_SELL) type = OP_BUY;
//CloseAllProfitAtLevel();
}
//if (currentProfit>0.05)
if (currentProfit>= profitTarget)
{
if (verbose) Print("Taking profit at grid level "+Ask);
takeProfit = true;
//just in case
subCloseOrder();
Sleep(1000);
return -1;
}
if (Lotz<=0)
{
if (verbose) Print("Checking for profit at Grid Line "+typeStr+", grid level
"+Ask+" Profit: "+DoubleToStr(currentProfit,2));
isNeutralizedSend = false;
if (thisLotz<MarketInfo(Symbol(),MODE_MINLOT))
return -2;
thisLotz =
MathRound(thisLotz/MarketInfo(Symbol(),MODE_LOTSTEP))*MarketInfo(Symbol(),MODE_LOTS
TEP);
if (lastOrderQty == thisLotz)
if (lastOrderQty>0) return -2;
else
lastOrderQty = thisLotz;
if (!onExecutionNow)
{
onExecutionNow = true;
if(type==OP_BUY)
{
for(c=0;c<NumberOfTries;c++)
{
entryPrice = NormalizeDouble(MarketInfo(Symbol(),MODE_ASK),Digits);
ticket=OrderSend(Symbol(),OP_BUY,thisLotz,entryPrice,Slippage,aStopLoss,aTakeProfit
,TicketComment,MagicNumber,0,Green);
err=GetLastError();
if (verbose) Print("OrderSend #",OrderTicket()," Code:
",err,"-",ErrorDescription(err));
if(err==0)
{
if(ticket>0) break;
}
else
{
if(err==0 || err==4 || err==136 || err==137 || err==138 || err==146)
//Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
if(ticket>0) break;
}
}
}
}
if(type==OP_SELL)
{
for(c=0;c<NumberOfTries;c++)
{
entryPrice = NormalizeDouble(MarketInfo(Symbol(),MODE_BID),Digits);
ticket=OrderSend(Symbol(),OP_SELL,thisLotz,entryPrice,Slippage,bStopLoss,bTakeProfi
t,TicketComment,MagicNumber,0,Red);
err=GetLastError();
if (verbose) Print("OrderSend #",OrderTicket()," Code:
",err,"-",ErrorDescription(err));
if(err==0)
{
if(ticket>0) break;
}
else
{
if(err==0 || err==4 || err==136 || err==137 || err==138 || err==146)
//Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
if(ticket>0) break;
}
}
}
}
onExecutionNow = false;
}
return(ticket);
}
void CloseAllProfit()
{
for(int i=OrdersTotal()-1; i>=0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
void CloseAllProfitAtLevel()
{
for(int i=OrdersTotal()-1; i>=0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (sideProfit>0)
{
if (orderType==OP_BUY)
{
CloseAllBuys();
Sleep(1000);
CloseAllBuys(); //go again just in case
}
if (orderType==OP_SELL)
{
CloseAllSells();
Sleep(1000);
CloseAllSells(); //go again just in case
}
}
}
void CloseAllBuys()
{
if (verbose) Print("Closing All BUY's orders at "+Bid);
for(int i=OrdersTotal()-1; i>=0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
}
}
}
}
void CloseAllSells()
{
if (verbose) Print("Closing All SELL's orders at "+Ask);
for(int i=OrdersTotal()-1; i>=0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
}
}
}
}
void subCloseAllOrder()
{
int
NumberOfTries=10,
cnt,
total = 0,
ticket = 0,
err = 0,
c = 0;
ticket=OrderClose(OrderTicket(),OrderLots(),entryPrice,Slippage,Violet);
err=GetLastError();
if (verbose) Print("OrderClose #",OrderTicket()," Code:
",err,"-",ErrorDescription(err));
if(err==0)
{
if(ticket>0) break;
}
else
{
if(err==0 || err==4 || err==136 || err==137 || err==138 ||
err==146) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
if(ticket>0) break;
}
}
}
break;
case OP_SELL :
for(c=0;c<NumberOfTries;c++)
{
entryPrice =
NormalizeDouble(MarketInfo(Symbol(),MODE_ASK),Digits);
ticket=OrderClose(OrderTicket(),OrderLots(),entryPrice,Slippage,Violet);
err=GetLastError();
if (verbose) Print("OrderClose #",OrderTicket()," Code:
",err,"-",ErrorDescription(err));
if(err==0)
{
if(ticket>0) break;
}
else
{
if(err==0 || err==4 || err==136 || err==137 || err==138 ||
err==146) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
if(ticket>0) break;
}
}
}
break;
case OP_BUYLIMIT :
case OP_BUYSTOP :
case OP_SELLLIMIT:
case OP_SELLSTOP :
OrderDelete(OrderTicket());
}
}
}
}
}
void subCloseOrder()
{
int
NumberOfTries=10,
cnt,
total = 0,
ticket = 0,
err = 0,
c = 0;
total = OrdersTotal();
for(cnt=total-1;cnt>=0;cnt--)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderMagicNumber()==MagicNumber)
{
if(OrderSymbol() == Symbol() )
{
switch(OrderType())
{
case OP_BUY :
for(c=0;c<NumberOfTries;c++)
{
entryPrice =
NormalizeDouble(MarketInfo(Symbol(),MODE_BID),Digits);
ticket=OrderClose(OrderTicket(),OrderLots(),entryPrice,Slippage,Violet);
err=GetLastError();
if (verbose) Print("OrderClose #",OrderTicket()," Code:
",err,"-",ErrorDescription(err));
if(err==0)
{
if(ticket>0) break;
}
else
{
if(err==0 || err==4 || err==136 || err==137 || err==138 ||
err==146) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
if(ticket>0) break;
}
}
}
break;
case OP_SELL :
for(c=0;c<NumberOfTries;c++)
{
entryPrice =
NormalizeDouble(MarketInfo(Symbol(),MODE_ASK),Digits);
ticket=OrderClose(OrderTicket(),OrderLots(),entryPrice,Slippage,Violet);
err=GetLastError();
if (verbose) Print("OrderClose #",OrderTicket()," Code:
",err,"-",ErrorDescription(err));
if(err==0)
{
if(ticket>0) break;
}
else
{
if(err==0 || err==4 || err==136 || err==137 || err==138 ||
err==146) //Busy errors
{
Sleep(5000);
continue;
}
else //normal error
{
if(ticket>0) break;
}
}
}
break;
}
}
}
}
void gridTradeManualLines()
{
//find takeProfit line:
if (ObjectFind(0,"takeProfit")>=0)
{
ObjectSet("takeProfit",OBJPROP_WIDTH,2);
ObjectSet("takeProfit",OBJPROP_COLOR,Blue);
double takeProfitLine = ObjectGetDouble(0,"takeProfit",OBJPROP_PRICE,0);
if (High[0]>takeProfitLine && Low[0]<takeProfitLine) //line crossed
{
CloseAllProfit();
ObjectDelete("takeProfit");
isBarInitialized = false;
SendMail(Symbol()+" Line takeProfit executed. "+MagicNumber,"");
Print("Line takeProfit executed. "+MagicNumber);
}
}
ObjectDelete("neutralize");
isBarInitialized = false;
SendMail(Symbol()+" Set neutralized by line neutralize. "+MagicNumber,"");
Print("Set neutralized by line neutralize. "+MagicNumber);
}
}
if (ObjectFind(0,"targetSell")>=0)
{
ObjectSet("targetSell",OBJPROP_WIDTH,3);
ObjectSet("targetSell",OBJPROP_COLOR,Aqua);
if (Close[0] < ObjectGetDouble(0,"targetSell",OBJPROP_PRICE,0))
{
CloseAllSells();
ObjectDelete("targetSell");
isBarInitialized = false;
SendMail(Symbol()+" Sell Target Line Executed. "+MagicNumber,"");
}
}
ObjectDelete("sellLimit");
isBarInitialized = false;
Trade = true;
SendMail(Symbol()+" Sell Limit Line Executed. "+MagicNumber,"");
}
}
}
double TotalAllMagicLots()
{
int cnt;
double total = 0;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY)
total += OrderLots();
if(OrderType()==OP_SELL)
total -= OrderLots();
}
}
return(total);
}