Experts: eaTemplate

 

eaTemplate:

This template code contains basic features and functions required for the developing the Expert Advisor:
  • Calculation of point for the 3-5 digit pairs;
  • Setup takeprofit and stoploss;
  • Identification number for tEA's orders - Magic number;
  • Ability to set a fixed trade volume;
  • The function of money management - calculation of the trade volume, based on a specified percentage of the current balance;
  • Ability for opening of the order in 2 steps (open the order, and then the set stops) - work on the ECN - accounts;
  • Ability to open positions in the opposite direction from the trading signal;
  • Limitation of work regarding of the maximum size of the spread;
  • Setting the maximum possible deviation of the price;
  • Placing Orders in several attempts in case of failure (the default count of attempts=10);
  • Function to calculate the total profits of EA's positions in the currency;
  • Function to close all EA's positions and orders;
  • Error Logging.

Author: Alexey Lopatin

 
Automated-Trading:

eaTemplate:

Author: Alexey Lopatin

wish add position management function.calculated positions for every symbol for b or s or pending.
 
AAASSS111:
wish add position management function.calculated positions for every symbol for b or s or pending.

You can modify function orders_count(). Add filter for symbols and make counters for buy, sell orders.

I've done the following class for calculation orders count in some EA:

class orders_counter
{
private:
   int orders_magic;
   string orders_symbol;
   int mode;
   int buys;
   int sells;
   int buy_limits;
   int sell_limits;
   int buy_stops;
   int sell_stops;
public:
   orders_counter(void);
   orders_counter(int magic, string symbol, int counter_mode = MODE_TRADES);
   void refresh_data(void);
   int get_orders_count(int type);
};

orders_counter::orders_counter(void)
{
   this.orders_magic = 0;
   this.orders_symbol = Symbol();
   this.mode = MODE_TRADES;
   this.buys = 0;
   this.sells = 0;
   this.buy_limits = 0;
   this.sell_limits = 0;
   this.buy_stops = 0;
   this.sell_stops = 0;
}

orders_counter::orders_counter(int magic,string symbol,int counter_mode=MODE_TRADES)
{
   this.orders_magic = magic;
   this.orders_symbol = symbol;
   this.mode = counter_mode;
   this.buys = 0;
   this.sells = 0;
   this.buy_limits = 0;
   this.sell_limits = 0;
   this.buy_stops = 0;
   this.sell_stops = 0;
}

void orders_counter::refresh_data(void)
{
    int orders_total = OrdersTotal();
    if( this.mode == MODE_HISTORY )
      orders_total = OrdersHistoryTotal();
    for( int i = 0; i < orders_total; i++ )
    {
        if( OrderSelect( i, SELECT_BY_POS, this.mode ) )
        {
            if( OrderSymbol() != this.orders_symbol )
                continue;
            if( OrderMagicNumber() == this.orders_magic || this.orders_magic == 0 )
            {
               switch(OrderType())
               {
                  case OP_BUY:
                     this.buys++;
                     break;
                  case OP_SELL:
                     this.sells++;
                     break;
                  case OP_BUYLIMIT:
                     this.buy_limits++;
                     break;
                  case OP_SELLLIMIT:
                     this.sell_limits++;
                     break;
                  case OP_BUYSTOP:
                     this.buy_stops++;
                     break;
                  case OP_SELLSTOP:
                     this.sell_stops++;
                     break;
                  default:
                     break;
               }
            }
        }
    }
}

int orders_counter::get_orders_count(int type)
{
   int count = 0;
   switch(type)
   {
      case -1:
         count = this.buys + this.sells + this.buy_limits + this.sell_limits + this.buy_stops + this.sell_stops;
         break;
      case OP_BUY:
         count = this.buys;
         break;
      case OP_SELL:
         count = this.sells;
         break;
      case OP_BUYLIMIT:
         count = this.buy_limits;
         break;
      case OP_SELLLIMIT:
         count = this.sell_limits;
         break;
      case OP_BUYSTOP:
         count = this.buy_stops;
         break;
      case OP_SELLSTOP:
         count = this.sell_stops;
         break;
      default:
         break;
    }
    return(count);
}

And use this class, for example, following way:

orders_counter trades_counter(MagicNumber, Symbol(), MODE_TRADES);
trades_counter.refresh_data();
if( trades_counter.get_orders_count(OP_SELL) < 1 )
{ /* made some manipulations */ }
if( trades_counter.get_orders_count(-1) < 1 )
{ /* made some manipulations */ }
 

Спасибо за комментарий выше (и в русском варианте также!)

выше указанный блок (class orders_counter) "подсчитывает" ордера (pendigs orders) только со своим MagicNumber,

(или я не совсем понял, пожалуйста поправьте)

а, как сделать/добавить в этот блок, также "подсчёт" ордеров  (pendigs orders),

которые дополнительно поставлены на график вручную, в этом случае у открытых вручную ордеров не присутствует MagicNumber, терминал их не указывает ?

Такая-же ситуация для BUY/SELL orders.

По общей логике(настоящая редакция EA-template ),

заложенной в EA-template все ордера открытые в ручную выпадают из торговли, т.к.терминал их не указывает MagicNumber !?

Как это поправить? , чтобы открытые вручную ордера  (также и pendigs orders), "подхватывались" и управлялись в EA-template совместно дальше?

P.S. извините за "назойливость", но всё это обязательно нужно и важно для дальнейшего использования EA-template 

 

How to implement functionality of closing all orders in one direction (say opened buy orders) when opposite signal (say sell signal) has occured?

Great template. Thanks for sharing 

 
Automated-Trading:

eaTemplate:

Author: Alexey Lopatin

For information :

Ability for opening of the order in 2 steps (open the order, and then the set stops) - work on the ECN - accounts;

This is no more needed since May 2013 and build 500 (approximatively). You can place an order with sl/tp even with "ECN" account.

 
ugene:

How to implement functionality of closing all orders in one direction (say opened buy orders) when opposite signal (say sell signal) has occured?

Great template. Thanks for sharing 

You can modify the function close_all_orders():

int close_all_orders( int magic, int type = -1 )
{
    int orders_count = OrdersTotal();
int ord_type = -1, n = 0;
string symbol = Symbol();

for( int i = orders_count-1; i >= 0; i--)
{
if( OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderMagicNumber() == magic )
{
if( symbol != OrderSymbol() )
continue;
          
     ord_type = OrderType();
     
     if( ord_type == type || type == -1 )
     {

     if( ord_type == OP_BUY  )
     {
     if( XOrderClose(OrderTicket(), OrderLots(), Bid, Slippage) )
         n++;
     continue;
     }
    
     if( ord_type == OP_SELL  )
     {
     if( XOrderClose(OrderTicket(), OrderLots(), Ask, Slippage) )
         n++;
     continue;
     }
                
     if( ord_type == OP_BUYSTOP || ord_type == OP_SELLSTOP || ord_type == OP_BUYLIMIT || ord_type == OP_SELLLIMIT )
     {
     if( OrderDelete( OrderTicket() ) )
         n++;
     continue;
     }
     }
}
}

return(n);
}
 
Automated-Trading:

eaTemplate:

Author: Alexey Lopatin

I think I found a little bug in the XOrderClose function.

I think that "strSymbol = Symbol()" must actually be "strSymbol = OrderSymbol()". Because we are dealing with an order and are as such not interested in the symbol of the current chart.  

        // collect details of order so that we can use GetMarketInfo later if needed
        if (!OrderSelect(ticket,SELECT_BY_TICKET)) {
                _OR_err = GetLastError();               
                XPrint( LOG_LEVEL_ERR, XErrorDescription(_OR_err));
                return(false);
        } else {
                nOrderType = OrderType();
                //strSymbol = Symbol();  -- BUG: This should be OrderSymbol()
                strSymbol = OrderSymbol();
        }
 
jansb000:

I think I found a little bug in the XOrderClose function.

I think that "strSymbol = Symbol()" must actually be "strSymbol = OrderSymbol()". Because we are dealing with an order and are as such not interested in the symbol of the current chart.  

Thanks a lot. I'll fix it.