//+------------------------------------------------------------------+ //| Demo_FileWriteString.mq5 | //| Copyright 2013, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2013, MetaQuotes Software Corp." #property link "https://www.mql5.com" #property version "1.00" //--- 启动脚本时显示输入参数的窗口 #property script_show_inputs //--- 接收程序端数据的参数 input string InpSymbolName="EURUSD"; // 货币组 input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // 时间帧 input int InpMAPeriod=14; // MA周期 input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // 价格类型 input datetime InpDateStart=D'2013.01.01 00:00'; // 复制起始日期的数据 //--- 编写文件数据的参数 input string InpFileName="RSI.csv"; // 文件名称 input string InpDirectoryName="Data"; // 目录名称 //+------------------------------------------------------------------+ //| 脚本程序启动函数 | //+------------------------------------------------------------------+ void OnStart() { datetime date_finish; // 复制结束日期的数据 double rsi_buff[]; // 指标值数组 datetime date_buff[]; // 指标日期数组 int rsi_size=0; // 指标数组大小 //--- 结束时间是当前时间 date_finish=TimeCurrent(); //--- 接收 RSI 指标句柄 ResetLastError(); int rsi_handle=iRSI(InpSymbolName,InpSymbolPeriod,InpMAPeriod,InpAppliedPrice); if(rsi_handle==INVALID_HANDLE) { //--- 接收指标句柄失败 PrintFormat("Error when receiving indicator handle. Error code = %d",GetLastError()); return; } //--- 循环直至指标计算所有值 while(BarsCalculated(rsi_handle)==-1) Sleep(10); // 暂停允许指标计算所有值 //--- 复制某段时间周期的指标值 ResetLastError(); if(CopyBuffer(rsi_handle,0,InpDateStart,date_finish,rsi_buff)==-1) { PrintFormat("Failed to copy indicator values. Error code = %d",GetLastError()); return; } //--- 复制相应的指标值时间 ResetLastError(); if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,date_buff)==-1) { PrintFormat("Failed to copy time values. Error code = %d",GetLastError()); return; } //--- 释放指标占据的内存 IndicatorRelease(rsi_handle); //--- 接收缓冲区大小 rsi_size=ArraySize(rsi_buff); //--- 打开编写指标值的文件(如果文件不在,则自动创建) ResetLastError(); int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_CSV|FILE_ANSI); if(file_handle!=INVALID_HANDLE) { PrintFormat("%s file is available for writing",InpFileName); PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH)); //--- 准备附加变量 string str=""; bool is_formed=false; //--- 写下形成超买和超卖区域的日期 for(int i=0;i<rsi_size;i++) { //--- 检查指标值 if(rsi_buff[i]>=70 || rsi_buff[i]<=30) { //--- 如果该值是该区域的第一个值 if(!is_formed) { //--- 添加值和日期 str=(string)rsi_buff[i]+"\t"+(string)date_buff[i]; is_formed=true; } else str+="\t"+(string)rsi_buff[i]+"\t"+(string)date_buff[i]; //--- 移动到下个循环迭代 continue; } //--- 检查标识 if(is_formed) { //--- 字符串形成,将其写入文件 FileWriteString(file_handle,str+"\r\n"); is_formed=false; } } //--- 关闭文件 FileClose(file_handle); PrintFormat("Data is written, %s file is closed",InpFileName); } else PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError()); } |