sureforexhedging_2.mq4
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «sureforexhedging_2.mq4» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Советник поддерживает два независимых стратегических режима с раздельными магическими числами, позволяет управлять лотами через фиксированный размер или расчёт от баланса, а также применяет мультипликаторы лота (мартингейл) для последующих хеджевых сделок. Имеется функция ограничения торговли по дневной прибыли и система повторных попыток отправки торговых команд при ошибках брокера.
Настройки программы
| Настройка | Описание |
|---|---|
| 0 - FIRST strategy, 1 - SECOND strategy (strategy_mode) | Режим стратегии — Выбор стратегии: 0 — первая, 1 — вторая |
| Direction of initial deal: 0 - buy deal, 1 - sell deal, other values - new opening disabled (initial_deal) | Направление начальной сделки — 0 — покупка, 1 — продажа, другие значения — новое открытие отключено |
| Stoploss for all deals (stoploss) | Стоп-лосс — Стоп-лосс для всех сделок в пунктах или ценовых единицах |
| takeprofit for all deals (takeprofit) | Тейк-профит — Тейк-профит для всех сделок в пунктах или ценовых единицах |
| If > 0, the initial deal will be opened with this lot (fixed_lot) | Фиксированный лот — Если больше 0, начальная сделка открывается с этим размером лота |
| If fixed_lot is 0 and deposit_lot > 0, initial deal will be opened with volume Balance / deposit_lot (deposit_lot) | Лот от депозита — Если fixed_lot равен 0 и deposit_lot больше 0, начальная сделка открывается с лотом Balance / deposit_lot |
| Lot multiplier for first hedging deal (martin_koeff1) | Множитель лота первого хеджа — Множитель лота для первой хеджевой сделки |
| Lot multiplier for second, third and further hedging deals (martin_koeff2) | Множитель лота последующих хеджей — Множитель лота для второй, третьей и дальнейших хеджевых сделок |
| Enable option to stop trading if a daily profit exceeds following values (it considers profit for AL (enable_daily_profi | Включить ограничение дневной прибыли — Останавливать торговлю, если дневная прибыль превышает заданные значения |
| Daily profit in the account currency (daily_profit) | Дневная прибыль — Порог дневной прибыли в валюте счёта |
| Daily profit as a percent to Balance of start of the day (daily_profit_percent) | Дневная прибыль в процентах — Порог дневной прибыли в процентах от баланса начала дня |
| If > 0, distance for placing 1-st hedging deal (distance0) | Расстояние 0 — Расстояние для размещения первой хеджевой сделки |
| If > 0, distance for placing 2-nd hedging deal (distance1) | Расстояние 1 — Расстояние для размещения второй хеджевой сделки |
| If > 0, distance for placing 3-rd hedging deal (distance2) | Расстояние 2 — Расстояние для размещения третьей хеджевой сделки |
| If > 0, distance for placing 4-th hedging deal (distance3) | Расстояние 3 — Расстояние для размещения четвёртой хеджевой сделки |
| If > 0, distance for placing 5-th hedging deal (distance4) | Расстояние 4 — Расстояние для размещения пятой хеджевой сделки |
| If > 0, distance for placing 6-th hedging deal (distance5) | Расстояние 5 — Расстояние для размещения шестой хеджевой сделки |
| If > 0, distance for placing 7-th hedging deal (distance6) | Расстояние 6 — Расстояние для размещения седьмой хеджевой сделки |
| If > 0, distance for placing 8-th hedging deal (distance7) | Расстояние 7 — Расстояние для размещения восьмой хеджевой сделки |
| If > 0, distance for placing 9-th hedging deal (distance8) | Расстояние 8 — Расстояние для размещения девятой хеджевой сделки |
| If > 0, distance for placing 10-th hedging deal (distance9) | Расстояние 9 — Расстояние для размещения десятой хеджевой сделки |
| This value in pips is substracted from SELL takeprofit and added to SELL stoploss to consider the sp (normal_spread) | Нормальный спред — Значение в пипсах, вычитаемое из тейк-профита SELL и добавляемое к стоп-лоссу SELL для учёта спреда |
| sep0 | Разделитель настроек — Текстовый разделитель для группировки параметров в панели настроек |
| If = 4, then stoploss, takeprofit and distances are specified in 4-digit points, if = 5, then in 5-d (params_digits) | Количество знаков параметров — 4 — стоп-лосс, тейк-профит и расстояния задаются в 4-значных пунктах, 5 — в 5-значных |
| Initial magic for 1-st strategy. Hedging deals add 1 to this number (initial_magic1) | Начальное магическое число 1 — Магическое число для первой стратегии; хеджевые сделки добавляют 1 к этому числу |
| Initial magic for 2-nd strategy. Hedging deals add 1 to this number (initial_magic2) | Начальное магическое число 2 — Магическое число для второй стратегии; хеджевые сделки добавляют 1 к этому числу |
| Set to 1 for ECN and STP accounts (stoploss and takeprofit are modified only after an order is sent) (market_execution) | Рыночное исполнение — Установите 1 для ECN и STP-счетов (стоп-лосс и тейк-профит корректируются только после отправки ордера) |
| Number of simultaneous attempts of sending broker requests (if some error occurs) (command_attempts) | Количество попыток отправки — Количество одновременных попыток отправки запросов брокеру при ошибке |
| Maximum slippage (max_slippage) | Максимальный проскальзывание — Допустимое максимальное проскальзывание в пунктах |
Поиск по коду файла
#include <stderror.mqh>
#define sec_wait_context 10
#define max_errors 30
#define wait_error 1000
#define busysleep 100
#define EB_NEXTTRY 0
#define EB_WAITTRY 1
#define EB_TERMINATE 2
#define StoplevelAdd 0
extern int strategy_mode = 1 ; // 0 - FIRST strategy, 1 - SECOND strategy
extern int initial_deal = 0 ; // Direction of initial deal: 0 - buy deal, 1 - sell deal, other values - new opening disabled
extern double stoploss = 60 ; // Stoploss for all deals
extern double takeprofit = 30 ; // takeprofit for all deals
extern double fixed_lot = 0.1 ; // If > 0, the initial deal will be opened with this lot
extern double deposit_lot = 0 ; // If fixed_lot is 0 and deposit_lot > 0, initial deal will be opened with volume Balance / deposit_lot lots
extern double martin_koeff1 = 3 ; // Lot multiplier for first hedging deal
extern double martin_koeff2 = 2 ; // Lot multiplier for second, third and further hedging deals
extern int enable_daily_profit = 0 ; // Enable option to stop trading if a daily profit exceeds following values (it considers profit for ALL currencies)
extern double daily_profit = 0 ; // Daily profit in the account currency
extern double daily_profit_percent = 0 ; // Daily profit as a percent to Balance of start of the day
extern double distance0 = 30 ; // If > 0, distance for placing 1-st hedging deal
extern double distance1 = 0 ; // If > 0, distance for placing 2-nd hedging deal
extern double distance2 = 0 ; // If > 0, distance for placing 3-rd hedging deal
extern double distance3 = 0 ; // If > 0, distance for placing 4-th hedging deal
extern double distance4 = 0 ; // If > 0, distance for placing 5-th hedging deal
extern double distance5 = 0 ; // If > 0, distance for placing 6-th hedging deal
extern double distance6 = 0 ; // If > 0, distance for placing 7-th hedging deal
extern double distance7 = 0 ; // If > 0, distance for placing 8-th hedging deal
extern double distance8 = 0 ; // If > 0, distance for placing 9-th hedging deal
extern double distance9 = 0 ; // If > 0, distance for placing 10-th hedging deal
extern double normal_spread = 0 ; // This value in pips is substracted from SELL takeprofit and added to SELL stoploss to consider the spread
extern string sep0 = " common EA settings " ;
extern int params_digits = 4 ; // If = 4, then stoploss, takeprofit and distances are specified in 4-digit points, if = 5, then in 5-digit pips
extern int initial_magic1 = 123000 ; // Initial magic for 1-st strategy. Hedging deals add 1 to this number
extern int initial_magic2 = 223000 ; // Initial magic for 2-nd strategy. Hedging deals add 1 to this number
extern int market_execution = 0 ; // Set to 1 for ECN and STP accounts (stoploss and takeprofit are modified only after an order is sent)
extern int command_attempts = 5 ; // Number of simultaneous attempts of sending broker requests (if some error occurs)
extern int max_slippage = 10 ; // Maximum slippage
int go = true ;
double point, d_stoplevel, d_freezelevel, d_buystop, d_sellstop, d_buytake, d_selltake ;
int errors = 0 ;
int lotsdigits ;
double dist [10] ;
int init()
{
// код доступен только после оплаты
}
int start()
{
// код доступен только после оплаты
}
int ErrorBlock (int err, int ms)
{
string str = "" ;
int res = EB_TERMINATE ;
switch (err)
{
case ERR_NO_ERROR:
str = "No error" ;
break ;
case ERR_NO_RESULT:
str = "Unknown result" ;
break ;
case ERR_COMMON_ERROR:
str = "Common error. Probably the signal was rejected by user or trade direction is denied in expert settings" ;
break ;
case ERR_INVALID_TRADE_PARAMETERS:
str = "Wrong trade function parameters" ;
break ;
case ERR_SERVER_BUSY:
str = "Server is busy. Waiting..." ;
res = EB_WAITTRY ;
break ;
case ERR_OLD_VERSION:
str = "Old version of client terminal" ;
break ;
case ERR_NO_CONNECTION:
str = "No connection with trade server. Waiting..." ;
res = EB_WAITTRY ;
break ;
case ERR_NOT_ENOUGH_RIGHTS:
str = "Not enough rights" ;
break ;
case ERR_TOO_MANY_REQUESTS:
case ERR_TOO_FREQUENT_REQUESTS:
str = "To many requests" ;
break ;
case ERR_MALFUNCTIONAL_TRADE:
str = "Malfunctional trade" ;
break ;
case ERR_ACCOUNT_DISABLED:
str = "The account is blocked" ;
break ;
case ERR_INVALID_ACCOUNT:
str = "Invalid account" ;
break ;
case ERR_TRADE_TIMEOUT:
str = "Trade timeout exceeded" ;
res = EB_NEXTTRY ;
break ;
case ERR_INVALID_PRICE:
str = "Wrong price" ;
res = EB_NEXTTRY ;
break ;
case ERR_INVALID_STOPS:
str = "Invalid stops" ;
break ;
case ERR_INVALID_TRADE_VOLUME:
str = "Invalid trade volume" ;
break ;
case ERR_MARKET_CLOSED:
str = "The market is closed" ;
break ;
case ERR_TRADE_DISABLED:
str = "Trade is disabled" ;
break ;
case ERR_NOT_ENOUGH_MONEY:
str = "Not enough money to complete operation" ;
break ;
case ERR_PRICE_CHANGED:
str = "The price has changed, trying again" ;
res = EB_NEXTTRY ;
break ;
case ERR_OFF_QUOTES:
str = "The broker sent offquotes. Trying again" ;
res = EB_NEXTTRY ;
break ;
case ERR_BROKER_BUSY:
str = "The broker is budy. Waiting..." ;
res = EB_WAITTRY ;
break ;
case ERR_REQUOTE:
str = "The broker sent requote. Trying again" ;
res = EB_WAITTRY ;
break ;
case ERR_ORDER_LOCKED:
str = "The order is already processing" ;
break ;
case ERR_LONG_POSITIONS_ONLY_ALLOWED:
str = "Only long positions allowed" ;
break ;
case ERR_TRADE_MODIFY_DENIED:
str = "Modification is denied because the order is too close to the price" ;
res = EB_WAITTRY ;
break ;
case ERR_TRADE_CONTEXT_BUSY:
if (_IsNotTradeContextBusy () >= 0)
{
res = EB_NEXTTRY ;
}
return (res) ;
case ERR_TRADE_EXPIRATION_DENIED:
str = "Expiration date usage is denied by the broker" ;
break ;
case ERR_TRADE_TOO_MANY_ORDERS:
str = "Too many orders" ;
break ;
case ERR_TRADE_HEDGE_PROHIBITED:
str = "Hedging is denied by broker" ;
break ;
case ERR_TRADE_PROHIBITED_BY_FIFO:
str = "Cannot close a deal because FIFO order is violated" ;
break ;
case 4107:
str = "Wrong price for OrderSend function" ;
break ;
case 4051:
str = "Wrong takeprofit for OrderModify function" ;
default:
str = "Unknown error ?" + DoubleToStr (err, 0) ;
}
str = StringConcatenate (str, " (the request is processed by broker in ", DoubleToStr (GetTickCount () - ms, 0), " ms)") ;
Print (str) ;
return (res) ;
}
int _IsNotTradeContextBusy()
{
if(IsTradeContextBusy())
{
int StartWaitingTime = GetTickCount();
Print("Trade context is busy. Waiting...");
while(true)
{
if(GetTickCount() - StartWaitingTime > sec_wait_context * 1000)
{
Print("Waiting limit exceeded (" + sec_wait_context + " sec.)!");
return(-2);
}
if(!IsTradeContextBusy())
{
return(0);
}
Sleep( busysleep );
}
}
else
{
return(1);
}
}
int MarketModify (int tick, double stop, double take)
{
if (! OrderSelect (tick, SELECT_BY_TICKET) || OrderType () >= 2 || OrderCloseTime () > 0)
{
Print ("Wrong ticket for MarketModify function") ;
return (-3) ;
}
double use_sl = 0, use_tp = 0 ;
if (stop > 0)
{
if (OrderType () == OP_BUY)
{
use_sl = OrderOpenPrice () - stop ;
}
else
{
use_sl = OrderOpenPrice () + stop ;
}
}
if (stop < 0)
{
use_sl = -stop ;
}
if (take > 0)
{
if (OrderType () == OP_BUY)
{
use_tp = OrderOpenPrice () + take ;
}
else
{
use_tp = OrderOpenPrice () - take ;
}
}
if (take < 0)
{
use_tp = -take ;
}
if (MathAbs (OrderStopLoss () - use_sl) < Point && MathAbs (use_tp - OrderTakeProfit ()) < Point)
{
Print ("There was an attempt to modify market order without changes to TP and SL") ;
return (-3) ;
}
int attempt = 1 ;
bool result = false ;
while (attempt <= command_attempts && ! result)
{/*
if ((OrderType () == OP_BUY && (MarketInfo (OrderSymbol (), MODE_BID) - use_sl < d_stoplevel || use_tp - MarketInfo (OrderSymbol (), MODE_BID) < d_stoplevel)) ||
(OrderType () == OP_SELL && (use_sl - MarketInfo (OrderSymbol (), MODE_ASK) < d_stoplevel || MarketInfo (OrderSymbol (), MODE_ASK) - use_tp < d_stoplevel)))
{
Print ("Couldn''t modify order ", tick, " because of broker stops level") ;
return (-2) ;
}
if ((OrderType () == OP_BUY && (MarketInfo (OrderSymbol (), MODE_BID) - use_sl < d_freezelevel || use_tp - MarketInfo (OrderSymbol (), MODE_BID) < d_freezelevel)) ||
(OrderType () == OP_SELL && (use_sl - MarketInfo (OrderSymbol (), MODE_ASK) < d_freezelevel || MarketInfo (OrderSymbol (), MODE_ASK) - use_tp < d_freezelevel)))
{
Print ("Couldn''t modify order ", tick, " because its level is too close to the price") ;
return (-2) ;
}*/
int ms = GetTickCount () ;
Print ("Attempt #", attempt, " to modify market order ", tick, " to stoploss ", DoubleToStr (use_sl, Digits), " and takeprofit ", DoubleToStr (use_tp, Digits)) ;
result = OrderModify (tick, OrderOpenPrice (), use_sl, use_tp, 0) ;
if (! result)
{
errors ++ ;
int err = GetLastError () ;
switch (ErrorBlock (err, ms))
{
case 0: // continue
break ;
case 1: // wait and continue
Sleep (wait_error) ;
break ;
case 2: // terminate
return (-1) ;
}
}
else
{
errors = 0 ;
Print ("Order successfully modified in ", GetTickCount () - ms, " ms") ;
}
if (errors > max_errors)
{
Print ("Exceeded maximum errors count while trying to send trading command.") ;
Print ("To continue you should restart terminal or the EA") ;
return (-1) ;
}
attempt ++ ;
if (attempt > command_attempts && ! result)
{
return (-1) ;
}
}
return (1) ;
}
int PendingSend (int type, double lots, double price, double stop, double take, int magic_number, string comm)
{
if (type < 2 || type > 5)
{
Print ("Error in type of pending order!") ;
return (-3) ;
}
bool price_err = false, sltp_err = false ;
RefreshRates () ;
double use_sl = 0, use_tp = 0 ;
if (stop > 0 && stop < d_stoplevel)
{
Print ("Stoploss for sending pending order is lesser that stops level!") ;
return (-3) ;
}
if (take > 0 && take < d_stoplevel)
{
Print ("Takeprofit for sending pending order is lesser that stops level!") ;
return (-3) ;
}
switch (type)
{
case OP_BUYLIMIT:
if (Ask - price < d_stoplevel)
{
price_err = true ;
}
if (stop != 0)
{
if (stop > 0)
{
use_sl = price - stop ;
}
else
{
use_sl = -stop ;
if (price - use_sl < d_stoplevel)
{
Print ("Stoploss for sending pending order is lesser that stops level!") ;
return (-3) ;
}
}
}
if (take != 0)
{
if (take > 0)
{
use_tp = price + take ;
}
else
{
use_tp = -take ;
if (use_tp - price < d_stoplevel)
{
Print ("Takeprofit for sending pending order is lesser that stops level!") ;
return (-3) ;
}
}
}
break ;
case OP_SELLLIMIT:
if (price - Bid < d_stoplevel)
{
price_err = true ;
}
if (stop != 0)
{
if (stop > 0)
{
use_sl = price + stop ;
}
else
{
use_sl = -stop ;
if (use_sl - price < d_stoПоказано первые 50% кода (символов: 22802)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.