Hi all,
Can someone help me solve the zero divide error while trading Gold and Silver (2 and 3 digits) ?
Thanks.
========================================================
//+------------------------------------------------------------------+
int init()
{
newTime = Time[0];
return(0);
}
int deinit()
{
return(0);
}
int start()
{
//if (ThereIsAlreadyATrade())
// return;
/*Only enter new trades when there is a new bar*/
AnalyzeNewBar();
if (NEW_BAR == true)
{
AnalyzeExitSituation();
AnalyzeOrderEntry();
}
return;
}
bool ThereIsAlreadyATrade()
{
bool found = false;
int totalOrders = OrdersTotal();
int i = 0;
while ((!found) && (i < totalOrders))
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES ) == true) // If there is the next one
{
if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicNumber)
{
found = true;
}
}
i++;
}
return (found);
}
void AnalyzeNewBar() // Funct. detecting ..
{ // .. a new bar
//static datetime newTime = 0; // Time of the current bar
NEW_BAR = false; // No new bar
if(newTime != Time[0]) // Compare time
{
newTime = Time[0]; // Now time is so
NEW_BAR = true; // A new bar detected
}
}
bool AnalyzeOrderEntry()
{
RefreshRates();
double ATR = iATR(NULL,1440,14,0) ;
double stopLossDistance = ATR * StopLossAsPercentOfATR/100.00 ;
double currentSpread = Ask - Bid;
double lots;
double stopLoss;
int ticket;
double pipRange = GetPipRange();
double TP;
//Long trade
if( BullishMomentum(barsToAnalyze) )
{
//CloseBearTrades();
stopLoss = Ask - stopLossDistance;
if (TargetAsPercentOfATR == 0)
TP = 0;
else
TP = Ask + ATR * TargetAsPercentOfATR/100.00 ;
lots = GetPositionSize(stopLossDistance, Maximum_Loss_Per_Trade);
if (lots > 0)
{
Sleep(10000);
RefreshRates();
ticket = OrderSend(Symbol(),OP_BUY, lots, Ask, 2, stopLoss, TP, SYSTEM_NAME + " Entry", magicNumber);
if (ticket < 0)
{
Print("Long OrderSend failed with error #", GetLastError());
return (false);
}
else
{
Print("Long Order entered Bought at: " + Ask + " SL: " + stopLoss + " TP: " + targetPoint);
//TP = Ask + (Ask - stopLoss) * 1.0 + currentSpread;
//OrderSend(Symbol(),OP_BUY, lots, Ask, 2, stopLoss, TP, SYSTEM_NAME + " Entry");
return(true);
}
}
}
if( BearishMomentum(barsToAnalyze) )
{
//CloseBullTrades();
stopLoss = Bid + stopLossDistance;
if (TargetAsPercentOfATR == 0)
TP = 0;
else
TP = Bid - ATR * TargetAsPercentOfATR/100.00;
lots = GetPositionSize(stopLossDistance, Maximum_Loss_Per_Trade);
if (lots > 0)
{
Sleep(10000);
RefreshRates();
ticket = OrderSend(Symbol(),OP_SELL, lots, Bid, 2, stopLoss, TP, SYSTEM_NAME + " Entry", magicNumber);
if(ticket < 0)
{
Print("Short OrderSend failed with error #", GetLastError());
return (false);
}
else
{
Print("Short Order entered Sold at: " + Bid + " SL: " + stopLoss + " TP: " + targetPoint);
//TP = Bid - (stopLoss - Bid) * 1.0 - currentSpread;
//OrderSend(Symbol(),OP_SELL, lots, Bid, 2, stopLoss, TP, SYSTEM_NAME + " Entry");
return (true);
}
}
}
return (false);
}
double GetPositionSize(double stopLossDistance, double risk)
{
//Analize taking into account the MAXIMUM_LOST_PER_TRADE parameter
double accountBalance = AccountBalance();
double maximumLoss = accountBalance * risk;
double accountFreeMargin = AccountFreeMargin(); // Free margin
double oneLotPrice = MarketInfo(Symbol(),MODE_MARGINREQUIRED); // Price of 1 lot
double minimumLotSize = MarketInfo(Symbol(), MODE_MINLOT);
double lotChangeStep = MarketInfo(Symbol(), MODE_LOTSTEP);
double pipValue = GetPipValue(Symbol());
double lotsizeUnits = maximumLoss / ((1/GetPipRange()) * (stopLossDistance * pipValue));
//Print ("units to play: " + lotsizeUnits);
double lotsizeValue = (lotsizeUnits / 100000) * oneLotPrice;
//Print ("valor de la jugada: " + lotsizeValue);
//Round Lot size
double lotsToPlay = MathFloor(lotsizeValue / oneLotPrice / lotChangeStep) * lotChangeStep;// For opening
if (lotsToPlay < minimumLotSize)
lotsToPlay = minimumLotSize; // Not less than minimal
if (lotsToPlay * oneLotPrice > accountFreeMargin) // Lot larger than free margin
{
Print("Not enough margin to enter new trade. Account free margin: " + accountFreeMargin);
return (0);
}
return (lotsToPlay);
}
double GetPipRange()
{
if (StringFind(Symbol(), "JPY", 0) > 0)
return (0.01);
else
return (0.0001);
}
double GetPipValue(string symbol)
{
double tickSize = 0.0001;
if (StringFind(symbol, "JPY", 0) != -1)
tickSize = 0.01;
//Case 1 - USD is in the second part of the pair
if (StringFind(symbol, "USD", 0) == 3)
{
return (0.0001);
}
//Case 2 - USD is in the first half of the name
if (StringFind(symbol, "USD", 0) == 0)
{
return ( tickSize / MarketInfo(symbol, MODE_BID) );
}
//Case 3 - USD doesnt appear in the name of the pair
if (StringFind(symbol, "USD", 0) == -1)
{
string matchingUSDpair = GetMatchingUSDPair(symbol);
//3.1 - the matching pair contains USD in the first position
if ( StringFind(matchingUSDpair, "USD", 0) == 0
{
return ( tickSize / MarketInfo(matchingUSDpair, MODE_BID) );
}
else //3.2 - the matching pair containd USD in the second half of the name
{
return ( tickSize * MarketInfo(matchingUSDpair, MODE_BID)/ MarketInfo(symbol, MODE_BID) );
}
}
}
string GetMatchingUSDPair(string symbol)
{
string matchingPair;
string usdPairs[13] = { "EURUSD", "GBPUSD", "USDJPY", "USDCHF", "USDCAD", "AUDUSD", "NZDUSD", "USDSGD", "USDNOK", "USDDKK", "USDSEK", "USDHKD", "USDMXN" };
//Get last 3 characters of symbol entered as parameter
string baseCurrency = StringSubstr(symbol, 3, 3);
bool found = false;
int i = 0;
while ((found == false) && (i < 13) )
{
if (usdPairs == baseCurrency + "USD" || usdPairs == "USD" + baseCurrency )
{
matchingPair = usdPairs;
found = true;
}
i++;
}
return (matchingPair);
}
void AnalyzeExitSituation()
{
//Close trades that are two bars old
int totalOrders = OrdersTotal();
int i = 0;
while (i < totalOrders)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES ) == true) // If there is the next one
{
if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicNumber)
{
if (Time[barsToExit] >= OrderOpenTime() )
{
if (OrderType() == OP_BUY)
OrderClose(OrderTicket(), OrderLots(), Bid, 3);
if (OrderType() == OP_SELL)
OrderClose(OrderTicket(), OrderLots(), Ask, 3);
}
}
}
i++;
}
}
bool BullishMomentum(int bars)
{
double yesterdayClose = Close[1];
int i = 2;
bool isHighest = true;
while (i <= bars && isHighest == true)
{
if (yesterdayClose < Close)
isHighest = false;
i++;
}
return (isHighest);
}
bool BearishMomentum(int bars)
{
double yesterdayClose = Close[1];
int i = 2;
bool isLowest = true;
while (i <= bars && isLowest == true)
{
if (yesterdayClose > Close)
isLowest = false;
i++;
}
return (isLowest);
}
Can someone help me solve the zero divide error while trading Gold and Silver (2 and 3 digits) ?
Thanks.
========================================================
//+------------------------------------------------------------------+
int init()
{
newTime = Time[0];
return(0);
}
int deinit()
{
return(0);
}
int start()
{
//if (ThereIsAlreadyATrade())
// return;
/*Only enter new trades when there is a new bar*/
AnalyzeNewBar();
if (NEW_BAR == true)
{
AnalyzeExitSituation();
AnalyzeOrderEntry();
}
return;
}
bool ThereIsAlreadyATrade()
{
bool found = false;
int totalOrders = OrdersTotal();
int i = 0;
while ((!found) && (i < totalOrders))
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES ) == true) // If there is the next one
{
if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicNumber)
{
found = true;
}
}
i++;
}
return (found);
}
void AnalyzeNewBar() // Funct. detecting ..
{ // .. a new bar
//static datetime newTime = 0; // Time of the current bar
NEW_BAR = false; // No new bar
if(newTime != Time[0]) // Compare time
{
newTime = Time[0]; // Now time is so
NEW_BAR = true; // A new bar detected
}
}
bool AnalyzeOrderEntry()
{
RefreshRates();
double ATR = iATR(NULL,1440,14,0) ;
double stopLossDistance = ATR * StopLossAsPercentOfATR/100.00 ;
double currentSpread = Ask - Bid;
double lots;
double stopLoss;
int ticket;
double pipRange = GetPipRange();
double TP;
//Long trade
if( BullishMomentum(barsToAnalyze) )
{
//CloseBearTrades();
stopLoss = Ask - stopLossDistance;
if (TargetAsPercentOfATR == 0)
TP = 0;
else
TP = Ask + ATR * TargetAsPercentOfATR/100.00 ;
lots = GetPositionSize(stopLossDistance, Maximum_Loss_Per_Trade);
if (lots > 0)
{
Sleep(10000);
RefreshRates();
ticket = OrderSend(Symbol(),OP_BUY, lots, Ask, 2, stopLoss, TP, SYSTEM_NAME + " Entry", magicNumber);
if (ticket < 0)
{
Print("Long OrderSend failed with error #", GetLastError());
return (false);
}
else
{
Print("Long Order entered Bought at: " + Ask + " SL: " + stopLoss + " TP: " + targetPoint);
//TP = Ask + (Ask - stopLoss) * 1.0 + currentSpread;
//OrderSend(Symbol(),OP_BUY, lots, Ask, 2, stopLoss, TP, SYSTEM_NAME + " Entry");
return(true);
}
}
}
if( BearishMomentum(barsToAnalyze) )
{
//CloseBullTrades();
stopLoss = Bid + stopLossDistance;
if (TargetAsPercentOfATR == 0)
TP = 0;
else
TP = Bid - ATR * TargetAsPercentOfATR/100.00;
lots = GetPositionSize(stopLossDistance, Maximum_Loss_Per_Trade);
if (lots > 0)
{
Sleep(10000);
RefreshRates();
ticket = OrderSend(Symbol(),OP_SELL, lots, Bid, 2, stopLoss, TP, SYSTEM_NAME + " Entry", magicNumber);
if(ticket < 0)
{
Print("Short OrderSend failed with error #", GetLastError());
return (false);
}
else
{
Print("Short Order entered Sold at: " + Bid + " SL: " + stopLoss + " TP: " + targetPoint);
//TP = Bid - (stopLoss - Bid) * 1.0 - currentSpread;
//OrderSend(Symbol(),OP_SELL, lots, Bid, 2, stopLoss, TP, SYSTEM_NAME + " Entry");
return (true);
}
}
}
return (false);
}
double GetPositionSize(double stopLossDistance, double risk)
{
//Analize taking into account the MAXIMUM_LOST_PER_TRADE parameter
double accountBalance = AccountBalance();
double maximumLoss = accountBalance * risk;
double accountFreeMargin = AccountFreeMargin(); // Free margin
double oneLotPrice = MarketInfo(Symbol(),MODE_MARGINREQUIRED); // Price of 1 lot
double minimumLotSize = MarketInfo(Symbol(), MODE_MINLOT);
double lotChangeStep = MarketInfo(Symbol(), MODE_LOTSTEP);
double pipValue = GetPipValue(Symbol());
double lotsizeUnits = maximumLoss / ((1/GetPipRange()) * (stopLossDistance * pipValue));
//Print ("units to play: " + lotsizeUnits);
double lotsizeValue = (lotsizeUnits / 100000) * oneLotPrice;
//Print ("valor de la jugada: " + lotsizeValue);
//Round Lot size
double lotsToPlay = MathFloor(lotsizeValue / oneLotPrice / lotChangeStep) * lotChangeStep;// For opening
if (lotsToPlay < minimumLotSize)
lotsToPlay = minimumLotSize; // Not less than minimal
if (lotsToPlay * oneLotPrice > accountFreeMargin) // Lot larger than free margin
{
Print("Not enough margin to enter new trade. Account free margin: " + accountFreeMargin);
return (0);
}
return (lotsToPlay);
}
double GetPipRange()
{
if (StringFind(Symbol(), "JPY", 0) > 0)
return (0.01);
else
return (0.0001);
}
double GetPipValue(string symbol)
{
double tickSize = 0.0001;
if (StringFind(symbol, "JPY", 0) != -1)
tickSize = 0.01;
//Case 1 - USD is in the second part of the pair
if (StringFind(symbol, "USD", 0) == 3)
{
return (0.0001);
}
//Case 2 - USD is in the first half of the name
if (StringFind(symbol, "USD", 0) == 0)
{
return ( tickSize / MarketInfo(symbol, MODE_BID) );
}
//Case 3 - USD doesnt appear in the name of the pair
if (StringFind(symbol, "USD", 0) == -1)
{
string matchingUSDpair = GetMatchingUSDPair(symbol);
//3.1 - the matching pair contains USD in the first position
if ( StringFind(matchingUSDpair, "USD", 0) == 0
{
return ( tickSize / MarketInfo(matchingUSDpair, MODE_BID) );
}
else //3.2 - the matching pair containd USD in the second half of the name
{
return ( tickSize * MarketInfo(matchingUSDpair, MODE_BID)/ MarketInfo(symbol, MODE_BID) );
}
}
}
string GetMatchingUSDPair(string symbol)
{
string matchingPair;
string usdPairs[13] = { "EURUSD", "GBPUSD", "USDJPY", "USDCHF", "USDCAD", "AUDUSD", "NZDUSD", "USDSGD", "USDNOK", "USDDKK", "USDSEK", "USDHKD", "USDMXN" };
//Get last 3 characters of symbol entered as parameter
string baseCurrency = StringSubstr(symbol, 3, 3);
bool found = false;
int i = 0;
while ((found == false) && (i < 13) )
{
if (usdPairs == baseCurrency + "USD" || usdPairs == "USD" + baseCurrency )
{
matchingPair = usdPairs;
found = true;
}
i++;
}
return (matchingPair);
}
void AnalyzeExitSituation()
{
//Close trades that are two bars old
int totalOrders = OrdersTotal();
int i = 0;
while (i < totalOrders)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES ) == true) // If there is the next one
{
if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicNumber)
{
if (Time[barsToExit] >= OrderOpenTime() )
{
if (OrderType() == OP_BUY)
OrderClose(OrderTicket(), OrderLots(), Bid, 3);
if (OrderType() == OP_SELL)
OrderClose(OrderTicket(), OrderLots(), Ask, 3);
}
}
}
i++;
}
}
bool BullishMomentum(int bars)
{
double yesterdayClose = Close[1];
int i = 2;
bool isHighest = true;
while (i <= bars && isHighest == true)
{
if (yesterdayClose < Close)
isHighest = false;
i++;
}
return (isHighest);
}
bool BearishMomentum(int bars)
{
double yesterdayClose = Close[1];
int i = 2;
bool isLowest = true;
while (i <= bars && isLowest == true)
{
if (yesterdayClose > Close)
isLowest = false;
i++;
}
return (isLowest);
}