//+------------------------------------------------------------------------------+ //| SV vX.X | //| Copyright © 2009-2010 gorby777 | //| gorby_e-mail@rambler.ru | //|Особое СПАСИБО Киму Игорю В. (aka KimIV, http://www.kimiv.ru) за его функции | //+------------------------------------------------------------------------------+ #property copyright "Copyright © 2009-2010 gorby777" #property link "gorby_e-mail@rambler.ru" extern int LevelHour = 5; extern int LevelRange = 4; extern int TradingHour = 8; extern int TradingMinute = 52; extern int PipsBack = 22; extern string n = "---------"; extern int TakeProfit = 280; extern int StopLoss = 240; extern int MinProfit = 130; extern int TrailingStop = 140; extern double CoeffToLot = 1; extern string s = "---------"; extern bool UseTrailing = true; extern bool SendMail_ = false; extern bool MM = false; extern bool TradeAllowed = true; // Остановка торговли советником static int TrailingStep = 3; static int ticket; int modeSetOrders = 1; // 0 - по заданной цене // 1 - скорректировать цены // 2 - вход по текущим ценам int Slippage = 0; color clOpenBuy = LightBlue; // Цвет значка открытия покупки color clOpenSell = LightCoral; // Цвет значка открытия продажи color clCloseBuy = Blue; // Цвет значка закрытия покупки color clCloseSell = Red; // Цвет значка закрытия продажи color clModifyBuy = Aqua; // Цвет значка модификации покупки color clModifySell = Tomato; // Цвет значка модификации продажи bool MarketWatch = True; // Запросы под исполнение "Market Watch". static double Point_; static int Magic,MagicOfName,MagicOfSymbol; static string symbol,ExpertName, AccNumber; static double Price_high = 0; static double Price_low = 0; static datetime DateExp = 0; static bool Start = true; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ int init(){ symbol = Symbol(); ExpertName = WindowExpertName(); Magic=Magic(ExpertName,symbol); Price_high=GlobalVariableGet(Magic+"_Price_high"); Price_low=GlobalVariableGet(Magic+"_Price_low"); DateExp=GlobalVariableGet(Magic+"_DateExp"); Start=GlobalVariableGet(Magic+"_Start"); Point_=Point; if((Digits == 3 || Digits == 5)){Point_ = 10*Point; } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ int deinit(){ ObjectsDeleteAll(); if(IsTesting()){ GlobalVariableSet(Magic+"_DateExp",0); GlobalVariableSet(Magic+"_Price_high",0); GlobalVariableSet(Magic+"_Price_low",0); GlobalVariableSet(Magic+"_Start",1); GlobalVariableSet("Time",0); GlobalVariableSet("Lot",0.1); } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ int start(){ SetLot(); Mail(); if (UseTrailing && !IsTradeContextBusy()) TrailPositions(); if (!TradeAllowed)return(0); if(Hour()==TradingHour && Minute() >= TradingMinute && DateExp< TimeCurrent()) { if(DayOfWeek()==5 && TradingHour >=22){DateExp=TimeCurrent()+24*60*60; return(0);} int shift=TradingHour-LevelHour; if(shift<=0) { if(DayOfWeek()==1) {shift=23+shift;} else shift=24+shift; } int pl=3; if(Month()==5 || Month()==6|| Month()==7 || Month()==11 || Month()==12)pl=NormalizeDouble(pl*1.7,0); Price_high=iHigh(symbol,60,iHighest(symbol,60,MODE_HIGH,LevelRange,shift)) + (3+pl)*Point_; Price_low=iLow(symbol,60,iLowest(symbol,60,MODE_LOW,LevelRange,shift))-pl*Point_; DateExp=TimeCurrent()+24*60*60; GlobalVariableSet(Magic+"_Price_high",Price_high); GlobalVariableSet(Magic+"_Price_low",Price_low); GlobalVariableSet(Magic+"_Start",0); GlobalVariableSet(Magic+"_DateExp",DateExp); } if(!IsTesting()) Comment("Price_high - ",DoubleToStr(Price_high,Digits),"\n", "Price_low - ",DoubleToStr(Price_low,Digits),"\n", "Magic - ",DoubleToStr(Magic,0)); Start=GlobalVariableGet(Magic+"_Start"); if(Start || IsTradeContextBusy())return(0); double MA14 = iMA(symbol,60,14,0,MODE_SMMA,PRICE_MEDIAN,1); double MA41 = iMA(symbol,60,41,0,MODE_SMMA,PRICE_MEDIAN,1); Price_high=GlobalVariableGet(Magic+"_Price_high"); Price_low=GlobalVariableGet(Magic+"_Price_low"); int pb=PipsBack; if(Month()==5 || Month()==6|| Month()==7 || Month()==11 || Month()==12)pb=NormalizeDouble(PipsBack*1.7,0); if(Bid >= Price_high+10*Point_){ double k=1; if(Price_low>MA41){k=0.5;Price_high=Price_high-pb*Point_;} double SSP=Price_high; DateExp=GlobalVariableGet(Magic+"_DateExp"); if(Price_high>MA14) ticket = OrderSend_(symbol, OP_SELLSTOP, GlobalVariableGet("Lot"), SSP, Slippage, SSP+StopLoss*k*Point_, SSP - TakeProfit*k*Point_, ExpertName, Magic,DateExp); if(ticket>0){ticket=-1; Price_high=0; Price_low=0; Start=1; GlobalVariableSet(Magic+"_Price_high",Price_high); GlobalVariableSet(Magic+"_Price_low",Price_low); GlobalVariableSet(Magic+"_Start",Start); return(0); } } if(Ask<=Price_low-10*Point_){ k=1; if(Price_high0){ticket=-1; Price_high=0; Price_low=0; Start=1; GlobalVariableSet(Magic+"_Price_high",Price_high); GlobalVariableSet(Magic+"_Price_low",Price_low); GlobalVariableSet(Magic+"_Start",Start); return(0); } } } //+----------------------------------------------------------------------------+ //| Описание : Отправляет ордер | //+----------------------------------------------------------------------------+ //| Параметры: | //| sy - наименование инструмента (NULL или "" - текущий символ) | //| op - операция | //| ll - лот | //| pp - цена | //| slip-слиппадж | //| sl - уровень стоп | //| tp - уровень тейк | //| co - комментарий | //| mn - Magic Number | //| ex - Срок истечения | //+----------------------------------------------------------------------------+ int OrderSend_(string sy, int op, double ll, double pp,double Slippage, double sl=0, double tp=0, string co="",int mn=0, datetime ex=0, color cl=0) { cl=IIFc(op==OP_BUYLIMIT || op==OP_BUYSTOP, clOpenBuy, clOpenSell); datetime ot; double pa, pb, mp; int err, it, ticket, msl; if (ex>0 && ex0) { break; } else { err=GetLastError(); if (err==128 || err==142 || err==143) { Sleep(1000*66); if (OrderExist_(sy, op, mn, ot)) { break; } Print("Error(",err,") set order: ",", try ",it); continue; } mp=Point_; pa=MarketInfo(sy, MODE_ASK); pb=MarketInfo(sy, MODE_BID); Print("Error(",err,") set order: ",", try ",it); Print("Ask=",pa," Bid=",pb," sy=",sy," ll=",ll," op=",op, " pp=",pp," sl=",sl," tp=",tp," mn=",mn); // Неправильные стопы if (err==130) { // Корректировка ценовых уровней if (modeSetOrders==1) { Sleep(1000*5.3); switch (op) { case OP_BUYLIMIT: if (pp>pa-msl*mp) pp=pa-msl*mp; if (sl>pp-(msl+1)*mp) sl=pp-(msl+1)*mp; if (tp>0 && tppp-(msl+1)*mp) sl=pp-(msl+1)*mp; if (tp>0 && tp0 && slpp-(msl+1)*mp) tp=pp-(msl+1)*mp; break; case OP_SELLSTOP: if (pp>pb-msl*mp) pp=pb-msl*mp; if (sl>0 && slpp-(msl+1)*mp) tp=pp-(msl+1)*mp; break; } Print("SetOrder(): Скорректированы ценовые уровни"); continue; } // Вход по текущим ценам if (modeSetOrders==2) { Print("SetOrder(): Вход по текущим ценам"); if (op==OP_BUYLIMIT || op==OP_BUYSTOP) OpenPosition(sy, OP_BUY, ll, sl, tp, mn, co); if (op==OP_SELLLIMIT || op==OP_SELLSTOP) OpenPosition(sy, OP_SELL, ll, sl, tp, mn, co); break; } } // Блокировка работы советника if (err==2 || err==64 || err==65 || err==133) { TradeAllowed=false; break; } // Длительная пауза if (err==4 || err==131 || err==132) { Sleep(1000*300); break; } // Слишком частые запросы (8) или слишком много запросов (141) if (err==8 || err==141) Sleep(1000*100); if (err==139 || err==140 || err==148) break; // Ожидание освобождения подсистемы торговли if (err==146) while (IsTradeContextBusy()) Sleep(1000*11); // Обнуление даты истечения if (err==147) { ex=0; continue; } if (err!=135 && err!=138) Sleep(1000*7.7); } } return(ticket); } //+----------------------------------------------------------------------------+ //| Описание : Возвращает результат проверки существования открытой позиции | //+----------------------------------------------------------------------------+ //| Параметры: | //| sy - наименование инструмента ("" - любой символ, | //| NULL - текущий символ) | //| op - операция (-1 - любой ордер) | //| mn - MagicNumber (-1 - любой магик) | //| ot - время открытия ( 0 - любое время установки) | //+----------------------------------------------------------------------------+ bool OrderExist_(string sy="", int op=-1, int mn=-1, datetime ot=0) { int i, k=OrdersTotal(), ty; if (sy=="0") sy=Symbol(); for (i=0; i1 && ty<6) { if ((OrderSymbol()==sy || sy=="") && (op<0 || ty==op)) { if (mn<0 || OrderMagicNumber()==mn) { if (ot<=OrderOpenTime()) return(True); } } } } } return(False); } //+----------------------------------------------------------------------------+ //| Описание : Возвращает одно из двух значений взависимости от условия. | //+----------------------------------------------------------------------------+ color IIFc(bool condition, color ifTrue, color ifFalse) { if (condition) return(ifTrue); else return(ifFalse); } //+----------------------------------------------------------------------------+ //| Версия : 10.04.2008 | //| Описание : Открывает позицию по рыночной цене. | //+----------------------------------------------------------------------------+ //| Параметры: | //| sy - наименование инструмента (NULL или "" - текущий символ) | //| op - операция | //| ll - лот | //| sl - уровень стоп | //| tp - уровень тейк | //| mn - MagicNumber | //| co - комментарий | //+----------------------------------------------------------------------------+ void OpenPosition(string sy, int op, double ll, double sl=0, double tp=0, int mn=0, string co="") { color clOpen; datetime ot; double pp, pa, pb; int dg, err, it, ticket=0; if (op==OP_BUY) clOpen=clOpenBuy; else clOpen=clOpenSell; for (it=1; it<=5; it++) { if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) { Print("OpenPosition(): Остановка работы функции"); break; } while (!IsTradeAllowed()) Sleep(5000); RefreshRates(); dg=MarketInfo(sy, MODE_DIGITS); pa=MarketInfo(sy, MODE_ASK); pb=MarketInfo(sy, MODE_BID); if (op==OP_BUY) pp=pa; else pp=pb; pp=NormalizeDouble(pp, dg); sl=NormalizeDouble(sl, dg); tp=NormalizeDouble(tp, dg); ot=TimeCurrent(); if (MarketWatch) ticket=OrderSend(sy, op, ll, pp, Slippage, 0, 0, co, mn, 0, clOpen); else ticket=OrderSend(sy, op, ll, pp, Slippage, sl, tp, co, mn, 0, clOpen); if (ticket>0) { break; } else { err=GetLastError(); // Вывод сообщения об ошибке Print("Error(",err,") opening position: ",", try ",it); Print("Ask=",pa," Bid=",pb," sy=",sy," ll=",ll," op=", " pp=",pp," sl=",sl," tp=",tp," mn=",mn); // Блокировка работы советника if (err==2 || err==64 || err==65 || err==133) { TradeAllowed=false; break; } // Длительная пауза if (err==4 || err==131 || err==132) { Sleep(1000*300); break; } if (err==128 || err==142 || err==143) { Sleep(1000*66.666); if (ExistPositions(sy, op, mn, ot)) { break; } } if (err==140 || err==148 || err==4110 || err==4111) break; if (err==141) Sleep(1000*100); if (err==145) Sleep(1000*17); if (err==146) while (IsTradeContextBusy()) Sleep(1000*11); if (err!=135) Sleep(1000*7.7); } } if (MarketWatch && ticket>0 && (sl>0 || tp>0)) { if (OrderSelect(ticket, SELECT_BY_TICKET)) OrderModify_(-1, sl, tp); } } //+----------------------------------------------------------------------------+ //| Версия : 06.03.2008 | //| Описание : Возвращает флаг существования позиций | //+----------------------------------------------------------------------------+ //| Параметры: | //| sy - наименование инструмента ("" - любой символ, | //| NULL - текущий символ) | //| op - операция (-1 - любая позиция) | //| mn - MagicNumber (-1 - любой магик) | //| ot - время открытия ( 0 - любое время открытия) | //+----------------------------------------------------------------------------+ bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=0) { int i, k=OrdersTotal(); if (sy=="0") sy=Symbol(); for (i=0; i TimeCurrent()) return(0); double LotNew = NormalizeDouble(AccountEquity()/100000*CoeffToLot,2); if (LotNew > GlobalVariableGet("Lot"))GlobalVariableSet("Lot",LotNew); GlobalVariableSet("Time",TimeCurrent()); } //ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ void Mail(){ static int LastHour; if(SendMail_ && LastHour!=Hour()){ int buys=0; int sells=0; int ords=0; for(int i=OrdersTotal()-1;i>=0;i--){ OrderSelect(i,SELECT_BY_POS); if(OrderType()==0)buys++; if(OrderType()==1)sells++; if(OrderType()>1)ords++; } string Level = "МНОГО "; if(AccountMargin()!=0)Level=DoubleToStr(100*AccountEquity()/AccountMargin(),0); SendMail(TimeToStr(TimeCurrent(),TIME_MINUTES)+", "+DoubleToStr(AccountNumber(),0)+" =", "= "+DoubleToStr(AccountEquity(),0)+", "+Level+"%, b-"+buys+", s-"+sells+", o-"+ords); LastHour=Hour(); } } //ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ