Учимся логике - страница 10

 

Наверно, как-то так, если без параметров:

bool IsActiveType()
{
   int type = OrderType();
   return (type == OP_BUY || type == OP_SELL);
}

bool IsAnySellType()
{
   int type = OrderType();
   return (type == OP_SELL || type == OP_SELLLIMIT || type == OP_SELLSTOP);
}

{
   if (IsActiveType())
   {
      //...
   }

   if (IsAnySellType())
   {
      //...
   }
}

 
//+----------------------------------------------------------------------------+
//|  Возвращает количество позиций.                                            |
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1 - любая позиция)                    |
//|    mn - MagicNumber                (-1 - любой магик)                      |
//+----------------------------------------------------------------------------+
int NumberOfPositions(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), kp=0;
  if (StringLen(sy)==1 && StringGetChar(sy, 0)==48) sy=Symbol();
 
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) kp++;
          }
        }
      }
    }
  }
  return(kp);
}
 
Mathemat:

Наверно, как-то так, если без параметров:

bool IsActiveType(int type = -1)
{
   if (type < 0) type = OrderType();
   return (type == OP_BUY || type == OP_SELL);
}
 
Дык это ж с параметром, который, правда, можно не указывать.
 
Я имел в виду убрать параметры из вызовов. А из описания функции убрать мне религия не позволяет.
 

Ну как же, это интеграция в существующую систему именования функций свойств ордера:  

   bool OrderIsActiveType(int type = -1)
   {
      if (type < 0) type = OrderType();
      return (type == OP_BUY || type == OP_SELL);
   }


   if (OrderIsActiveType())
   {
      //...
   }

   if (OrderIsAnySellType())
   {
      //...
   }
 

Неочевидно, посему как по мне не катит.

Да и как-то по сути то же самое, но с параметром нагляднее, вобщем ни к чему умолчания, имхо.

_______

Че-то мы чистоплюйством уже занимаемся. Даешь реальные коды на переделку, обсуждение и т.п.
 

А вот я из кучи кода достал:

bool SafelyCloseOrder(int orderticket, string operation = "")
{
   bool closed = false;
   LastError = 0;
   string ordercomment = "";
   
   for(int attempt = 0; attempt <= 10 && !closed; attempt++)
   if (OrderSelect(orderticket, SELECT_BY_TICKET, MODE_TRADES))
   if (WaitForConnection(6, operation))
   {  
      ordercomment = OrderComment();
      if (OrderType() == OP_BUY) 
         closed = OrderClose(orderticket, OrderLots(), NormalizeDouble(MarketInfo(OrderSymbol(), MODE_BID), 
                    MarketInfo(OrderSymbol(), MODE_DIGITS)), Set_slippage, Blue);
      else                       
         closed = OrderClose(orderticket, OrderLots(), NormalizeDouble(MarketInfo(OrderSymbol(), MODE_ASK), 
                    MarketInfo(OrderSymbol(), MODE_DIGITS)), Set_slippage, Red);
      LastError = LastError();
      if (LastError != 0)
         Print(WindowExpertName() + " " + operation + " " + ErrorDescription(LastError));
      if (!closed)
      {  Sleep(3000 + attempt * 1000);
         RefreshRates();
      }
   }
   if (closed)
   {  Alert(WindowExpertName() + " " + operation + " Ордер " + orderticket + " " + ordercomment + "  закрыт!");
      PlaySound("Case.wav");
      Sleep(555);
   }
   else
   {  Alert(WindowExpertName() + " " + operation + " Не закрывается ордер " + orderticket + " " + ordercomment + "!");
      PlaySound("NT_Ball_BAMMM!.WAV");
      Sleep(555);
   }
   return(closed);
}
 

А как вам такой вариант?

// основные битовые маски
#define ORD_SELL             1
#define ORD_BUY              2
#define ORD_MARKET           4
#define ORD_LIMIT            8
#define ORD_STOP             16
#define ORD_INVALID          32

// комбинированные битовые маски
#define ORD_MARKET_SELL      5        // ORD_SELL | ORD_MARKET
#define ORD_MARKET_BUY       6        // ORD_BUY | ORD_MARKET
#define ORD_LIMIT_SELL       9        // ORD_SELL | ORD_LIMIT
#define ORD_LIMIT_BUY        10       // ORD_BUY | ORD_LIMIT
#define ORD_STOP_SELL        17       // ORD_SELL | ORD_STOP
#define ORD_STOP_BUY         18       // ORD_BUY | ORD_STOP
#define ORD_PENDING          24       // ORD_STOP | ORD_LIMIT

// получение битовой маски для текущего ордера
int OrderTypeBitmask() {
   int orderType = OrderType();
   int bitmask = ORD_INVALID;
   switch (orderType) {
      case OP_SELL:
         bitmask = ORD_MARKET_SELL;
         break;
      case OP_BUY:
         bitmask = ORD_MARKET_BUY;
         break;
      case OP_SELLLIMIT:
         bitmask = ORD_LIMIT_SELL;
         break;
      case OP_BUYLIMIT:
         bitmask = ORD_LIMIT_BUY;
         break;
      case OP_SELLSTOP:
         bitmask = ORD_STOP_SELL;
         break;
      case OP_BUYSTOP:
         bitmask = ORD_STOP_BUY;
         break;
   }
   return (bitmask);
}

// проверка по маске
bool CheckMask(int value, int mask) {
   return ((value & mask) != 0);
}

// пример:
for (int i = OrdersTotal() - 1; i >= 0; i--) {
   // выбор ордера, отбрасывание по символу, magic'у и т.п.
   if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      continue;
   if (OrderSymbol() != Symbol)
      continue;
   ...

   // обработка ордера
   int ordType = OrderTypeBitmask();

   bool removeOrder = false;
   if ((signal == SIG_BUY) && CheckMask(ordType, ORD_SELL))
      removeOrder = true;
   else if ((signal == SIG_SELL) && CheckMask(ordType, ORD_BUY))
      removeOrder = true;

   if (!removeOrder)
      continue;

   if (CheckMask(ordType, ORD_MARKET))
      RemoveMarketOrder();
   else if (CheckMask(ordType, ORD_PENDING))
      RemovePendingOrder();
}
 
Mathemat:

Наверно, как-то так, если без параметров:

bool IsActiveType()
{
   int type = OrderType();
   return (type == OP_BUY || type == OP_SELL);
}

это некорректно использовать в силу, того что ордерселект может вернуть false, а IsActiveType() вернет 0, т.е. OP_BUY, что неправильно..
Причина обращения: