//+------------------------------------------------------------------+ //| Demo_FileWriteArray.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" //--- 输入参数 input string InpFileName="data.bin"; input string InpDirectoryName="SomeFolder"; //+------------------------------------------------------------------+ //| 存储价格数据的结构 | //+------------------------------------------------------------------+ struct prices { datetime date; // 日期 double bid; // 买入价 double ask; // 卖出价 }; //--- 全局变量 int count=0; int size=20; string path=InpDirectoryName+"//"+InpFileName; prices arr[]; //+------------------------------------------------------------------+ //| 专家初始化函数 | //+------------------------------------------------------------------+ int OnInit() { //--- 为数组分配内存 ArrayResize(arr,size); //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| 专家去初始化函数 | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- 如果计数,编写其余的计数字符串<n WriteData(count); } //+------------------------------------------------------------------+ //| 专家订单号函数 | //+------------------------------------------------------------------+ void OnTick() { //--- 保存数组数据 arr[count].date=TimeCurrent(); arr[count].bid=SymbolInfoDouble(Symbol(),SYMBOL_BID); arr[count].ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK); //--- 显示当前数据 Print("Date = ",arr[count].date," Bid = ",arr[count].bid," Ask = ",arr[count].ask); //--- 增加计数器 count++; //--- 如果填写数组,向文件写入数据和零 if(count==size) { WriteData(size); count=0; } } //+------------------------------------------------------------------+ //| 向文件写下数组的n元素 | //+------------------------------------------------------------------+ void WriteData(const int n) { //--- 打开文件 ResetLastError(); int handle=FileOpen(path,FILE_READ|FILE_WRITE|FILE_BIN); if(handle!=INVALID_HANDLE) { //--- 向文件结尾写下数组数据 FileSeek(handle,0,SEEK_END); FileWriteArray(handle,arr,0,n); //--- 关闭文件 FileClose(handle); } else Print("Failed to open the file, error ",GetLastError()); } |