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

project 12.mq4

Вы автор или правообладатель?

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

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

О программе

Данный код представляет собой торговый советник для платформы MetaTrader 4, ориентированный на скальпинг. Советник отслеживает пробои ценовых уровней на основе волатильности и выбранного технического индикатора, после чего открывает отложенные ордера BUYSTOP или SELLSTOP в зависимости от направления движения цены.

Советник поддерживает три типа индикаторов для определения ценового канала: скользящие средние, полосы Боллинджера и огибающие. Включён расчёт среднего спреда за последние 30 тиков, фильтрация по максимальному допустимому спреду и контроль скорости исполнения ордеров. Также реализована проверка уровня свободной маржи перед торговлей.

В советнике реализованы функции управления размером лота на основе процента риска или фиксированного ручного значения, трейлинг-стоп, режим ECN (отправка ордеров без стоп-лосса и тейк-профита с последующей модификацией), обратная торговля, а также отображение графической информации на графике и создание скриншотов.

Советник отслеживает и подсчитывает ошибки сервера, выводит статистику по открытым и закрытым позициям, а также поддерживает автоматический расчёт магического номера ордера.

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

НастройкаОписание
Money_Management Управление денежными средствами — Текстовый разделитель для настроек управления денежными средствами
Money Management (MoneyManagement) Управление денежными средствами — Включает или отключает автоматический расчёт размера лота на основе процента риска
MinLots (MinLots) Минимальный лот — Минимально допустимый размер лота
MaxLots (MaxLots) Максимальный лот — Максимально допустимый размер лота
Risk (Risk) Риск — Процент риска для расчёта размера лота
ManualLotsize (ManualLotsize) Ручной размер лота — Ручной размер лота при отключённом автоматическом управлении
MIN margin Level (MinMarginLevel) Минимальный уровень маржи — Минимальный уровень маржи в процентах, при котором допускается торговля
ReverseTrade Обратная торговля — Включает или отключает обратное направление торговли
TradingSettings Настройки торговли — Текстовый разделитель для настроек торговли
TimeFrame: (TimeFrame) Таймфрейм — Таймфрейм для анализа ценовых данных
MaxSprea (MaxSpread) Максимальный спред — Максимально допустимый спред в пунктах для открытия сделок
Stop Loss Points (StopLoss) Стоп-лосс — Стоп-лосс в пунктах
TakeProfitPoints (TakeProfit) Тейк-профит — Тейк-профит в пунктах
Trailing StartPoints (TrailingStart) Начало трейлинг-стопа — Расстояние в пунктах от начала трейлинг-стопа
Commission (Commission) Комиссия — Комиссия за сделку в пунктах
Slippage in Points (Slippage) Проскальзывание — Допустимое проскальзывание в пунктах
Magic (Magic) Магический номер — Магический номер ордера для идентификации сделок советника
Comment (OrderCmt) Комментарий ордера — Комментарий, присваиваемый ордерам
Colors for sub_Display at upper left (DisplayGraphics) Отображение графики — Текстовый разделитель для настроек отображения и цветов
Heading_Size: Font size for headline (Heading_Size) Размер заголовка — Размер шрифта заголовка на графике
Text_Size: Font size for texts (Text_Size) Размер текста — Размер шрифта текстовых надписей на графике
Color for text lines (Color_Heading) Цвет заголовка — Цвет текста заголовка на графике
Color for text lines (Color_Section1) Цвет секции 1 — Цвет текстовых линий на графике
Color for text linese (Color_Section2) Цвет секции 2 — Цвет текстовых линий на графике
Color for text lines (Color_Section3) Цвет секции 3 — Цвет текстовых линий на графике
Color for text lines (Color_Section4) Цвет секции 4 — Цвет текстовых линий на графике
Получить полный код

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

#property version   "1.00"
#property strict

extern string  Money_Management           = "==== Money Management ====";
extern bool    MoneyManagement            = TRUE; // Money Management
extern double  MinLots                    = 0.01; // MinLots
extern double  MaxLots                    = 100.0; // MaxLots
extern double  Risk                       = 2.0; // Risk
extern double  ManualLotsize              = 0.1; // ManualLotsize
extern double  MinMarginLevel             = 100; // MIN margin Level
extern bool    ReverseTrade               = FALSE; 

 bool    ECN_Mode                   = FALSE; // ECN_Mode: True for brokers that don't accept SL and TP to be sent at the same time as the order
 bool    Debug                      = FALSE; // Debug: Print huge log files with info, only for debugging purposes
 bool    Verbose                    = FALSE; // Verbose: Additional log information printed in the Expert tab
extern string  TradingSettings            = "==== Trade settings ====";
extern ENUM_TIMEFRAMES TimeFrame          = PERIOD_M15; // TimeFrame:
extern double  MaxSpread                  = 30.0; // MaxSprea
 int     MaxExecution               = 0; // MaxExecution: Max allowed average execution time in ms (0 means no restrictions)
 int     MaxExecutionMinutes        = 5; // MaxExecutionMinutes: How often in minutes should fake orders be sent to measure execution speed
extern double  StopLoss                   = 60; // Stop Loss Points
extern double  TakeProfit                 = 100; // TakeProfitPoints
 double  AddPriceGap                = 0; // AddPriceGap: Additional price gap in points added to SL and TP in order to avoid Error 130
extern double  TrailingStart              = 20; // Trailing StartPoints
extern double  Commission                 = 0; // Commission
extern int     Slippage                   = 3; // Slippage in Points
 double  MinimumUseStopLevel        = 0; // MinimumUseStopLevel: Stoplevel to use will be max value of either this value or broker stoplevel
 string  VolatilitySettings         = "==== Volatility Settings ====";
 bool    UseDynamicVolatilityLimit  = TRUE; // UseDynamicVolatilityLimit: Calculated based on INT (spread * VolatilityMultiplier)
 double  VolatilityMultiplier       = 125; // VolatilityMultiplier: A multiplier that only is used if UseDynamicVolatilityLimit is set to TRUE
 double  VolatilityLimit            = 180; // VolatilityLimit: A fix value that only is used if UseDynamicVolatilityLimit is set to FALSE
 bool    UseVolatilityPercentage    = TRUE; // UseVolatilityPercentage: If true, then price must break out more than a specific percentage
 double  VolatilityPercentageLimit  = 0; // VolatilityPercentageLimit: Percentage of how much iHigh-iLow difference must differ from VolatilityLimit.
 string  UseIndicatorSet            = "=== Indicators: 1 = Moving Average, 2 = BollingerBand, 3 = Envelopes";
 int     UseIndicatorSwitch         = 1; // UseIndicatorSwitch: Choose of indicator for price channel.
 int     Indicatorperiod            = 3; // Indicatorperiod: Period in bars for indicator
 double  BBDeviation                = 2.0; // BBDeviation: Deviation for the iBands indicator only
 double  EnvelopesDeviation         = 0.07; // EnvelopesDeviation: Deviation for the iEnvelopes indicator only
 int     OrderExpireSeconds         = 3600; // OrderExpireSeconds: Orders are deleted after so many seconds

extern int     Magic                      = 88493; // Magic
extern string  OrderCmt                   = "Perfect Shot"; // Comment

string  Screen_Shooter             = "==== Screen Shooter ====";
 bool    TakeShots                  = FALSE; // TakeShots: Save screen shots for each opened order
 int     DelayTicks                 = 1; // DelayTicks: Delay so many ticks after new bar
 int     ShotsPerBar                = 1; // ShotsPerBar: How many screen shots per bar
extern string  DisplayGraphics            = "=== Display Graphics ==="; // Colors for sub_Display at upper left
extern int     Heading_Size               = 13;  // Heading_Size: Font size for headline
extern int     Text_Size                  = 12;  // Text_Size: Font size for texts
extern color   Color_Heading              = Lime;   // Color for text lines
extern color   Color_Section1             = Yellow; // Color for text lines
extern color   Color_Section2             = Aqua;   // Color for text linese
extern color   Color_Section3             = Orange; // Color for text lines
extern color   Color_Section4             = Magenta;// Color for text lines

string EA_version = "EA R Scalper v. 1.0";

datetime StartTime;        // Initial time
datetime LastTime;         // For measuring tics

int BrokerDigits = 0;      // Nnumber of digits that the broker uses for this currency pair
int GlobalError = 0;       // To keep track on number of added errors
int TickCounter = 0;       // Counting tics
int UpTo30Counter = 0;     // For calculating average spread
int Execution = -1;        // For Execution speed, -1 means no speed
int Avg_execution = 0;     // Average Execution speed
int Execution_samples = 0; // For calculating average Execution speed
int Leverage;              // Account Leverage in percentage
int Err_unchangedvalues;   // Error count for unchanged values (modify to the same values)
int Err_busyserver;        // Error count for busy server
int Err_lostconnection;    // Error count for lost connection
int Err_toomanyrequest;    // Error count for too many requests
int Err_invalidprice;      // Error count for invalid price
int Err_invalidstops;      // Error count for invalid SL and/or TP
int Err_invalidtradevolume;// Error count for invalid lot size
int Err_pricechange;       // Error count for change of price
int Err_brokerbuzy;        // Error count for broker is buzy
int Err_requotes;          // Error count for requotes
int Err_toomanyrequests;   // Error count for too many requests
int Err_trademodifydenied; // Error count for modify orders is denied
int Err_tradecontextbuzy;  // error count for trade context is buzy
int SkippedTicks = 0;      // Used for simulation of latency during backtests, how many tics that should be skipped
int Ticks_samples = 0;     // Used for simulation of latency during backtests, number of tick samples
int Tot_closed_pos;        // Number of closed positions for this EA
int Tot_Orders;            // Number of open orders disregarding of magic and pairs
int Tot_open_pos;          // Number of open positions for this EA

double LotBase;            // Amount of money in base currency for 1 lot
double Tot_open_profit;    // A summary of the current open profit/loss for this EA
double Tot_open_lots;      // A summary of the current open lots for this EA
double Tot_open_swap;      // A summary of the current charged swaps of the open positions for this EA
double Tot_open_commission;// A summary of the currebt charged commission of the open positions for this EA
double G_equity;           // Current equity for this EA
double Changedmargin;      // Free margin for this account
double Tot_closed_lots;    // A summary of the current closed lots for this EA
double Tot_closed_profit;  // A summary of the current closed profit/loss for this EA
double Tot_closed_swap;    // A summary of the current closed swaps for this EA
double Tot_closed_comm;    // A summary of the current closed commission for this EA
double G_balance = 0;      // Balance for this EA
double Array_spread[30];   // Store spreads for the last 30 tics
double LotSize;            // Lotsize
double Highest;            // LotSize indicator value
double Lowest;             // Lowest indicator value
double StopLevel;          // Broker StopLevel
double StopOut;            // Broker stoput percentage
double LotStep;            // Broker LotStep
double MarginForOneLot;    // Margin required for 1 lot
double Avg_tickspermin;    // Used for simulation of latency during backtests
double MarginFree;         // Free margin in percentage

void OnInit()
{
      // код доступен только после оплаты
   }

void OnDeinit( const int reason )
{
   string text = "";

   sub_printsumofbrokererrors();

   sub_DeleteDisplay();

   sub_CheckThroughAllClosedOrders();

   if ( IsTesting ( ) == TRUE )
   {
      Print ( "Total closed lots = ", DoubleToStr ( Tot_closed_lots, 2 ) );
      Print ( "Total closed swap = ", DoubleToStr ( Tot_closed_swap, 2 ) );
      Print ( "Total closed commission = ", DoubleToStr ( Tot_closed_comm, 2 ) );

      if ( MaxExecution > 0 )
      {
         text = text + "During backtesting " + (string) SkippedTicks + " number of ticks was ";
         text = text + "skipped to simulate latency of up to " + (string) MaxExecution + " ms";
         sub_printandcomment ( text );
      }
   }

   Print ( EA_version, " has been deinitialized!" );

   Print ( __FUNCTION__, "_Uninitalization reason code = ", reason );

   Print ( __FUNCTION__, "_UninitReason = ", sub_UninitReasonText( _UninitReason ) );

}

void OnTick()
{
      // код доступен только после оплаты
   }

void sub_trade()
{
   string textstring;
   string pair;
   string indy;

   datetime orderexpiretime;

   bool select = FALSE;
   bool wasordermodified = FALSE;
   bool ordersenderror = FALSE;
   bool isbidgreaterthanima = FALSE;
   bool isbidgreaterthanibands = FALSE;
   bool isbidgreaterthanenvelopes = FALSE;
   bool isbidgreaterthanindy = FALSE;

   int orderticket;
   int loopcount2;
   int loopcount1;
   int pricedirection;
   int counter1;
   int counter2;
   int askpart;
   int bidpart;

   double ask;
   double bid;
   double askplusdistance;
   double bidminusdistance;
   double volatilitypercentage = 0;
   double orderprice;
   double orderstoploss;
   double ordertakeprofit;
   double ihigh;
   double ilow;
   double imalow = 0;
   double imahigh = 0;
   double imadiff;
   double ibandsupper = 0;
   double ibandslower = 0;
   double ibandsdiff;
   double envelopesupper = 0;
   double envelopeslower = 0;
   double envelopesdiff;
   double volatility;
   double spread;
   double avgspread;
   double realavgspread;
   double fakeprice;
   double sumofspreads;
   double askpluscommission;
   double bidminuscommission;
   double skipticks;
   double am = 0.000000001;  // Set variable to a very small number
   double marginlevel;
   double tmpexecution;

   MarginFree = AccountFreeMargin();

   if ( AccountMargin() != 0 )
      am = AccountMargin();
   marginlevel = AccountEquity() / am * 100;

   if ( marginlevel < MinMarginLevel )
   {
      Print ( "Warning! Free Margin " + DoubleToStr ( marginlevel, 2 ) + " is lower than MinMarginLevel!" );
      Alert ( "Warning! Free Margin " + DoubleToStr ( marginlevel, 2 ) + " is lower than MinMarginLevel!" );
      return;
   }

   if ( LastTime < Time[0] )
   {

      if ( Ticks_samples < 10 )
         Ticks_samples ++;
      Avg_tickspermin = Avg_tickspermin + ( TickCounter - Avg_tickspermin ) / Ticks_samples;

      LastTime = Time[0];
      TickCounter = 0;
   }

   else
      TickCounter ++;

   if ( IsTesting() && MaxExecution != 0 && Execution != -1 )
   {
      skipticks = MathRound ( Avg_tickspermin * MaxExecution / ( 60 * 1000 ) );
      if ( SkippedTicks >= skipticks )
      {
         Execution = -1;
         SkippedTicks = 0;
      }
      else
      {
         SkippedTicks ++;
      }
   }

   ask = MarketInfo ( Symbol(), MODE_ASK );
   bid = MarketInfo ( Symbol(), MODE_BID );

   ihigh = iHigh ( Symbol(), TimeFrame, 0 );
   ilow = iLow ( Symbol(), TimeFrame, 0 );
   volatility = ihigh - ilow;

   indy = "";

   if ( UseIndicatorSwitch == 1 || UseIndicatorSwitch == 4 )
   {
      imalow = iMA ( Symbol(), TimeFrame, Indicatorperiod, 0, MODE_LWMA, PRICE_LOW, 0 );
      imahigh = iMA ( Symbol(), TimeFrame, Indicatorperiod, 0, MODE_LWMA, PRICE_HIGH, 0 );
      imadiff = imahigh - imalow;
      isbidgreaterthanima = bid >= imalow + imadiff / 2.0;
      indy = "iMA_low: " + sub_dbl2strbrokerdigits ( imalow ) + ", iMA_high: " + sub_dbl2strbrokerdigits ( imahigh ) + ", iMA_diff: " + sub_dbl2strbrokerdigits ( imadiff );
   }

   if ( UseIndicatorSwitch == 2 )
   {
      ibandsupper = iBands ( Symbol(), TimeFrame, Indicatorperiod, BBDeviation, 0, PRICE_OPEN, MODE_UPPER, 0 );
      ibandslower = iBands ( Symbol(), TimeFrame, Indicatorperiod, BBDeviation, 0, PRICE_OPEN, MODE_LOWER, 0 );
      ibandsdiff = ibandsupper - ibandslower;
      isbidgreaterthanibands = bid >= ibandslower + ibandsdiff / 2.0;
      indy = "iBands_upper: " + sub_dbl2strbrokerdigits ( ibandsupper ) + ", iBands_lower: " + sub_dbl2strbrokerdigits ( ibandslower ) + ", iBands_diff: " + sub_dbl2strbrokerdigits ( ibandsdiff );
   }

   if ( UseIndicatorSwitch == 3 )
   {
      envelopesupper = iEnvelopes ( Symbol(), TimeFrame, Indicatorperiod, MODE_LWMA, 0, PRICE_OPEN, EnvelopesDeviation, MODE_UPPER, 0 );
      envelopeslower = iEnvelopes ( Symbol(), TimeFrame, Indicatorperiod, MODE_LWMA, 0, PRICE_OPEN, EnvelopesDeviation, MODE_LOWER, 0 );
      envelopesdiff = envelopesupper - envelopeslower;
      isbidgreaterthanenvelopes = bid >= envelopeslower + envelopesdiff / 2.0;
      indy = "iEnvelopes_upper: " + sub_dbl2strbrokerdigits ( envelopesupper ) + ", iEnvelopes_lower: " + sub_dbl2strbrokerdigits ( envelopeslower ) + ", iEnvelopes_diff: " + sub_dbl2strbrokerdigits ( envelopesdiff) ;
   }

   isbidgreaterthanindy = FALSE;

   pricedirection = 0;

   if ( UseIndicatorSwitch == 1 && isbidgreaterthanima == TRUE )
   {
      isbidgreaterthanindy = TRUE;
      Highest = imahigh;
      Lowest = imalow;
   }

   else if ( UseIndicatorSwitch == 2 && isbidgreaterthanibands == TRUE )
   {
      isbidgreaterthanindy = TRUE;
      Highest = ibandsupper;
      Lowest = ibandslower;
   }

   else if ( UseIndicatorSwitch == 3 && isbidgreaterthanenvelopes == TRUE )
   {
      isbidgreaterthanindy = TRUE;
      Highest = envelopesupper;
      Lowest = envelopeslower;
   }

   spread = ask - bid;

   LotSize = sub_calculatelotsize();

   if ( OrderExpireSeconds != 0 )
      orderexpiretime = TimeCurrent() + OrderExpireSeconds;
   else
      orderexpiretime = 0;

   ArrayCopy ( Array_spread, Array_spread, 0, 1, 29 );
   Array_spread[29] = spread;
   if ( UpTo30Counter < 30 )
      UpTo30Counter ++;
   sumofspreads = 0;
   loopcount2 = 29;
   for ( loopcount1 = 0; loopcount1 < UpTo30Counter; loopcount1 ++ )
   {
      sumofspreads += Array_spread[loopcount2];
      loopcount2 --;
   }

   avgspread = sumofspreads / UpTo30Counter;

   askpluscommission = sub_normalizebrokerdigits ( ask + Commission );
   bidminuscommission = sub_normalizebrokerdigits ( bid - Commission );
   realavgspread = avgspread + Commission;

   if ( UseDynamicVolatilityLimit == TRUE )
      VolatilityLimit = realavgspread * VolatilityMultiplier;

   if ( volatility && VolatilityLimit && Lowest && Highest && UseIndicatorSwitch != 4 )
   {

      if ( volatility > VolatilityLimit )
      {

         volatilitypercentage = volatility / VolatilityLimit;

         if ( ( UseVolatilityPercentage == FALSE ) || ( UseVolatilityPercentage == TRUE && volatilitypercentage > VolatilityPercentageLimit ) )
         {
            if ( bid < Lowest )
            {
               if ( ReverseTrade == FALSE )
                  pricedirection = -1; // BUY or BUYSTOP
               else // ReverseTrade == true
                  pricedirection = 1; // SELL or SELLSTOP
            }
            else if ( bid > Highest )
            {
               if ( ReverseTrade == FALSE )
                  pricedirection = 1;  // SELL or SELLSTOP
               else // ReverseTrade == true
                  pricedirection = -1; // BUY or BUYSTOP
            }
         }
      }

      else
         volatilitypercentage = 0;
   }

   if ( AccountEquity() <= 0.0 )
   {
      Print ( "ERROR -- Account Equity is " + DoubleToStr ( MathRound ( AccountEquity() ), 0 ) );
      return;
   }

   Execution = -1;

   counter1 = 0;
   counter2 = 0;

   for ( loopcount2 = 0; loopcount2 < OrdersTotal(); loopcount2 ++ )
   {

      select = OrderSelect ( loopcount2, SELECT_BY_POS, MODE_TRADES );

      if ( OrderMagicNumber() == Magic && OrderCloseTime() == 0 )
      {

         if ( OrderSymbol() != Symbol() )
         {

            counter2 ++;
            continue;
         }

         switch ( OrderType() )
         {

         case OP_BUY:

            while ( TRUE )
            {

               RefreshRates();

               orderstoploss = OrderStopLoss();
               ordertakeprofit = OrderTakeProfit();

               if ( ordertakeprofit < sub_normalizebrokerdigits ( askpluscommission + TakeProfit * Point + AddPriceGap ) && askpluscommission + TakeProfit * Point + AddPriceGap - ordertakeprofit > TrailingStart )
               {

                  orderstoploss = sub_normalizebrokerdigits ( bid - StopLoss * Point - AddPriceGap );
                  ordertakeprofit = sub_normalizebrokerdigits ( askpluscommission + TakeProfit * Point + AddPriceGap );

                  if ( orderstoploss != OrderStopLoss() && ordertakeprofit != OrderTakeProfit() )
                  {

                     Execution = (int) GetTickCount();

                     wasordermodified = OrderModify ( OrderTicket(), 0, orderstoploss, ordertakeprofit, orderexpiretime, Lime );
                  }

                  if ( wasordermodified == TRUE )
                  {

                     Execution = (int) GetTickCount() - Execution;

                     if ( TakeShots && !IsTesting() )
                        sub_takesnapshot();

                     break;
                  }

                  else
                  {

                     Execution = -1;

                     sub_errormessages();

                     if ( Debug || Verbose )
                        Print ( "Order could not be modified because of ",  ( GetLastError() ) );

                     if ( orderstoploss == 0 )

                        wasordermodified = OrderModify ( OrderTicket(), 0, NormalizeDouble ( Bid - 30, BrokerDigits ), 0, 0, Red );
                  }
               }

               break;
            }

            counter1 ++;

            break;

         case OP_SELL:

            while ( TRUE )
            {

               RefreshRates();

               orderstoploss = OrderStopLoss();
               ordertakeprofit = OrderTakeProfit();

               if ( ordertakeprofit > sub_normalizebrokerdigits ( bidminuscommission - TakeProfit * Point - AddPriceGap ) && ordertakeprofit - bidminuscommission + TakeProfit * Point - AddPriceGap > TrailingStart )
               {

                  orderstoploss = sub_normalizebrokerdigits ( ask + StopLoss * Point + AddPriceGap );
                  ordertakeprofit = sub_normalizebrokerdigits ( bidminuscommission - TakeProfit * Point - AddPriceGap );

                  if ( orderstoploss != OrderStopLoss() && ordertakeprofit != OrderTakeProfit() )
                  {

                     Execution = (int) GetTickCount();
                     wasordermodified = OrderModify ( OrderTicket(), 0, orderstoploss, ordertakeprofit, orderexpiretime, Orange );
                  }

                  if ( wasordermodified == TRUE )
                  {

                     Execution = (int) GetTickCount() - Execution;

                     if ( TakeShots && !IsTesting() )
                        sub_takesnapshot();

                     break;
                  }

                  else
                  {

                     Execution = -1;

                     sub_errormessages();

                     if ( Debug || Verbose )
                        Print ( "Order could not be modified because of ",  ( GetLastError() ) );

                     Sleep ( 1000 );

                     if ( orderstoploss == 0 )

                        wasordermodified = OrderModify ( OrderTicket(), 0, NormalizeDouble ( Ask + 30, BrokerDigits), 0, 0, Red );
                  }
               }

               break;
            }

            counter1 ++;

            break;

         case OP_BUYSTOP:

            if ( isbidgreaterthanindy == FALSE )
            {

               orderprice = sub_normalizebrokerdigits ( ask + StopLevel + AddPriceGap );
               orderstoploss = sub_normalizebrokerdigits ( orderprice - spread - StopLoss * Point - AddPriceGap );
               ordertakeprofit = sub_normalizebrokerdigits ( orderprice + Commission + TakeProfit * Point + AddPriceGap );

               while ( TRUE )
               {

                  if ( orderprice < OrderOpenPrice() && OrderOpenPrice() - orderprice > TrailingStart )
                  {

                     if ( orderstoploss != OrderStopLoss() && ordertakeprofit != OrderTakeProfit() )
                     {
                        RefreshRates();

                        Execution = (int) GetTickCount();
                        wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, 0, Lime );
                     }

                     if ( wasordermodified == TRUE )
                     {

                        Execution = (int) GetTickCount() - Execution;

                        if ( Debug || Verbose )
                           Print ( "Order executed in " + (string) Execution + " ms" );
                     }

                     else
                     {

                        Execution = -1;

                        sub_errormessages();
                     }
                  }

                  break;
               }

               counter1 ++;
            }

            else

               select = OrderDelete ( OrderTicket() );

            break;

         case OP_SELLSTOP:

            if ( isbidgreaterthanindy == TRUE )
            {

               orderprice = sub_normalizebrokerdigits ( bid - StopLevel - AddPriceGap );
               orderstoploss = sub_normalizebrokerdigits ( orderprice + spread + StopLoss * Point + AddPriceGap );
               ordertakeprofit = sub_normalizebrokerdigits ( orderprice - Commission - TakeProfit * Point - AddPriceGap );

               while ( TRUE )
               {

                  if ( orderprice > OrderOpenPrice() && orderprice - OrderOpenPrice() > TrailingStart)
                  {

                     if ( orderstoploss != OrderStopLoss() && ordertakeprofit != OrderTakeProfit() )
                     {
                        RefreshRates();

                        Execution = (int) GetTickCount();
                        wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, 0, Orange );
                     }

                     if ( wasordermodified == TRUE )
                     {

                        Execution = (int) GetTickCount() - Execution;

                        if ( Debug || Verbose )
                           Print ( "Order executed in " + (string) Execution + " ms" );
                     }

                     else
                     {

                        Execution = -1;

                        sub_errormessages();
                     }
                  }

                  break;
               }

               counter1 ++;
            }

            else
               select = OrderDelete ( OrderTicket() );
         } // end of switch
      }  // end if OrderMagicNumber
   } // end for loopcount2 - end of loop through open orders

   if ( GlobalError >= 0 || GlobalError == -2 )
   {
      bidpart = (int) NormalizeDouble ( bid / Point, 0 );
      askpart = (int) NormalizeDouble ( ask / Point, 0 );
      if ( bidpart % 10 != 0 || askpart % 10 != 0 )
         GlobalError = -1;
      else
      {
         if ( GlobalError >= 0 && GlobalError < 10 )
            GlobalError ++;
         else
            GlobalError = -2;
      }
   }

   ordersenderror = FALSE;

   if ( pricedirection != 0 && MaxExecution > 0 && Avg_execution > MaxExecution )
   {
      pricedirection = 0; // Ignore the order opening triger
      if ( Debug || Verbose )
         Print ( "Server is too Slow. Average Execution: " + (string) Avg_execution );
   }

   askplusdistance = ask + StopLevel;
   bidminusdistance = bid - StopLevel;

   if ( counter1 == 0 && pricedirection != 0 && sub_normalizebrokerdigits ( realavgspread) <= sub_normalizebrokerdigits ( MaxSpread * Point ) && GlobalError == -1 )
   {

      if ( pricedirection == -1 || pricedirection == 2 ) // Send a BUYSTOP
      {

         orderprice = ask + StopLevel;

         if ( ECN_Mode == TRUE )
         {

            orderprice = askplusdistance;
            orderstoploss =  0;
            ordertakeprofit = 0;

            Execution = (int) GetTickCount();

            orderticket = OrderSend ( Symbol(), OP_BUYSTOP, LotSize, orderprice, Slippage, orderstoploss, ordertakeprofit, OrderCmt, Magic, 0, Lime );

            if ( orderticket > 0 )
            {

               Execution = (int) GetTickCount() - Execution;
               if ( Debug || Verbose )
                  Print ( "Order executed in " + (string) Execution + " ms" );

               if ( TakeShots && !IsTesting() )
                  sub_takesnapshot();
            }  // end if ordersend

            else
            {
               ordersenderror = TRUE;
               Execution = -1;

               sub_errormessages();
            }

            if ( OrderSelect ( orderticket, SELECT_BY_TICKET ) )
            {
               RefreshRates();

               orderprice = OrderOpenPrice();
               orderstoploss =  sub_normalizebrokerdigits ( orderprice - spread - StopLoss * Point - AddPriceGap );
               ordertakeprofit = sub_normalizebrokerdigits ( orderprice + TakeProfit * Point + AddPriceGap );

               Execution = (int) GetTickCount();

               wasordermodified = OrderModify ( OrderTicket(), orderprice, orderstoploss, ordertakeprofit, orderexpiretime, Lime );

               if ( wasordermodified == TRUE )
               {

                  Execution = (int) GetTickCount() - Execution;
                  if ( Debug || Verbose )
                     Print ( "Order executed in " + (string) Execution + " ms" );

                  if ( TakeShots && !IsTesting() )
                     sub_takesnapshot();
               } // end successful ordermodiify

               else
               {
                  ordersenderror = TRUE;
                  Execution = -1;

                  sub_errormessages();
               } // end if-else
            }  // end if ordermodify
         } // end if ECN_Mode

         else
         {
            RefreshRates();

            orderprice = askplusdistance;//ask+StopLevel
            orderstoploss =  sub_normalizebrokerdigits ( orderprice - spread - StopLoss * Point - AddPriceGap );
            ordertakeprofit = sub_normalizebrokerdigits ( orderprice + TakeProfit * Point + AddPriceGap );

            Execution = (int) GetTickCount();

            orderticket = OrderSend ( Symbol(), OP_BUYSTOP, LotSize, orderprice, Slippage, orderstoploss, ordertakeprofit, OrderCmt, Magic, orderexpiretime, Lime );
            if ( orderticket > 0 ) // OrderSend was executed suxxessfully
            {

               Execution = (int) GetTickCount() - Execution;
        

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

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
3 982₽ ≈ $48.67