Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «copierreceiverfilter_5391011682577322108.mqh» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
Краткий обзор
О программе
Данная библиотека предоставляет набор фильтрующих функций для системы копирования торговых сигналов. Она позволяет пользователю настраивать обработку входящих и исходящих ордеров на стороне реципиента, включая блокировку, модификацию и управление позициями.
Библиотека содержит структуру OrderDef, описывающую данные ордера, и набор фильтрующих функций, которые вызываются копирующим советником на различных этапах обработки торговых операций. Фильтры могут разрешать или блокировать операции, а также изменять параметры ордеров перед их исполнением.
Для передачи данных между советником-реципиентом и фильтрующими функциями используется сериализация структуры OrderDef в строку и обратно. Библиотека поддерживает как MQL4, так и MQL5 через условную компиляцию.
Функция FilterManageOrders вызывается периодически, не реже чем OnTick(), и предоставляет возможность мониторинга и управления текущими ордерами на счёте реципиента.
Структура, определяющая данные ордера или позиции: тикет, идентификатор позиции, тип, символ, объём, цены открытия и закрытия, время открытия, стоп-лосс, тейк-профит, прибыль, своп, комиссия, комментарий и магическое число.
Фильтр проверки нового ордера. Вызывается перед размещением ордера на стороне реципиента. Возвращает true для разрешения или false для блокировки ордера. При true позволяет изменить параметры нового ордера.
Функцияbool FilterCloseOrder(string Channel, OrderDef& receiverOrder, int reason)
Фильтр закрытия ордера. Вызывается перед закрытием позиции на стороне реципиента. Возвращает false для предотвращения закрытия. Параметр reason указывает причину закрытия.
Фильтр модификации ордера. Вызывается при изменении цен входа, стоп-лосса или тейк-профита. Возвращает false для блокировки изменения или позволяет переопределить новые уровни.
Функция периодического управления ордерами. Вызывается не реже OnTick() и получает массив текущих ордеров реципиента. Позволяет мониторить, модифицировать, закрывать или открывать ордера.
/* *************************************************************************************
Library which allows bespoke modifications to the copier's trading.
Only used if the UseExternalFilters setting is turned on in the copier.
************************************************************************************* */
#property library
#property strict
/* *************************************************************************************
Order definition used by the copier
************************************************************************************* */
#ifdef __MQL5__
#define TICKET ulong
#else
#define TICKET int
#endif
struct OrderDef {
TICKET ticket; // for existing orders/positions, the local ticket number of the order/position
string positionId; // the external position ID, from the sender
int type; // type of order/position, using the MT4 values: 0=buy, 1=sell, 2=buy-limit, 3=sell-limit, 4=buy-stop, 5=sell-stop
string symbol;
double volume; // For the sender's order, the *NOTIONAL VOLUME*: lots x contract size. For receiver orders, the local lot size.
double openprice;
double closeprice; // As in MT4&5: current/close price. Opposite side of spread for market orders; same side of spread for pending orders
datetime opentime;
double sl;
double tp;
double profit;
double swap;
double commission;
string comment; // DO NOT ALTER unless you also turn on UseOriginalOrderComments or UseCustomOrderComment (and then override the comment here). This can orphan positions, and make the copier close them because they cannot be reconciled against the sender's heartbeat
int magic; // DO NOT ALTER. This will orphan positions. The copier will ignore and not manage any trades which don't have its specified magic number.
};
/* *************************************************************************************
Function which filters new order requests into the copier, after all internal
checks and conversions have taken place. Returns true to allow the order to be
placed on the receiver, or false to block it. If the function returns true,
then it is allowed to modify the values in newOrder to change the new order which
the receiver will then place. Parameters for the function are the new order
from the sender (note: where the volume is a cash/unit amount such as 20000, not a lots
value such 0.20); an array of local tickets currently being managed by the copier;
and the new order which the copier is about to place, having already done all
its standard checks and conversions.
Note: you can use this function (or any other) to place additional new orders of
your own onto the account. However, if you want to associate these orders with
sender positions, so that they are automatically closed if the sender's trade
is closed, then you need to do at least two things:
* Use the same magic number as the copier, which will be newOrder.magic
* Link this order of yours to the sender position. You can do this
either by using the same order comment, newOrder.comment, which the
copier would use itself, or by using MapTicketNumberToBroadcasterPositionId below.
If your additional order is for a different symbol, then you also need to prevent
the copier trying to copy any s/l or t/p - because the prices won't be applicable
to your order on a different market. You need to use FilterOrderModify, below,
to stop the mirroring of the s/l and t/p onto your own orders.
************************************************************************************* */
bool FilterCheckNewOrder(string Channel, OrderDef& senderOrder, OrderDef& existingOrders[], OrderDef& newOrder)
{
return true;
}
/* *************************************************************************************
Called when the copier is about to close/delete a position/order. This function can
then return false to prevent the order being closed. The reason parameter explains why
the copier is closing the order:
0 = normal close instruction from sender
1 = ticket is no longer on sender's heartbeat
2 = sender position is partially closed, and PreventPartialExits is turned on
3 = sender position is partially closed, and receiver's order is still pending
4 = sender position is partially closed, and rounded/converted lot size on receiver leads to a full close
5 = receiver has a filled position; sender's order is still pending; time since fill exceeds RequireSenderFillWithinMinutes
10 = order being closed because of drawdown-shutdown
11 = order profit has breached MaxCashRisk
12 = new position has failed post-trade check on slippage (ImmediateCloseOnSlippagePips)
13 = close button in UI (for MT5 netting accounts)
Note: if you suppress a close for reason #0, the copier will then make repeated
requests to close the order with reason=#1 because the order will not be on the
sender's heartbeat.
************************************************************************************* */
bool FilterCloseOrder(string Channel, OrderDef& receiverOrder, int reason)
{
return true;
}
/* *************************************************************************************
Called when the copier is about to do a partial close. The SenderCloseFactor is the
amount of the sender's position which has been closed (e.g. 0.5, for 50%). The LotsToClose
is the amount which the copier intends to close of its local order. This filter
can return false to prevent the partial close entirely. If it returns true, then it can
change the amount of the partial close by modifying the by-reference LotsToClose value.
(This function can also prevent a partial close by setting LotsToClose=0 as well as
by returning false. But that route creates extra entries in the logs.)
************************************************************************************* */
bool FilterPartialClose(string Channel, OrderDef& receiverOrder, double SenderCloseFactor, double & LotsToClose)
{
return true;
}
/* *************************************************************************************
Called when the copier is about to change an order's s/l or t/p as a result of
a modification received in the sender's heartbeat. This function can return false
to prevent the modification. If it returns true then it can override the new levels
by changing the by-reference values such as NewSL.
************************************************************************************* */
bool FilterOrderModify(string Channel, OrderDef& receiverOrder, double & NewEntryPrice, double & NewSL, double & NewTP)
{
/*
For example, if a position has an existing s/l, then the following code prevents a change to
the s/l which widens it and increases the risk on the trade:
switch (receiverOrder.type) {
case 0: // Buy order
if (receiverOrder.sl && NewSL < receiverOrder.sl) {
Print("Preventing stop being widened on #", receiverOrder.ticket , " from " , receiverOrder.sl , " to ", NewSL);
NewSL = receiverOrder.sl; // Can also return false to prevent the change entirely
}
break;
case 1: // Sell order
if (receiverOrder.sl && NewSL > receiverOrder.sl) {
Print("Preventing stop being widened on #", receiverOrder.ticket , " from " , receiverOrder.sl , " to ", NewSL);
NewSL = receiverOrder.sl; // Can also return false to prevent the change entirely
}
break;
}
*/
return true;
}
/* *************************************************************************************
Called periodically with a list of the copier's current orders in the existingOrders[]
array, lett
Показано первые 50% кода (символов: 12778)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.