<code>//+----------------------------------------------------------------------------+ //| Автор : Ким Игорь В. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Версия : 01.02.2008 | //| Описание : Возвращает одно из двух значений взависимости от условия. | //+----------------------------------------------------------------------------+ string IIFs(bool condition, string ifTrue, string ifFalse) { if (condition) return(ifTrue); else return(ifFalse); } //+----------------------------------------------------------------------------+ //| Автор : Ким Игорь В. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Версия : 01.09.2005 | //| Описание : Вывод сообщения в коммент и в журнал | //+----------------------------------------------------------------------------+ //| Параметры: | //| m - текст сообщения | //+----------------------------------------------------------------------------+ void Message(string m) { Comment(m); if (StringLen(m)>0) Print(m); } //+----------------------------------------------------------------------------+ //| Автор : Ким Игорь В. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Версия : 28.11.2006 | //| Описание : Модификация одного предварительно выбранного ордера. | //+----------------------------------------------------------------------------+ //| Параметры: | //| pp - цена установки ордера | //| sl - ценовой уровень стопа | //| tp - ценовой уровень тейка | //| ex - дата истечения | //+----------------------------------------------------------------------------+ void ModifyOrder(double pp=-1, double sl=0, double tp=0, datetime ex=0) { bool fm; color cl=IIFc(OrderType()==OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP, clModifyBuy, clModifySell); double op, pa, pb, os, ot; int dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er, it; if (pp<=0) pp=OrderOpenPrice(); if (sl<0 ) sl=OrderStopLoss(); if (tp<0 ) tp=OrderTakeProfit(); pp=NormalizeDouble(pp, dg); sl=NormalizeDouble(sl, dg); tp=NormalizeDouble(tp, dg); op=NormalizeDouble(OrderOpenPrice() , dg); os=NormalizeDouble(OrderStopLoss() , dg); ot=NormalizeDouble(OrderTakeProfit(), dg); if (pp!=op || sl!=os || tp!=ot) { for (it=1; it<=NumberOfTry; it++) { if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break; while (!IsTradeAllowed()) Sleep(5000); RefreshRates(); fm=OrderModify(OrderTicket(), pp, sl, tp, ex, cl); if (fm) { if (UseSound) PlaySound(SoundSuccess); break; } else { er=GetLastError(); if (UseSound) PlaySound(SoundError); pa=MarketInfo(OrderSymbol(), MODE_ASK); pb=MarketInfo(OrderSymbol(), MODE_BID); Print("Error(",er,") modifying order: ",ErrorDescription(er),", try ",it); Print("Ask=",pa," Bid=",pb," sy=",OrderSymbol(), " op="+GetNameOP(OrderType())," pp=",pp," sl=",sl," tp=",tp); Sleep(1000*10); } } } } //+----------------------------------------------------------------------------+ //| Автор : Ким Игорь В. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Версия : 23.04.2009 | //| Описание : Перенос уровня стопа в безубыток | //+----------------------------------------------------------------------------+ //| Параметры: | //| sy - наименование инструмента ( "" - любой символ, | //| NULL - текущий символ) | //| op - операция ( -1 - любая позиция) | //| mn - MagicNumber ( -1 - любой магик) | //+----------------------------------------------------------------------------+ void MovingInWL(string sy="", int op=-1, int mn=-1) { double po, pp; int i, k=OrdersTotal(); if (sy=="0") sy=Symbol(); for (i=0; i<k; i++) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) { if (mn<0 || OrderMagicNumber()==mn) { po=MarketInfo(OrderSymbol(), MODE_POINT); if (OrderType()==OP_BUY) { if (OrderStopLoss()-OrderOpenPrice()<LevelWLoss*po) { pp=MarketInfo(OrderSymbol(), MODE_BID); if (pp-OrderOpenPrice()>LevelProfit*po) { ModifyOrder(-1, OrderOpenPrice()+LevelWLoss*po, -1); } } } if (OrderType()==OP_SELL) { if (OrderStopLoss()==0 || OrderOpenPrice()-OrderStopLoss()<LevelWLoss*po) { pp=MarketInfo(OrderSymbol(), MODE_ASK); if (OrderOpenPrice()-pp>LevelProfit*po) { ModifyOrder(-1, OrderOpenPrice()-LevelWLoss*po, -1); } } } } } } } } //+----------------------------------------------------------------------------+</code>
//+----------------------------------------------------------------------------+
//| e-MovingInWL2.mq4 |
//| |
//| Ким Игорь В. aka KimIV |
//| http://www.kimiv.ru |
//| |
//| 27.10.2008 Советник перемещает стоп в безубыток. |
//+----------------------------------------------------------------------------+
#property copyright "Kim Igor V. aka KimIV"
#property link "http://www.kimiv.ru"
//------- Внешние параметры советника -----------------------------------------+
extern string _P_Expert = "---------- Параметры советника";
extern bool AllSymbols = True; // Следить за позициями всех символов
extern int Magic = -1; // Идентификатор позиций
extern int LevelProfit = 25; // Уровень профита в пунктах
extern int LevelWLoss = 1; // Уровень безубытка в пунктах
extern bool ShowComment = True; // Показывать комментарий
//------- Параметры исполнения торговых приказов ------------------------------+
extern string _P_Performance = "---------- Параметры исполнения";
extern bool UseSound = True; // Использовать звуковой сигнал
extern string SoundSuccess = "expert.wav"; // Звук успеха
extern string SoundError = "timeout.wav"; // Звук ошибки
extern int NumberOfTry = 2; // Количество торговых попыток
//------- Глобальные переменные советника -------------------------------------+
bool gbDisabled = False; // Флаг блокировки советника
bool gbNoInit = False; // Флаг неудачной инициализации
color clModifyBuy = Aqua; // Цвет значка модификации покупки
color clModifySell = Tomato; // Цвет значка модификации продажи
//------- Подключение внешних модулей -----------------------------------------+
#include <stdlib.mqh>
//+----------------------------------------------------------------------------+
//| |
//| ПРЕДОПРЕДЕЛЁННЫЕ ФУНКЦИИ |
//| |
//+----------------------------------------------------------------------------+
//| expert initialization function |
//+----------------------------------------------------------------------------+
void init() {
gbNoInit=False;
if (!IsTradeAllowed()) {
Message("Для нормальной работы советника необходимо\n"+
"Разрешить советнику торговать");
gbNoInit=True; return;
}
if (!IsLibrariesAllowed()) {
Message("Для нормальной работы советника необходимо\n"+
"Разрешить импорт из внешних экспертов");
gbNoInit=True; return;
}
if (!IsTesting()) {
if (IsExpertEnabled()) Message("Советник будет запущен следующим тиком");
else Message("Отжата кнопка \"Разрешить запуск советников\"");
}
start();
}
//+----------------------------------------------------------------------------+
//| expert deinitialization function |
//+----------------------------------------------------------------------------+
void deinit() {
if (!IsTesting()) Comment("");
}
//+----------------------------------------------------------------------------+
//| expert start function |
//+----------------------------------------------------------------------------+
void start() {
if (gbDisabled) {
Message("Критическая ошибка! Советник ОСТАНОВЛЕН!"); return;
}
if (gbNoInit) {
Message("Не удалось инициализировать советник!"); return;
}
if (ShowComment) {
Comment(IIFs(AllSymbols, "AllSymbols ", "")
,"Magic="+IIFs(Magic<0, "Любой", DoubleToStr(Magic, 0))+" "
,"LevelProfit="+DoubleToStr(LevelProfit, 0)+"п "
,"LevelWLoss="+DoubleToStr(LevelWLoss, 0)+"п "
);
} else Comment("");
string sy=IIFs(AllSymbols, "", NULL);
MovingInWL(sy, -1, Magic);
}
//+----------------------------------------------------------------------------+
//| |
//| ПОЛЬЗОВАТЕЛЬСКИЕ ФУНКЦИИ |
//| |
//+----------------------------------------------------------------------------+
//| Автор : Ким Игорь В. aka KimIV, http://www.kimiv.ru |
//+----------------------------------------------------------------------------+
//| Версия : 01.09.2005 |
//| Описание : Возвращает наименование торговой операции |
//+----------------------------------------------------------------------------+
//| Параметры: |
//| op - идентификатор торговой операции |
//+----------------------------------------------------------------------------+
string GetNameOP(int op) {
switch (op) {
case OP_BUY : return("Buy");
case OP_SELL : return("Sell");
case OP_BUYLIMIT : return("BuyLimit");
case OP_SELLLIMIT: return("SellLimit");
case OP_BUYSTOP : return("BuyStop");
case OP_SELLSTOP : return("SellStop");
default : return("Unknown Operation");
}
}
//+----------------------------------------------------------------------------+
//| Автор : Ким Игорь В. aka KimIV, http://www.kimiv.ru |
//+----------------------------------------------------------------------------+
//| Версия : 18.07.2008 |
//| Описание : Возвращает одно из двух значений взависимости от условия. |
//+----------------------------------------------------------------------------+
color IIFc(bool condition, color ifTrue, color ifFalse) {
if (condition) return(ifTrue); else return(ifFalse);
}
Witar