您现在的位置: 比特财富网 >> 财经 >  >> 外匯
MT4 MQL4學習 --- 自己編寫EA總結篇
外_匯_邦 WaiHuiBang.com 學好智能交易系統(EA),讓你的夢想從這裡起飛
MT4外匯交易平台裡給我們提供了一套非常完美的交易系統設計語言-MQL4,通過MQL4語言可以設計出我們想要的賺錢模式,一套完美的智能交易系統(EA),讓我們躺在睡覺一樣能賺錢的程序,iMT4論壇為我們提供了一個能實現我們夢想的MT4專業平台,讓你的夢想從這裡起飛。www.emoneybtc.com

學習寫EA第一講:編程基礎知識——語法
代碼格式
空格建、Tab鍵、換行鍵和換頁符都可以成為代碼排版的分隔符,你能使用各種符號來增加代碼的可讀性。

注釋 
多行注釋使用 /* 作為開始到 */ 結束,在這之間不能夠嵌套。單行注釋使用 // 作為開始到新的一行結束,可以被嵌套到多行注釋之中。
示例:
// 單行注釋
/* 多行
注釋 // 嵌套的單行注釋
注釋結束 */
標識符 
標識符用來給變量、函數和數據類型進行命名,長度不能超過31個字節
你可以使用數字0-9、拉丁字母大寫A-Z和小寫a-z(大小寫有區分的)還有下劃線(_)。此外首字母不可以是數字,標識符不能和保留字沖突.
示例:
// NAME1namel Total_5 Paper
保留字 
下面列出的是固定的保留字。不能使用以下任何保留字進行命名。
     
數據類型
  
      
存儲類型
  
      
操作符
  
      
其它
  
      
bool
  
      
extern
  
      
break
  
      
false
  
      
color
  
      
static
  
      
case
  
      
true
  
      
datetime
  
     
      
continue
  
     
      
double
  
     
      
default
  
     
      
int
  
     
      
else
  
     
      
string
  
     
      
for
  
     
      
void
  
     
      
if
  
     
     
     
      
return
  
     
     
     
      
switch
  
     
     
     
      
while
  
     
  


學習寫EA第二講:數據類型概述
主要數據類型有:
Integer (int)
Boolean (bool)
Char (char)
String (string)
Floating-point number (double)
Color (color)
Datetime (datetime)
我們用Integer類型數據來作為DateTime和Color數據的存儲。
使用以下方式可以進行類型站換:
int (bool,color,datetime);
double;
string;

Integer 類型
十進制: 數字0-9;0不能作為第一個字母
示例:
12, 111, -956 1007
十六進制: 數字0-9;拉丁字母a-f或A-F用來表示10-15;使用0x或者0X作為開始。
示例:
0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7
Integer 變量的取值范圍為-2147483648到2147483647。

Literal 類型
任意在單引號中的字符或十六進制的任意ASCII碼例如'x10'都是被看作為一個字符,
一些字符例如單引號('),雙引號("),問號(?),反斜槓()和一些控制符都需要在之前加一個反斜槓()進行轉意後表示出來:

line feed NL (LF) n
horizontal tab HT t
carriage return CR r
reverse slash \
single quote ' '
double quote " "
hexadecimal ASCII-code hh xhh
以上字符如果不經過反斜槓進行轉意將不能被使用
示例:
int a = 'A';
int b = '$';
int c = '©'; // code 0xA9
int d = 'xAE'; // symbol code ®

Boolean 類型
Boolean 用來表示 是 和 否, 還可以用數字 1 和 0 進行表示。True和Flase可以忽略大小寫。
示例:
bool a = true;
bool b = false;
bool c = 1;

Floating-point number 類型
浮點型變量在整數型後面加一個點(.)用來更精確的表示十進制數字。
示例:
double a = 12.111;
double b = -956.1007;
double c = 0.0001;
double d = 16;
浮點型的取值范圍從 2.2e-308 到 1.8e308.

String 類型
字符串型是用來表示連續的ASCII碼字符的使用連續的兩個雙引號來包括需要表示的內容如:"Character constant".
示例:
"This is a character string"
"Copyright symbol txA9"
"this line with LF symbol n"
"A" "1234567890" "0" "$"

Color 類型
顏色類型可以使用以下示例裡的幾種方式進行定義。
示例:
// symbol constants
C'128,128,128' // gray
C'0x00,0x00,0xFF' // blue
// named color
Red
Yellow
Black
// integer-valued representation
0xFFFFFF // white
16777215 // white
0x008000 // green
32768 // green

Datetime 類型
時間類型使用年、月、日、時、分、秒來進行定義,你可以使用以下示例中的方式來定義變量。
示例:
D'2004.01.01 00:00' // New Year
D'1980.07.19 12:30:27'
D'19.07.1980 12:30:27'
D'19.07.1980 12' //equal to D'1980.07.19 12:00:00'
D'01.01.2004' //equal to D'01.01.2004 00:00:00'
D'12:30:27' //equal to D'[compilation date] 12:30:27'
D'' //equal to D'[compilation date] 00:00:00'

學習寫EA第三講:賦值運算符
賦值運算符
注:將右側的結果賦值給左側的變量
將x的值賦值給y y = x;
將x的值加到y上面 y += x;
在y上面減去x的值 y -= x;
得到y的x倍的值 y *= x;
得到y除以x的值 y /= x;
取y除以x後的余數 y %= x;
y向右位移x位 y >>= x;
y向左位移x位 y <<= x;
得到邏輯AND的值 y &= x;
得到邏輯OR的值 y |= x;
得到邏輯非OR的值 y ^= x;
注:一個表達式只能有一個賦值運算符.

關系運算符
用返回0(False)或1(True)來表示兩個量之間的關系。
a是否等於b a == b;
a是否不等於b a != b;
a是否小於b a < b;
a是否大於b a > b;
a是否小於等於b a <= b;
a是否大於等於b a >= b;
真假運算符
否定運算符(!),用來表示真假的反面的結果。
// 如果a不是真的
if(!a)
Print("not 'a'");
邏輯運算符或(||)用來表示兩個表達式只要有一個成立即可。
示例:
if(xl)
Print("out of range");
邏輯運算符和(&&)用來表示兩個表達式要同時成立才行。
示例:
if(p!=x && p>y)
Print("true");
n++;
位邏輯運算符
~ 運算符對操作數執行按位求補操作。
b = ~n;
>> 運算符對操作數執行向右位移操作。
x = x >> y;
<< 運算符對操作數執行向左位移操作。
x = x << y;
一元 & 運算符返回操作數的地址
為整型和 bool 類型預定義了二進制 & 運算符。對於整型,& 計算操作數的按位“與”。對於 bool 操作數,& 計算操作數的邏輯“與”;也就是說,當且僅當兩個操作數均為 true 時,其結果才為 true。
b = ((x & y) != 0);
二進制 | 運算符是為整型和 bool 類型預定義的。對於整型,| 對操作數進行按位“或”運算。對於 bool 操作數,| 對操作數進行邏輯“或”計算,也就是說,當且僅當兩個操作數均為 false 時,其結果才為 false。
b = x | y;
為整型和 bool 類型預定義了 ^ 二進制操作數。對於整型,^ 計算操作數的按位“異或”。對於 bool 操作數,^ 計算操作數的邏輯“異或”;也就是說,當且僅當只有一個操作數為 true 時,其結果才為 true。
b = x ^ y;
注:位邏輯運算符只作用於Integers類型

其它運算符
索引、定位在數組中i位置的值。
array = 3;
//
3負值到array數組第i位置上
使用 x1,x2,...,xn 這樣的方法將各種值傳送到function中進行運算。
示例:
double SL=Ask-25*Point;
double TP=Ask+25*Point;
int ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,SL,TP,
"My comment",123,0,Red);
優先級規則
下面是從上到下的運算優先規則,優先級高的將先被運算。
() Function call From left to right
[] Array element selection
! Negation From left to right
~ Bitwise negation
- Sign changing operation
* Multiplication From left to right
/ Division
% Module division
+ Addition From left to right
- Subtraction
<< Left shift From left to right
>> Right shift
< Less than From left to right
<= Less than or equals
> Greater than
>= Greater than or equals
== Equals From left to right
!= Not equal
& Bitwise AND operation From left to right
^ Bitwise exclusive OR From left to right
| Bitwise OR operation From left to right
&& Logical AND From left to right
|| Logical OR From left to right
= Assignment From right to left
+= Assignment addition
-= Assignment subtraction
*= Assignment multiplication
/= Assignment division
%= Assignment module
>>= Assignment right shift
<<= Assignment left shift
&= Assignment bitwise AND
|= Assignment bitwise OR
^= Assignment exclusive OR

學習寫EA第四講:操作符
格式和嵌套
格式.一個操作符可以占用一行或者多行,兩個或多個操作符可以占用更多的行。
嵌套.執行控制符(if,if-else, switch, while and for)可以進行任意嵌套.

復合操作符
一個復合操作符有一個(一個區段)和由一個或多個任何類型的操作符組成的的附件{}. 每個表達式使用分號作為結束(;)
示例:
if(x==0)
{
x=1; y=2; z=3;
}
表達式操作符
任何以分號(;)結束的表達式都被視為是一個操作符。
Assignment operator.
Identifier=expression;
標識符=表達式;
示例:
x=3;
y=x=3; // 這是錯誤的
一個操作符中只能有一個表達式。
調用函數操作符
Function_name(argument1,..., argumentN);
函數名稱(參數1,...,參數N);
示例:
fclose(file);
空操作符
只有一個分號組成(;).我們用它來表示沒有任何表達式的空操作符.

停止操作符
一個break; , 我們將其放在嵌套內的指定位置,用來在指定情況下跳出循環操作.
示例:
// 從0開始搜索數組
for(i=0;i<ARRAY_SIZE;I++)
if((array==0)
break;

繼續操作符
一個continue;我們將其放在嵌套內的指定位置,用來在指定情況下跳過接下來的運算,直接跳入下一次的循環。
示例:
// summaryof nonzero elements of array
int func(int array[])
{
int array_size=ArraySize(array);
int sum=0;
for(int i=0;i
{
if(a==0) continue;
sum+=a
;
}
return(sum);
}
返回操作符
一個return;將需要返回的結果放在return後面的()中。
示例:
return(x+y);
條件操作符 if
if (expression)
operator;

如果表達式為真那麼執行操作。
示例:
if(a==x)
temp*=3;
temp=MathAbs(temp);
條件操作符 if-else
if (expression)
operator1
else
operator2

如果表達式為真那麼執行operator1,如果為假執行operator2,else後還可以跟進多個if執行多項選擇。詳見示例。
示例:
if(x>1)
if(y==2)
z=5;
else
z=6;
if(x>l)
{
if(y==2) z=5;
}
else
{
z=6;
}
// 多項選擇
if(x=='a')
{
y=1;
}
else if(x=='b')
{
y=2;
z=3;
}
else if(x=='c')
{
y = 4;
}
else
{
Print("ERROR");
}
選擇操作符 switch
switch (expression)
{
case constant1: operators; break;
case constant2: operators; break;
...
default: operators; break;
}

當表達式expression的值等於結果之一時,執行其結果下的操作。不管結果如何都將執行default中的操作。
示例:
case 3+4://正確的
case X+Y: //錯誤的
被選擇的結果只可以是常數,不可為變量或表達式。
示例:
switch(x)
{
case 'A':
Print("CASE An");
break;
case 'B':
case 'C':
Print("CASE B or Cn");
break;
default:
Print("NOT A, B or Cn");
break;
}
循環操作符 while
while (expression)
operator;

只要表達式expression為真就執行操作operator
示例:
while(k<N)
{
y=y*x;
k++;
}
循環操作符 for
for (expression1; expression2;expression3)
operator;

用表達式1(expression1)來定義初始變量,當表達式2(expression2)為真的時候執行操作operator,在每次循環結束後執行表達式3(expression3)
用while可以表示為這樣:
expression1;
while (expression2)
{
operator;
expression3;
};

示例:
for(x=1;x<=7;x++)
Print(MathPower(x,2));
使用for(;;)可以造成一個死循環如同while(true)一樣.
表達式1和表達式3都可以內嵌多個用逗號(,)分割的表達式。
示例:
for(i=0,j=n-l;i<N;I++,J--)
a=a[j];










學習寫EA第五講:函數定義
函數定義
一個函數是由返回值、輸入參數、內嵌操作所組成的。
示例:
double // 返回值類型
linfunc (double x, double a, double b) // 函數名和輸入參數
{
// 內嵌的操作
return (a*x + b); // 返回值
}
如果沒有返回值那麼返回值的類型可以寫為void
示例:
voiderrmesg(string s)
{
Print("error: "+s);
}
函數調用
function_name (x1,x2,...,xn)
示例:
intsomefunc()
{
double a=linfunc(0.3, 10.5, 8);
}
double linfunc(double x, double a, double b)
{
return (a*x + b);
}
特殊函數 init()deinit()start()
init()在載入時調用,可以用此函數在開始自定義指標或者自動交易之前做初始化操作。
deinit()在卸載時調用,可以用此函數在去處自定義指標或者自動交易之前做初始化操作。
start()當數據變動時觸發,對於自定義指標或者自動交易的編程主要依靠此函數進行。












學習寫EA第六講:定義變量

定義基本類型
基本類型包括
string - 字符串型;
int - 整數型;
double - 雙精度浮點數型;
bool - 布爾型
示例:
string MessageBox;
int Orders;
double SymbolPrice;
bool bLog;

定義附加類型
附加類型包括

datetime - 時間型,使用無符號整型數字存儲,是1970.1.1 0:0:0開始的秒數
color - 顏色,使用三色的整型數字編碼而成
示例:
extern datetime tBegin_Data = D'2004.01.01 00:00';
extern color cModify_Color = C'0x44,0xB9,0xE6';
定義數組類型
示例:
int a[50]; //一個一維由五十個int組成的數組
double m[7][50]; //一個兩維由7x50個double組成的數組

內部變量定義
內部變量顧名思義是在內部使用的,可以理解為在當前嵌套內所使用的變量。

函數參數定義
示例:
void func(int x, double y, bool z)
{
...
}

函數的參數內的變量只能在函數內才生效,在函數外無法使用,而且在函數內對變量進行的修改在函數外無法生效。
調用函數示例:
func(123, 0.5);

如果有需要在變量傳入由參數傳入函數內操作後保留修改在函數外生效的情況的話,可以在參數定義的類型名稱後加上修飾符(&)。
示例:
void func(int& x, double& y, double& z[])
{
...
}

靜態變量定義
在數據類型前加上static就可以將變量定義成靜態變量
示例:
{
static int flag
}

全局變量定義
全局變量是指在整個程序中都能夠調用的變量,只需將變量定義卸載所有嵌套之外即可。
示例:
int Global_flag;
int start()
{
...
}

附加變量定義
附加變量可以允許由用戶自己輸入。
示例:
extern double InputParameter1 = 1.0;
int init()
{
...
}

初始化變量
變量必須經過初始化才可以使用。

基本類型
示例:
int mt = 1; // integer 初始化
// double 初始化
double p = MarketInfo(Symbol(),MODE_POINT);
// string 初始化
string s = "hello";

數組類型
示例:
int mta[6] = {1,4,9,16,25,36};

變量
外部函數引用
示例:
#import "user32.dll"
int MessageBoxA(int hWnd ,string szText,
string szCaption,int nType);
int SendMessageA(int hWnd,int Msg,int wParam,int lParam);
#import "lib.ex4"
double round(double value);
#import



學習寫EA第七講:預處理程序
定義常數
#defineidentifier_value
常數可以是任何類型的,常數在程序中不可更改。
示例:
#defineABC 100
#define PI 0.314
#define COMPANY_NAME "MetaQuotes Software Corp."
編譯參數定義
#property identifier_value
示例:
#propertylink "http://www.metaquotes.net"
#property copyright "MetaQuotes Software Corp."
#property stacksize 1024
以下是所有的參數名稱:    
參數名稱
  
      
類型
  
      
說明
  
      
link
  
      
string
  
      
設置一個鏈接到公司網站
  
      
copyright
  
      
string
  
      
公司名稱
  
      
stacksize
  
      
int
  
      
堆棧大小
  
      
indicator_chart_window
  
      
void
  
      
顯示在走勢圖窗口
  
      
indicator_separate_window
  
      
void
  
      
顯示在新區塊
  
      
indicator_buffers
  
      
int
  
      
顯示緩存最高8
  
      
indicator_minimum
  
      
int
  
      
圖形區間最低點
  
      
indicator_maximum
  
      
int
  
      
圖形區間最高點
  
      
indicator_colorN
  
      
color
  
      
第N根線的顏色,最高8根線
  
      
indicator_levelN
  
      
double
  
      
predefined level N for separate window custom indicator
  
      
show_confirm
  
      
void
  
      
當程序執行之前是否經過確認
  
      
show_inputs
  
      
void
  
      
before script run its property sheet appears; disables  show_confirm property
  
       
  
       
  
       
  
  


嵌入文件
#include<file_name>
示例:
#include<win32.h>
#include"file_name"
示例:
#include"mylib.h"
引入函數或其他模塊
#import "file_name"
func1();
func2();
#import

示例:
#import"user32.dll"
int MessageBoxA(int hWnd,string lpText,string lpCaption,
int uType);
int MessageBoxExA(int hWnd,string lpText,string lpCaption,
int uType,int wLanguageId);
#import "melib.ex4"
#import "gdi32.dll"
int GetDC(int hWnd);
int ReleaseDC(int hWnd,int hDC);
#import


學習寫EA第八講:賬戶信息
double AccountBalance()
返回賬戶余額

示例:
Print("Account balance = ",AccountBalance());

double AccountCredit()
返回賬戶信用點數
示例:
Print("Account number ", AccountCredit());

string AccountCompany()
返回賬戶公司名
示例:
Print("Account company name ", AccountCompany());

string AccountCurrency()
返回賬戶所用的通貨名稱

示例:
Print("account currency is ", AccountCurrency());

double AccountEquity()
返回資產淨值

示例:
Print("Account equity = ",AccountEquity());

double AccountFreeMargin()
Returns free margin value of the current account.

示例:
Print("Account free margin = ",AccountFreeMargin());

int AccountLeverage()
返回槓桿比率

示例:
Print("Account #",AccountNumber(), " leverage is ",AccountLeverage());

double AccountMargin()
Returns margin value of the current account.

示例:
Print("Account margin ", AccountMargin());

string AccountName()
返回賬戶名稱

示例:
Print("Account name ", AccountName());

int AccountNumber()
返回賬戶數字

示例:
Print("account number ", AccountNumber());

double AccountProfit()
返回賬戶利潤

示例:
Print("Account profit ", AccountProfit());








學習寫EA第九講:數組函數和類型轉換函數


數組函數 [ArrayFunctions]
int ArrayBsearch( double array[], double value, int count=WHOLE_ARRAY, intstart=0, int direction=MODE_ASCEND)
搜索一個值在數組中的位置
此函數不能用在字符型或連續數字的數組上.
:: 輸入參數
array[] - 需要搜索的數組
value - 將要搜索的值
count - 搜索的數量,默認搜索所有的數組
start - 搜索的開始點,默認從頭開始
direction - 搜索的方向,MODE_ASCEND 順序搜索 MODE_DESCEND 倒序搜索
示例:
datetime daytimes[];
int shift=10,dayshift;
// All the Time[] timeseries are sorted in descendant mode
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
if(Time[shift]>>=daytimes[0]) dayshift=0;
else
{
dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND);
if(Period()<ERIOD_D1)
dayshift++;
}
Print(TimeToStr(Time[shift])," corresponds to ",dayshift," daybar opened at ",
TimeToStr(daytimes[dayshift]));
int ArrayCopy( object& dest[], object source[], int start_dest=0, intstart_source=0, int count=WHOLE_ARRAY)
復制一個數組到另外一個數組。
只有double[],int[], datetime[], color[], 和 bool[] 這些類型的數組可以被復制。
:: 輸入參數
dest[] - 目標數組
source[] - 源數組
start_dest - 從目標數組的第幾位開始寫入,默認為0
start_source - 從源數組的第幾位開始讀取,默認為0
count - 讀取多少位的數組
示例:
double array1[][6];
double array2[10][6];
// fill array with some data
ArrayCopyRates(array1);
ArrayCopy(array2, array1,0,Bars-9,10);
// now array2 has first 10 bars in the history
int ArrayCopyRates( double& dest_array[], string symbol=NULL, inttimeframe=0)
復制一段走勢圖上的數據到一個二維數組,數組的第二維只有6個項目分別是:
0 - 時間,
1 - 開盤價,
2 - 最低價,
3 - 最高價,
4 - 收盤價,
5 - 成交量.
:: 輸入參數
dest_array[] - 目標數組
symbol - 標示,當前所需要的通貨的標示
timeframe - 圖表的時間線
示例:
double array1[][6];
ArrayCopyRates(array1,"EURUSD", PERIOD_H1);
Print("Current bar ",TimeToStr(array1[0][0]),"Open",array1[0][1]);
int ArrayCopySeries( double& array[], int series_index, string symbol=NULL,int timeframe=0)
復制一個系列的走勢圖數據到數組上
注: 如果series_index是MODE_TIME,那麼第一個參數必須是日期型的數組
:: 輸入參數
dest_array[] - 目標數組
series_index - 想要取的系列的名稱或編號,0-5
symbol - 標示,當前所需要的通貨的標示
timeframe - 圖表的時間線
示例:
datetime daytimes[];
int shift=10,dayshift;
// All the Time[] timeseries are sorted in descendant mode
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
if(Time[shift]>=daytimes[0]) dayshift=0;
else
{
dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND);
if(Period()
}
Print(TimeToStr(Time[shift])," corresponds to ",dayshift," daybar opened at ", TimeToStr(daytimes[dayshift]));
int ArrayDimension( int array[])
返回數組的維數
:: 輸入參數
array[] - 需要檢查的數組

示例:
int num_array[10][5];
int dim_size;
dim_size=ArrayDimension(num_array);
// dim_size is 2
bool ArrayGetAsSeries(object array[])
檢查數組是否是有組織序列的數組(是否從最後到最開始排序過的),如果不是返回否
:: 輸入參數
array[] - 需要檢查的數組

示例:
if(ArrayGetAsSeries(array1)==true)
Print("array1 is indexed as a series array");
else
Print("array1 is indexed normally (from left to right)");
int ArrayInitialize( double& array[], double value)
對數組進行初始化,返回經過初始化的數組項的個數
:: 輸入參數
array[] - 需要初始化的數組
value - 新的數組項的值

示例:
//---- 把所有數組項的值設置為2.1
double myarray[10];
ArrayInitialize(myarray,2.1);
bool ArrayIsSeries( object array[])
檢查數組是否連續的(time,open,close,high,low, or volume).
:: 輸入參數
array[] - 需要檢查的數組

示例:
if(ArrayIsSeries(array1)==false)
ArrayInitialize(array1,0);
else
{
Print("Series array cannot be initialized!");
return(-1);
}
int ArrayMaximum( double array[], int count=WHOLE_ARRAY, int start=0)
找出數組中最大值的定位
:: 輸入參數
array[] - 需要檢查的數組
count - 搜索數組中項目的個數
start - 搜索的開始點

示例:
double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9};
int maxValueIdx=ArrayMaximum(num_array);
Print("Max value = ", num_array[maxValueIdx]);
int ArrayMinimum( double array[], int count=WHOLE_ARRAY, int start=0)
找出數組中最小值的定位
:: 輸入參數
array[] - 需要檢查的數組
count - 搜索數組中項目的個數
start - 搜索的開始點

示例:
double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9};
double minValueidx=ArrayMinimum(num_array);
Print("Min value = ", num_array[minValueIdx]);
int ArrayRange( object array[], int range_index)
取數組中指定維數中項目的數量。
:: 輸入參數
array[] - 需要檢查的數組
range_index - 指定的維數

示例:
int dim_size;
double num_array[10,10,10];
dim_size=ArrayRange(num_array, 1);
int ArrayResize( object& array[], int new_size)
重定義數組大小
:: 輸入參數
array[] - 需要檢查的數組
new_size - 第一維中數組的新大小

示例:
double array1[][4];
int element_count=ArrayResize(array, 20);
// 數組中總項目數為80
bool ArraySetAsSeries( double& array[], bool set)
設置指數數組為系列數組,數組0位的值是最後的值。返回之前的數組狀態
:: 輸入參數
array[] - 需要處理的數組
set - 是否是設置為系列數組,true或者false
示例:
double macd_buffer[300];
double signal_buffer[300];
int i,limit=ArraySize(macd_buffer);
ArraySetAsSeries(macd_buffer,true);
for(i=0; i

macd_buffer=iMA(NULL,0,12,0,MODE_EMA,PRICE_CLOSE,i)-iMA(NULL,0,26,0,MODE_EMA,PRICE_CLOSE,i);
for(i=0; i
signal_buffer=iMAOnArray(macd_buffer,limit,9,0,MODE_SMA,i);
int ArraySize( object array[])
返回數組的項目數
:: 輸入參數
array[] - 需要處理的數組

示例:
int count=ArraySize(array1);
for(int i=0; i
{
// do some calculations.
}
int ArraySort( double& array[], int count=WHOLE_ARRAY, int start=0, intsort_dir=MODE_ASCEND)
對數組進行排序,系列數組不可進行排序
:: 輸入參數
array[] - 需要處理的數組
count - 對多少個數組項進行排序
start - 排序的開始點
sort_dir - 排序方式,MODE_ASCEND順序排列 MODE_DESCEND倒序排列

示例:
double num_array[5]={4,1,6,3,9};
// now array contains values 4,1,6,3,9
ArraySort(num_array);
// now array is sorted 1,3,4,6,9
ArraySort(num_array,MODE_DESCEND);
// now array is sorted 9,6,4,3,1
=============================================================================================
2類型轉換函數[Conversion Functions]
string CharToStr( int char_code)
將字符型轉換成字符串型結果返回
:: 輸入參數
char_code - 字符的ACSII碼

示例:
string str="WORL" + CharToStr(44); // 44 is code for 'D'
// resulting string will be WORLD
string DoubleToStr( double value, int digits)
將雙精度浮點型轉換成字符串型結果返回
:: 輸入參數
value - 浮點型數字
digits - 小數點後多少位,0-8

示例:
string value=DoubleToStr(1.28473418, 5);
// value is 1.28473
double NormalizeDouble( double value, int digits)
將雙精度浮點型格式化後結果返回
:: 輸入參數
value - 浮點型數字
digits - 小數點後多少位,0-8

示例:
double var1=0.123456789;
Print(NormalizeDouble(var1,5));
// output: 0.12346
double StrToDouble( string value)
將字符串型轉換成雙精度浮點型結果返回
:: 輸入參數
value - 數字的字符串

示例:
double var=StrToDouble("103.2812");
int StrToInteger( string value)
將字符串型轉換成整型結果返回
:: 輸入參數
value - 數字的字符串

示例:
int var1=StrToInteger("1024");
datetime StrToTime( string value)
將字符串型轉換成時間型結果返回,輸入格式為 yyyy.mm.dd hh:mi
:: 輸入參數
value - 時間的字符串
示例:
datetime var1;
var1=StrToTime("2003.8.12 17:35");
var1=StrToTime("17:35"); // returns with current date
var1=StrToTime("2003.8.12"); // returns with midnight time"00:00"
string TimeToStr( datetime value, int mode=TIME_DATE|TIME_MINUTES)
將時間型轉換成字符串型返回
:: 輸入參數
value - 時間的數字,從1970.1.1 0:0:0 到現在的秒數
mode - 返回字符串的格式TIME_DATE(yyyy.mm.dd),TIME_MINUTES(hh:mi),TIME_SECONDS(hh:mi:ss)

示例:
strign var1=TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS);




學習寫EA第十講:公用函數
公用函數 [Common Functions]
void Alert( ... )
彈出一個顯示信息的警告窗口
:: 輸入參數
... - 任意值,如有多個可用逗號分割

示例:
if(Close[0]>SignalLevel)
Alert("Close price coming ", Close[0],"!!!");
string ClientTerminalName()
返回客戶終端名稱

示例:
Print("Terminal name is ",ClientTerminalName());
string CompanyName()
返回公司名稱

示例:
Print("Company name is ",CompanyName());
void Comment( ... )
顯示信息在走勢圖左上角
:: 輸入參數
... - 任意值,如有多個可用逗號分割

示例:
double free=AccountFreeMargin();
Comment("Account free margin is",DoubleToStr(free,2),"n","Current time is",TimeToStr(CurTime()));
int GetLastError()
取最後錯誤在錯誤中的索引位置

示例:
int err;
int handle=FileOpen("somefile.dat", FILE_READ|FILE_BIN);
if(handle<1)
{
err=GetLastError();
Print("error(",err,"): ",ErrorDescription(err));
return(0);
}
int GetTickCount()
取時間標記,函數取回用毫秒標示的時間標記。

示例:
int start=GetTickCount();
// do some hard calculation...
Print("Calculation time is ", GetTickCount()-start, "milliseconds.");
void HideTestIndicators(bool hide)
使用此函數設置一個在Expert Advisor的開關,在測試完成之前指標不回顯示在圖表上。
:: 輸入參數
hide - 是否隱藏 True或者False

示例:
HideTestIndicators(true);
bool IsConnected()
返回客戶端是否已連接

示例:
if(!IsConnected())
{
Print("Connection is broken!");
return(0);
}
// Expert body that need opened connection
// ...
bool IsDemo()
返回是否是模擬賬戶

示例:
if(IsDemo()) Print("I am working on demo account");
else Print("I am working on real account");
bool IsDllsAllowed()
返回是否允許載入Dll文件

示例:
#import "user32.dll"
int MessageBoxA(int hWnd ,string szText, string szCaption,int nType);
...
...
if(IsDllsAllowed()==false)
{
Print("DLL call is not allowed. Experts cannot run.");
return(0);
}
// expert body that calls external DLL functions
MessageBoxA(0,"an message","Message",MB_OK);
bool IsLibrariesAllowed()
返回是否允許載入庫文件

示例:
#import "somelibrary.ex4"
int somefunc();
...
...
if(IsLibrariesAllowed()==false)
{
Print("Library call is not allowed. Experts cannot run.");
return(0);
}
// expert body that calls external DLL functions
somefunc();
bool IsStopped()
返回是否處於停止狀態

示例:
while(expr!=false)
{
if(IsStopped()==true) return(0);
// long time procesing cycle
// ...
}
bool IsTesting()
返回是否處於測試模式

示例:
if(IsTesting()) Print("I am testing now");
bool IsTradeAllowed()
返回是否允許交易

示例:
if(IsTradeAllowed()) Print("Trade allowed");
double MarketInfo( string symbol, int type)
返回市場當前情況
:: 輸入參數
symbol - 通貨代碼
type - 返回結果的類型

示例:
double var;
var=MarketInfo("EURUSD",MODE_BID);
int MessageBox( string text=NULL, string caption=NULL, int flags=EMPTY)
彈出消息窗口,返回消息窗口的結果
:: 輸入參數
text - 窗口顯示的文字
caption - 窗口上顯示的標題
flags - 窗口選項開關

示例:
#include
if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30',1.0045)==false)
{
int ret=MessageBox("ObjectCreate() fails with code"+GetLastError()+"nContinue?", "Question",MB_YESNO|MB_ICONQUESTION);
if(ret==IDNO) return(false);
}
// continue
int Period()
返回圖表時間線的類型

示例:
Print("Period is ", Period());
void PlaySound( string filename)
播放音樂文件
:: 輸入參數
filename - 音頻文件名

示例:
if(IsDemo()) PlaySound("alert.wav");
void Print( ... )
將文本打印在結果窗口內
:: 輸入參數
... - 任意值,復數用逗號分割

示例:
Print("Account free margin is ", AccountFreeMargin());
Print("Current time is ", TimeToStr(CurTime()));
double pi=3.141592653589793;
Print("PI number is ", DoubleToStr(pi,8));
// Output: PI number is 3.14159265
// Array printing
for(int i=0;i<10;i++)
Print(Close);
bool RefreshRates()
返回數據是否已經被刷新過了

示例:
int ticket;
while(true)
{
ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expertcomment",255,0,CLR_NONE);
if(ticket<=0)
{
int error=GetLastError();
if(error==134) break; // not enough money
if(error==135) RefreshRates(); // prices changed
break;
}
else { OrderPrint(); break; }
//---- 10 seconds wait
Sleep(10000);
}
void SendMail( string subject, string some_text)
發送郵件到指定信箱,需要到菜單 Tools -> Options -> Email 中將郵件打開.
:: 輸入參數
subject - 郵件標題
some_text - 郵件內容

示例:
double lastclose=Close[0];
if(lastclose<MY_SIGNAL)
SendMail("from your expert", "Price dropped down to"+DoubleToStr(lastclose));
string ServerAddress()
返回服務器地址

示例:
Print("Server address is ", ServerAddress());
void Sleep( int milliseconds)
設置線程暫停時間
:: 輸入參數
milliseconds - 暫停時間 1000 = 1秒

示例:
Sleep(5);
void SpeechText( string text, int lang_mode=SPEECH_ENGLISH)
使用Speech進行語音輸出
:: 輸入參數
text - 閱讀的文字
lang_mode - 語音模式 SPEECH_ENGLISH (默認的) 或SPEECH_NATIVE

示例:
double lastclose=Close[0];
SpeechText("Price dropped down to "+DoubleToStr(lastclose));
string Symbol()
返回當前當前通貨的名稱

示例:
int total=OrdersTotal();
for(int pos=0;pos<TOTALOS++)
{
// check selection result becouse order may be closed or deleted at this time!
if(OrderSelect(pos, SELECT_BY_POS)==false) continue;
if(OrderType()>OP_SELL || OrderSymbol()!=Symbol()) continue;
// do some orders processing...
}

int UninitializeReason()
取得程序末初始化的理由
示例:
// this is example
int deinit()
{
switch(UninitializeReason())
{
case REASON_CHARTCLOSE:
case REASON_REMOVE: CleanUp(); break; // clean up and free all expert'sresources.
case REASON_RECOMPILE:
case REASON_CHARTCHANGE:
case REASON_PARAMETERS:
case REASON_ACCOUNT: StoreData(); break; // prepare to restart
}
//...
}
  外_匯_邦 WaiHuiBang.com
  • 尋找無風險套利機會

    最近在對一些權證資料進行整理分析,原來的目的只是想通過權證做一些投機的買賣,卻從中發現了一些可能會出現的沒有任何風險的套利機會。  認購權證

  • 頭肩形態

    歡迎訪問 外 匯 邦 WWW.WaiHuiBang.com 頭肩形態是實際價格形態中

  • 外匯教程詳解

    外匯學習—外匯教程詳解  一、認識外匯市場  (一)外匯匯率定義  外匯匯率是一國貨幣對外國貨幣的兌換率,取決於兩國相互間的國際

  • 寫書評賺錢的正規網站

    最佳答案: 寫書評賺錢的正規網站有很多,下面主要介紹以下三個:1、頭條號。創作者可以通過頭條號網頁後

  • 濕紙巾哪個牌子好?

    最佳答案: 濕紙巾的功能分為:面部用和廁紙,一般廁紙會多一個殺菌的功能,但是面部用的濕紙巾也會有,具

  風險提示:比特財富網的各種信息資料僅供參考,不構成任何投資建議,不對任何交易提供任何擔保,亦不構成任何邀約,不作為任何法律文件,投資人據此進行投資交易而產生的後果請自行承擔,本網站不承擔任何責任,理財有風險,投資需謹慎。
比特財富網 版權所有 © www.emoneybtc.com