← К каталогу
Исходный код · ID 5033

Scouts Gold V9.4

scouts gold v9.4.mq4
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

Scouts Gold V9.4 — торговый советник для платформы MetaTrader 4, реализующий сеточную торговую систему с прогрессивным увеличением лотов. Советник автоматически открывает и управляет ордерами на покупку и продажу, отслеживая виртуальные сеточные уровни и корректируя объёмы позиций в зависимости от удаления цены от последнего ордера.

В состав входят механизмы контроля рисков: ограничение дневной потери, процент риска от маржи, стоп-выход по пятнице и автовыключение при достижении лимита. Также реализованы трейлинг-стопы, модификация ордеров и кнопки на графике для ручного закрытия позиций.

Советник отображает информационную панель с балансом, прибылью и свободной маржой. Встроена проверка лицензии и привязка к допустимым торговым аккаунтам. Торговые операции выполняются через стандартные API MetaTrader 4 с проверкой маржи и допустимых объёмов.

Настройки программы

НастройкаОписание
Max_Daily_Loss Допустимая дневная потеря в процентах от баланса. При достижении или превышении этого порога советник закрывает все позиции и останавливает торговлю до следующего дня.
Lots Начальный размер лота для открытия ордеров. Используется как базовый объём при первом открытии позиции и при построении виртуальной сетки.
MaxLots Максимально допустимый размер лота. Все рассчитанные объёмы ордеров ограничиваются этим значением сверху.

Поиск по коду файла

#property version   "9.40"
#property strict

#include <stdlib.mqh>
#include <Arrays\List.mqh>
#include <ChartObjects\ChartObjectsLines.mqh>

input double Max_Daily_Loss = 20.0; // Max Daily Loss (%)
input double Lots           = 0.01; // Initial Lot Size
input double MaxLots        = 0.2;  // Maximum Lot Size

double   g_lot_multiplier        = 1.35;                 
uchar    g_max_trades            = 14;                   
bool     g_use_add_lot           = false;                
double   g_lot_add_step          = 0.01;                 
int      g_slippage              = 2;                    
int      g_magic                 = 1493892;              
string   g_trade_comment         = "Scouts Gold V9.4";   
short    g_sl_pips               = 400;                  
short    g_tp_pips               = 100;                  
int      g_btn_slippage          = 5;                    
short    g_vclear_pips           = 50;                   
short    g_tp2_pips              = 37;                   
double   g_max_risk_pct          = 40.0;                 
uchar    g_real_lot_scale_at     = 7;                    
uchar    g_vgrid_lot_scale_at    = 7;                    
uchar    g_vgrid_bypass_cnt      = 7;                    
uchar    g_real_avg_from_cnt     = 2;                    
double   g_grid_step_pips        = 85.0;                 
double   g_grid_step_add_pts     = 40.0;                 
bool     g_use_trailing_tp2      = true;                 
double   g_trail_stop_pts        = 50.0;                 
double   g_trail_step_pts        = 50.0;                 
bool     g_use_last_trail        = true;                 
double   g_last_trail_stop_pts   = 200.0;                
double   g_last_trail_step_pts   = 100.0;                
int      g_last_trail_min_orders = 6;                    
bool     g_unused_flag_8c        = true;                 
double   g_single_trail_stop_pts = 100.0;                
double   g_single_trail_step_pts = 100.0;                
int      g_friday_stop_hour      = 18;                   
int      g_friday_stop_min       = 0;                    
bool     g_draw_virtual_lines    = false;                
int      g_last_ticket_ret       = 0;                    
int      g_point_mult            = 0;                    
int      g_timeframe             = 0;                    
int      g_n_buy                 = 0;                    
int      g_n_sell                = 0;                    
double   g_pip                   = 0.0;                  
double   g_pip_inv_unused        = 0.0;                  

double   g_arr_0104[131];                                // G[0x0104] (unused)
double   g_vsell_min_unused[131];                        // G[0x0550] (zero-initialized; read at Bid > arr[n_sell])
double   g_arr_099c[131];                                // G[0x099c] (unused)
double   g_arr_0de8[131];                                // G[0x0de8] (unused)
double   g_vbuy_price[131];                              // G[0x1234]
double   g_vsell_price[131];                             // G[0x1680]
double   g_vbuy_lot[131];                                // G[0x1acc]
double   g_vsell_lot[131];                               // G[0x1f18]

double   g_current_step          = 0.0;                  // G[0x2330]
datetime g_last_bar_time         = 0;                    // G[0x2338]
bool     g_vtp_buy_active        = false;                // G[0x2340]
bool     g_vtp_sell_active       = false;                // G[0x2341]
string   g_vol_error_msg         = "";                   // G[0x2348]
double   g_unused_2358           = 0.0;                  // G[0x2358]
double   g_unused_2360           = 0.0;                  // G[0x2360]
double   g_unused_2368           = 0.0;                  // G[0x2368]
string   g_allowed_accounts      = "[52248295],[45333010],[45322876]"; // G[0x2370]
datetime g_expire_time           = D'2022.09.17 00:00:00'; // G[0x2380] (1663372800)
string   g_expire_str            = "2022.09.17";         // G[0x2388]
string   g_telegram              = "Telegram @jacknguyenkt"; // G[0x2398]
string   g_telegram_link         = ""; // G[0x23a8]
int      g_ui_clr_1              = clrYellow;            // G[0x23b4]
int      g_ui_clr_2              = clrYellow;            // G[0x23b8]
int      g_ui_clr_3              = clrAqua;              // G[0x23bc]
int      g_ui_font_size          = 20;                   // G[0x23c0]
int      g_ui_unused_23c4        = 0;                    // G[0x23c4]
CList    g_hline_list;                                   // G[0x23c8]
double   g_unused_2410           = 0.0;                  // G[0x2410]
double   g_unused_2418           = 0.0;                  // G[0x2418]
double   g_unused_2420           = 0.0;                  // G[0x2420]
double   g_unused_2428           = 0.0;                  // G[0x2428]
double   g_daily_net             = 0.0;                  // G[0x2430]
double   g_max_dd                = 0.0;                  // G[0x2438]
double   g_balance               = 0.0;                  // G[0x2440]
double   g_equity                = 0.0;                  // G[0x2448]
double   g_cur_dd                = 0.0;                  // G[0x2450]
double   g_peak_dd               = 0.0;                  // G[0x2458]
double   g_step_ratio            = 0.0;                  // G[0x2460]
double   g_vbuy_first_price      = 0.0;                  // G[0x2468]
double   g_vsell_first_price     = 0.0;                  // G[0x2470]
bool     g_is_weekend_stop       = false;                // G[0x2478]
double   g_unused_2480           = 0.0;                  // G[0x2480]
double   g_daily_closed_profit   = 0.0;                  // G[0x2488]
double   g_unused_2490           = 0.0;                  // G[0x2490]

bool CreateHLine(CChartObjectHLine *line, const string name, double price, color clr, ENUM_LINE_STYLE style)
{
   if(line == NULL)
      return false;
   if(!line.Create(0, name, 0, price))
      return false;
   line.Selectable(false);
   line.Hidden(true);
   line.Color(clr);
   line.Style(style);
   return true;
}

void CheckLicenseAndBanner()
{
   /*if(TimeLocal() > g_expire_time || TimeCurrent() > g_expire_time)
   {
      Alert("EA time limit to : " + IntegerToString((long)g_expire_time) + "\n\nContact: | Telegram: @jacknguyenkt | Expired");
      string exp_txt = "Expired from " + TimeToStr(g_expire_time, TIME_DATE | TIME_MINUTES);
      ObjectCreate("BaoMat0", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
      ObjectSetText("BaoMat0", exp_txt, 16, "Arial", clrYellow);
      ObjectSet("BaoMat0", OBJPROP_CORNER, 0.0);
      ObjectSet("BaoMat0", OBJPROP_XDISTANCE, 125.0);
      ObjectSet("BaoMat0", OBJPROP_YDISTANCE, 65.0);

      string contact_txt = "Please Contact: " + g_telegram;
      ObjectCreate("BaoMat1", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
      ObjectSetText("BaoMat1", contact_txt, 16, "Arial", clrYellow);
      ObjectSet("BaoMat1", OBJPROP_CORNER, 0.0);
      ObjectSet("BaoMat1", OBJPROP_XDISTANCE, 125.0);
      ObjectSet("BaoMat1", OBJPROP_YDISTANCE, 105.0);

      Print("Expired | Telegram: @jacknguyenkt");
      ExpertRemove();
   }*/

   if(g_allowed_accounts != "")
   {
      string acct_tag = "[" + IntegerToString(AccountNumber()) + "]";
      if(StringFind(g_allowed_accounts, acct_tag, 0) == -1)
      {
         Alert("This only for ID: " + g_allowed_accounts + "  | Telegram: @jacknguyenkt");
         string id_txt = "This only for ID: " + g_allowed_accounts;
         ObjectCreate("BaoMat5", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
         ObjectSetText("BaoMat5", id_txt, 16, "Arial", clrYellow);
         ObjectSet("BaoMat5", OBJPROP_CORNER, 0.0);
         ObjectSet("BaoMat5", OBJPROP_XDISTANCE, 225.0);
         ObjectSet("BaoMat5", OBJPROP_YDISTANCE, 85.0);

         string contact_txt = "Please Contact: " + g_telegram;
         ObjectCreate("BaoMat6", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
         ObjectSetText("BaoMat6", contact_txt, 16, "Arial", clrYellow);
         ObjectSet("BaoMat6", OBJPROP_CORNER, 0.0);
         ObjectSet("BaoMat6", OBJPROP_XDISTANCE, 225.0);
         ObjectSet("BaoMat6", OBJPROP_YDISTANCE, 125.0);

         Print("Only for ID corres | Contact:  Telegram: @jacknguyenkt");
         ExpertRemove();
      }
   }

   if(IsTesting())
   {
      Alert("This EA run muti time so can't backtest \n\nContact:  Telegram: @jacknguyenkt ");
      ObjectCreate("BaoMat5", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
      ObjectSetText("BaoMat5", "This EA run muti time - Can't backtest  ", 20, "Arial", clrRed);
      ObjectSet("BaoMat5", OBJPROP_CORNER, 0.0);
      ObjectSet("BaoMat5", OBJPROP_XDISTANCE, 325.0);
      ObjectSet("BaoMat5", OBJPROP_YDISTANCE, 105.0);

      string contact_txt = "Please Contact: " + g_telegram;
      ObjectCreate("BaoMat6", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
      ObjectSetText("BaoMat6", contact_txt, 20, "Arial", clrRed);
      ObjectSet("BaoMat6", OBJPROP_CORNER, 0.0);
      ObjectSet("BaoMat6", OBJPROP_XDISTANCE, 325.0);
      ObjectSet("BaoMat6", OBJPROP_YDISTANCE, 155.0);

      Print("Can't backtest | Telegram: @jacknguyenkt");
      ExpertRemove();
   }
}

void ShowInfoPanel()
{
   color rainbow = clrRed;
   color prof_clr = clrLime;
   if(AccountEquity() - AccountBalance() < 0.0)
      prof_clr = clrRed;

   int sec = Seconds();
   if(sec >= 0  && sec < 10)  rainbow = clrRed;
   if(sec >= 10 && sec < 20)  rainbow = clrViolet;
   if(sec >= 20 && sec < 30)  rainbow = clrOrange;
   if(sec >= 30 && sec < 40)  rainbow = clrBlue;
   if(sec >= 40 && sec < 50)  rainbow = clrYellow;
   if(sec >= 50 && sec <= 59) rainbow = clrAqua;

   string sep     = "----------------------------------------------------------";
   double bal     = NormalizeDouble(AccountBalance(), 2);
   double eq      = NormalizeDouble(AccountEquity(), 2);
   double fmargin = NormalizeDouble(AccountFreeMargin(), 2);
   double prof    = NormalizeDouble(AccountProfit(), 2);

   if(ObjectFind("L01") < 0)
      ObjectCreate("L01", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
   ObjectSetText("L01", sep, 9, "Arial", g_ui_clr_2);
   ObjectSet("L01", OBJPROP_CORNER, 1.0);
   ObjectSet("L01", OBJPROP_XDISTANCE, 10.0);
   ObjectSet("L01", OBJPROP_YDISTANCE, 30.0);

   if(ObjectFind("L02") < 0)
      ObjectCreate("L02", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
   ObjectSetText("L02", g_trade_comment, 20, "Verdana", rainbow);
   ObjectSet("L02", OBJPROP_CORNER, 1.0);
   ObjectSet("L02", OBJPROP_XDISTANCE, 10.0);
   ObjectSet("L02", OBJPROP_YDISTANCE, 45.0);

   if(ObjectFind("L03") < 0)
      ObjectCreate("L03", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
   ObjectSetText("L03", sep, 9, "Arial", g_ui_clr_2);
   ObjectSet("L03", OBJPROP_CORNER, 1.0);
   ObjectSet("L03", OBJPROP_XDISTANCE, 10.0);
   ObjectSet("L03", OBJPROP_YDISTANCE, 80.0);

   if(ObjectFind("L04") < 0)
      ObjectCreate("L04", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
   ObjectSetText("L04", "Balance: " + DoubleToStr(bal, 2), g_ui_font_size, "Arial", clrWhite);
   ObjectSet("L04", OBJPROP_CORNER, 1.0);
   ObjectSet("L04", OBJPROP_XDISTANCE, 10.0);
   ObjectSet("L04", OBJPROP_YDISTANCE, 260.0);

   if(ObjectFind("L05") < 0)
      ObjectCreate("L05", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
   ObjectSetText("L05", "Profit: " + DoubleToStr(prof, 2), g_ui_font_size, "Arial", clrAqua);
   ObjectSet("L05", OBJPROP_CORNER, 1.0);
   ObjectSet("L05", OBJPROP_XDISTANCE, 10.0);
   ObjectSet("L05", OBJPROP_YDISTANCE, 300.0);

   if(ObjectFind("L06") < 0)
      ObjectCreate("L06", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
   ObjectSetText("L06", "F.Margin: " + DoubleToStr(fmargin, 2), g_ui_font_size, "Arial", clrYellow);
   ObjectSet("L06", OBJPROP_CORNER, 1.0);
   ObjectSet("L06", OBJPROP_XDISTANCE, 10.0);
   ObjectSet("L06", OBJPROP_YDISTANCE, 340.0);

   ObjectCreate("j", OBJ_LABEL, 0, 0, 0.0, 0, 0.0, 0, 0.0);
   ObjectSet("j", OBJPROP_CORNER, 3.0);
   ObjectSet("j", OBJPROP_XDISTANCE, 10.0);
   ObjectSet("j", OBJPROP_YDISTANCE, 10.0);
   ObjectSetText("j", "© 2022 || Telegram: @jacknguyenkt || Whatsapp: +84935526126", 9, "SKY HIDE", rainbow);
}

int CountOrders(const string side)
{
   int cnt = 0;
   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         int err = GetLastError();
         Print("Error in OrderSellect count_45 . Error code=", err);
      }
      if(OrderSymbol() != _Symbol || OrderMagicNumber() != g_magic)
         continue;
      if(side == "buy" && OrderType() == OP_BUY)
         cnt++;
      if(side == "sell" && OrderType() == OP_SELL)
         cnt++;
   }
   return cnt;
}

double GetLastOrderInfo(const string mode, const string side)
{
   double last_open = 0.0;
   double last_lots = 0.0;
   int    last_ticket = 0;

   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         int err = GetLastError();
         Print("Error in OrderSelect select(). Error code=", err);
      }
      if(OrderSymbol() != _Symbol || OrderMagicNumber() != g_magic)
         continue;
      if(side == "buy" && OrderType() == OP_BUY && OrderTicket() > last_ticket)
      {
         last_open   = OrderOpenPrice();
         last_lots   = OrderLots();
         last_ticket = OrderTicket();
      }
      if(side == "sell" && OrderType() == OP_SELL && OrderTicket() > last_ticket)
      {
         last_open   = OrderOpenPrice();
         last_lots   = OrderLots();
         last_ticket = OrderTicket();
      }
   }

   if(mode == "lastopen") return last_open;
   if(mode == "lastlots") return last_lots;
   return 0.0;
}

double GetRealAveragePrice(const string side)
{
   double sum_price_lots = 0.0;
   double sum_lots = 0.0;

   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         int err = GetLastError();
         Print("Error in OrderSelect avp_2. Error code=", err);
      }
      if(OrderSymbol() != _Symbol || OrderMagicNumber() != g_magic)
         continue;
      if(side == "buy" && OrderType() == OP_BUY)
      {
         sum_price_lots += OrderOpenPrice() * OrderLots();
         sum_lots       += OrderLots();
      }
      if(side == "sell" && OrderType() == OP_SELL)
      {
         sum_price_lots += OrderOpenPrice() * OrderLots();
         sum_lots       += OrderLots();
      }
   }

   if(sum_lots == 0.0)
      return 0.0;
   return NormalizeDouble(sum_price_lots / sum_lots, Digits);
}

double GetVirtualAveragePrice(const string side)
{
   double sum_price_lots = 0.0;
   double sum_lots = 0.0;
   int total = g_n_buy + g_n_sell;

   for(int i = total; i >= 1; i--)
   {
      if(side == "buy" && i < ArraySize(g_vbuy_price) && i < ArraySize(g_vbuy_lot))
      {
         sum_price_lots += g_vbuy_price[i] * g_vbuy_lot[i];
         sum_lots       += g_vbuy_lot[i];
      }
      if(side == "sell" && i < ArraySize(g_vsell_price) && i < ArraySize(g_vsell_lot))
      {
         sum_price_lots += g_vsell_price[i] * g_vsell_lot[i];
         sum_lots       += g_vsell_lot[i];
      }
   }

   if(sum_lots == 0.0)
      return 0.0;
   return NormalizeDouble(sum_price_lots / sum_lots, Digits);
}

void CloseSideOrders(const int order_type)
{
   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         continue;
      if(OrderSymbol() != _Symbol || OrderMagicNumber() != g_magic)
         continue;
      if(OrderType() != order_type)
         continue;
      if(order_type == OP_BUY)
      {
         if(OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Bid, Digits), g_slippage, clrBlue))
            Print(_Symbol, "Closing  transaction", OrderLots());
      }
      else if(order_type == OP_SELL)
      {
         if(OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Ask, Digits), g_slippage, clrRed))
            Print(_Symbol, "Closing  transaction", OrderLots());
      }
   }
}

double DistanceFromLastOrder(const string side)
{
   double dist = 0.0;
   if(side == "buy")
      dist = NormalizeDouble(GetLastOrderInfo("lastopen", side) - Ask, Digits);
   if(side == "sell")
      dist = NormalizeDouble(Bid - GetLastOrderInfo("lastopen", side), Digits);
   return dist;
}

double CalcNextLot(const string side)
{
   double k_step_ratio = 0.0;
   double next_lot     = 0.0;
   double min_lot      = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double lot_step     = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   int    lot_digits   = (int)MathCeil(-MathLog(lot_step) / 2.302585092994046);

   if(side == "buy")
   {
      k_step_ratio = DistanceFromLastOrder(side) / g_current_step;
      if(CountOrders(side) >= g_real_lot_scale_at)
      {
         double last_lot = GetLastOrderInfo("lastlots", side);
         if(!g_use_add_lot)
            next_lot = StrToDouble(DoubleToStr(g_lot_multiplier * k_step_ratio * last_lot, lot_digits));
         else
            next_lot = StrToDouble(DoubleToStr(g_lot_add_step * k_step_ratio + last_lot, lot_digits));
      }
      else
         next_lot = NormalizeDouble(Lots, lot_digits);
   }

   if(side == "sell")
   {
      k_step_ratio = DistanceFromLastOrder(side) / g_current_step;
      if(CountOrders(side) >= g_real_lot_scale_at)
      {
         double last_lot = GetLastOrderInfo("lastlots", side);
         if(!g_use_add_lot)
            next_lot = StrToDouble(DoubleToStr(last_lot * g_lot_multiplier * k_step_ratio, lot_digits));
         else
            next_lot = StrToDouble(DoubleToStr(g_lot_add_step * k_step_ratio + last_lot, lot_digits));
      }
      else
         next_lot = NormalizeDouble(Lots, lot_digits);
   }

   if(next_lot > MaxLots)
      next_lot = MaxLots;
   if(next_lot < min_lot)
      next_lot = min_lot;

   double margin_req = MarketInfo(_Symbol, MODE_MARGINREQUIRED);
   if(margin_req != 0.0 && lot_step != 0.0)
   {
      double max_aff_lot = MathFloor((AccountFreeMargin() * 99.0 / 100.0) / margin_req / lot_step) * lot_step;
      if(next_lot > max_aff_lot && max_aff_lot > 0.0)
         next_lot = NormalizeDouble(max_aff_lot, lot_digits);
   }

   return next_lot;
}

bool ValidateMarginAndVolume(const int order_type, double vol, const string side)
{
   if(AccountFreeMarginCheck(_Symbol, order_type, vol) < 0.0)
   {
      string dir_str = (order_type == OP_BUY) ? "Buy" : ((order_type == OP_SELL) ? "Sell" : "Order");
      int err = GetLastError();
      Print("Not enough money for ", dir_str, " ", vol, " Error code=", err);
      return false;
   }

   int max_orders = (int)AccountInfoInteger(ACCOUNT_LIMIT_ORDERS);
   if(max_orders != 0 && OrdersTotal() >= max_orders)
      return false;

   double min_vol  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double max_vol  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double step_vol = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);

   bool vol_ok = true;
   if(vol < min_vol)
   {
      Print("Volume less than the minimum allowed. The minimum volume is ", min_vol);
      g_vol_error_msg = "";
      vol_ok = false;
   }
   else if(vol > max_vol)
   {
      Print("Volume greater than the maximum allowed. The maximum volume is ", max_vol);
      g_vol_error_msg = "";
      vol_ok = false;
   }
   else if(step_vol != 0.0)
   {
      int steps = (int)MathRound(vol / step_vol);
      if(MathAbs(steps * step_vol - vol) > 1e-7)
      {
         Print("The volume is not multiple of the minimum gradation ", step_vol, ". Volume closest to the valid ", steps * step_vol);
         g_vol_error_msg = "";
         vol_ok = false;
      }
   }

   if(!vol_ok)
   {
      Print(_Symbol, " volume_check ", side, " ", g_vol_error_msg);
      return false;
   }

   if(AccountFreeMarginCheck(_Symbol, order_type, vol) <= 0.0 || GetLastError() == 134)
   {
      int err = GetLastError();
      Print("Check sell: ", err);
      return false;
   }
   return true;
}

void OpenBuy()
{
   double vol = CalcNextLot("buy");
   if(!ValidateMarginAndVolume(OP_BUY, vol, "buy"))
      return;

   g_last_ticket_ret = 0;
   while(g_last_ticket_ret < 1)
   {
      double price = NormalizeDouble(Ask, Digits);
      double lots  = CalcNextLot("buy");
      g_last_ticket_ret = OrderSend(_Symbol, OP_BUY, lots, price, g_slippage, 0.0, 0.0, g_trade_comment, g_magic, 0, clrBlue);
      if(g_last_ticket_ret < 1)
      {
         Print("Error: ", GetLastError());
         Sleep(1000);
         RefreshRates();
      }
      else
      {
         g_vtp_buy_active = true;
      }
   }
}

void OpenSell()
{
   double vol = CalcNextLot("sell");
   if(!ValidateMarginAndVolume(OP_SELL, vol, "sell"))
      return;

   g_last_ticket_ret = 0;
   while(g_last_ticket_ret < 1)
   {
      double price = NormalizeDouble(Bid, Digits);
      double lots  = CalcNextLot("sell");
      g_last_ticket_ret = OrderSend(_Symbol, OP_SELL, lots, price, g_slippage, 0.0, 0.0, g_trade_comment, g_magic, 0, clrRed);
      if(g_last_ticket_ret < 1)
      {
         Print("Error: ", GetLastError());
         Sleep(1000);
         RefreshRates();
      }
      else
      {
         g_vtp_sell_active = true;
      }
   }
}

bool ShouldOpenGridOrder(const string side)
{
   bool allow = false;
   int cnt = CountOrders(side);

   if(side == "buy")
   {
      if(DistanceFromLastOrder(side) >= g_current_step && cnt < g_max_trades && g_max_trades > 7 && cnt <= 7)
         allow = true;

      for(int lvl = 8; lvl <= 14; lvl++)
      {
         if(cnt == lvl && cnt < g_max_trades)
         {
            g_current_step += g_grid_step_add_pts * (double)(lvl - 7) * Point;
            if(DistanceFromLastOrder(side) >= g_current_step)
               allow = true;
         }
      }
      if(cnt >= 15 && cnt < g_max_trades)
      {
         g_current_step += g_grid_step_add_pts * 8.0 * Point;
         if(DistanceFromLastOrder(side) >= g_current_step)
            allow = true;
      }
   }

   if(side == "sell")
   {
      if(DistanceFromLastOrder(side) >= g_current_step && cnt < g_max_trades && g_max_trades > 7 && cnt <= 7)
         allow = true;

      for(int lvl = 8; lvl <= 14; lvl++)
      {
         if(cnt == lvl && cnt < g_max_trades)
         {
            g_current_step += g_grid_step_add_pts * (double)(lvl - 7) * Point;
            if(DistanceFromLastOrder(side) >= g_current_step)
               allow = true;
         }
      }
      if(cnt >= 15 && cnt < g_max_trades)
      {
         g_current_step += g_grid_step_add_pts * 8.0 * Point;
         if(DistanceFromLastOrder(side) >= g_current_step)
            allow = true;
      }
   }

   return allow;
}

void UpdateVirtualGrid()
{
   double lot_step   = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   int    lot_digits = (int)MathCeil(-MathLog(lot_step) / 2.302585092994046);
   double bar_high1  = iHigh(_Symbol, g_timeframe, 1);
   double bar_low1   = iLow(_Symbol, g_timeframe, 1);

   if((bar_high1 > bar_low1 && g_n_buy == 0) ||
      (g_n_buy > 0 && g_vbuy_price[g_n_buy] - Ask > g_current_step))
   {
      g_n_buy++;
      GlobalVariableCheck("buy_virtual_tp");
      GlobalVariableCheck("buy_virtual_tp2");
      GlobalVariableCheck("buy_virtual_tp2_fibo");

      g_vbuy_price[g_n_buy] = NormalizeDouble(Ask, Digits);
      if(g_n_buy == 1)
         g_vbuy_first_price = g_vbuy_price[g_n_buy];

      g_step_ratio = NormalizeDouble(g_vbuy_price[g_n_buy - 1] - g_vbuy_price[g_n_buy], Digits) / g_current_step;

      if(g_n_buy <= g_vgrid_lot_scale_at)
         g_vbuy_lot[g_n_buy] = Lots;
      else if(!g_use_add_lot)
         g_vbuy_lot[g_n_buy] = NormalizeDouble(g_lot_multiplier * g_step_ratio * g_vbuy_lot[g_n_buy - 1], lot_digits);
      else
         g_vbuy_lot[g_n_buy] = NormalizeDouble(g_vbuy_lot[g_n_buy - 1] + g_lot_add_step, lot_digits);

      if(g_draw_virtual_lines)
      {
         CChartObjectHLine *line = new CChartObjectHLine();
         string lname = "buy_virtual_line #" + IntegerToString(g_n_buy) + "/" + DoubleToString(g_vbuy_lot[g_n_buy]);
         CreateHLine(line, lname, g_vbuy_price[g_n_buy], clrGreen, STYLE_DASHDOT);
         if(CheckPointer(line) != POINTER_INVALID)
            g_hline_list.Add(line);

         if(g_n_buy == 1 && g_tp_pips > 0)
         {
            CChartObjectHLine *tp_line = new CChartObjectHLine();
            CreateHLine(tp_line, "buy_virtual_tp", g_vbuy_price[1] + g_tp_pips * g_pip, clrRed, STYLE_DASHDOT);
            if(CheckPointer(tp_line) != POINTER_INVALID)
               g_hline_list.Add(tp_line);
         }
      }
      Print("#Buy:  ", g_vbuy_lot[g_n_buy], "|| n_buy: ", g_n_buy);
   }

   if((bar_high1 < bar_low1 && g_n_sell == 0) ||
      (g_n_sell > 0 && Bid - g_vsell_price[g_n_sell] > g_current_step && Bid > g_vsell_min_unused[g_n_sell]))
   {
      g_n_sell++;
      GlobalVariableCheck("sell_virtual_tp");
      GlobalVariableCheck("sell_virtual_tp2");
      GlobalVariableCheck("sell_virtual_tp2_fibo");

      g_vsell_price[g_n_sell] = NormalizeDouble(Bid, Digits);
      if(g_n_sell == 1)
         g_vsell_first_price = g_vsell_price[g_n_sell];

      g_step_ratio = NormalizeDouble(g_vsell_price[g_n_sell] - g_vsell_price[g_n_sell - 1], Digits) / g_current_step;

      if(g_n_sell <= g_vgrid_lot_scale_at)
         g_vsell_lot[g_n_sell] = Lots;
      else if(!g_use_add_lot)
         g_vsell_lot[g_n_sell] = NormalizeDouble(g_vsell_lot[g_n_sell - 1] * g_lot_multiplier * g_step_ratio, lot_digits);
      else
         g_vsell_lot[g_n_sell] = NormalizeDouble(g_vsell_lot[g_n_sell - 1] + g_lot_add_step, lot_digits);

      if(g_draw_virtual_lines)
      {
         CChartObjectHLine *line = new CChartObjectHLine();
         string lname = "sell_virtual_line#" + IntegerToString(g_n_sell) + "/" + DoubleToString(g_vsell_lot[g_n_sell]);
         CreateHLine(line, lname, g_vsell_price[g_n_sell], clrGreen, STYLE_DASHDOT);
         if(CheckPointer(line) != POINTER_INVALID)
            g_hline_list.Add(line);

         if(g_n_sell == 1 && g_tp_pips > 0)
         {
            CChartObjectHLine *tp_line = new CChartObjectHLine();
            CreateHLine(tp_line, "sell_virtual_tp", g_vsell_price[1] - g_tp_pips * g_pip, clrRed, STYLE_DASHDOT);
            if(CheckPointer(tp_line) != POINTER_INVALID)
               g_hline_list.Add(tp_line);
         }
      }
      Print("#Sell:  ", g_vsell_lot[g_n_sell], "|| n_sell: ", g_n_sell);
   }
}

void ResetVirtualGrid(const string side)
{
   for(int i = 0; i <= 130; i++)
   {
      if(side == "buy" && CountOrders(side) == 0)
      {
         g_vbuy_price[i] = 0.0;
         g_vbuy_lot[i]   = 0.0;
         g_n_buy         = 0;
         ObjectsDeleteAll(0, "buy_virtual", 0, OBJ_HLINE);
      }
      if(side == "sell" && CountOrders(side) == 0)
      {
         g_vsell_price[i] = 0.0;
         g_vsell_lot[i]   = 0.0;
         g_n_sell         = 0;
         ObjectsDeleteAll(0, "sell_virtual", 0, OBJ_HLINE);
      }
   }
}

void TrailSingleOrderWithBE(const string side)
{
   double last_open = 0.0;
   double last_lots = 0.0;
   double last_sl   = 0.0;
   int    last_tkt  = 0;

   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         continue;
      if(OrderSymbol() != _Symbol || OrderMagicNumber() != g_magic)
         continue;

      if(side == "buy" && OrderType() == OP_BUY && OrderTicket() > last_tkt)
      {
         last_open = OrderOpenPrice();
         last_lots = OrderLots();
         last_tkt  = OrderTicket();
         last_sl   = Ord

Показано первые 50% кода (символов: 38681)