簡體   English   中英

如何從現有的MT4指標代碼導出到CSV文件

[英]How to export to a CSV file from an Existent MT4 Indicator code

我想將結果導出到CSV文件。 這是MT4的iExposure指標(iExposure.mq4)。 目前,我知道如何將值導出到CSV

這是我嘗試使用的代碼,可以導出為CSV。

int h1;
h1 = FileOpen("data3.csv", FILE_CSV | FILE_WRITE | FILE_READ, ',');
FileSeek( ExtSymbolsSummaries[i][DEALS]=0, ExtSymbolsSummaries[i],

 [BUY_PRICE]=0,ExtSymbolsSummaries[i][SELL_LOTS]=0 ,ExtSymbolsSummaries[i]  
[SELL_PRICE]=0,ExtSymbolsSummaries[i][NET_LOTS]=0, ExtSymbolsSummaries[i][PROFIT]=0, SEEK_END);
FileWrite(h1, Symbols[i]=SymbolName, ExtSymbolsSummaries[i][DEALS]=0, ExtSymbolsSummaries[i]
[BUY_PRICE]=0,ExtSymbolsSummaries[i][SELL_LOTS]=0 ,ExtSymbolsSummaries[i]  
[SELL_PRICE]=0,ExtSymbolsSummaries[i][NET_LOTS]=0, ExtSymbolsSummaries[i][PROFIT]=0 );
FileClose(h1)

這是原始代碼:

     //+------------------------------------------------------------------+
//|                                                    iExposure.mq4 |
//|                      Copyright © 2007, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_minimum 0.0
#property indicator_maximum 0.1

#define SYMBOLS_MAX 1024
#define DEALS          0
#define BUY_LOTS       1
#define BUY_PRICE      2
#define SELL_LOTS      3
#define SELL_PRICE     4
#define NET_LOTS       5
#define PROFIT         6

extern color ExtColor=LightSeaGreen;

string ExtName="Exposure";
string ExtSymbols[SYMBOLS_MAX];
int    ExtSymbolsTotal=0;
double ExtSymbolsSummaries[SYMBOLS_MAX][7];
int    ExtLines=-1;
string ExtCols[8]={"Symbol",
                   "Deals",
                   "Buy lots",
                   "Buy price",
                   "Sell lots",
                   "Sell price",
                   "Net lots",
                   "Profit"};
int    ExtShifts[8]={ 10, 80, 130, 180, 260, 310, 390, 460 };
int    ExtVertShift=14;
double ExtMapBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void init()
  {
    IndicatorShortName(ExtName);
   SetIndexBuffer(0,ExtMapBuffer);
   SetIndexStyle(0,DRAW_NONE);
   IndicatorDigits(0);
    SetIndexEmptyValue(0,0.0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void deinit()
  {
   int windex=WindowFind(ExtName);
   if(windex>0) ObjectsDeleteAll(windex);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
void start()
  {
   string name;
   int    i,col,line,windex=WindowFind(ExtName);
//----
   if(windex<0) return;
//---- header line
   if(ExtLines<0)
     {
      for(col=0; col<8; col++)
        {
         name="Head_"+col;
         if(ObjectCreate(name,OBJ_LABEL,windex,0,0))
           {
            ObjectSet(name,OBJPROP_XDISTANCE,ExtShifts[col]);
            ObjectSet(name,OBJPROP_YDISTANCE,ExtVertShift);
            ObjectSetText(name,ExtCols[col],9,"Arial",ExtColor);
           }
        }
      ExtLines=0;
     }
//----
   ArrayInitialize(ExtSymbolsSummaries,0.0);
   int total=Analyze();
   if(total>0)
     {
      line=0;
      for(i=0; i<ExtSymbolsTotal; i++)
        {
         if(ExtSymbolsSummaries[i][DEALS]<=0) continue;
         line++;
         //---- add line
         if(line>ExtLines)
           {
            int y_dist=ExtVertShift*(line+1)+1;
            for(col=0; col<8; col++)
              {
               name="Line_"+line+"_"+col;
               if(ObjectCreate(name,OBJ_LABEL,windex,0,0))
                 {
                  ObjectSet(name,OBJPROP_XDISTANCE,ExtShifts[col]);
                  ObjectSet(name,OBJPROP_YDISTANCE,y_dist);
                 }
              }
            ExtLines++;
           }
         //---- set line
         int    digits=MarketInfo(ExtSymbols[i],MODE_DIGITS);
         double buy_lots=ExtSymbolsSummaries[i][BUY_LOTS];
         double sell_lots=ExtSymbolsSummaries[i][SELL_LOTS];
         double buy_price=0.0;
         double sell_price=0.0;
         if(buy_lots!=0)  buy_price=ExtSymbolsSummaries[i][BUY_PRICE]/buy_lots;
         if(sell_lots!=0) sell_price=ExtSymbolsSummaries[i][SELL_PRICE]/sell_lots;
         name="Line_"+line+"_0";
         ObjectSetText(name,ExtSymbols[i],9,"Arial",ExtColor);
         name="Line_"+line+"_1";
         ObjectSetText(name,DoubleToStr(ExtSymbolsSummaries[i][DEALS],0),9,"Arial",ExtColor);
         name="Line_"+line+"_2";
         ObjectSetText(name,DoubleToStr(buy_lots,2),9,"Arial",ExtColor);
         name="Line_"+line+"_3";
         ObjectSetText(name,DoubleToStr(buy_price,digits),9,"Arial",ExtColor);
         name="Line_"+line+"_4";
         ObjectSetText(name,DoubleToStr(sell_lots,2),9,"Arial",ExtColor);
         name="Line_"+line+"_5";
         ObjectSetText(name,DoubleToStr(sell_price,digits),9,"Arial",ExtColor);
         name="Line_"+line+"_6";
         ObjectSetText(name,DoubleToStr(buy_lots-sell_lots,2),9,"Arial",ExtColor);
         name="Line_"+line+"_7";
         ObjectSetText(name,DoubleToStr(ExtSymbolsSummaries[i][PROFIT],2),9,"Arial",ExtColor);
        }
     }
//---- remove lines
   if(total<ExtLines)
     {
      for(line=ExtLines; line>total; line--)
        {
         name="Line_"+line+"_0                                    ";
         ObjectSetText(name,"");
         name="Line_"+line+"_1";
         ObjectSetText(name,"");
         name="Line_"+line+"_2";
         ObjectSetText(name,"");
         name="Line_"+line+"_3";
         ObjectSetText(name,"");
         name="Line_"+line+"_4";
         ObjectSetText(name,"");
         name="Line_"+line+"_5";
         ObjectSetText(name,"");
         name="Line_"+line+"_6";
         ObjectSetText(name,"","                       ");
         name="Line_"+line+"_7";
         ObjectSetText(name,"","                           ");
        }
     }
//---- to avoid minimum==maximum
   ExtMapBuffer[Bars-1]=-1;
//----
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int Analyze()
  {
   double profit;
   int    i,index,type,total=OrdersTotal();
//----
   for(i=0; i<total; i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS)) continue;
      type=OrderType();
      if(type!=OP_BUY && type!=OP_SELL) continue;
      index=SymbolsIndex(OrderSymbol());
      if(index<0 || index>=SYMBOLS_MAX) continue;
      //----
      ExtSymbolsSummaries[index][DEALS]++;
      profit=OrderProfit()+OrderCommission()+OrderSwap();
      ExtSymbolsSummaries[index][PROFIT]+=profit;
      if(type==OP_BUY)
        {
         ExtSymbolsSummaries[index][BUY_LOTS]+=OrderLots();
         ExtSymbolsSummaries[index][BUY_PRICE]+=OrderOpenPrice()*OrderLots();
        }
      else
        {
         ExtSymbolsSummaries[index][SELL_LOTS]+=OrderLots();
         ExtSymbolsSummaries[index][SELL_PRICE]+=OrderOpenPrice()*OrderLots();
        }
     }
//----
   total=0;
   for(i=0; i<ExtSymbolsTotal; i++)
     {
      if(ExtSymbolsSummaries[i][DEALS]>0) total++;
     }
//----
   return(total);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int SymbolsIndex(string SymbolName)
  {
   bool found=false;
//----
   for(int i=0; i<ExtSymbolsTotal; i++)
     {
      if(SymbolName==ExtSymbols[i])
        {
         found=true;
         break;
        }
     }
//----
   if(found) return(i);
   if(ExtSymbolsTotal>=SYMBOLS_MAX) return(-1);
//----
   i=ExtSymbolsTotal;
   ExtSymbolsTotal++;
   ExtSymbols[i]=SymbolName;
   ExtSymbolsSummaries[i][DEALS]=0;
   ExtSymbolsSummaries[i][BUY_LOTS]=0;
   ExtSymbolsSummaries[i][BUY_PRICE]=0;
   ExtSymbolsSummaries[i][SELL_LOTS]=0;
   ExtSymbolsSummaries[i][SELL_PRICE]=0;
   ExtSymbolsSummaries[i][NET_LOTS]=0;
   ExtSymbolsSummaries[i][PROFIT]=0;




//----
   return(i);
  }



//+------------------------------------------------------------------+

代碼尾

CSV輸出示例:

對於此示例,我將描述一種實現以下目標的方法:

  1. 添加文件夾和CSV文件名的輸入字符串。
  2. 創建一個用於生成CSV的按鈕。
  3. 監聽事件,以便我們可以檢測到何時單擊了按鈕。
  4. 解析對象列表,並將對象的名稱和描述寫入CSV文件。

注意:如果無法完成第2步,請跳至第3步,查看OnChartEvent()內的代碼,然后在要編寫CSV文件時對其進行自定義。 但是,請注意,如果每次OnCalculate()事件發生時都在寫入文件,將會寫入大量文件。

由於默認情況下iExposure.mq4可用(至少對於版本:4.0 Build 765),所以我們從創建原始副本開始。 我將示例命名為iExposureTest。

步驟1:為我們的文件夾和CSV文件添加輸入字符串。

這是我們最簡單的步驟之一,只需為Folder和CSV文件添加輸入字符串。 我在其他輸入變量旁邊添加了這些。

//Step 1
input string  InputFileName="iExposure.csv";      // File name
input string  InputDirectoryName="Data";     // Folder name

第2步:創建CSV按鈕。

包括ChartObjectPanel.mqh的標題。 我選擇將包含行直接放置在輸入變量上方。

//Part of Step 2
#include <ChartObjects\ChartObjectPanel.mqh>

這使我們可以創建CChartObjectButton類型,並且Globally此示例中,我們需要Globally訪問按鈕,因此在OnInit()之前添加下一行代碼。

//Part of Step 2
CChartObjectButton CSVButton;

我們有CChartObjectButton的按鈕類型,但尚未實例化。 讓我們使用從OnInit()調用的函數來完成此操作。

OnInit()內部,在下面添加以下代碼:

//Part of Step 2
CreateCSVButton(0);

現在我們需要實際的功能,因此在指標代碼的末尾,讓我們接下來添加此功能。

//Part of Step 2
bool CreateCSVButton(const long chart_ID=0)
{ 
     //--- reset the error value
     ResetLastError();

     //--- set property values
     if(!CSVButton.Create(0,"CSVButton",0,10,25,75,15))
     {
         //--- display the error message in Experts journal
         Print(__FUNCTION__+", Error Code = ",GetLastError());
         return(false);
     }

     CSVButton.Description("CSV");

     CSVButton.FontSize(10);
     CSVButton.Corner(CORNER_LEFT_LOWER);
     CSVButton.Anchor(ANCHOR_CENTER);

     CSVButton.State(false);

     return true;
} 

此時,當我們編譯時,窗口上應該有一個CSV按鈕可用。 這主要是創建的,因此我們可以通過單擊生成CSV。 它看起來應類似於下圖。

CSV按鈕

如果您有CSV按鈕,那么我們就完成了步驟2。

第3步:偵聽事件並捕獲CSV按鈕已被單擊。

我們可以使用內置的OnChartEvent()捕獲所需的事件。

在我們的OnChartEvent() ,我們正在檢查事件是否為CHARTEVENT_OBJECT_CLICK事件,然后如果sparam等於CSVButton且按鈕狀態為true,則我們進行文件工作。

另外,請注意,我們調用了尚不存在的函數WriteCSVObjects ,並將其傳遞給file_handle 我們將在步驟4中創建它。

  //step 3
  void OnChartEvent(const int id,
                    const long &lparam,
                    const double &dparam,
                    const string &sparam)
    {

     if(id==CHARTEVENT_OBJECT_CLICK)
       {  
           if (sparam=="CSVButton") 
           {
              if(CSVButton.State() == true)
              {

                 ResetLastError();

                 int file_handle=FileOpen(InputDirectoryName+"//"+InputFileName,FILE_READ|FILE_WRITE|FILE_CSV);

                 if(file_handle!=INVALID_HANDLE)
                 {
                    PrintFormat("%s file is available for writing",InputFileName);
                    PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));

                    //Call Step 4  
                    WriteCSVObjects(file_handle);   

                    //--- close the file
                    FileClose(file_handle);

                    PrintFormat("Data is written, %s file is closed",InputFileName);

                 }
                 else
                 {
                    PrintFormat("Failed to open %s file, Error code = %d",InputFileName,GetLastError());
                 }

              }

              ChartRedraw();
           }

       }
    }

步驟4:解析“對象”列表,並將名稱和描述寫入CSV。

快好了! 這是解決您的問題的最后一部分。 將此函數添加到我們的代碼示例的末尾。

  //Step 4
  void WriteCSVObjects(int file_hand)
  {
     int obj_total=ObjectsTotal();
     string name;
     string desc;

     for(int i=obj_total;i>=0;i--)
      {
        name = ObjectName(i);
        desc = ObjectDescription(name);

        if(name == "")
        {
         name = "Empty Name";
        }

        if(desc == "")
        {
         desc = "Empty Desc";
        }
        FileWrite(file_hand, name + "," + desc);    
      }
  }

在上面的函數中,請注意我們正在循環對象,並寫出每個對象的名稱和描述。 輸出和對象的順序可能不是您的目標,因此請相應地進行修改。

此時,當我們編譯並單擊CSV按鈕時,它應將值生成為存儲在Files//Data//iExposure.csv的CSV文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM