//+-------------------------------------------------+
//|                              UOutCSV_script.mq4 |
//|                                        KUROKUWA |
//|                            https://www.mql5.com |
//+-------------------------------------------------+
#property copyright "KUROKUWA"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+-------------------------------------------------+
//| Script program start function                   |
//+-------------------------------------------------+ 

//ｽﾀｰﾄ関数
void OnStart()
{
//---
  MqlDateTime tst; //Mqlの datetime 構造体

  //変数の定義
  //ｻｰﾊﾞ日時とﾛｰｶﾙ日時の差
  datetime lnow, snow, dft; //ﾛｰｶﾙ時間 ｻｰﾊﾞ時間 差
  lnow = TimeLocal();   //ﾛｰｶﾙ時間
  snow = TimeCurrent(); //ｻｰﾊﾞｰ時間
  dft = 3600 * 6; //6時間の時間差
  

  datetime dtm;
  string str, sop, shi, slo, scl;
  string spst[];
  int sepnum;


  //ﾌｧｲﾙの最後の行を読込む
  //ﾌｧｲﾙｵｰﾌﾟﾝ(読込/書込用)


  str = Symbol() + IntegerToString(_Period) + ".CSV";
  int handle = FileOpen( str, FILE_CSV|FILE_READ|FILE_WRITE, ',' );

  if(handle == INVALID_HANDLE) return;

  //最終行の 2行前 最終項目
  FileSeek(handle, -77, SEEK_END);
  str = FileReadString(handle); //2行前の最終項目読込
  str = FileReadString(handle); //最終行の日付
  sepnum = StringSplit(str, '/', spst);
  if(sepnum>0) str = spst[0] + "." + spst[1] + 
    "." + spst[2];
  str = str + " " + FileReadString(handle); //最終行の時間
  //MessageBox(str);
  FileSeek(handle, 0, SEEK_END);  //最終位置に移動

  dtm = StrToTime(str);

  int iStart = iBarShift(NULL, 0, dtm) -1;
  //MessageBox(IntegerToString(iStart));

  //最終行の後に追加するのでﾀｲﾄﾙは書き出さない
  //FileWrite(handle, "SDate", "STime", "Open",
  //  "High", "Low", "Close", "LDate","LTime", "MA200");

  for(int j = iStart; j >= 1; j--){
        //ｻｰﾊﾞ日時
    TimeToStruct(Time[j], tst);
    string sDate = //2024/06/01
        StringFormat("%4d/%02d/%02d", tst.year, tst.mon, tst.day);
    string sTime =  //24:00
        StringFormat("%02d:%02d", tst.hour, tst.min); 

    //ﾛｰｶﾙ日時
    lnow = Time[j]+dft;
    TimeToStruct(lnow, tst);

    string lDate = //2024/06/01
        StringFormat("%4d/%02d/%02d", tst.year, tst.mon, tst.day); 
    string lTime = //24:00
        StringFormat("%02d:%02d", tst.hour, tst.min); 

    double ma200 = iMA(NULL, 0, 200, 0, 
        MODE_SMA, PRICE_CLOSE, j);
    str = DoubleToStr(ma200, 3);   //単純移動平均 200
    sop = DoubleToStr(Open[j], 3); //始値
    shi = DoubleToStr(High[j], 3); //高値
    slo = DoubleToStr(Low[j], 3);  //安値
    scl = DoubleToStr(Close[j], 3);//終値

    FileWrite(handle, sDate, sTime, sop,
        shi, slo, scl, lDate, lTime, str);
  }
  //ﾌｧｲﾙｸﾛｰｽﾞ
  FileClose(handle);

  MessageBox("End of OutputData");
  
}
//+-------------------------------------------------+
