//+------------------------------------------------------------------+ //| News trading v.01.mq4 | //| Vorese | //| vorese@yandex.ru| //+------------------------------------------------------------------+ #property copyright "Vorese" #property link "http://www.mql5.com" #property version "1.03" #property strict #property description "Необходимо добавить адрес ' http://ru.investing.com/economic-calendar/ '" #property description "в список разрешенных URL во вкладке ' Сервис / Настройки / Советники '." #property description "Календарь обновляется каждые 15 мин. или при выходе выбранной новости ," #property description "в течении 1-й минуты , с установленной переодичностью-pause" #property description "mck_local_times - разница во времени между локальным временем и Москвой " //------------------------------------------------------------------- //Исправлена ошибка установки локального времени //------------------------------------------------------------------- input string s1=NULL;//ОРДЕР input int Magic=777; input int TakeProfit=0; input int StopLoss=0; input double Lots=0.1; input int Slippage=3; //+++++++++++++++++++++++++++++ input bool only_buy=true; //открыть только Buy input bool only_sell=true; //открыть только Sell //+++++++++++++++++++++++++++++ input bool order_buy=false; //в соотв. с ожиданиями - BUY input bool order_sell=false; //в соотв. с ожиданиями - SELL //+++++++++++++++++++++++++++++ input string s2=NULL;//НАСТРОЙКИ КАЛЕНДАРЯ input bool auto_update=true;//автообновление input bool update_time=false;//обновление по времени input int pause=9;//период обновления (сек.) input int mck_local_times=0;// разница во времени относ. Москвы input color col_text=clrBlack; input color border=clrGreen; input color button_off=clrLimeGreen; input color button_on=clrGold; input color backdrop=clrBlack; input color trading_clr=clrWhite; input color Col_01=clrTurquoise; input color Col_02=clrAliceBlue; input color Col_03=clrDarkOrange; input color Col_04=clrLimeGreen; input int X_DISTANCE=5; input int Y_DISTANCE=15; input string file_name="Calendar html"; //+++++++++++++++++++++++++++++ string time_ind[70],//время currency[70],// валюта volatility[70],//волатильность text_ind[70],//текст previous[70],//предыдущий forecast[70],//прогноз fact[70],//факт compliance[70];//ожидания //+++++++++++++++++++++++++++++ bool button_0=false; bool button_1=false; bool button_2=false; bool button_3=false; bool button_4=false; bool button_5=false; bool button_time=false; bool trading=false; color col_but0=clrNONE; color col_but1=clrNONE; color col_but2=clrNONE; color col_but3=clrNONE; color col_but4=clrNONE; color col_but5=clrNONE; string symb_0=""; string symb_1=""; int r=0; int t=0; int file_size=0; int counter_timer=0; int str_trading=0; int digits=0; double point=0; datetime local_time=NULL; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { if(button_0)col_but0=button_on; else col_but0=button_off; if(button_1)col_but1=button_on; else col_but1=button_off; if(button_2)col_but2=button_on; else col_but2=button_off; if(button_3)col_but3=button_on; else col_but3=button_off; if(button_4)col_but4=button_on; else col_but4=button_off; if(button_5)col_but5=button_on; else col_but5=button_off; ButtonCreate("table",X_DISTANCE+103,Y_DISTANCE,143,9," предш. прогн. факт."+" ",7,col_text,Col_01); ButtonCreate("time",X_DISTANCE,Y_DISTANCE,102,9,"Local",7,col_text,Col_01); ButtonCreate("gmt",X_DISTANCE+516,Y_DISTANCE,111,9,"Terminal",7,col_text,Col_01); symb_0=StringSubstr(_Symbol,0,3); symb_1=StringSubstr(_Symbol,3,0); digits=_Digits; point=_Point; //--- create timer EventSetTimer(1); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { f_Delete_object(r); ObjectDelete("table"); ObjectDelete("time"); ObjectDelete("gmt"); ObjectDelete("button0"); ObjectDelete("button1"); ObjectDelete("button2"); ObjectDelete("button3"); ObjectDelete("button4"); ObjectDelete("button5"); // ObjectsDeleteAll(); //--- destroy timer EventKillTimer(); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { ResetLastError(); bool open_order=true; if(trading) { for(int i=OrdersTotal()-1; i>=0; i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) continue; if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) { open_order=false; Print("Имеется открытый ордер Magic=",Magic); } } if(open_order) { double tp=0,sl=0; if((currency[str_trading]==symb_0 && compliance[str_trading]=="+" && only_buy) || (currency[str_trading]==symb_1 && compliance[str_trading]=="-" && only_buy) || ((currency[str_trading]==symb_0 || currency[str_trading]==symb_1) && compliance[str_trading]=="=" && order_buy)) { if(TakeProfit>0) tp=NormalizeDouble(Ask+TakeProfit*point,digits); else tp=0; if(StopLoss>0) sl=NormalizeDouble(Bid-StopLoss*point,digits); else sl=0; if(OrderSend(Symbol(),OP_BUY,Lots,NormalizeDouble(Ask,digits),Slippage,sl,tp,"News trading",Magic,0,clrGreen)<0) Print(" Ошибка открытия ордера #",GetLastError()); } if((currency[str_trading]==symb_0 && compliance[str_trading]=="-" && only_sell) || (currency[str_trading]==symb_1 && compliance[str_trading]=="+" && only_sell) || ((currency[str_trading]==symb_0 || currency[str_trading]==symb_1) && compliance[str_trading]=="=" && order_sell)) { if(TakeProfit>0) tp=NormalizeDouble(Bid-TakeProfit*point,digits); else tp=0; if(StopLoss>0) sl=NormalizeDouble(Ask+StopLoss*point,digits); else sl=0; if(OrderSend(Symbol(),OP_SELL,Lots,NormalizeDouble(Bid,digits),Slippage,sl,tp,"News trading",Magic,0,clrRed)<0) Print(" Ошибка открытия ордера #",GetLastError()); } } } } //+------------------------------------------------------------------+ //| Timer function | //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ void OnTimer() { ResetLastError(); local_time=TimeLocal(); //===========условия для загрузки страницы============================ bool tic=false; if(counter_timer==1) { if(auto_update) { if(file_size<100000) // если страница не загружена или загружена не полностью { file_size=f_Calendar();tic=true;} if((Minute()==0 || Minute()==15 || Minute()==30 || Minute()==45) && !tic && update_time) //каждые 15 минут ,кроме выходных { file_size=f_Calendar(); tic=true;} } if(button_4 && !tic) // нажата кнопка "обновить" индикатора { file_size=f_Calendar(); button_4=false; col_but4=button_off; } } counter_timer++; if(counter_timer>=pause)counter_timer=0; //=====верхняя строка календаря======================================= ObjectSetString(0,"time",OBJPROP_TEXT,TimeToString(local_time,TIME_SECONDS)); ButtonCreate("button0",X_DISTANCE+250,Y_DISTANCE,40,9,"текст",6,col_text,col_but0,button_0); ButtonCreate("button1",X_DISTANCE+291,Y_DISTANCE,40,9,"$$$",6,col_text,col_but1,button_1); ButtonCreate("button2",X_DISTANCE+332,Y_DISTANCE,40,9,"$$",6,col_text,col_but2,button_2); ButtonCreate("button3",X_DISTANCE+373,Y_DISTANCE,40,9,"$",6,col_text,col_but3,button_3); ButtonCreate("button4",X_DISTANCE+414,Y_DISTANCE,50,9,"обновить",6,col_text,col_but4,button_4); ButtonCreate("button5",X_DISTANCE+465,Y_DISTANCE,50,9,"торговля",6,col_text,col_but5,button_5); //=====читаем файл , находим начало и конец таблицы=================== int handle; int string_counter=0; int begin_table=0; int end_table=0; string temp_array[6000]; handle=FileOpen(file_name,FILE_CSV|FILE_READ|FILE_SHARE_READ,CP_ACP); if(handle<1)Print("Файл не прочитан ",handle); else while(!FileIsEnding(handle)) { temp_array[string_counter]=FileReadString(handle); if(f_Position(temp_array[string_counter],0)>=0 && string_counter>600) { begin_table=string_counter; } if(begin_table>0 && f_Position(temp_array[string_counter],1)>=0) { end_table=string_counter; break; } string_counter++; } FileClose(handle); //===============Вырезаем текст из тегов============================== string array_table="", volatility_str="?", compliance_str="?", previous_str="", forecast_str="", fact_str=""; int sum_string=0, td_class=0, td=0, angle=0, span=0, span_1=0, pos_begin=0, pos_end=0, counter_news=0, counter_str=0, pos_t=0, i=begin_table; //------------------------------------------------------------------- while(i!=end_table && counter_news<70)// не более 70 строк { td_class=f_Position(temp_array[i],2); td=f_Position(temp_array[i],3); if(td_class<0 && td<0) // ищем строки новостей { sum_string=0; i++; continue; } else { if(td==0) { i++;continue;} else sum_string++; } angle=f_Position(temp_array[i],4); span=f_Position(temp_array[i],5); span_1=f_Position(temp_array[i],6); pos_t=f_Position(temp_array[i],14); if(sum_string==1) //время { if(pos_t<0) time_ind[counter_news]=StringSubstr(temp_array[i],angle+1,5); else time_ind[counter_news]=StringSubstr(temp_array[i],pos_t+13,5); } if(sum_string==2) //валюта { currency[counter_news]=StringSubstr(temp_array[i],span+8,3); } if(sum_string==3) //волатильность { array_table=StringSubstr(temp_array[i],0,angle); volatility_str=f_Cyrillic(array_table); if(f_Position(volatility_str,7)>0) volatility[counter_news]="$$$"; else { if(f_Position(volatility_str,8)>0) volatility[counter_news]="$$"; else { if(f_Position(volatility_str,9)>0) volatility[counter_news]="$"; else { volatility[counter_news]="?"; } } } } if(sum_string==4) //текст { if(span_1<0) array_table=StringSubstr(temp_array[i],angle+1,td-angle-1); else array_table=StringSubstr(temp_array[i],angle+1,span_1-angle-7); text_ind[counter_news]=StringTrimLeft(f_Cyrillic(array_table)); } if(sum_string==5) //результат ожиданий , факт { array_table=StringSubstr(temp_array[i],0,angle+1); compliance_str=f_Cyrillic(array_table); if(f_Position(compliance_str,10)>0) compliance[counter_news]="+"; else { if(f_Position(compliance_str,11)>0) compliance[counter_news]="="; else { if(f_Position(compliance_str,12)>0) compliance[counter_news]="-"; else { compliance[counter_news]="?"; } } } fact_str=StringSubstr(temp_array[i],angle+1,td-angle-1); if(f_Position(fact_str,13)>=0) fact[counter_news]="----"; else fact[counter_news]=fact_str; } if(sum_string==6) //прогноз forecast_str=StringSubstr(temp_array[i],angle+1,td-angle-1); if(f_Position(forecast_str,13)>=0) forecast[counter_news]="----"; else forecast[counter_news]=forecast_str; if(sum_string==7) //предыдущий previous_str=StringSubstr(temp_array[i],angle+1,td-angle-1); if(f_Position(previous_str,13)>=0) previous[counter_news]="----"; else previous[counter_news]=previous_str; if(sum_string==8) { counter_news++; counter_str++; } i++; } //=========формируем таблицу========================================== if(counter_str!=r && r>0)//удаляем все объекты после измен. в календаре в начале дня { f_Delete_object(r); Print("Обновление календаря ",TimeToString(local_time,TIME_DATE|TIME_SECONDS)); } r=0; t=0; color color_button=Col_04; color color_compliance=Col_04; while(r!=counter_str) //фильтруем по волатильности { if(volatility[r]=="$$$" && button_1) { r++;continue; } if(volatility[r]=="$$" && button_2) { r++;continue; } if(volatility[r]=="$" && button_3) { r++;continue; } //--------------------------------------------------------------- //цвет прошедших и будущих новостей if(button_5 && str_trading==r && button_time) color_button=trading_clr; else { if((StrToTime(time_ind[r])>=(local_time-mck_local_times*3600)) || TimeDayOfWeek(local_time)==0 || TimeDayOfWeek(local_time)==6) color_button=Col_04; else color_button=Col_01; } if(compliance[r]=="+")color_compliance=Col_02; else { if(compliance[r]=="-")color_compliance=Col_03; else { color_compliance=color_button; } } // создаем таблицу ButtonCreate("time"+(string)(r),X_DISTANCE,Y_DISTANCE+13+11*t,40,9,TimeToString(StringToTime(time_ind[r])+mck_local_times*3600,TIME_MINUTES),6,col_text,color_button,false,border); ButtonCreate("currency"+(string)(r),X_DISTANCE+41,Y_DISTANCE+13+11*t,30,9,currency[r],6,col_text,color_button,false,border); ButtonCreate("volatility"+(string)(r),X_DISTANCE+72,Y_DISTANCE+13+11*t,30,9,volatility[r],6,col_text,color_button,false,border); ButtonCreate("previous"+(string)(r),X_DISTANCE+103,Y_DISTANCE+13+11*t,40,9,previous[r],6,col_text,color_button,false,border); ButtonCreate("forecast"+(string)(r),X_DISTANCE+144,Y_DISTANCE+13+11*t,40,9,forecast[r],6,col_text,color_button,false,border); ButtonCreate("fact"+(string)(r),X_DISTANCE+185,Y_DISTANCE+13+11*t,40,9,fact[r],6,col_text,color_compliance,false,border); ButtonCreate("compliance"+(string)(r),X_DISTANCE+226,Y_DISTANCE+13+11*t,20,9,compliance[r],6,col_text,color_compliance,false,border); if(!button_0) { RectLabelCreate("LabelCreate"+(string)r,X_DISTANCE+247,Y_DISTANCE+12+11*t,380,12,backdrop,backdrop); f_Label("text"+(string)r,X_DISTANCE+250,Y_DISTANCE+10+11*t,(string)(r+1)+" "+text_ind[r],7,color_button); } r++; t++; } if(!button_5) button_time=false; ObjectSetString(0,"gmt",OBJPROP_TEXT,"№"+(string)(str_trading+1)+"# "+TimeToString(StringToTime(time_ind[str_trading])-(local_time-mck_local_times*3600),TIME_SECONDS)); //==============условия для торговли================================= if(button_5 && button_time)// если выбрана строка календаря { if(!IsTradeAllowed()) Print("Разрешить советнику торговать"); if(currency[str_trading]==symb_0 || currency[str_trading]==symb_1) // если наша валюта { if(time_ind[str_trading]==TimeToString(local_time-mck_local_times*3600,TIME_MINUTES))// время выхода новости { // file_size=0; - так было if(compliance[str_trading]=="?") file_size=0; // перезагрузим календарь если еще нет результатов trading=true; } else trading=false; } else Print("Не наша валюта"); } //=================================================================== ChartRedraw(); } //==================================================================== //+------------------------------------------------------------------+ //| ChartEvent function | //+------------------------------------------------------------------+ //==================================================================== void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam) { //--- сбросим значение ошибки ResetLastError(); //--- проверка события нажатия на кнопку мыши if(id==CHARTEVENT_OBJECT_CLICK) { //--------------кнопка "текст"---------------------------------- if(sparam=="button0" && !button_0) { button_0=true; col_but0=button_on;f_Delete_object(r);// запомним , что кнопка нажата return; } if(sparam=="button0" && button_0) { button_0=false; col_but0=button_off;f_Delete_object(r); // запомним , что кнопка отжата return; } //---------------кнопка "$$$"----------------------------------- if(sparam=="button1" && !button_1) { button_1=true; col_but1=button_on;f_Delete_object(r); return; } if(sparam=="button1" && button_1) { button_1=false; col_but1=button_off;f_Delete_object(r); return; } //---------------кнопка "$$"------------------------------------ if(sparam=="button2" && !button_2) { button_2=true; col_but2=button_on;f_Delete_object(r); return; } if(sparam=="button2" && button_2) { button_2=false; col_but2=button_off;f_Delete_object(r); return; } //---------------кнопка "$"-------------------------------------- if(sparam=="button3" && !button_3) { button_3=true; col_but3=button_on;f_Delete_object(r); return; } if(sparam=="button3" && button_3) { button_3=false; col_but3=button_off;f_Delete_object(r); return; } //---------------кнопка "обновить"------------------------------ if(sparam=="button4" && !button_4) { button_4=true; col_but4=button_on; return; } if(sparam=="button4" && button_4) { button_4=false; col_but4=button_off; return; } //-------------кнопка "торговля"-------------------------------- if(sparam=="button5" && !button_5) { button_5=true; col_but5=button_on; return; } if(sparam=="button5" && button_5) { button_5=false; col_but5=button_off; str_trading=0; return; } //------------------кнопки"time"+(string)r---------------------- for(int d=0;d<=r;d++) { if(sparam=="time"+(string)d && button_5) { str_trading=d; button_time=true; return; } } } //-------------------------------------------------------------------- ChartRedraw(); return; } //+------------------------------------------------------------------+ //======загрузка страницы============================================= int f_Calendar() { string cookie=NULL,headers; char post[],result[]; int res=0; string investing_url="http://ru.investing.com/economic-calendar/"; //--- обнуляем код последней ошибки ResetLastError(); res=WebRequest("GET",investing_url,cookie,NULL,50,post,0,result,headers); //--- проверка ошибок if(res==-1) { Print("Ошибка в WebRequest. Код ошибки =",GetLastError()); //--- возможно URL отсутствует в списке, выводим сообщение о необходимости его добавления // MessageBox("Необходимо добавить адрес '"+investing_url+"' в список разрешенных URL во вкладке 'Советники'","Ошибка",MB_ICONINFORMATION); } else { if(ArraySize(result)<100000) PrintFormat("Файл загружен не полностью, Размер файла =%d байт.",ArraySize(result)); else { PrintFormat("Файл успешно загружен, Размер файла =%d байт.",ArraySize(result));//--- успешная загрузка //--- сохраняем данные в файл int filehandle=FileOpen(file_name,FILE_WRITE|FILE_BIN); //--- проверка ошибки if(filehandle!=INVALID_HANDLE) { //--- сохраняем содержимое массива result[] в файл FileWriteArray(filehandle,result,0,ArraySize(result)); //--- закрываем файл FileClose(filehandle); } else Print("Ошибка в FileOpen. Код ошибки =",GetLastError()); } } return(ArraySize(result)); } //+------------------------------------------------------------------+ //=================================================================== void f_Delete_object(int max) { for(int v=0;v","",">","","