bool GetRates()
//+------------------------------------------------------------------+
{
bool ret = RefreshRates();
//remember Ask/Bid changes -- used to detect levels crossing
if (currentAsk != previousAsk || currentBid != previousBid) {
previousAsk = currentAsk;
previousBid = currentBid;
}
currentAsk = Ask; currentBid = Bid;
return(ret);
}//GetRates()
//+------------------------------------------------------------------+
int _OrderSend(string symbol, int type, double lots, double price, int slippage, double stoploss, double takeprofit, string comment, int magic, datetime expiration, color arrow_color)
//+------------------------------------------------------------------+
{
#define MAX_RETRIES 10
//"reliable" version of OrderSend(): will retry 10 times before failing
int i,j,err,ticket;
// Make sure Spread is not too large
if (MarketInfo(symbol, MODE_SPREAD) > MaxSpread) {
_Alert("Order was NOT SENT because SPREAD is TOO HIGH ("+DoubleToStr(MarketInfo(symbol, MODE_SPREAD)/pipMult,1)+")");
return(-1);
}
for (i=0;i<MAX_RETRIES;i++) {
for (j=0;j<MAX_RETRIES && !IsTradeAllowed();j++) Sleep(500); // wait for Trade to be allowed(free context)
if (j==MAX_RETRIES) {
_Alert("OrderSend() FAILED: trade not allowed");
return (-1);
}
// send order with 0 SL, then modify order to apply SL -- a common counter-ECN method found in SteveHopwood's bots...
if (!brokerIsECN) {
ticket = OrderSend(symbol, type, lots, price, slippage, stoploss, takeprofit, comment, magic, expiration, arrow_color);
if (ticket != -1) return (ticket);
} else {
ticket = OrderSend(symbol, type, lots, price, slippage, 0/*stoploss*/, 0/*takeprofit*/, comment, magic, expiration, arrow_color);
if (ticket != -1) {
if (stoploss!=0 || takeprofit!=0) {
Sleep(2000);//wait before modifying the open order
_OrderModify(ticket, price, stoploss, takeprofit, expiration, arrow_color);
}
return(ticket);//success
}
}
err = GetLastError();
switch (err) {
case ERR_INVALID_STOPS: break;//130=invalid stops: SL or TP are set too close to open price;
case ERR_INVALID_TRADE_VOLUME: break;//131=invalid trade volume: lot size is too small, or does not follow the LOTSTEP value (eg 0.12 lots for a 0.1 LOTSTEP account);
}
}
_Alert("OrderSend() FAILED: "+DoubleToStr(lots,2)+" lots at "+DoubleToStr(price,Digits)+",SL="+DoubleToStr(stoploss,Digits)+",TP="+DoubleToStr(takeprofit,Digits)+",Ask="+DoubleToStr(Ask,Digits)+" ("+err+"): "+ErrorDescription(err));
return(-1);
}
//+------------------------------------------------------------------+
bool _OrderModify(int ticket, double price, double stoploss, double takeprofit, datetime expiration, color arrow_color)
//+------------------------------------------------------------------+
{
//"reliable" version of OrderModify(): will retry 10 times before failing
int i,j,err,ret;
for (i=0;i<MAX_RETRIES;i++) {
for (j=0;j<MAX_RETRIES && !IsTradeAllowed();j++) Sleep(500); // wait for Trade to be allowed(free context)
if (j==MAX_RETRIES) {
_Alert("OrderModify(#"+ticket+") FAILED: trade not allowed");
return(false);
}
ret = OrderModify(ticket, price, stoploss, takeprofit, expiration, arrow_color);
if (ret == true) return(true);//success
err = GetLastError();
switch (err) {
case ERR_NO_RESULT: // error 1 means OrderModify() was called with unchanged values
case ERR_INVALID_STOPS:// error 130 "invalid stops" when SL is set too close to current price
case ERR_INVALID_TRADE_VOLUME://131=invalid trade volume: lot size is too small, or does not follow the LOTSTEP value (eg 0.12 lots for a 0.1 LOTSTEP account);
return(true);
}
}
_Alert("OrderModify(#"+ticket+") FAILED ("+err+"): "+ErrorDescription(err));
return(false);
}
/*
//+------------------------------------------------------------------+
bool _OrderClose( int ticket, double lots, double price, int slippage, color Color)
//+------------------------------------------------------------------+
{
//"reliable" version of OrderClose(): will retry 10 times before failing
int i,j,err;
bool ret;
for (i=0;i<MAX_RETRIES;i++) {
for (j=0;j<MAX_RETRIES && !IsTradeAllowed();j++) Sleep(500); // wait for Trade to be allowed(free context)
if (j==MAX_RETRIES) {
_Alert("OrderClose(#"+ticket+") FAILED: trade not allowed");
return(false);
}
ret = OrderClose(ticket, lots, price, slippage, Color);
if (ret == true) return(true);//success
}
err = GetLastError();
_Alert("OrderClose(#"+ticket+") FAILED ("+err+"): "+ErrorDescription(err));
return(false);
}
*/
/*
//+------------------------------------------------------------------+
bool _OrderDelete(int ticket, color Color)
//+------------------------------------------------------------------+
{
//"reliable" version of OrderDelete(): will retry 10 times before failing
int i,j,err;
bool ret;
for (i=0;i<MAX_RETRIES;i++) {
for (j=0;j<MAX_RETRIES && !IsTradeAllowed();j++) Sleep(500); // wait for Trade to be allowed(free context)
if (j==MAX_RETRIES) {
_Alert("OrderDelete(#"+ticket+") FAILED: trade not allowed");
return(false);
}
ret = OrderDelete(ticket, Color);
if (ret == true) return(true);//success
}
err = GetLastError();
_Alert("OrderDelete(#"+ticket+") FAILED ("+err+"): "+ErrorDescription(err));
return(false);
}
*/
hope this is the good part as it is alot of code
Thanks... I removed the spread limitations.. However strange thing is that in startegy tester i put spread 2.. but also not seems to work as i had my maximum spread to 4 (which i now removed).
show spread on the market watch, so you'll know exactly how much spread GBPJPY.
Usually in brokerage mt4 4 digits spread gbpjpy 5 to 7, and mt4 5 digits 20 to 35
get also this error
2016.12.08 12:20:39.714 3 Tier London Breakout EA v1.3b GBPJPYecn,M15: invalid lots amount for OrderSend function
means invalid amount of lots for the order..
I use risk size positions. which works on my 2 other non asian pairs.. but not on GBPJPY
When i set a fixed lot size its working..
how do get the risk postion working?
get also this error
2016.12.08 12:20:39.714 3 Tier London Breakout EA v1.3b GBPJPYecn,M15: invalid lots amount for OrderSend function
means invalid amount of lots for the order..
I use risk size positions. which works on my 2 other non asian pairs.. but not on GBPJPY
When i set a fixed lot size its working..
how do get the risk postion working?
error invalid lots amount.
where your code for calculation lots size
extern double Lot = 0.01;
extern double MaxRisk = 0; // if 0 then use fixed Lots above
double BuyEntry,BuyTP1,BuyTP2,BuyTP3,BuyTP4,BuyTP5,BuySL;
double SellEntry,SellTP1,SellTP2,SellTP3,SellTP4,SellTP5,SellSL;
int SL_pips,TP1_pips,TP2_pips,TP3_pips,TP4_pips,TP5_pips,MoveToBE_pips;
double TP1FactorInput,TP2FactorInput,TP3FactorInput,TP4FactorInput,TP5FactorInput,SLFactorInput;
//box and session
datetime tBoxStart,tBoxEnd,tSessionStart,tSessionEnd,tLastComputedSessionStart,tLastComputedSessionEnd;
double boxHigh,boxLow,boxExtent,boxMedianPrice;
int magic1,magic2,magic3,magic4,magic5;
// market info
int pipMult; // multiplier to convert pips to Points;
double pip,pipvalue;
int digits;
double minlot,lotstep;
int SLIPPAGE;
double previousAsk,currentAsk,previousBid,currentBid;
//Risk Management
int maxSL;
string op_str[5] = { "BUY","SELL","BUYLIMIT","SELLLIMIT","BUYSTOP","SELLSTOP"};
int init()
//+------------------------------------------------------------------+
{
RobotDisabled = false;
TradingStatus = Status_initializing;
getpip(); // get pip multiplier and digit
SLIPPAGE = Slippage*pipMult;
MaxSpread *= pipMult;
symbol = Symbol(); // used throughout all functions
RemoveObjects(objPrefix);
if (Lot < minlot) {
DisabledMessage = "Lot must be >= "+minlot+NL;
RobotDisabled = true;
_Alert (DisabledMessage);
Comment("The robot is NOT trading because ", DisabledMessage);
return;
}
//Check MaxRisk value
if (MaxRisk > 100) {
MessageBox("INVALID MaxRisk value " + MaxRisk + NL
+ "Please reload the robot with valid MaxRisk.");
DisabledMessage = "MaxRisk value ("+MaxRisk+") is INVALID";
RobotDisabled = true;
_Alert (DisabledMessage);
Comment("The robot is NOT trading because ", DisabledMessage);
return;
}
if (SendTrades == false) {
DisabledMessage = "SendTrades is set to FALSE"+NL;
RobotDisabled = true;
void _SetFibLevel(string objname, int level, double value, string description)
//+------------------------------------------------------------------+
{
ObjectSet(objname,OBJPROP_FIRSTLEVEL+level,value);
ObjectSetFiboDescription(objname,level,description);
}
void CheckForOpen()
//+------------------------------------------------------------------+
{
double lotsToTrade,TP_pips;
GetRates();
//buy on BuyEntry crossup: (make sure price is still closer to Entry than TP1, to allow a minimum profit, and keep SL as low as possible)
if (iClose(NULL,TFforReentry,1) <= BuyEntry && Ask >= BuyEntry && Ask < (BuyEntry+BuyTP1)/2) {
lotsToTrade = get_lotsToTrade(magic1, TP_pips,SL_pips);
_OrderSend(symbol,OP_BUY,lotsToTrade,Ask,SLIPPAGE,BuySL, BuyTP1,TradeComment,magic1,0,Blue);
if (NumTradesToOpen>=2) {
GetRates();
_OrderSend(symbol,OP_BUY,lotsToTrade,Ask,SLIPPAGE,BuySL, BuyTP2,TradeComment,magic2,0,Blue);
}
if (NumTradesToOpen>=3) {
GetRates();
_OrderSend(symbol,OP_BUY,lotsToTrade,Ask,SLIPPAGE,BuySL, BuyTP3,TradeComment,magic3,0,Blue);
}
if (NumTradesToOpen>=4) {
GetRates();
_OrderSend(symbol,OP_BUY,lotsToTrade,Ask,SLIPPAGE,BuySL, BuyTP4,TradeComment,magic4,0,Blue);
}
if (NumTradesToOpen>=5) {
GetRates();
_OrderSend(symbol,OP_BUY,lotsToTrade,Ask,SLIPPAGE,BuySL, BuyTP5,TradeComment,magic5,0,Blue);
}
}
else //sell on SellEntry crossdown:
if (iClose(NULL,TFforReentry,1) >= SellEntry && Bid <= SellEntry && Bid > (SellEntry+SellTP1)/2) {
lotsToTrade = get_lotsToTrade(magic1, TP_pips,SL_pips);
_OrderSend(symbol,OP_SELL,lotsToTrade,Bid,SLIPPAGE,SellSL, SellTP1,TradeComment,magic1,0,Blue);
if (NumTradesToOpen>=2) {
GetRates();
_OrderSend(symbol,OP_SELL,lotsToTrade,Bid,SLIPPAGE,SellSL, SellTP2,TradeComment,magic2,0,Blue);
}
if (NumTradesToOpen>=3) {
GetRates();
_OrderSend(symbol,OP_SELL,lotsToTrade,Bid,SLIPPAGE,SellSL, SellTP3,TradeComment,magic3,0,Blue);
}
if (NumTradesToOpen>=4) {
GetRates();
_OrderSend(symbol,OP_SELL,lotsToTrade,Bid,SLIPPAGE,SellSL, SellTP4,TradeComment,magic4,0,Blue);
}
if (NumTradesToOpen>=5) {
GetRates();
_OrderSend(symbol,OP_SELL,lotsToTrade,Bid,SLIPPAGE,SellSL, SellTP5,TradeComment,magic5,0,Blue);
}
}
}
}//CheckForOpen
//+------------------------------------------------------------------+
void ManageOpenTrades()
//+------------------------------------------------------------------+
{
int magic,cc,last_closed_ticket1=0;
double initialSL;
datetime last_closed_opentime1;
//find last closed trade#1 in trades history; start from last history trade=latest
for (cc = OrdersHistoryTotal()-1; cc >= 0; cc--)
{
OrderSelect(cc, SELECT_BY_POS, MODE_HISTORY);
if (OrderMagicNumber()==magic1 && OrderSymbol()==symbol && OrderType()<=OP_SELL) {
last_closed_ticket1 = OrderTicket();
last_closed_opentime1 = OrderOpenTime();
break;
}
}
// manage open trades
for (cc = OrdersTotal() - 1; cc >=0; cc--)
{
if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
magic = OrderMagicNumber();
if (OrderSymbol() == symbol && OrderCloseTime() == 0)
{
if (OrderOpenTime() < tSessionStart || OrderOpenTime() > tSessionEnd) {
// this trade belongs to a different box/session:
// we must recompute the corresponding box and levels values to handle it properly
compute_LB_Indi_LEVELS(OrderOpenTime());
}
// other trades will see their SL follow the TP levels each time a new TP level is hit:
// when TP2 hit, move all SL to TP1+BEprofit, when TP3 is hit, move SL to TP2+BEprofit, etc.
if (MoveSLwhenProfit(MoveToBE_pips, BreakEvenProfitInPips)) continue;
if (MoveSLwhenProfit(TP2_pips, TP1_pips)) continue;
if (MoveSLwhenProfit(TP3_pips, TP2_pips)) continue;
if (MoveSLwhenProfit(TP4_pips, TP3_pips)) continue;
if (MoveSLwhenProfit(TP5_pips, TP4_pips)) continue;
}
}
double get_lotsToTrade(int magic, int TP_pips, int SL_pips)
//+------------------------------------------------------------------+
{
double lotsToTrade,profitpips=0,currentProfit=0,pips_to_recoup=0,factor=1,last_trade_profit=0;
int last_ticket=0;
if (!UseMartingale)
{
//adjust Lot based on MaxRisk and SL value
if (MaxRisk > 0) return (MathMin(Lot,GetMaxLot(SL_pips,MaxRisk)));
else return (Lot);
}
// if orders are still open, then use the same multiplier as the open trades
// except for non-auto-martingale mode: use the PREVIOUS (lower) multiplier
if (TradesOpen>0) {
if (!AutoMartingale && MartDepth>0 && LastLotMultiplier>1) {
// non auto-martingale: use PREVIOUS multiplier
for (Mart_Idx=0; Mart_Idx < MartDepth-1; Mart_Idx++) {
if (MartFactor[Mart_Idx] >= LastLotMultiplier) break;// found current multiplier
}
Mart_Idx--; // use PREVIOUS multiplier
Print ("### Trades still open, using PREVIOUS MartFactor=",MartFactor[Mart_Idx]);
return (MartFactor[Mart_Idx] * Lot);
} else {
Print ("### Trades still open, using same MartFactor=",LastLotMultiplier);
return (LastLotMultiplier * Lot);
}
}
// No open trades;
// Martingale is used: determine the martingale factor based on results of last trades
//cumulate past profits/losses
//search trade history for past trades, start from end of history(=newest trades)
//if no past buy/sell trade can be found, then the mart factor will not change;
for (int cc = OrdersHistoryTotal()-1; cc >= 0; cc--)
{
OrderSelect(cc, SELECT_BY_POS, MODE_HISTORY);
if (OrderMagicNumber()!=magic1 && OrderMagicNumber()!=magic2 && OrderMagicNumber()!=magic3 && OrderMagicNumber()!=magic4 && OrderMagicNumber()!=magic5) continue;
if (OrderSymbol()!=symbol || OrderType()>OP_SELL) continue;
if (last_ticket==0) {
last_ticket = OrderTicket();
factor = MathFloor(OrderLots()/Lot + 0.5); // compute nearest integer value to prevent division approximation
last_trade_profit = OrderProfit();
}
profitpips = (OrderClosePrice()-OrderOpenPrice())/pip*OrderLots()/Lot;
if (OrderType()==OP_SELL) profitpips = -profitpips;
//OrderProfit()/pipvalue/Lot;
currentProfit += profitpips;
//if (maxProfit < currentProfit) maxProfit = currentProfit;
if (Debug) Print (" #",OrderTicket()," profit = ",DoubleToStr(OrderLots()/Lot,0)," x ",profitpips/(OrderLots()/Lot)," = ",profitpips,"pips, currentProfit=",currentProfit,"pips");
// we stop scanning past trades when we have reached the first trade of the last series, ie the trade with a factor of 1
if (OrderMagicNumber()==magic1 && OrderLots()==Lot) break;
}
// if no pips to recoup, then go back to initial Lot size
if (currentProfit >= 0) {
Print ("### Current Profit=",currentProfit,"pips; No pips to recoup, MartFactor=1");
Mart_Idx = 0;//reset mart sequence
return (Lot);
}
// when ResetMartAtFirstProfit option is true, then reset the Mart sequence at the first profitable trade;
if (ResetMartAtFirstProfit==true && last_trade_profit>=0) {
Print ("### Current Profit=",currentProfit,"pips; No pips to recoup, MartFactor=1");
Mart_Idx = 0;//reset mart sequence
return (Lot);
}
// there are pips to recoup, compute the next Mart factor
pips_to_recoup = -currentProfit;
double GetMaxLot(int SL, double Risk)
//+------------------------------------------------------------------+
{
double lotsize,tickvalue,pipvaluefor1lot,SLfor1lotfor1percent,maxLot;
lotsize = MarketInfo(Symbol(),MODE_LOTSIZE);
tickvalue = MarketInfo(Symbol(),MODE_TICKVALUE);
pipvaluefor1lot = lotsize*tickvalue*pip;
maxLot = NormalizeDouble(AccountFreeMargin()*Risk/100/pipvaluefor1lot/SL,2);
return(maxLot);
}
ool BreakEvenStopLoss(int profit_pips_target, int pips_to_lock)
//+------------------------------------------------------------------+
{
//Lock-in some profit after a minimum profit target is reached:
//(move SL to BE+pips_to_lock)
double SL;
//Long
if (OrderType() == OP_BUY && Bid >= OrderOpenPrice()+profit_pips_target*pip && OrderStopLoss() < OrderOpenPrice()) {
SL = NormalizeDouble(OrderOpenPrice() + (pips_to_lock*pip), Digits);
_Alert(" #"+OrderTicket()+" moving to BE+"+pips_to_lock+"pips");
_OrderModify(OrderTicket(), OrderOpenPrice(), SL, OrderTakeProfit(), OrderExpiration(), Green);
return(true);
}
//Short
if (OrderType() == OP_SELL && Ask <= OrderOpenPrice()-profit_pips_target*pip && (OrderStopLoss() > OrderOpenPrice() || OrderStopLoss()==0)) {
SL = NormalizeDouble(OrderOpenPrice() - (pips_to_lock*pip), Digits);
_Alert(" #"+OrderTicket()+" moving to BE+"+pips_to_lock+"pips");
_OrderModify(OrderTicket(), OrderOpenPrice(), SL, OrderTakeProfit(), OrderExpiration(), Green);
return(true);
}
return(false);//did not move to BE
}//BreakEvenStopLoss()
*/
int _OrderSend(string symbol, int type, double lots, double price, int slippage, double stoploss, double takeprofit, string comment, int magic, datetime expiration, color arrow_color)
//+------------------------------------------------------------------+
{
#define MAX_RETRIES 10
//"reliable" version of OrderSend(): will retry 10 times before failing
int i,j,err,ticket;
// Make sure Spread is not too large
if (MarketInfo(symbol, MODE_SPREAD) > MaxSpread) {
_Alert("Order was NOT SENT because SPREAD is TOO HIGH ("+DoubleToStr(MarketInfo(symbol, MODE_SPREAD)/pipMult,1)+")");
return(-1);
}
for (i=0;i<MAX_RETRIES;i++) {
for (j=0;j<MAX_RETRIES && !IsTradeAllowed();j++) Sleep(500); // wait for Trade to be allowed(free context)
if (j==MAX_RETRIES) {
_Alert("OrderSend() FAILED: trade not allowed");
return (-1);
}
// send order with 0 SL, then modify order to apply SL -- a common counter-ECN method found in SteveHopwood's bots...
if (!brokerIsECN) {
ticket = OrderSend(symbol, type, lots, price, slippage, stoploss, takeprofit, comment, magic, expiration, arrow_color);
if (ticket != -1) return (ticket);
} else {
ticket = OrderSend(symbol, type, lots, price, slippage, 0/*stoploss*/, 0/*takeprofit*/, comment, magic, expiration, arrow_color);
if (ticket != -1) {
if (stoploss!=0 || takeprofit!=0) {
Sleep(2000);//wait before modifying the open order
_OrderModify(ticket, price, stoploss, takeprofit, expiration, arrow_color);
}
return(ticket);//success
}
}
err = GetLastError();
switch (err) {
case ERR_INVALID_STOPS: break;//130=invalid stops: SL or TP are set too close to open price;
case ERR_INVALID_TRADE_VOLUME: break;//131=invalid trade volume: lot size is too small, or does not follow the LOTSTEP value (eg 0.12 lots for a 0.1 LOTSTEP account);
}
}
_Alert("OrderSend() FAILED: "+DoubleToStr(lots,2)+" lots at "+DoubleToStr(price,Digits)+",SL="+DoubleToStr(stoploss,Digits)+",TP="+DoubleToStr(takeprofit,Digits)+",Ask="+DoubleToStr(Ask,Digits)+" ("+err+"): "+ErrorDescription(err));
return(-1);
}
sorry i hope its in here
Please use the SRC button when posting code.
I have done it for you. Next time, please don't forget
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
I have opened 3 charts : EURUSD GBPUSD & GBPJPY. Apllied the ea to all 3 charts with different magicnumber.
EURUSD & GBPUSD do take autotrades of my ea but GBPJPY doesnt. Can anybody help me why.
This is an error i get from my experts tab:
2016.12.08 10:16:29.728 3 Tier London Breakout EA v1.3b GBPJPYecn,M15: Alert: LB EA: GBPJPYecn OrderSend() FAILED: 0.00 lots at 143.990,SL=143.405,TP=144.535,Ask=143.990 (4051): invalid function parameter value
All my lots lots and risk settings are the same on all 3 pairs.