Experts: Simple Scalping EA

 

Simple Scalping EA:

Very simple scalping EA, no Indicators. Logic is based on very fast price movements.

Author: yan

 

Hello picassoinaction,

I love the idea that you've scheduled your EA. I have been reviewing the code
and the functioning of the ea and believe that I have seen the bug that causes what your say.
It's the part that calculates the Take profit, in the code is that it does not calculate equal
that the stop loss and also in practices it is not the same as take the settings and which leaves
in the trades-

with regard to putting a stop loss of 5 or 7 pips, cannot be because they do not support brokers,

normally have a minimum of 15 pips stop, but a virtual stop, hidden to the broker, can be programmed

by the value you want without any limitation. I can schedule this part, but repair the calculating

the takeprofit I'll leave to you, which for me is rather complicated.

Sorry for my bad English.

a greeting
 
Jumper:

Hello picassoinaction,

I love the idea that you've scheduled your EA. I have been reviewing the code
and the functioning of the ea and believe that I have seen the bug that causes what your say.
It's the part that calculates the Take profit, in the code is that it does not calculate equal
that the stop loss and also in practices it is not the same as take the settings and which leaves
in the trades-

with regard to putting a stop loss of 5 or 7 pips, cannot be because they do not support brokers,

normally have a minimum of 15 pips stop, but a virtual stop, hidden to the broker, can be programmed

by the value you want without any limitation. I can schedule this part, but repair the calculating

the takeprofit I'll leave to you, which for me is rather complicated.

Sorry for my bad English.

a greeting


Hi

I am using Alpary US and they do allow 6-7 points stop loss and profits.

I realize that many brokers won't let it. So it's easily adjustable. There has to be somewhere else the bug that stops the program after 1-2 orders...

 

Hi,

You have checked if it calculates the take profit correctly? I mean within the OrderSend function.

a greeting

 
picassoinaction:


Hi

I am using Alpary US and they do allow 6-7 points stop loss and profits.

I realize that many brokers won't let it. So it's easily adjustable. There has to be somewhere else the bug that stops the program after 1-2 orders...

Hello, now if I have found the bug.

It is in the function CountAll, which counts orders stop based on
a variable called Magic, which is not the number magic of each trade.
Then at the beginning of start() accounts the trades based on MagicNumberU and
MagicNumberD, that does not correspond to the variable Magic.

There is error.

a greeting
 

There were several problems with the code, one of the main ones is that MetaTrader changes the MagicNumber when the Buy or Sell Stop is comitted. As such using the MagicNumber as in the code won't work orders get orphaned. I completely rewrote the code last night and have set it so that there is always at least one Buy and one sell order. I think it is what you are looking for. It should be easier now to mess around with the settings to make it do what you want.

#include <stderror.mqh>

// Lots to use
extern double Lots = 0.1;
// Limit (tp) setting
extern int Limit = 20;
// Stop (sl) setting
extern int Stop = 18;

// Timeout 10 seconds
int Timeout = 10000;
// Number of retries upon failure
int Retries = 10;
// Current symbol to use if different from Chart
string CurrentSymbol = "";
// Current number of Digits
int CurrentDigits = 5;
// Current Points
double CurrentPoints = 0.0001;
// Stop distance from price
int Distance = 100;

/// <summary>
/// Initialize
/// </summary>
/// <returns>Result</returns>
int init()
{
// If no symbol set use current chart
if(StringLen(CurrentSymbol) == 0)
CurrentSymbol = Symbol();

CurrentPoints = MarketInfo(CurrentSymbol, MODE_POINT);
CurrentDigits = MarketInfo(CurrentSymbol, MODE_DIGITS);

// Check the digits and points
if(CurrentPoints == 0.001)
{
CurrentPoints = 0.01;
CurrentDigits = 3;
}
else if(CurrentPoints == 0.00001)
{
CurrentPoints = 0.0001;
CurrentDigits = 5;
}
return(0);
}

/// <summary>
/// UnInitialize
/// </summary>
/// <returns>Result</returns>
int deinit()
{
return(0);
}

/// <summary>
/// Ezpert Start
/// </summary>
/// <returns>Result</returns>
int start()
{
// Check Buy Stops
if(CountStops(OP_BUYSTOP) < 1)
{
// No Buy stops open one
NewStopOrder(OP_BUYSTOP);
}
else
{
// Update Stoploss and Takeprofit
StopUpdate();
}

// Check Sell Stops
if(CountStops(OP_SELLSTOP) < 1)
{
// No Sell stops open one
NewStopOrder(OP_SELLSTOP);
}
else
{
// Update Stoploss and Takeprofit
StopUpdate();
}
return(0);
}

/// <summary>
/// Stop Update
/// </summary>
void StopUpdate()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == CurrentSymbol)
{
switch(OrderType())
{
case OP_BUYSTOP:
if ((OrderOpenPrice() - Ask) < 0.0005)
OrderUpdate(OrderTicket());
else if ((OrderOpenPrice() - Ask) > 0.0007)
OrderUpdate(OrderTicket());
break;
case OP_SELLSTOP:
if ((OrderOpenPrice() + Bid) > 0.007)
OrderUpdate(OrderTicket());
else if ((OrderOpenPrice() + Bid) < 0.0005)
OrderUpdate(OrderTicket());
break;
}
}
}
}

/// <summary>
/// New Stop Order
/// </summary>
/// <param name="orderType">Type of order to open</param>
void NewStopOrder(int orderType)
{
bool loop = True;
int count = 0;
while (loop && count < Retries)
{
while (IsTradeContextBusy())
{
Sleep(Timeout);
count++;
}

RefreshRates();
double ask = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_ASK), CurrentDigits);
double bid = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_BID), CurrentDigits);
double point = MarketInfo(CurrentSymbol, MODE_POINT);
switch(orderType)
{
case OP_BUYSTOP:
OrderSend(CurrentSymbol, OP_BUYSTOP, Lots, bid + Distance * point, 0, SL(OP_BUY, ask + Distance * point), TP(OP_BUY, bid), "", 0, 0, CLR_NONE);
break;
case OP_SELLSTOP:
OrderSend(CurrentSymbol, OP_SELLSTOP, Lots, bid - Distance * point, 0, SL(OP_SELL, ask - Distance * point), TP(OP_SELL, bid), "", 0, 0, CLR_NONE);
break;
}
loop = parseError();
}
}

/// <summary>
/// Order Update
/// </summary>
/// <param name="ticketNumber">ticket Number</param>
void OrderUpdate(int ticketNumber)
{
bool loop = True;
int count = 0;

while (loop && count < Retries)
{
while (IsTradeContextBusy())
{
Sleep(Timeout);
count++;
}

RefreshRates();
double ask = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_ASK), CurrentDigits);
double bid = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_BID), CurrentDigits);
double point = MarketInfo(CurrentSymbol, MODE_POINT);

if (OrderSelect(ticketNumber, SELECT_BY_TICKET))
{
switch(OrderType())
{
case OP_SELL:
OrderModify(ticketNumber, bid - Distance * point, SL(OP_SELL, ask - Distance * point), TP(OP_SELL, bid), 0, CLR_NONE);
break;
case OP_BUY:
OrderModify(ticketNumber, bid + Distance * point, SL(OP_BUY, bid + Distance * point), TP(OP_BUY, bid), 0, CLR_NONE);
break;
}
}
loop = parseError();
}
}

/// <summary>
/// Count All
/// </summary>
/// <param name="orderTyper">Order Type</param>
/// <returns>Count</returns>
int CountStops(int orderType)
{
int count = 0;
for (int i = 0; i < OrdersTotal(); i++)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == CurrentSymbol)
{
if (OrderType() == orderType)
count++;
}
}
return (count);
}

/// <summary>
/// Calculate Stop Loss
/// </summary>
/// <param name="orderType">Order Type</param>
/// <param name="price">Price</param>
/// <returns>Stop Loss</returns>
double SL(int orderType, double price)
{
double buffer = 0;
if(Stop > 0)
{
switch(orderType)
{
case OP_BUY:
buffer = NormalizeDouble(price - (Stop * CurrentPoints), CurrentDigits);
break;
case OP_SELL:
buffer = (NormalizeDouble(price + (Stop * CurrentPoints), CurrentDigits));
break;
}
}
return (buffer);
}

/// <summary>
/// Calculate Take Profit
/// </summary>
/// <param name="orderType">Order Type</param>
/// <param name="price">Price</param>
/// <returns>Take Profit</returns>
double TP(int orderType, double price)
{
double buffer = 0;
if (Limit > 0)
{
switch(orderType)
{
case OP_BUY:
buffer = NormalizeDouble(price + (Limit * CurrentPoints), CurrentDigits);
break;
case OP_SELL:
buffer = NormalizeDouble(price - (Limit * CurrentPoints), CurrentDigits);
break;
}
}
return (buffer);
}

/// <summary>
/// Parse the Error
/// </summary>
/// <returns>True or False</returns>
bool parseError()
{
bool buffer = false;
int Err = GetLastError();
switch (Err)
{
case ERR_NO_ERROR:
buffer = false;
break;
case ERR_SERVER_BUSY:
case ERR_NO_CONNECTION:
case ERR_INVALID_PRICE:
case ERR_OFF_QUOTES:
case ERR_BROKER_BUSY:
case ERR_TRADE_CONTEXT_BUSY:
case ERR_PRICE_CHANGED:
case ERR_REQUOTE:
buffer = true;
break;
case ERR_INVALID_STOPS:
buffer = false;
Print("Invalid Stops");
break;
case ERR_INVALID_TRADE_VOLUME:
buffer = false;
Print("Invalid Lots");
break;
case ERR_MARKET_CLOSED:
buffer = false;
Print("Market Close");
break;
case ERR_TRADE_DISABLED:
buffer = false;
Print("Trades Disabled");
break;
case ERR_NOT_ENOUGH_MONEY:
buffer = false;
Print("Not Enough Money");
break;
case ERR_TRADE_TOO_MANY_ORDERS:
buffer = false;
Print("Too Many Orders");
break;
case ERR_NO_RESULT:
default:
if(Err > 1)
Print("Unknown Error ", Err);
else
buffer = false;
break;
}
return (buffer);
}

 
Guiri:

There were several problems with the code, one of the main ones is that MetaTrader changes the MagicNumber when the Buy or Sell Stop is comitted. As such using the MagicNumber as in the code won't work orders get orphaned. I completely rewrote the code last night and have set it so that there is always at least one Buy and one sell order. I think it is what you are looking for. It should be easier now to mess around with the settings to make it do what you want.

#include <stderror.mqh>

// Lots to use
extern double Lots = 0.1;
// Limit (tp) setting
extern int Limit = 20;
// Stop (sl) setting
extern int Stop = 18;

// Timeout 10 seconds
int Timeout = 10000;
// Number of retries upon failure
int Retries = 10;
// Current symbol to use if different from Chart
string CurrentSymbol = "";
// Current number of Digits
int CurrentDigits = 5;
// Current Points
double CurrentPoints = 0.0001;
// Stop distance from price
int Distance = 100;

/// <summary>
/// Initialize
/// </summary>
/// <returns>Result</returns>
int init()
{
// If no symbol set use current chart
if(StringLen(CurrentSymbol) == 0)
CurrentSymbol = Symbol();

CurrentPoints = MarketInfo(CurrentSymbol, MODE_POINT);
CurrentDigits = MarketInfo(CurrentSymbol, MODE_DIGITS);

// Check the digits and points
if(CurrentPoints == 0.001)
{
CurrentPoints = 0.01;
CurrentDigits = 3;
}
else if(CurrentPoints == 0.00001)
{
CurrentPoints = 0.0001;
CurrentDigits = 5;
}
return(0);
}

/// <summary>
/// UnInitialize
/// </summary>
/// <returns>Result</returns>
int deinit()
{
return(0);
}

/// <summary>
/// Ezpert Start
/// </summary>
/// <returns>Result</returns>
int start()
{
// Check Buy Stops
if(CountStops(OP_BUYSTOP) < 1)
{
// No Buy stops open one
NewStopOrder(OP_BUYSTOP);
}
else
{
// Update Stoploss and Takeprofit
StopUpdate();
}

// Check Sell Stops
if(CountStops(OP_SELLSTOP) < 1)
{
// No Sell stops open one
NewStopOrder(OP_SELLSTOP);
}
else
{
// Update Stoploss and Takeprofit
StopUpdate();
}
return(0);
}

/// <summary>
/// Stop Update
/// </summary>
void StopUpdate()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == CurrentSymbol)
{
switch(OrderType())
{
case OP_BUYSTOP:
if ((OrderOpenPrice() - Ask) < 0.0005)
OrderUpdate(OrderTicket());
else if ((OrderOpenPrice() - Ask) > 0.0007)
OrderUpdate(OrderTicket());
break;
case OP_SELLSTOP:
if ((OrderOpenPrice() + Bid) > 0.007)
OrderUpdate(OrderTicket());
else if ((OrderOpenPrice() + Bid) < 0.0005)
OrderUpdate(OrderTicket());
break;
}
}
}
}

/// <summary>
/// New Stop Order
/// </summary>
/// <param name="orderType">Type of order to open</param>
void NewStopOrder(int orderType)
{
bool loop = True;
int count = 0;
while (loop && count < Retries)
{
while (IsTradeContextBusy())
{
Sleep(Timeout);
count++;
}

RefreshRates();
double ask = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_ASK), CurrentDigits);
double bid = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_BID), CurrentDigits);
double point = MarketInfo(CurrentSymbol, MODE_POINT);
switch(orderType)
{
case OP_BUYSTOP:
OrderSend(CurrentSymbol, OP_BUYSTOP, Lots, bid + Distance * point, 0, SL(OP_BUY, ask + Distance * point), TP(OP_BUY, bid), "", 0, 0, CLR_NONE);
break;
case OP_SELLSTOP:
OrderSend(CurrentSymbol, OP_SELLSTOP, Lots, bid - Distance * point, 0, SL(OP_SELL, ask - Distance * point), TP(OP_SELL, bid), "", 0, 0, CLR_NONE);
break;
}
loop = parseError();
}
}

/// <summary>
/// Order Update
/// </summary>
/// <param name="ticketNumber">ticket Number</param>
void OrderUpdate(int ticketNumber)
{
bool loop = True;
int count = 0;

while (loop && count < Retries)
{
while (IsTradeContextBusy())
{
Sleep(Timeout);
count++;
}

RefreshRates();
double ask = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_ASK), CurrentDigits);
double bid = NormalizeDouble(MarketInfo(CurrentSymbol, MODE_BID), CurrentDigits);
double point = MarketInfo(CurrentSymbol, MODE_POINT);

if (OrderSelect(ticketNumber, SELECT_BY_TICKET))
{
switch(OrderType())
{
case OP_SELL:
OrderModify(ticketNumber, bid - Distance * point, SL(OP_SELL, ask - Distance * point), TP(OP_SELL, bid), 0, CLR_NONE);
break;
case OP_BUY:
OrderModify(ticketNumber, bid + Distance * point, SL(OP_BUY, bid + Distance * point), TP(OP_BUY, bid), 0, CLR_NONE);
break;
}
}
loop = parseError();
}
}

/// <summary>
/// Count All
/// </summary>
/// <param name="orderTyper">Order Type</param>
/// <returns>Count</returns>
int CountStops(int orderType)
{
int count = 0;
for (int i = 0; i < OrdersTotal(); i++)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == CurrentSymbol)
{
if (OrderType() == orderType)
count++;
}
}
return (count);
}

/// <summary>
/// Calculate Stop Loss
/// </summary>
/// <param name="orderType">Order Type</param>
/// <param name="price">Price</param>
/// <returns>Stop Loss</returns>
double SL(int orderType, double price)
{
double buffer = 0;
if(Stop > 0)
{
switch(orderType)
{
case OP_BUY:
buffer = NormalizeDouble(price - (Stop * CurrentPoints), CurrentDigits);
break;
case OP_SELL:
buffer = (NormalizeDouble(price + (Stop * CurrentPoints), CurrentDigits));
break;
}
}
return (buffer);
}

/// <summary>
/// Calculate Take Profit
/// </summary>
/// <param name="orderType">Order Type</param>
/// <param name="price">Price</param>
/// <returns>Take Profit</returns>
double TP(int orderType, double price)
{
double buffer = 0;
if (Limit > 0)
{
switch(orderType)
{
case OP_BUY:
buffer = NormalizeDouble(price + (Limit * CurrentPoints), CurrentDigits);
break;
case OP_SELL:
buffer = NormalizeDouble(price - (Limit * CurrentPoints), CurrentDigits);
break;
}
}
return (buffer);
}

/// <summary>
/// Parse the Error
/// </summary>
/// <returns>True or False</returns>
bool parseError()
{
bool buffer = false;
int Err = GetLastError();
switch (Err)
{
case ERR_NO_ERROR:
buffer = false;
break;
case ERR_SERVER_BUSY:
case ERR_NO_CONNECTION:
case ERR_INVALID_PRICE:
case ERR_OFF_QUOTES:
case ERR_BROKER_BUSY:
case ERR_TRADE_CONTEXT_BUSY:
case ERR_PRICE_CHANGED:
case ERR_REQUOTE:
buffer = true;
break;
case ERR_INVALID_STOPS:
buffer = false;
Print("Invalid Stops");
break;
case ERR_INVALID_TRADE_VOLUME:
buffer = false;
Print("Invalid Lots");
break;
case ERR_MARKET_CLOSED:
buffer = false;
Print("Market Close");
break;
case ERR_TRADE_DISABLED:
buffer = false;
Print("Trades Disabled");
break;
case ERR_NOT_ENOUGH_MONEY:
buffer = false;
Print("Not Enough Money");
break;
case ERR_TRADE_TOO_MANY_ORDERS:
buffer = false;
Print("Too Many Orders");
break;
case ERR_NO_RESULT:
default:
if(Err > 1)
Print("Unknown Error ", Err);
else
buffer = false;
break;
}
return (buffer);
}

Thanks a lot. I spent hours trying to figure out the simple thing.

Yan.

 

Hello,

I'm backtesting this EA on EUR/USD and it don't trade.

Do you have any idea what am I doing wrong ?

 

I see several modifications of the code, but its not exactly how i wanted.

The pending order has to be constantly modified to stay 5-10 pips above and below.

If price changes even for a pip the updated order has to be fired.

The whole point of this EA is that it won't be able to get updated if there are very fast market movement. ( does not happened all the time but usually 2-3 times a day with euro)

SO, the faster market moves the better chance the order will get executed and move with market for a move 10 pips +

I checked 2 revisions that were posted here and i don't see that pending orders constantly getting updated.

 
picassoinaction:

I see several modifications of the code, but its not exactly how i wanted.

The pending order has to be constantly modified to stay 5-10 pips above and below.

If price changes even for a pip the updated order has to be fired.

The whole point of this EA is that it won't be able to get updated if there are very fast market movement. ( does not happened all the time but usually 2-3 times a day with euro)

SO, the faster market moves the better chance the order will get executed and move with market for a move 10 pips +

I checked 2 revisions that were posted here and i don't see that pending orders constantly getting updated.


Here is the code original, with number magic, fully repaired and working 100%.

One question picassoinaction, in which pairs of currencies so you put?

//+------------------------------------------------------------------+
#property copyright "Interbank FX, LLC" //( original template)
#property copyright "PicassoInActions , 123@donothing.us" //( original idea)
#include <stderror.mqh> 
//+------------------------------------------------------------------+
//| Global Variables / Includes                                      |
//+------------------------------------------------------------------+
datetime   CurrTime = 0;
datetime   PrevTime = 0;
  string        Sym = "";
     int  TimeFrame = 0;
     int      Shift = 1;
     int  SymDigits = 5;
  double  SymPoints = 0.0001;
//+------------------------------------------------------------------+
//| Expert User Inputs                                               |
//+------------------------------------------------------------------+
extern   bool   UseCompletedBars = true;
extern    int      Periods = 14;
extern double         Lots = 0.1;
extern    int  MagicNumberD = 1235;
extern    int  MagicNumberU = 1237;
extern    int ProfitTarget =  20; 
extern    int     StopLoss =  18; 
extern    int     Slippage =    3;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
         Sym = Symbol();
   TimeFrame = Period();   
   SymPoints = MarketInfo( Sym, MODE_POINT  );
   SymDigits = MarketInfo( Sym, MODE_DIGITS );
   //---
        if( SymPoints == 0.001   ) { SymPoints = 0.01;   SymDigits = 3; }
   else if( SymPoints == 0.00001 ) { SymPoints = 0.0001; SymDigits = 5; }
  
   //----
   return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() { return(0); }
//+------------------------------------------------------------------+
//| Expert start function                                            |
//+------------------------------------------------------------------+
int start() 
{    
int ordenesb = CountAllB(Sym, MagicNumberU);
int ordeness = CountAllS(Sym, MagicNumberD);
Comment("ordenes buy = ",ordenesb,"\n",
       "ordenes sell = ",ordeness);
     
      if(ordenesb == 0)
       {
       //Print ("test");
        EnterLong(Sym, Lots, "");
       }
      else
       {
       //Print (MagicNumberU);
       UpdateU ( Sym, MagicNumberU);
       }
      if(ordeness == 0)
      {
        EnterShrt(Sym, Lots, "");
      }
      else
       {
        UpdateD ( Sym, MagicNumberU);
       }
    //----
   return(0); 
}
//+------------------------------------------------------------------+
//| Expert Custom Functions                                          |
//+------------------------------------------------------------------+
//| Update for Sell Stop()                                                       |
//+------------------------------------------------------------------+
int UpdateD( string Symbole, int Magic )
{
    //---- 
    
int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0; int tic =0; 
    
    
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
                              
                if ((OrderOpenPrice()+Bid)>0.007  )
                {
                   EnterShrtUpdate (Symbole,Lots,"updated",OrderTicket( ));
                }
               else if ((OrderOpenPrice()+Bid)<0.0005 )
                {
                   EnterShrtUpdate (Symbole,Lots,"updated",OrderTicket( ));
                }
     }
    //----
    return(0);
}
//| Place Short Update Order                                                 |
//+------------------------------------------------------------------+
int EnterShrtUpdate( string FinalSymbol, double FinalLots, string EA_Comment, int tic )
{
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
   
                     
   while( !OrderLoop )
   {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
      double point=MarketInfo(Symbol(),MODE_POINT);
      
             if( OrderSelect( tic, SELECT_BY_TICKET ) )
              if (      OrderType()<2 ) continue;
             { OrderModify( tic, SymBid-100*point, StopShrt(SymAsk-100*point,StopLoss, SymPoints,SymDigits), TakeShrt(SymBid,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); } 
                                         
      int Err=GetLastError();
      
      switch (Err) 
      {
           //---- Success
           case               ERR_NO_ERROR: OrderLoop = true; 
                                       //     if( OrderSelect( Ticket, SELECT_BY_TICKET ) )
                                      //      { OrderModify( Ticket, OrderOpenPrice(), StopLong(SymBid,StopLoss, SymPoints,SymDigits), TakeLong(SymAsk,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); }
                                           break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; break;
           case          ERR_PRICE_CHANGED:
           case                ERR_REQUOTE: continue;
     
           //---- Fatal known Error 
           case          ERR_INVALID_STOPS: OrderLoop = true; Print( "Invalid Stops"    ); break; 
           case   ERR_INVALID_TRADE_VOLUME: OrderLoop = true; Print( "Invalid Lots"     ); break; 
           case          ERR_MARKET_CLOSED: OrderLoop = true; Print( "Market Close"     ); break; 
           case         ERR_TRADE_DISABLED: OrderLoop = true; Print( "Trades Disabled"  ); break; 
           case       ERR_NOT_ENOUGH_MONEY: OrderLoop = true; Print( "Not Enough Money" ); break; 
           case  ERR_TRADE_TOO_MANY_ORDERS: OrderLoop = true; Print( "Too Many Orders"  ); break; 
              
           //---- Fatal Unknown Error
           case              ERR_NO_RESULT:
                                   default: OrderLoop = true; Print( "Unknown Error - " + Err ); break; 
           //----                         
       }  
       // end switch 
       if( TryCount > 10) { OrderLoop = true; }
   }
   //----               
   return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Update for Buy Stop()                                                       |
//+------------------------------------------------------------------+
int UpdateU( string Symbole, int Magic )
{
int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0; int tic =0; 
    
    
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
        
               if ((OrderOpenPrice()-Ask)<0.0005 )
                {
                   EnterLongUpdate (Symbole,Lots,"updated",OrderTicket( ));
                }
               else if ((OrderOpenPrice()-Ask)>0.0007 )
                {
                   EnterLongUpdate (Symbole,Lots,"updated",OrderTicket( ));
                }
    }
    //----
    return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Place Long Order                                                 |
//+------------------------------------------------------------------+
int EnterLongUpdate( string FinalSymbol, double FinalLots, string EA_Comment, int tic )
{
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
   
   while( !OrderLoop )
   {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
      double point=MarketInfo(Symbol(),MODE_POINT);
      
                                       if( OrderSelect( tic, SELECT_BY_TICKET ) )
                                       
                                      
                                       
                                       if (      OrderType()<2 ) continue;
                                       
                                        { OrderModify( tic, SymBid+100*point, StopLong(SymBid+80*point,StopLoss, SymPoints,SymDigits), TakeLong(SymBid,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); } 
                                         
      int Err=GetLastError();
      
      switch (Err) 
      {
           //---- Success
           case               ERR_NO_ERROR: OrderLoop = true; 
                                                       break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; break;
           case          ERR_PRICE_CHANGED:
           case                ERR_REQUOTE: continue;
     
           //---- Fatal known Error 
           case          ERR_INVALID_STOPS: OrderLoop = true; Print( "Invalid Stops"    ); break; 
           case   ERR_INVALID_TRADE_VOLUME: OrderLoop = true; Print( "Invalid Lots"     ); break; 
           case          ERR_MARKET_CLOSED: OrderLoop = true; Print( "Market Close"     ); break; 
           case         ERR_TRADE_DISABLED: OrderLoop = true; Print( "Trades Disabled"  ); break; 
           case       ERR_NOT_ENOUGH_MONEY: OrderLoop = true; Print( "Not Enough Money" ); break; 
           case  ERR_TRADE_TOO_MANY_ORDERS: OrderLoop = true; Print( "Too Many Orders"  ); break; 
              
           //---- Fatal Unknown Error
           case              ERR_NO_RESULT:
                                   default: OrderLoop = true; Print( "Unknown Error - " + Err ); break; 
           //----                         
       }  
       // end switch 
       if( TryCount > 10) { OrderLoop = true; }
   }
   //----               
   return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| CountAll()                                                       |
//+------------------------------------------------------------------+
int CountAllB( string Symbole, int Magic)
{
    //---- 
    int countb = 0;
    if (OrdersTotal()<1)
    {
    return(countb);
    }
    
    
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
        
             if ( OrderType() == OP_BUYSTOP  ) { countb++; }
             if ( OrderType() == OP_BUY ) { countb++; }
    }
    //----
    return(countb);
}
//+------------------------------------------------------------------+
int CountAllS( string Symbole, int Magic )
{
    //---- 
    int counts = 0;
    if (OrdersTotal()<1)
    {
    return(counts);
    }
    
    
    for (int j = OrdersTotal() - 1; j >= 0; j--)
    {
        OrderSelect(j, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
        
             if ( OrderType() == OP_SELL  ) { counts++; }
             if ( OrderType() == OP_SELLSTOP ) { counts++; }
    }
    //----
    return(counts);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate Stop Long                                              |
//+------------------------------------------------------------------+
double StopLong(double price,double stop,double point,double SymDgts )
{
if(stop==0) { return(0); }
else        { return(NormalizeDouble( price-(stop*point),SymDgts)); }
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate Stop Short                                             |
//+------------------------------------------------------------------+
double StopShrt(double price,double stop,double point,double SymDgts )
{
if(stop==0) { return(0); }
else        { return(NormalizeDouble( price+(stop*point),SymDgts)); }
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate Profit Target Long                                     |
//+------------------------------------------------------------------+
double TakeLong(double price,double take,double point,double SymDgts )
{
if(take==0) {  return(0);}
else        {  return(NormalizeDouble( price+(take*point),SymDgts));}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate Profit Target Long                                     |
//+------------------------------------------------------------------+
double TakeShrt(double price,double take,double point,double SymDgts )
{
if(take==0) {  return(0);}
else        {  return(NormalizeDouble( price-(take*point),SymDgts));}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Place Long Order                                                 |
//+------------------------------------------------------------------+
int EnterLong( string FinalSymbol, double FinalLots, string EA_Comment )
{
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
                     
   while( !OrderLoop )
   {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
      double point=MarketInfo(Symbol(),MODE_POINT);
                           
Ticket=OrderSend(FinalSymbol,OP_BUYSTOP,FinalLots,SymBid+100*point,0,StopLong(SymAsk+100*point,StopLoss, SymPoints,SymDigits),TakeLong(SymBid,ProfitTarget, SymPoints,SymDigits),"Scalping ea mg",MagicNumberU,0,CLR_NONE);
    
      int Err=GetLastError();
      
      switch (Err) 
      {
           //---- Success
          // case               ERR_NO_ERROR: OrderLoop = true; 
                                       //     if( OrderSelect( Ticket, SELECT_BY_TICKET ) )
                                      //      { OrderModify( Ticket, OrderOpenPrice(), StopLong(SymBid,StopLoss, SymPoints,SymDigits), TakeLong(SymAsk,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); }
                                      //      break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; break;
           case          ERR_PRICE_CHANGED:
           case                ERR_REQUOTE: continue;
     
           //---- Fatal known Error 
           case          ERR_INVALID_STOPS: OrderLoop = true; Print( "Invalid Stops"    ); break; 
           case   ERR_INVALID_TRADE_VOLUME: OrderLoop = true; Print( "Invalid Lots"     ); break; 
           case          ERR_MARKET_CLOSED: OrderLoop = true; Print( "Market Close"     ); break; 
           case         ERR_TRADE_DISABLED: OrderLoop = true; Print( "Trades Disabled"  ); break; 
           case       ERR_NOT_ENOUGH_MONEY: OrderLoop = true; Print( "Not Enough Money" ); break; 
           case  ERR_TRADE_TOO_MANY_ORDERS: OrderLoop = true; Print( "Too Many Orders"  ); break; 
              
           //---- Fatal Unknown Error
           case              ERR_NO_RESULT:
                                   default: OrderLoop = true; Print( "Unknown Error - " + Err ); break; 
           //----                         
       }  
       // end switch 
       if( TryCount > 10) { OrderLoop = true; }
   }
   //----               
   return(Ticket);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Place Shrt Order                                                 |
//+------------------------------------------------------------------+
int EnterShrt( string FinalSymbol, double FinalLots, string EA_Comment )
{
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
                     
   while( !OrderLoop )
   {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
      double point=MarketInfo(Symbol(),MODE_POINT);
                               
     // Ticket = OrderSend( FinalSymbol, OP_SELL, FinalLots, SymBid, 0,  0.0,0.0, EA_Comment, MagicNumber, 0, CLR_NONE ); 
      Ticket=OrderSend(FinalSymbol,OP_SELLSTOP,FinalLots,SymBid-100*point,0,StopShrt(SymAsk-100*point,StopLoss, SymPoints,SymDigits),TakeShrt(SymBid,ProfitTarget, SymPoints,SymDigits),"Scalping ea mg",MagicNumberD,0,CLR_NONE);
     // ticket=OrderSend(Symbol(),OP_SELLSTOP,0.1,price-70*point,0,price+100*point,price-200*point,"some comment",mgnD,0,CLR_NONE);
                           
      int Err=GetLastError();
      
      switch (Err) 
      {
           //---- Success
             //    case               ERR_NO_ERROR: OrderLoop = true;
                                                 // if( OrderSelect( Ticket, SELECT_BY_TICKET ) )
                                                 // { OrderModify( Ticket, OrderOpenPrice(), StopShrt(SymAsk,StopLoss, SymPoints,SymDigits), TakeShrt(SymBid,ProfitTarget, SymPoints,SymDigits), 0, CLR_NONE ); }
                                                 // break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; bre
 
Jumper123:
picassoinaction:

I see several modifications of the code, but its not exactly how i wanted.

The pending order has to be constantly modified to stay 5-10 pips above and below.

If price changes even for a pip the updated order has to be fired.

The whole point of this EA is that it won't be able to get updated if there are very fast market movement. ( does not happened all the time but usually 2-3 times a day with euro)

SO, the faster market moves the better chance the order will get executed and move with market for a move 10 pips +

I checked 2 revisions that were posted here and i don't see that pending orders constantly getting updated.


Here is the code original, with number magic, fully repaired and working 100%.

One question picassoinaction, in which pairs of currencies so you put?

//+------------------------------------------------------------------+
#property copyright "Interbank FX, LLC" //( original template)
#property copyright "PicassoInActions , 123@donothing.us" //( original idea)
#include <stderror.mqh> 
//+------------------------------------------------------------------+
//| Global Variables / Includes                                      |
//+------------------------------------------------------------------+
datetime   CurrTime = 0;
datetime   PrevTime = 0;
  string        Sym = "";
     int  TimeFrame = 0;
     int      Shift = 1;
     int  SymDigits = 5;
  double  SymPoints = 0.0001;
//+------------------------------------------------------------------+
//| Expert User Inputs                                               |
//+------------------------------------------------------------------+
extern   bool   UseCompletedBars = true;
extern    int      Periods = 14;
extern double         Lots = 0.1;
extern    int  MagicNumberD = 1235;
extern    int  MagicNumberU = 1237;
extern    int ProfitTarget =  20; 
extern    int     StopLoss =  18; 
extern    int     Slippage =    3;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
         Sym = Symbol();
   TimeFrame = Period();   
   SymPoints = MarketInfo( Sym, MODE_POINT  );
   SymDigits = MarketInfo( Sym, MODE_DIGITS );
   //---
        if( SymPoints == 0.001   ) { SymPoints = 0.01;   SymDigits = 3; }
   else if( SymPoints == 0.00001 ) { SymPoints = 0.0001; SymDigits = 5; }
  
   //----
   return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() { return(0); }
//+------------------------------------------------------------------+
//| Expert start function                                            |
//+------------------------------------------------------------------+
int start() 
{    
int ordenesb = CountAllB(Sym, MagicNumberU);
int ordeness = CountAllS(Sym, MagicNumberD);
Comment("ordenes buy = ",ordenesb,"\n",
       "ordenes sell = ",ordeness);
     
      if(ordenesb == 0)
       {
       //Print ("test");
        EnterLong(Sym, Lots, "");
       }
      else
       {
       //Print (MagicNumberU);
       UpdateU ( Sym, MagicNumberU);
       }
      if(ordeness == 0)
      {
        EnterShrt(Sym, Lots, "");
      }
      else
       {
        UpdateD ( Sym, MagicNumberU);
       }
    //----
   return(0); 
}
//+------------------------------------------------------------------+
//| Expert Custom Functions                                          |
//+------------------------------------------------------------------+
//| Update for Sell Stop()                                                       |
//+------------------------------------------------------------------+
int UpdateD( string Symbole, int Magic )
{
    //---- 
    
int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0; int tic =0; 
    
    
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
                              
                if ((OrderOpenPrice()+Bid)>0.007  )
                {
                   EnterShrtUpdate (Symbole,Lots,"updated",OrderTicket( ));
                }
               else if ((OrderOpenPrice()+Bid)<0.0005 )
                {
                   EnterShrtUpdate (Symbole,Lots,"updated",OrderTicket( ));
                }
     }
    //----
    return(0);
}
//| Place Short Update Order                                                 |
//+------------------------------------------------------------------+
int EnterShrtUpdate( string FinalSymbol, double FinalLots, string EA_Comment, int tic )
{
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
   
                     
   while( !OrderLoop )
   {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
      double point=MarketInfo(Symbol(),MODE_POINT);
      
             if( OrderSelect( tic, SELECT_BY_TICKET ) )
              if (      OrderType()<2 ) continue;
             { OrderModify( tic, SymBid-100*point, StopShrt(SymAsk-100*point,StopLoss, SymPoints,SymDigits), TakeShrt(SymBid,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); } 
                                         
      int Err=GetLastError();
      
      switch (Err) 
      {
           //---- Success
           case               ERR_NO_ERROR: OrderLoop = true; 
                                       //     if( OrderSelect( Ticket, SELECT_BY_TICKET ) )
                                      //      { OrderModify( Ticket, OrderOpenPrice(), StopLong(SymBid,StopLoss, SymPoints,SymDigits), TakeLong(SymAsk,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); }
                                           break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; break;
           case          ERR_PRICE_CHANGED:
           case                ERR_REQUOTE: continue;
     
           //---- Fatal known Error 
           case          ERR_INVALID_STOPS: OrderLoop = true; Print( "Invalid Stops"    ); break; 
           case   ERR_INVALID_TRADE_VOLUME: OrderLoop = true; Print( "Invalid Lots"     ); break; 
           case          ERR_MARKET_CLOSED: OrderLoop = true; Print( "Market Close"     ); break; 
           case         ERR_TRADE_DISABLED: OrderLoop = true; Print( "Trades Disabled"  ); break; 
           case       ERR_NOT_ENOUGH_MONEY: OrderLoop = true; Print( "Not Enough Money" ); break; 
           case  ERR_TRADE_TOO_MANY_ORDERS: OrderLoop = true; Print( "Too Many Orders"  ); break; 
              
           //---- Fatal Unknown Error
           case              ERR_NO_RESULT:
                                   default: OrderLoop = true; Print( "Unknown Error - " + Err ); break; 
           //----                         
       }  
       // end switch 
       if( TryCount > 10) { OrderLoop = true; }
   }
   //----               
   return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Update for Buy Stop()                                                       |
//+------------------------------------------------------------------+
int UpdateU( string Symbole, int Magic )
{
int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0; int tic =0; 
    
    
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
        
               if ((OrderOpenPrice()-Ask)<0.0005 )
                {
                   EnterLongUpdate (Symbole,Lots,"updated",OrderTicket( ));
                }
               else if ((OrderOpenPrice()-Ask)>0.0007 )
                {
                   EnterLongUpdate (Symbole,Lots,"updated",OrderTicket( ));
                }
    }
    //----
    return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Place Long Order                                                 |
//+------------------------------------------------------------------+
int EnterLongUpdate( string FinalSymbol, double FinalLots, string EA_Comment, int tic )
{
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
   
   while( !OrderLoop )
   {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
      double point=MarketInfo(Symbol(),MODE_POINT);
      
                                       if( OrderSelect( tic, SELECT_BY_TICKET ) )
                                       
                                      
                                       
                                       if (      OrderType()<2 ) continue;
                                       
                                        { OrderModify( tic, SymBid+100*point, StopLong(SymBid+80*point,StopLoss, SymPoints,SymDigits), TakeLong(SymBid,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); } 
                                         
      int Err=GetLastError();
      
      switch (Err) 
      {
           //---- Success
           case               ERR_NO_ERROR: OrderLoop = true; 
                                                       break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; break;
           case          ERR_PRICE_CHANGED:
           case                ERR_REQUOTE: continue;
     
           //---- Fatal known Error 
           case          ERR_INVALID_STOPS: OrderLoop = true; Print( "Invalid Stops"    ); break; 
           case   ERR_INVALID_TRADE_VOLUME: OrderLoop = true; Print( "Invalid Lots"     ); break; 
           case          ERR_MARKET_CLOSED: OrderLoop = true; Print( "Market Close"     ); break; 
           case         ERR_TRADE_DISABLED: OrderLoop = true; Print( "Trades Disabled"  ); break; 
           case       ERR_NOT_ENOUGH_MONEY: OrderLoop = true; Print( "Not Enough Money" ); break; 
           case  ERR_TRADE_TOO_MANY_ORDERS: OrderLoop = true; Print( "Too Many Orders"  ); break; 
              
           //---- Fatal Unknown Error
           case              ERR_NO_RESULT:
                                   default: OrderLoop = true; Print( "Unknown Error - " + Err ); break; 
           //----                         
       }  
       // end switch 
       if( TryCount > 10) { OrderLoop = true; }
   }
   //----               
   return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| CountAll()                                                       |
//+------------------------------------------------------------------+
int CountAllB( string Symbole, int Magic)
{
    //---- 
    int countb = 0;
    if (OrdersTotal()<1)
    {
    return(countb);
    }
    
    
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
        
             if ( OrderType() == OP_BUYSTOP  ) { countb++; }
             if ( OrderType() == OP_BUY ) { countb++; }
    }
    //----
    return(countb);
}
//+------------------------------------------------------------------+
int CountAllS( string Symbole, int Magic )
{
    //---- 
    int counts = 0;
    if (OrdersTotal()<1)
    {
    return(counts);
    }
    
    
    for (int j = OrdersTotal() - 1; j >= 0; j--)
    {
        OrderSelect(j, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
        
             if ( OrderType() == OP_SELL  ) { counts++; }
             if ( OrderType() == OP_SELLSTOP ) { counts++; }
    }
    //----
    return(counts);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate Stop Long                                              |
//+------------------------------------------------------------------+
double StopLong(double price,double stop,double point,double SymDgts )
{
if(stop==0) { return(0); }
else        { return(NormalizeDouble( price-(stop*point),SymDgts)); }
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate Stop Short                                             |
//+------------------------------------------------------------------+
double StopShrt(double price,double stop,double point,double SymDgts )
{
if(stop==0) { return(0); }
else        { return(NormalizeDouble( price+(stop*point),SymDgts)); }
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate Profit Target Long                                     |
//+------------------------------------------------------------------+
double TakeLong(double price,double take,double point,double SymDgts )
{
if(take==0) {  return(0);}
else        {  return(NormalizeDouble( price+(take*point),SymDgts));}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate Profit Target Long                                     |
//+------------------------------------------------------------------+
double TakeShrt(double price,double take,double point,double SymDgts )
{
if(take==0) {  return(0);}
else        {  return(NormalizeDouble( price-(take*point),SymDgts));}
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Place Long Order                                                 |
//+------------------------------------------------------------------+
int EnterLong( string FinalSymbol, double FinalLots, string EA_Comment )
{
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
                     
   while( !OrderLoop )
   {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
      double point=MarketInfo(Symbol(),MODE_POINT);
                           
Ticket=OrderSend(FinalSymbol,OP_BUYSTOP,FinalLots,SymBid+100*point,0,StopLong(SymAsk+100*point,StopLoss, SymPoints,SymDigits),TakeLong(SymBid,ProfitTarget, SymPoints,SymDigits),"Scalping ea mg",MagicNumberU,0,CLR_NONE);
    
      int Err=GetLastError();
      
      switch (Err) 
      {
           //---- Success
          // case               ERR_NO_ERROR: OrderLoop = true; 
                                       //     if( OrderSelect( Ticket, SELECT_BY_TICKET ) )
                                      //      { OrderModify( Ticket, OrderOpenPrice(), StopLong(SymBid,StopLoss, SymPoints,SymDigits), TakeLong(SymAsk,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); }
                                      //      break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; break;
           case          ERR_PRICE_CHANGED:
           case                ERR_REQUOTE: continue;
     
           //---- Fatal known Error 
           case          ERR_INVALID_STOPS: OrderLoop = true; Print( "Invalid Stops"    ); break; 
           case   ERR_INVALID_TRADE_VOLUME: OrderLoop = true; Print( "Invalid Lots"     ); break; 
           case          ERR_MARKET_CLOSED: OrderLoop = true; Print( "Market Close"     ); break; 
           case         ERR_TRADE_DISABLED: OrderLoop = true; Print( "Trades Disabled"  ); break; 
           case       ERR_NOT_ENOUGH_MONEY: OrderLoop = true; Print( "Not Enough Money" ); break; 
           case  ERR_TRADE_TOO_MANY_ORDERS: OrderLoop = true; Print( "Too Many Orders"  ); break; 
              
           //---- Fatal Unknown Error
           case              ERR_NO_RESULT:
                                   default: OrderLoop = true; Print( "Unknown Error - " + Err ); break; 
           //----                         
       }  
       // end switch 
       if( TryCount > 10) { OrderLoop = true; }
   }
   //----               
   return(Ticket);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Place Shrt Order                                                 |
//+------------------------------------------------------------------+
int EnterShrt( string FinalSymbol, double FinalLots, string EA_Comment )
{
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
                     
   while( !OrderLoop )
   {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
      double point=MarketInfo(Symbol(),MODE_POINT);
                               
     // Ticket = OrderSend( FinalSymbol, OP_SELL, FinalLots, SymBid, 0,  0.0,0.0, EA_Comment, MagicNumber, 0, CLR_NONE ); 
      Ticket=OrderSend(FinalSymbol,OP_SELLSTOP,FinalLots,SymBid-100*point,0,StopShrt(SymAsk-100*point,StopLoss, SymPoints,SymDigits),TakeShrt(SymBid,ProfitTarget, SymPoints,SymDigits),"Scalping ea mg",MagicNumberD,0,CLR_NONE);
     // ticket=OrderSend(Symbol(),OP_SELLSTOP,0.1,price-70*point,0,price+100*point,price-200*point,"some comment",mgnD,0,CLR_NONE);
                           
      int Err=GetLastError();
      
      switch (Err) 
      {
           //---- Success
             //    case               ERR_NO_ERROR: OrderLoop = true;
                                                 // if( OrderSelect( Ticket, SELECT_BY_TICKET ) )
                                                 // { OrderModify( Ticket, OrderOpenPrice(), StopShrt(SymAsk,StopLoss, SymPoints,SymDigits), TakeShrt(SymBid,ProfitTarget, SymPoints,SymDigits), 0, CLR_NONE ); }
                                                 // break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case</s