语法 [Syntax]
代码格式
空格建、Tab键、换行键和换页符都可以成为代码排版的分隔符,你能使用各种符号来增加代码的可读性。
注释
多行注释使用 /* 作为开始到 */ 结束,在这之间不能够嵌套。单行注释使用 // 作为开始到新的一行结束,可以被嵌套到多行注释之中。
示例:
// 单行注释
/* 多行注释
// 嵌套的单行注释
注释结束 */
标识符
标识符用来给变量、函数和数据类型进行命名,长度不能超过31个字节
你可以使用数字0-9、拉丁字母大写A-Z和小写a-z(大小写有区分的)还有下划线(_)。此外首字母不可以是数字,标识符不能和保留字冲突.
示例:
// NAME1 namel Total_5 Paper
保留字
下面列出的是固定的保留字。不能使用以下任何保留字进行命名。
数据类型 存储类型 操作符 其它
bool extern break false
color static case true
datetime continue
double default
int else
string for
void if
return
switch
while
数据类型 [Data types]
数据类型概述
主要数据类型有:
• Integer (int)
• Boolean (bool)
• ëèòåðàëû (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'
运算符和表达式 [Operations & Expressions]
表达式
一个表达式可以拥有多个字符和操作符,一个表达式可以写在几行里面。
示例:
a++; b = 10; x = (y*z)/w;
注:分号(;)是表达式的结束符。
算术运算符
Sum of values i = j + 2;
Difference of values i = j – 3;
Changing the operation sign x = – x;
Product of values z = 3 * x;
Division quotient i = j / 5;
Division remainder minutes = time % 60;
Adding 1 to the variable value i++;
Subtracting 1 from the variable value k–;
加减1的运算符不能被嵌套在表达式中
int a=3;
a++; // 可行的表达式
int b=(a++)*3; // 不可行的表达式
赋值运算符
注:将右侧的结果赋值给左侧的变量
将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
, Comma From left to right
操作符 [Operators]
格式和嵌套
格式.一个操作符可以占用一行或者多行,两个或多个操作符可以占用更多的行。
嵌套.执行控制符(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;我们将其放在嵌套内的指定位置,用来在指定情况下跳过接下来的运算,直接跳入下一次的循环。
示例:
// summary of 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];
函数 [Function]
函数定义
一个函数是由返回值、输入参数、内嵌操作所组成的。
示例:
double // 返回值类型
linfunc (double x, double a, double b) // 函数名和输入参数
{
// 内嵌的操作
return (a*x + b); // 返回值
}
如果没有返回值那么返回值的类型可以写为void
示例:
void errmesg(string s)
{
Print("error: "+s);
}
函数调用
function_name (x1,x2,…,xn)
示例:
int somefunc()
{
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()当数据变动时触发,对于自定义指标或者自动交易的编程主要依靠此函数进行。
变量 [Variables]
定义变量
定义基本类型
基本类型包括
• 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]; //一个两维由7×50个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
预处理程序 [Preprocessor]
定义常数
#define identifier_value
常数可以是任何类型的,常数在程序中不可更改。
示例:
#define ABC 100
#define PI 0.314
#define COMPANY_NAME "MetaQuotes Software Corp."
编译参数定义
#property identifier_value
示例:
#property link "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
账户信息 [Account Information]
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());
数组函数 [Array Functions]
int ArrayBsearch( double array[], double value, int count=WHOLE_ARRAY, int start=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," day bar opened at ",
TimeToStr(daytimes[dayshift]));
int ArrayCopy( object& dest[], object source[], int start_dest=0, int start_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, int timeframe=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," day bar 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, int sort_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
类型转换函数 [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);
公用函数 [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("eriod 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("I 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,"expert comment",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", "rice 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("rice 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's resources.
case REASON_RECOMPILE:
case REASON_CHARTCHANGE:
case REASON_PARAMETERS:
case REASON_ACCOUNT: StoreData(); break; // prepare to restart
}
//…
}
自定义指标函数 [Custom Indicator Functions]
void IndicatorBuffers(int count)
设置自定义指标缓存数
:: 输入参数
count – 缓存数量
示例:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//—- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//—- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+——————————————————————+
//| Custom indicator initialization function |
//+——————————————————————+
int init()
{
//—- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//—- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//—- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//—- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//—- initialization done
return(0);
}
int IndicatorCounted()
返回缓存数量
示例:
int start()
{
int limit;
int counted_bars=IndicatorCounted();
//—- check for possible errors
if(counted_bars<0) return(-1);
//—- last counted bar will be recounted
if(counted_bars>0) counted_bars–;
limit=Bars-counted_bars;
//—- main loop
for(int i=0; i
{
//—- ma_shift set to 0 because SetIndexShift called abowe
ExtBlueBuffer=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtRedBuffer=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtLimeBuffer=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
}
//—- done
return(0);
}
void IndicatorDigits( int digits)
设置指标精确度
:: 输入参数
digits – 小数点后的小数位数
示例:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//—- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//—- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+——————————————————————+
//| Custom indicator initialization function |
//+——————————————————————+
int init()
{
//—- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//—- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//—- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//—- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//—- initialization done
return(0);
}
void IndicatorShortName( string name)
设置指标的简称
:: 输入参数
name – 新的简称
示例:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//—- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//—- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+——————————————————————+
//| Custom indicator initialization function |
//+——————————————————————+
int init()
{
//—- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//—- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//—- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//—- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//—- initialization done
return(0);
}
void SetIndexArrow( int index, int code)
在指标上设置一个箭头符号
:: 输入参数
index – 第几根指标线 0-7
code – 符号的编码,参照 Wingdings 字体
示例:
SetIndexArrow(0, 217);
bool SetIndexBuffer( int index, double array[])
设置指标线的缓存数组
:: 输入参数
index – 第几根指标线 0-7
array[] – 缓存的数组
示例:
double ExtBufferSilver[];
int init()
{
SetIndexBuffer(0, ExtBufferSilver); // set buffer for first line
// …
}
void SetIndexDrawBegin( int index, int begin)
设置划线的开始点
:: 输入参数
index – 第几根指标线 0-7
begin – 划线的开始点
示例:
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//—- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//—- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+——————————————————————+
//| Custom indicator initialization function |
//+——————————————————————+
int init()
{
//—- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//—- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//—- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//—- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//—- initialization done
return(0);
}
void SetIndexEmptyValue( int index, double value)
设置划线的空值,空值不划在和出现在数据窗口
:: 输入参数
index – 第几根指标线 0-7
value – 新的空值
示例:
SetIndexEmptyValue(6,0.0001);
void SetIndexLabel( int index, string text)
设置指标线的名称
:: 输入参数
index – 第几根指标线 0-7
text – 线的名称,Null不会显示在数据窗口中
示例:
//+——————————————————————+
//| Ichimoku Kinko Hyo initialization function |
//+——————————————————————+
int init()
{
//—-
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,Tenkan_Buffer);
SetIndexDrawBegin(0,Tenkan-1);
SetIndexLabel(0,"Tenkan Sen");
//—-
SetIndexStyle(1,DRAW_LINE);
SetIndexBuffer(1,Kijun_Buffer);
SetIndexDrawBegin(1,Kijun-1);
SetIndexLabel(1,"Kijun Sen");
//—-
a_begin=Kijun; if(a_begin SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(2,SpanA_Buffer);
SetIndexDrawBegin(2,Kijun+a_begin-1);
SetIndexShift(2,Kijun);
//—- Up Kumo bounding line does not show in the DataWindow
SetIndexLabel(2,NULL);
SetIndexStyle(5,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(5,SpanA2_Buffer);
SetIndexDrawBegin(5,Kijun+a_begin-1);
SetIndexShift(5,Kijun);
SetIndexLabel(5,"Senkou Span A");
//—-
SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(3,SpanB_Buffer);
SetIndexDrawBegin(3,Kijun+Senkou-1);
SetIndexShift(3,Kijun);
//—- Down Kumo bounding line does not show in the DataWindow
SetIndexLabel(3,NULL);
//—-
SetIndexStyle(6,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(6,SpanB2_Buffer);
SetIndexDrawBegin(6,Kijun+Senkou-1);
SetIndexShift(6,Kijun);
SetIndexLabel(6,"Senkou Span B");
//—-
SetIndexStyle(4,DRAW_LINE);
SetIndexBuffer(4,Chinkou_Buffer);
SetIndexShift(4,-Kijun);
SetIndexLabel(4,"Chinkou Span");
//—-
return(0);
}
void SetIndexShift( int index, int shift)
设置指标线的位移数
:: 输入参数
index – 第几根指标线 0-7
shift – 位移多少
示例:
//+——————————————————————+
//| Alligator initialization function |
//+——————————————————————+
int init()
{
//—- line shifts when drawing
SetIndexShift(0,JawsShift);
SetIndexShift(1,TeethShift);
SetIndexShift(2,LipsShift);
//—- first positions skipped when drawing
SetIndexDrawBegin(0,JawsShift+JawsPeriod);
SetIndexDrawBegin(1,TeethShift+TeethPeriod);
SetIndexDrawBegin(2,LipsShift+LipsPeriod);
//—- 3 indicator buffers mapping
SetIndexBuffer(0,ExtBlueBuffer);
SetIndexBuffer(1,ExtRedBuffer);
SetIndexBuffer(2,ExtLimeBuffer);
//—- drawing settings
SetIndexStyle(0,DRAW_LINE);
SetIndexStyle(1,DRAW_LINE);
SetIndexStyle(2,DRAW_LINE);
//—- index labels
SetIndexLabel(0,"Gator Jaws");
SetIndexLabel(1,"Gator Teeth");
SetIndexLabel(2,"Gator Lips");
//—- initialization done
return(0);
}
void SetIndexStyle( int index, int type, int style=EMPTY, int width=EMPTY, color clr=CLR_NONE)
设置指标线的样式
:: 输入参数
index – 第几根指标线 0-7
type – 线形状的种类,详见线条种类
style – 划线的样式
width – 显得宽度(1,2,3,4,5)
clr – 线的颜色
示例:
SetIndexStyle(3, DRAW_LINE, EMPTY, 2, Red);
日期时间函数 [Date & Time Functions]
datetime CurTime( )
返回当前时间
示例:
if(CurTime()-OrderOpenTime()<360) return(0);
int Day()
返回当前日期
示例:
if(Day()<5) return(0);
int DayOfWeek( )
返回当前日期是星期几 0-星期天,1,2,3,4,5,6
示例:
// do not work on holidays.
if(DayOfWeek()==0 || DayOfWeek()==6) return(0);
int DayOfYear( )
返回当前日期在年内的第几天
示例:
if(DayOfYear()==245)
return(true);
int Hour()
返回当前的小时数 0-23
示例:
bool is_siesta=false;
if(Hour()>=12 || Hour()<17)
is_siesta=true;
datetime LocalTime()
返回当前电脑时间
示例:
if(LocalTime()-OrderOpenTime()<360) return(0);
int Minute()
返回当前分钟
示例:
if(Minute()<=15)
return("first quarter");
int Month()
返回当前月份
示例:
if(Month()<=5)
return("first half of year");
int Seconds()
返回当前秒数
示例:
if(Seconds()<=15)
return(0);
int TimeDay( datetime date)
返回输入日期中的日期
:: 输入参数
date – 输入日期
示例:
int day=TimeDay(D'2003.12.31');
// day is 31
int TimeDayOfWeek( datetime date)
返回输入日期中的日期是星期几 (0-6)
:: 输入参数
date – 输入日期
示例:
int weekday=TimeDayOfWeek(D'2004.11.2');
// day is 2 – tuesday
int TimeDayOfYear( datetime date)
返回输入日期中的日期在当年中的第几天
:: 输入参数
date – 输入日期
示例:
int day=TimeDayOfYear(CurTime());
int TimeHour( datetime time)
返回输入日期中的小时
:: 输入参数
date – 输入日期
示例:
int h=TimeHour(CurTime());
int TimeMinute( datetime time)
返回输入日期中的分钟
:: 输入参数
date – 输入日期
示例:
int m=TimeMinute(CurTime());
int TimeMonth( datetime time)
返回输入日期中的月份
:: 输入参数
date – 输入日期
示例:
int m=TimeMonth(CurTime());
int TimeSeconds( datetime time)
返回输入日期中的秒钟
:: 输入参数
date – 输入日期
示例:
int m=TimeSeconds(CurTime());
int TimeYear( datetime time)
返回输入日期中的年份
:: 输入参数
date – 输入日期
示例:
int y=TimeYear(CurTime());
int TimeYear( datetime time)
返回当前年份
示例:
// return if date before 1 May 2002
if(Year()==2002 && Month()<5)
return(0);
文件处理函数 [File Functions]
void FileClose(int handle)
关闭正在已经打开的文件.
:: 输入参数
handle – FileOpen()返回的句柄
示例:
int handle=FileOpen("filename", FILE_CSV|FILE_READ);
if(handle>0)
{
// working with file …
FileClose(handle);
}
void FileDelete(string filename)
删除文件,如果发生错误可以通过GetLastError()来查询
注:你只能操作terminal_direxpertsfiles目录下的文件
:: 输入参数
filename – 目录和文件名
示例:
// file my_table.csv will be deleted from terminal_direxpertsfiles directory
int lastError;
FileDelete("my_table.csv");
lastError=GetLastError();
if(laseError!=ERR_NOERROR)
{
Print("An error ocurred while (",lastError,") deleting file my_table.csv");
return(0);
}
void FileFlush(int handle)
将缓存中的数据刷新到磁盘上去
:: 输入参数
handle – FileOpen()返回的句柄
示例:
int bars_count=Bars;
int handle=FileOpen("mydat.csv",FILE_CSV|FILE_WRITE);
if(handle>0)
{
FileWrite(handle, "#","OPEN","CLOSE","HIGH","LOW");
for(int i=0;i<BARS_COUNT;I++)
FileWrite(handle, i+1,Open,Close,High, Low);
FileFlush(handle);
…
for(int i=0;i<BARS_COUNT;I++)
FileWrite(handle, i+1,Open,Close,High, Low);
FileClose(handle);
}
bool FileIsEnding(int handle)
检查是否到了文件尾.
:: 输入参数
handle – FileOpen()返回的句柄
示例:
if(FileIsEnding(h1))
{
FileClose(h1);
return(false);
}
bool FileIsLineEnding( int handle)
检查行是否到了结束
:: 输入参数
handle – FileOpen()返回的句柄
示例:
if(FileIsLineEnding(h1))
{
FileClose(h1);
return(false);
}
int FileOpen( string filename, int mode, int delimiter=';')
打开文件,如果失败返回值小于1,可以通过GetLastError()获取错误
注:只能操作terminal_direxpertsfiles目录的文件
:: 输入参数
filename – 目录文件名
mode – 打开模式 FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE.
delimiter – CSV型打开模式用的分割符,默认为分号(;).
示例:
int handle;
handle=FileOpen("my_data.csv",FILE_CSV|FILE_READ,';');
if(handle<1)
{
Print("File my_data.dat not found, the last error is ", GetLastError());
return(false);
}
int FileOpenHistory( string filename, int mode, int delimiter=';')
打开历史数据文件,如果失败返回值小于1,可以通过GetLastError()获取错误
:: 输入参数
filename – 目录文件名
mode – 打开模式 FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE.
delimiter – CSV型打开模式用的分割符,默认为分号(;).
示例:
int handle=FileOpenHistory("USDX240.HST",FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("Cannot create file USDX240.HST");
return(false);
}
// work with file
// …
FileClose(handle);
int FileReadArray( int handle, object& array[], int start, int count)
将二进制文件读取到数组中,返回读取的条数,可以通过GetLastError()获取错误
注:在读取之前要调整好数组大小
:: 输入参数
handle – FileOpen()返回的句柄
array[] – 写入的数组
start – 在数组中存储的开始点
count – 读取多少个对象
示例:
int handle;
double varray[10];
handle=FileOpen("filename.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
FileReadArray(handle, varray, 0, 10);
FileClose(handle);
}
double FileReadDouble( int handle, int size=DOUBLE_VALUE)
从文件中读取浮点型数据,数字可以是8byte的double型或者是4byte的float型。
:: 输入参数
handle – FileOpen()返回的句柄
size – 数字个是大小,DOUBLE_VALUE(8 bytes) 或者 FLOAT_VALUE(4 bytes).
示例:
int handle;
double value;
handle=FileOpen("mydata.dat",FILE_BIN);
if(handle>0)
{
value=FileReadDouble(handle,DOUBLE_VALUE);
FileClose(handle);
}
int FileReadInteger( int handle, int size=LONG_VALUE)
从文件中读取整形型数据,数字可以是1,2,4byte的长度
:: 输入参数
handle – FileOpen()返回的句柄
size – 数字个是大小,CHAR_VALUE(1 byte), SHORT_VALUE(2 bytes) 或者 LONG_VALUE(4 bytes).
示例:
int handle;
int value;
handle=FileOpen("mydata.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
value=FileReadInteger(h1,2);
FileClose(handle);
}
double FileReadNumber( int handle)
从文件中读取数字,只能在CSV里使用
:: 输入参数
handle – FileOpen()返回的句柄
示例:
int handle;
int value;
handle=FileOpen("filename.csv", FILE_CSV, ';');
if(handle>0)
{
value=FileReadNumber(handle);
FileClose(handle);
}
string FileReadString( int handle, int length=0)
从文件中读取字符串
:: 输入参数
handle – FileOpen()返回的句柄
length – 读取字符串长度
示例:
int handle;
string str;
handle=FileOpen("filename.csv", FILE_CSV|FILE_READ);
if(handle>0)
{
str=FileReadString(handle);
FileClose(handle);
}
bool FileSeek( int handle, int offset, int origin)
移动指针移动到某一点,如果成功返回true
:: 输入参数
handle – FileOpen()返回的句柄
offset – 设置的原点
origin – SEEK_CUR从当前位置开始 SEEK_SET从文件头部开始 SEEK_END 从文件尾部开始
示例:
int handle=FileOpen("filename.csv", FILE_CSV|FILE_READ, ';');
if(handle>0)
{
FileSeek(handle, 10, SEEK_SET);
FileReadInteger(handle);
FileClose(handle);
handle=0;
}
int FileSize( int handle)
返回文件大小
:: 输入参数
handle – FileOpen()返回的句柄
示例:
int handle;
int size;
handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
size=FileSize(handle);
Print("my_table.dat size is ", size, " bytes");
FileClose(handle);
}
int FileTell( int handle)
返回文件读写指针当前的位置
:: 输入参数
handle – FileOpen()返回的句柄
示例:
int handle;
int pos;
handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ);
// reading some data
pos=FileTell(handle);
Print("current position is ", pos);
int FileWrite( int handle, … )
向文件写入数据
:: 输入参数
handle – FileOpen()返回的句柄
… – 写入的数据
示例:
int handle;
datetime orderOpen=OrderOpenTime();
handle=FileOpen("filename", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
FileWrite(handle, Close[0], Open[0], High[0], Low[0], TimeToStr(orderOpen));
FileClose(handle);
}
int FileWriteArray( int handle, object array[], int start, int count)
向文件写入数组
:: 输入参数
handle – FileOpen()返回的句柄
array[] – 要写入的数组
start – 写入的开始点
count – 写入的项目数
示例:
int handle;
double BarOpenValues[10];
// copy first ten bars to the array
for(int i=0;i<10; i++)
BarOpenValues=Open;
// writing array to the file
handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE);
if(handle>0)
{
FileWriteArray(handle, BarOpenValues, 3, 7); // writing last 7 elements
FileClose(handle);
}
int FileWriteDouble( int handle, double value, int size=DOUBLE_VALUE)
向文件写入浮点型数据
:: 输入参数
handle – FileOpen()返回的句柄
value – 要写入的值
size – 写入的格式,DOUBLE_VALUE (8 bytes, default)或FLOAT_VALUE (4 bytes).
示例:
int handle;
double var1=0.345;
handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteDouble(h1, var1, DOUBLE_VALUE);
//…
FileClose(handle);
int FileWriteInteger( int handle, int value, int size=LONG_VALUE)
向文件写入整型数据
:: 输入参数
handle – FileOpen()返回的句柄
value – 要写入的值
size – 写入的格式,CHAR_VALUE (1 byte),SHORT_VALUE (2 bytes),LONG_VALUE (4 bytes, default).
示例:
int handle;
int value=10;
handle=FileOpen("filename.dat", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteInteger(handle, value, SHORT_VALUE);
//…
FileClose(handle);
int FileWriteString( int handle, string value, int length)
向文件写入字符串数据
:: 输入参数
handle – FileOpen()返回的句柄
value – 要写入的值
length – 写入的字符长度
示例:
int handle;
string str="some string";
handle=FileOpen("filename.bin", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteString(h1, str, 8);
FileClose(handle);
全局变量函数 [Global Variables Functions]
bool GlobalVariableCheck( string name)
检查全局变量是否存在
:: 输入参数
name – 全局变量的名称
示例:
// check variable before use
if(!GlobalVariableCheck("g1"))
GlobalVariableSet("g1",1);
bool GlobalVariableDel( string name)
删除全局变量
:: 输入参数
name – 全局变量的名称
示例:
// deleting global variable with name "gvar_1"
GlobalVariableDel("gvar_1");
double GlobalVariableGet( string name)
获取全局变量的值
:: 输入参数
name – 全局变量的名称
示例:
double v1=GlobalVariableGet("g1");
//—- check function call result
if(GetLastError()!=0) return(false);
//—- continue processing
double GlobalVariableGet( string name)
获取全局变量的值
:: 输入参数
name – 全局变量的名称
示例:
double v1=GlobalVariableGet("g1");
//—- check function call result
if(GetLastError()!=0) return(false);
//—- continue processing
datetime GlobalVariableSet( string name, double value )
设置全局变量的值
:: 输入参数
name – 全局变量的名称
value – 全局变量的值
示例:
//—- try to set new value
if(GlobalVariableSet("BarsTotal",Bars)==0)
return(false);
//—- continue processing
bool GlobalVariableSetOnCondition( string name, double value, double check_value)
有条件的设置全局变量的值
:: 输入参数
name – 全局变量的名称
value – 全局变量的值
check_value – 检查变量的值
示例:
int init()
{
//—- create global variable
GlobalVariableSet("DATAFILE_SEM",0);
//…
}
int start()
{
//—- try to lock common resource
while(!IsStopped())
{
//—- locking
if(GlobalVariableSetOnCondition("DATAFILE_SEM",1,0)==true) break;
//—- may be variable deleted?
if(GetLastError()==ERR_GLOBAL_VARIABLE_NOT_FOUND) return(0);
//—- sleeping
Sleep(500);
}
//—- resource locked
// … do some work
//—- unlock resource
GlobalVariableSet("DATAFILE_SEM",0);
}
void GlobalVariablesDeleteAll( )
删除所有全局变量
示例:
GlobalVariablesDeleteAll();
数学运算函数 [Math & Trig]
double MathAbs( double value)
返回数字的绝对值
:: 输入参数
value – 要处理的数字
示例:
double dx=-3.141593, dy;
// calc MathAbs
dy=MathAbs(dx);
Print("The absolute value of ",dx," is ",dy);
// Output: The absolute value of -3.141593 is 3.141593
double MathArccos( double x)
计算反余弦值
:: 输入参数
value – 要处理的数字,范围-1到1
示例:
double x=0.32696, y;
y=asin(x);
Print("Arcsine of ",x," = ",y);
y=acos(x);
Print("Arccosine of ",x," = ",y);
//Output: Arcsine of 0.326960=0.333085
//Output: Arccosine of 0.326960=1.237711
double MathArcsin( double x)
计算反正弦值
:: 输入参数
x – 要处理的值
示例:
double x=0.32696, y;
y=MathArcsin(x);
Print("Arcsine of ",x," = ",y);
y=acos(x);
Print("Arccosine of ",x," = ",y);
//Output: Arcsine of 0.326960=0.333085
//Output: Arccosine of 0.326960=1.237711
double MathArctan( double x)
计算反正切值
:: 输入参数
x – 要处理的值
示例:
double x=-862.42, y;
y=MathArctan(x);
Print("Arctangent of ",x," is ",y);
//Output: Arctangent of -862.42 is -1.5696
double MathCeil( double x)
返回向前进位后的值
:: 输入参数
x – 要处理的值
示例:
double y;
y=MathCeil(2.8);
Print("The ceil of 2.8 is ",y);
y=MathCeil(-2.8);
Print("The ceil of -2.8 is ",y);
/*Output:
The ceil of 2.8 is 3
The ceil of -2.8 is -2*/
double MathCos( double value)
计算余弦值
:: 输入参数
value – 要处理的值
示例:
double pi=3.1415926535;
double x, y;
x=pi/2;
y=MathSin(x);
Print("MathSin(",x,") = ",y);
y=MathCos(x);
Print("MathCos(",x,") = ",y);
//Output: MathSin(1.5708)=1
// MathCos(1.5708)=0
double MathExp( double d)
Returns value the number e raised to the power d. On overflow, the function returns INF (infinite) and on underflow, MathExp returns 0.
:: 输入参数
d – A number specifying a power.
示例:
double x=2.302585093,y;
y=MathExp(x);
Print("MathExp(",x,") = ",y);
//Output: MathExp(2.3026)=10
double MathFloor( double x)
返回向后进位后的值
:: 输入参数
x – 要处理的值
示例:
double y;
y=MathFloor(2.8);
Print("The floor of 2.8 is ",y);
y=MathFloor(-2.8);
Print("The floor of -2.8 is ",y);
/*Output:
The floor of 2.8 is 2
The floor of -2.8 is -3*/
double MathLog( double x)
计算对数
:: 输入参数
x – 要处理的值
示例:
double x=9000.0,y;
y=MathLog(x);
Print("MathLog(",x,") = ", y);
//Output: MathLog(9000)=9.10498
double MathMax( double value1, double value2)
计算两个值中的最大值
:: 输入参数
value1 – 第一个值
value2 – 第二个值
示例:
double result=MathMax(1.08,Bid);
double MathMin( double value1, double value2)
计算两个值中的最小值
:: 输入参数
value1 – 第一个值
value2 – 第二个值
示例:
double result=MathMin(1.08,Ask);
double MathMod( double value, double value2)
计算两个值相除的余数
:: 输入参数
value – 被除数
value2 – 除数
示例:
double x=-10.0,y=3.0,z;
z=MathMod(x,y);
Print("The remainder of ",x," / ",y," is ",z);
//Output: The remainder of -10 / 3 is -1
double MathPow( double base, double exponent)
计算指数
:: 输入参数
base – 基数
exponent – 指数
示例:
double x=2.0,y=3.0,z;
z=MathPow(x,y);
Printf(x," to the power of ",y," is ", z);
//Output: 2 to the power of 3 is 8
int MathRand( )
取随机数
示例:
MathSrand(LocalTime());
// Display 10 numbers.
for(int i=0;i<10;i++ )
Print("random value ", MathRand());
double MathRound( double value)
取四舍五入的值
:: 输入参数
value – 要处理的值
示例:
double y=MathRound(2.8);
Print("The round of 2.8 is ",y);
y=MathRound(2.4);
Print("The round of -2.4 is ",y);
//Output: The round of 2.8 is 3
// The round of -2.4 is -2
double MathSin( double value)
计算正弦数
:: 输入参数
value – 要处理的值
示例:
double pi=3.1415926535;
double x, y;
x=pi/2;
y=MathSin(x);
Print("MathSin(",x,") = ",y);
y=MathCos(x);
Print("MathCos(",x,") = ",y);
//Output: MathSin(1.5708)=1
// MathCos(1.5708)=0
double MathSqrt( double x)
计算平方根
:: 输入参数
x – 要处理的值
示例:
double question=45.35, answer;
answer=MathSqrt(question);
if(question<0)
Print("Error: MathSqrt returns ",answer," answer");
else
Print("The square root of ",question," is ", answer);
//Output: The square root of 45.35 is 6.73
void MathSrand( int seed)
通过Seed产生随机数
:: 输入参数
seed – 随机数的种子
示例:
MathSrand(LocalTime());
// Display 10 numbers.
for(int i=0;i<10;i++ )
Print("random value ", MathRand());
double MathTan( double x)
计算正切值
:: 输入参数
x – 要计算的角度
示例:
double pi=3.1415926535;
double x,y;
x=MathTan(pi/4);
Print("MathTan(",pi/4," = ",x);
//Output: MathTan(0.7856)=1
物体函数 [Object Functions]
bool ObjectCreate( string name, int type, int window, datetime time1, double price1, datetime time2=0, double price2=0, datetime time3=0, double price3=0)
创建物件
:: 输入参数
name – 物件名称
type – 物件类型.
window – 物件所在窗口的索引值
time1 – 时间点1
price1 – 价格点1
time2 – 时间点2
price2 – 价格点2
time3 – 时间点3
price3 – 价格点3
示例:
// new text object
if(!ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045))
{
Print("error: can't create text_object! code #",GetLastError());
return(0);
}
// new label object
if(!ObjectCreate("label_object", OBJ_LABEL, 0, 0, 0))
{
Print("error: can't create label_object! code #",GetLastError());
return(0);
}
ObjectSet("label_object", OBJPROP_XDISTANCE, 200);
ObjectSet("label_object", OBJPROP_YDISTANCE, 100);
bool ObjectDelete( string name)
删除物件
:: 输入参数
name – 物件名称
示例:
ObjectDelete("text_object");
string ObjectDescription( string name)
返回物件描述
:: 输入参数
name – 物件名称
示例:
// writing chart's object list to the file
int handle, total;
string obj_name,fname;
// file name
fname="objlist_"+Symbol();
handle=FileOpen(fname,FILE_CSV|FILE_WRITE);
if(handle!=false)
{
total=ObjectsTotal();
for(int i=-;i<TOTAL;I++)
{
obj_name=ObjectName(i);
FileWrite(handle,"Object "+obj_name+" description= "+ObjectDescription(obj_name));
}
FileClose(handle);
}
int ObjectFind( string name)
寻找物件,返回物件的索引值
:: 输入参数
name – 物件名称
示例:
if(ObjectFind("line_object2")!=win_idx) return(0);
double ObjectGet( string name, int index)
获取物件的值
:: 输入参数
name – 物件名称
index – 取值属性的索引
示例:
color oldColor=ObjectGet("hline12", OBJPROP_COLOR);
string ObjectGetFiboDescription( string name, int index)
取物件的斐波纳契数列地描述
:: 输入参数
name – 物件名称
index – 斐波纳契数列的等级索引
示例:
#include
…
string text;
for(int i=0;i<32;i++)
{
text=ObjectGetFiboDescription(MyObjectName,i);
//—- check. may be objects's level count less than 32
if(GetLastError()!=ERR_NO_ERROR) break;
Print(MyObjectName,"level: ",i," description: ",text);
}
int ObjectGetShiftByValue( string name, double value)
取物件的位移值
:: 输入参数
name – 物件名称
value – 价格
示例:
int shift=ObjectGetShiftByValue("MyTrendLine#123", 1.34);
double ObjectGetValueByShift( string name, int shift)
取物件位移后的值
:: 输入参数
name – 物件名称
shift – 位移数
示例:
double price=ObjectGetValueByShift("MyTrendLine#123", 11);
bool ObjectMove( string name, int point, datetime time1, double price1)
移动物件
:: 输入参数
name – 物件名称
point – 调整的索引
time1 – 新的时间
price1 – 新的价格
示例:
ObjectMove("MyTrend", 1, D'2005.02.25 12:30', 1.2345);
string ObjectName( int index)
取物件名称
:: 输入参数
index – 物件的索引
示例:
int obj_total=ObjectsTotal();
string name;
for(int i=0;i<OBJ_TOTAL;I++)
{
name=ObjectName(i);
Print(i,"Object name is " + name);
}
int ObjectsDeleteAll( int window, int type=EMPTY)
删除所有物件
:: 输入参数
window – 物件所在的窗口索引
type – 删除物件的类型
示例:
ObjectsDeleteAll(2, OBJ_HLINE); // removes all horizontal line objects from window 3 (index 2).
bool ObjectSet( string name, int index, double value)
设置物件的值
:: 输入参数
name – 物件的名称
index – 物件属性的索引值
value – 新的属性值
示例:
// moving first coord to last bar time
ObjectSet("MyTrend", OBJPROP_TIME1, Time[0]);
// setting second fibo level
ObjectSet("MyFibo", OBJPROP_FIRSTLEVEL+1, 1.234);
// setting object visibility. object will be shown only on 15 minute and 1 hour charts
ObjectSet("MyObject", OBJPROP_TIMEFRAMES, OBJ_PERIOD_M15 | OBJ_PERIOD_H1);
bool ObjectSetFiboDescription( string name, int index, string text)
设置物件斐波纳契数列的描述
:: 输入参数
name – 物件的名称
index – 物件斐波纳契数列的索引值
text – 新的描述
示例:
ObjectSetFiboDescription("MyFiboObject,2,"Second line");
bool ObjectSetText( string name, string text, int font_size, string font=NULL, color text_color=CLR_NONE)
设置物件的描述
:: 输入参数
name – 物件的名称
text – 文本
font_size – 字体大小
font – 字体名称
text_color – 字体颜色
示例:
ObjectSetText("text_object", "Hello world!", 10, "Times New Roman", Green);
void ObjectsRedraw( )
重绘所有物件
示例:
ObjectsRedraw();
int ObjectsTotal( )
取物件总数
示例:
int obj_total=ObjectsTotal();
string name;
for(int i=0;i<OBJ_TOTAL;I++)
{
name=ObjectName(i);
Print(i,"Object name is for object #",i," is " + name);
}
int ObjectType( string name)
取物件类型
:: 输入参数
name – 物件的名称
示例:
if(ObjectType("line_object2")!=OBJ_HLINE) return(0);
预定义变量 [Pre-defined Variables]
double Ask
通货的买入价
示例:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25)
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point,
"My order #2",3,D'2005.10.10 12:30',Red);
return;
}
int Bars
返回图表中的柱数
示例:
int counter=1;
for(int i=1;i<=Bars;i++)
{
Print(Close[i-1]);
}
double Bid
通货的卖价
示例:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderSend("EURUSD",OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point,
"My order #2",3,D'2005.10.10 12:30',Red);
return(0);
}
double Close[]
返回指定索引位置的收盘价格
示例:
int handle, bars=Bars;
handle=FileOpen("file.csv",FILE_CSV|FILE_WRITE,';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i
FileWrite(handle, Time, Open, High, Low, Close, Volume);
FileClose(handle);
}
int Digits
返回当前通货的汇率小数位
示例:
Print(DoubleToStr(Close[i-1], Digits));
double High[]
返回指定索引位置的最高价格
示例:
int handle, bars=Bars;
handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i
FileWrite(handle, Time, Open, High, Low, Close, Volume);
FileClose(handle);
}
double Low[]
返回指定索引位置的最低价格
示例:
int handle, bars=Bars;
handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ";");
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i
FileWrite(handle, Time, Open, High, Low, Close, Volume);
FileClose(handle);
}
double Open[]
返回指定索引位置的开盘价格
示例:
int handle, bars=Bars;
handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i
FileWrite(handle, Time, Open, High, Low, Close, Volume);
FileClose(handle);
}
double Point
返回当前图表的点值
示例:
OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,Red);
datetime Time[]
返回指定索引位置的时间
示例:
int handle, bars=Bars;
handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i
FileWrite(handle, Time, Open, High, Low, Close, Volume);
FileClose(handle);
}
double Volume[]
返回指定索引位置的成交量
示例:
int handle, bars=Bars;
handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// erite data
for(int i=0; i
FileWrite(handle, Time, Open, High, Low, Close, Volume);
FileClose(handle);
)
字符串函数 [String Functions]
string StringConcatenate( … )
字符串连接
:: 输入参数
… – 任意值,用逗号分割
示例:
string text;
text=StringConcatenate("Account free margin is ", AccountFreeMargin(), "Current time is ", TimeToStr(CurTime()));
// slow text="Account free margin is " + AccountFreeMargin() + "Current time is " + TimeToStr(CurTime())
Print(text);
int StringFind( string text, string matched_text, int start=0)
在字符串中寻找符合条件的字符串返回索引位置
:: 输入参数
text – 被搜索的字符串
matched_text – 需要搜索的字符串
start – 搜索开始索引位置
示例:
string text="The quick brown dog jumps over the lazy fox";
int index=StringFind(text, "dog jumps", 0);
if(index!=16)
Print("oops!");
int StringGetChar( string text, int pos)
取字符串中的某一个字符
:: 输入参数
text – 字符串
pos – 取字符的位置
示例:
int char_code=StringGetChar("abcdefgh", 3);
// char code 'c' is 99
int StringLen( string text)
返回字符串长度
:: 输入参数
text – 字符串
示例:
string str="some text";
if(StringLen(str)<5) return(0);
string StringSetChar( string text, int pos, int value)
在字符串中设置一个字符
:: 输入参数
text – 字符串
pos – 设置字符的位置
value – 新的字符
示例:
string str="abcdefgh";
string str1=StringSetChar(str, 3, 'D');
// str1 is "abcDefgh"
string StringSubstr( string text, int start, int count=EMPTY)
从字符串中截取一段字符串
:: 输入参数
text – 字符串
start – 开始索引位置
count – 截取字符数
示例:
string text="The quick brown dog jumps over the lazy fox";
string substr=StringSubstr(text, 4, 5);
// subtracted string is "quick" word
string StringTrimLeft( string text)
字符串左侧去空格
:: 输入参数
text – 字符串
示例:
string str1=" Hello world ";
string str2=StringTrimLeft(str);
// after trimming the str2 variable will be "Hello World "
string StringTrimRight( string text)
字符串右侧去空格
:: 输入参数
text – 字符串
示例:
string str1=" Hello world ";
string str2=StringTrimRight(str);
// after trimming the str2 variable will be " Hello World"
标准常量 [Standard Constants]
Applied price enumeration
价格类型枚举
示例:
Constant Value Description
PRICE_CLOSE 0 收盘价
PRICE_OPEN 1 开盘价
PRICE_HIGH 2 最高价
PRICE_LOW 3 最低价
PRICE_MEDIAN 4 最高价和最低价的平均价
PRICE_TYPICAL 5 最高价、最低价和收盘价的平均价
PRICE_WEIGHTED 6 开、收盘价和最高最低价的平均价
Drawing shape style enumeration
画图形状样式枚举,
形状:
Constant Value Description
DRAW_LINE 0 Drawing line.
DRAW_SECTION 1 Drawing sections.
DRAW_HISTOGRAM 2 Drawing histogram.
DRAW_ARROW 3 Drawing arrows (symbols).
DRAW_NONE 12 No drawing.
样式:
Constant Value Description
STYLE_SOLID 0 The pen is solid.
STYLE_DASH 1 The pen is dashed.
STYLE_DOT 2 The pen is dotted.
STYLE_DASHDOT 3 The pen has alternating dashes and dots.
STYLE_DASHDOTDOT 4 The pen has alternating dashes and double dots.
Error codes
错误代码,使用GetLastError()可返回错误代码,错误代码定义在stderror.mqh文件里,可以使用ErrorDescription()取得说明
#include
void SendMyMessage(string text)
{
int check;
SendMail("some subject", text);
check=GetLastError();
if(check!=ERR_NO_MQLERROR) Print("Cannot send message, error: ",ErrorDescription(check));
}
交易服务器返回的错误:
Constant Value Description
ERR_NO_ERROR 0 No error returned.
ERR_NO_RESULT 1 No error returned, but the result is unknown.
ERR_COMMON_ERROR 2 Common error.
ERR_INVALID_TRADE_PARAMETERS 3 Invalid trade parameters.
ERR_SERVER_BUSY 4 Trade server is busy.
ERR_OLD_VERSION 5 Old version of the client terminal.
ERR_NO_CONNECTION 6 No connection with trade server.
ERR_NOT_ENOUGH_RIGHTS 7 Not enough rights.
ERR_TOO_FREQUENT_REQUESTS 8 Too frequent requests.
ERR_MALFUNCTIONAL_TRADE 9 Malfunctional trade operation.
ERR_ACCOUNT_DISABLED 64 Account disabled.
ERR_INVALID_ACCOUNT 65 Invalid account.
ERR_TRADE_TIMEOUT 128 Trade timeout.
ERR_INVALID_PRICE 129 Invalid price.
ERR_INVALID_STOPS 130 Invalid stops.
ERR_INVALID_TRADE_VOLUME 131 Invalid trade volume.
ERR_MARKET_CLOSED 132 Market is closed.
ERR_TRADE_DISABLED 133 Trade is disabled.
ERR_NOT_ENOUGH_MONEY 134 Not enough money.
ERR_PRICE_CHANGED 135 Price changed.
ERR_OFF_QUOTES 136 Off quotes.
ERR_BROKER_BUSY 137 Broker is busy.
ERR_REQUOTE 138 Requote.
ERR_ORDER_LOCKED 139 Order is locked.
ERR_LONG_POSITIONS_ONLY_ALLOWED 140 Long positions only allowed.
ERR_TOO_MANY_REQUESTS 141 Too many requests.
ERR_TRADE_MODIFY_DENIED 145 Modification denied because order too close to market.
ERR_TRADE_CONTEXT_BUSY 146 Trade context is busy.
MT4返回的运行错误:
Constant Value Description
ERR_NO_MQLERROR 4000 No error.
ERR_WRONG_FUNCTION_POINTER 4001 Wrong function pointer.
ERR_ARRAY_INDEX_OUT_OF_RANGE 4002 Array index is out of range.
ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK 4003 No memory for function call stack.
ERR_RECURSIVE_STACK_OVERFLOW 4004 Recursive stack overflow.
ERR_NOT_ENOUGH_STACK_FOR_PARAMETER 4005 Not enough stack for parameter.
ERR_NO_MEMORY_FOR_PARAMETER_STRING 4006 No memory for parameter string.
ERR_NO_MEMORY_FOR_TEMP_STRING 4007 No memory for temp string.
ERR_NOT_INITIALIZED_STRING 4008 Not initialized string.
ERR_NOT_INITIALIZED_ARRAYSTRING 4009 Not initialized string in array.
ERR_NO_MEMORY_FOR_ARRAYSTRING 4010 No memory for array string.
ERR_TOO_LONG_STRING 4011 Too long string.
ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 Remainder from zero divide.
ERR_ZERO_DIVIDE 4013 Zero divide.
ERR_UNKNOWN_COMMAND 4014 Unknown command.
ERR_WRONG_JUMP 4015 Wrong jump (never generated error).
ERR_NOT_INITIALIZED_ARRAY 4016 Not initialized array.
ERR_DLL_CALLS_NOT_ALLOWED 4017 DLL calls are not allowed.
ERR_CANNOT_LOAD_LIBRARY 4018 Cannot load library.
ERR_CANNOT_CALL_FUNCTION 4019 Cannot call function.
ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED 4020 Expert function calls are not allowed.
ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING 4021 Not enough memory for temp string returned from function.
ERR_SYSTEM_BUSY 4022 System is busy (never generated error).
ERR_INVALID_FUNCTION_PARAMETERS_COUNT 4050 Invalid function parameters count.
ERR_INVALID_FUNCTION_PARAMETER_VALUE 4051 Invalid function parameter value.
ERR_STRING_FUNCTION_INTERNAL_ERROR 4052 String function internal error.
ERR_SOME_ARRAY_ERROR 4053 Some array error.
ERR_INCORRECT_SERIES_ARRAY_USING 4054 Incorrect series array using.
ERR_CUSTOM_INDICATOR_ERROR 4055 Custom indicator error.
ERR_INCOMPATIBLE_ARRAYS 4056 Arrays are incompatible.
ERR_GLOBAL_VARIABLES_PROCESSING_ERROR 4057 Global variables processing error.
ERR_GLOBAL_VARIABLE_NOT_FOUND 4058 Global variable not found.
ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE 4059 Function is not allowed in testing mode.
ERR_FUNCTION_NOT_CONFIRMED 4060 Function is not confirmed.
ERR_SEND_MAIL_ERROR 4061 Send mail error.
ERR_STRING_PARAMETER_EXPECTED 4062 String parameter expected.
ERR_INTEGER_PARAMETER_EXPECTED 4063 Integer parameter expected.
ERR_DOUBLE_PARAMETER_EXPECTED 4064 Double parameter expected.
ERR_ARRAY_AS_PARAMETER_EXPECTED 4065 Array as parameter expected.
ERR_HISTORY_WILL_UPDATED 4066 Requested history data in updating state.
ERR_END_OF_FILE 4099 End of file.
ERR_SOME_FILE_ERROR 4100 Some file error.
ERR_WRONG_FILE_NAME 4101 Wrong file name.
ERR_TOO_MANY_OPENED_FILES 4102 Too many opened files.
ERR_CANNOT_OPEN_FILE 4103 Cannot open file.
ERR_INCOMPATIBLE_ACCESS_TO_FILE 4104 Incompatible access to a file.
ERR_NO_ORDER_SELECTED 4105 No order selected.
ERR_UNKNOWN_SYMBOL 4106 Unknown symbol.
ERR_INVALID_PRICE_PARAM 4107 Invalid price.
ERR_INVALID_TICKET 4108 Invalid ticket.
ERR_TRADE_NOT_ALLOWED 4109 Trade is not allowed.
ERR_LONGS__NOT_ALLOWED 4110 Longs are not allowed.
ERR_SHORTS_NOT_ALLOWED 4111 Shorts are not allowed.
ERR_OBJECT_ALREADY_EXISTS 4200 Object exists already.
ERR_UNKNOWN_OBJECT_PROPERTY 4201 Unknown object property.
ERR_OBJECT_DOES_NOT_EXIST 4202 Object does not exist.
ERR_UNKNOWN_OBJECT_TYPE 4203 Unknown object type.
ERR_NO_OBJECT_NAME 4204 No object name.
ERR_OBJECT_COORDINATES_ERROR 4205 Object coordinates error.
ERR_NO_SPECIFIED_SUBWINDOW 4206 No specified subwindow.
Ichimoku Kinko Hyo modes enumeration
Ichimoku指标模式枚举
Constant Value Description
MODE_TENKANSEN 1 Tenkan-sen.
MODE_KIJUNSEN 2 Kijun-sen.
MODE_SENKOUSPANA 3 Senkou Span A.
MODE_SENKOUSPANB 4 Senkou Span B.
MODE_CHINKOUSPAN 5 Chinkou Span.
Indicators line identifiers
指标线标示符
指标线模式,使用在 iMACD(), iRVI() 和 iStochastic() 中:
Constant Value Description
MODE_MAIN 0 Base indicator line.
MODE_SIGNAL 1 Signal line.
指标线模式,使用在 iADX() 中:
Constant Value Description
MODE_MAIN 0 Base indicator line.
MODE_PLUSDI 1 +DI indicator line.
MODE_MINUSDI 2 -DI indicator line.
指标线模式,使用在 iBands(), iEnvelopes(), iEnvelopesOnArray(), iFractals() and iGator() 中:
Constant Value Description
MODE_UPPER 1 Upper line.
MODE_LOWER 2 Lower line.
Market information identifiers
市场信息标识
Constant Value Description
MODE_LOW 1 Low day price.
MODE_HIGH 2 High day price.
MODE_TIME 5 The last incoming quotation time.
MODE_BID 9 Last incoming bid price.
MODE_ASK 10 Last incoming ask price.
MODE_POINT 11 Point size.
MODE_DIGITS 12 Digits after decimal point.
MODE_SPREAD 13 Spread value in points.
MODE_STOPLEVEL 14 Stop level in points.
MODE_LOTSIZE 15 Lot size in the base currency.
MODE_TICKVALUE 16 Tick value.
MODE_TICKSIZE 17 Tick size.
MODE_SWAPLONG 18 Swap of the long position.
MODE_SWAPSHORT 19 Swap of the short position.
MODE_STARTING 20 Market starting date (usually used for future markets).
MODE_EXPIRATION 21 Market expiration date (usually used for future markets).
MODE_TRADEALLOWED 22 Trade is allowed for the symbol.
MessageBox return codes
消息窗口返回值
Constant Value Description
IDOK 1 OK button was selected.
IDCANCEL 2 Cancel button was selected.
IDABORT 3 Abort button was selected.
IDRETRY 4 Retry button was selected.
IDIGNORE 5 Ignore button was selected.
IDYES 6 Yes button was selected.
IDNO 7 No button was selected.
IDTRYAGAIN 10 Try Again button was selected.
IDCONTINUE 11 Continue button was selected.
MessageBox behavior flags
消息窗口行为代码
消息窗口显示的按钮种类:
Constant Value Description
MB_OK 0x00000000 The message box contains one push button: OK. This is the default.
MB_OKCANCEL 0x00000001 The message box contains two push buttons: OK and Cancel.
MB_ABORTRETRYIGNORE 0x00000002 The message box contains three push buttons: Abort, Retry, and Ignore.
MB_YESNOCANCEL 0x00000003 The message box contains three push buttons: Yes, No, and Cancel.
MB_YESNO 0x00000004 The message box contains two push buttons: Yes and No.
MB_RETRYCANCEL 0x00000005 The message box contains two push buttons: Retry and Cancel.
MB_CANCELTRYCONTINUE 0x00000006 Windows 2000: The message box contains three push buttons: Cancel, Try Again, Continue. Use this message box type instead of MB_ABORTRETRYIGNORE.
消息窗口显示图标的类型:
Constant Value Description
MB_ICONSTOP, MB_ICONERROR, MB_ICONHAND 0x00000010 A stop-sign icon appears in the message box.
MB_ICONQUESTION 0x00000020 A question-mark icon appears in the message box.
MB_ICONEXCLAMATION, MB_ICONWARNING 0x00000030 An exclamation-point icon appears in the message box.
MB_ICONINFORMATION, MB_ICONASTERISK 0x00000040 An icon consisting of a lowercase letter i in a circle appears in the message box.
消息窗口默认按钮设置:
Constant Value Description
MB_DEFBUTTON1 0x00000000 The first button is the default button. MB_DEFBUTTON1 is the default unless MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified.
MB_DEFBUTTON2 0x00000100 The second button is the default button.
MB_DEFBUTTON3 0x00000200 The third button is the default button.
MB_DEFBUTTON4 0x00000300 The fourth button is the default button.
Moving Average method enumeration
移动平均线模式枚举,iAlligator(), iEnvelopes(), iEnvelopesOnArray, iForce(), iGator(), iMA(), iMAOnArray(), iStdDev(), iStdDevOnArray(), iStochastic()这些会调用此枚举
Constant Value Description
MODE_SMA 0 Simple moving average,
MODE_EMA 1 Exponential moving average,
MODE_SMMA 2 Smoothed moving average,
MODE_LWMA 3 Linear weighted moving average.
Object properties enumeration
物件属性枚举
Constant Value Description
OBJPROP_TIME1 0 Datetime value to set/get first coordinate time part.
OBJPROP_PRICE1 1 Double value to set/get first coordinate price part.
OBJPROP_TIME2 2 Datetime value to set/get second coordinate time part.
OBJPROP_PRICE2 3 Double value to set/get second coordinate price part.
OBJPROP_TIME3 4 Datetime value to set/get third coordinate time part.
OBJPROP_PRICE3 5 Double value to set/get third coordinate price part.
OBJPROP_COLOR 6 Color value to set/get object color.
OBJPROP_STYLE 7 Value is one of STYLE_SOLID, STYLE_DASH, STYLE_DOT, STYLE_DASHDOT, STYLE_DASHDOTDOT constants to set/get object line style.
OBJPROP_WIDTH 8 Integer value to set/get object line width. Can be from 1 to 5.
OBJPROP_BACK 9 Boolean value to set/get background drawing flag for object.
OBJPROP_RAY 10 Boolean value to set/get ray flag of object.
OBJPROP_ELLIPSE 11 Boolean value to set/get ellipse flag for fibo arcs.
OBJPROP_SCALE 12 Double value to set/get scale object property.
OBJPROP_ANGLE 13 Double value to set/get angle object property in degrees.
OBJPROP_ARROWCODE 14 Integer value or arrow enumeration to set/get arrow code object property.
OBJPROP_TIMEFRAMES 15 Value can be one or combination (bitwise addition) of object visibility constants to set/get timeframe object property.
OBJPROP_DEVIATION 16 Double value to set/get deviation property for Standard deviation objects.
OBJPROP_FONTSIZE 100 Integer value to set/get font size for text objects.
OBJPROP_CORNER 101 Integer value to set/get anchor corner property for label objects. Must be from 0-3.
OBJPROP_XDISTANCE 102 Integer value to set/get anchor X distance object property in pixels.
OBJPROP_YDISTANCE 103 Integer value is to set/get anchor Y distance object property in pixels.
OBJPROP_FIBOLEVELS 200 Integer value to set/get Fibonacci object level count. Can be from 0 to 32.
OBJPROP_FIRSTLEVEL+ n 210 Fibonacci object level index, where n is level index to set/get. Can be from 0 to 31.
Object type enumeration
物件类型枚举
Constant Value Description
OBJ_VLINE 0 Vertical line. Uses time part of first coordinate.
OBJ_HLINE 1 Horizontal line. Uses price part of first coordinate.
OBJ_TREND 2 Trend line. Uses 2 coordinates.
OBJ_TRENDBYANGLE 3 Trend by angle. Uses 1 coordinate. To set angle of line use ObjectSet() function.
OBJ_REGRESSION 4 Regression. Uses time parts of first two coordinates.
OBJ_CHANNEL 5 Channel. Uses 3 coordinates.
OBJ_STDDEVCHANNEL 6 Standard deviation channel. Uses time parts of first two coordinates.
OBJ_GANNLINE 7 Gann line. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_GANNFAN 8 Gann fan. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_GANNGRID 9 Gann grid. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_FIBO 10 Fibonacci retracement. Uses 2 coordinates.
OBJ_FIBOTIMES 11 Fibonacci time zones. Uses 2 coordinates.
OBJ_FIBOFAN 12 Fibonacci fan. Uses 2 coordinates.
OBJ_FIBOARC 13 Fibonacci arcs. Uses 2 coordinates.
OBJ_EXPANSION 14 Fibonacci expansions. Uses 3 coordinates.
OBJ_FIBOCHANNEL 15 Fibonacci channel. Uses 3 coordinates.
OBJ_RECTANGLE 16 Rectangle. Uses 2 coordinates.
OBJ_TRIANGLE 17 Triangle. Uses 3 coordinates.
OBJ_ELLIPSE 18 Ellipse. Uses 2 coordinates.
OBJ_PITCHFORK 19 Andrews pitchfork. Uses 3 coordinates.
OBJ_CYCLES 20 Cycles. Uses 2 coordinates.
OBJ_TEXT 21 Text. Uses 1 coordinate.
OBJ_ARROW 22 Arrows. Uses 1 coordinate.
OBJ_LABEL 23 Text label. Uses 1 coordinate in pixels.
Object visibility enumeration
物件显示枚举
Constant Value Description
OBJ_PERIOD_M1 0x0001 Object shown is only on 1-minute charts.
OBJ_PERIOD_M5 0x0002 Object shown is only on 5-minute charts.
OBJ_PERIOD_M15 0x0004 Object shown is only on 15-minute charts.
OBJ_PERIOD_M30 0x0008 Object shown is only on 30-minute charts.
OBJ_PERIOD_H1 0x0010 Object shown is only on 1-hour charts.
OBJ_PERIOD_H4 0x0020 Object shown is only on 4-hour charts.
OBJ_PERIOD_D1 0x0040 Object shown is only on daily charts.
OBJ_PERIOD_W1 0x0080 Object shown is only on weekly charts.
OBJ_PERIOD_MN1 0x0100 Object shown is only on monthly charts.
OBJ_ALL_PERIODS 0x01FF Object shown is on all timeframes.
NULL 0 Object shown is on all timeframes.
EMPTY -1 Hidden object on all timeframes.
Predefined Arrow codes enumeration
预定义箭头代码枚举
Constant Value Description
SYMBOL_THUMBSUP 67 Thumb up symbol ( C ).
SYMBOL_THUMBSDOWN 68 Thumb down symbol ( D ).
SYMBOL_ARROWUP 241 Arrow up symbol ( ñ ).
SYMBOL_ARROWDOWN 242 Arrow down symbol ( ò ).
SYMBOL_STOPSIGN 251 Stop sign symbol ( û ).
SYMBOL_CHECKSIGN 252 Check sign symbol ( ü ).
Constant Value Description
1 Upwards arrow with tip rightwards ( ↱ ).
2 Downwards arrow with tip rightwards ( ↳ ).
3 Left pointing triangle ( ◄ ).
4 En Dash symbol (–).
SYMBOL_LEFTPRICE 5 Left sided price label.
SYMBOL_RIGHTPRICE 6 Right sided price label.
Series array identifier
系列数组标识符
Constant Value Description
MODE_OPEN 0 Open price.
MODE_LOW 1 Low price.
MODE_HIGH 2 High price.
MODE_CLOSE 3 Close price.
MODE_VOLUME 4 Volume, used in Lowest() and Highest() functions.
MODE_TIME 5 Bar open time, used in ArrayCopySeries() function.
Special constants
特殊常量
Constant Value Description
NULL 0 Indicates empty state of the string.
EMPTY -1 Indicates empty state of the parameter.
EMPTY_VALUE 0x7FFFFFFF Default custom indicator empty value.
CLR_NONE 0xFFFFFFFF Indicates empty state of colors.
WHOLE_ARRAY 0 Used with array functions. Indicates that all array elements will be processed.
Time frame enumeration
特殊常量
Constant Value Description
PERIOD_M1 1 1 minute.
PERIOD_M5 5 5 minutes.
PERIOD_M15 15 15 minutes.
PERIOD_M30 30 30 minutes.
PERIOD_H1 60 1 hour.
PERIOD_H4 240 4 hour.
PERIOD_D1 1440 Daily.
PERIOD_W1 10080 Weekly.
PERIOD_MN1 43200 Monthly.
0 (zero) 0 Time frame used on the chart.
Trade operation enumeration
交易类型
Constant Value Description
OP_BUY 0 Buying position.
OP_SELL 1 Selling position.
OP_BUYLIMIT 2 Buy limit pending position.
OP_SELLLIMIT 3 Sell limit pending position.
OP_BUYSTOP 4 Buy stop pending position.
OP_SELLSTOP 5 Sell stop pending position.
Uninitialize reason codes
末初始化理由代码
Constant Value Description
REASON_REMOVE 1 Expert removed from chart.
REASON_RECOMPILE 2 Expert recompiled.
REASON_CHARTCHANGE 3 symbol or timeframe changed on the chart.
REASON_CHARTCLOSE 4 Chart closed.
REASON_PARAMETERS 5 Inputs parameters was changed by user.
REASON_ACCOUNT 6 Other account activated.
Wingdings symbols
图形符号代码
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
160 161 162 163 164 165 166 167 • 168 169 170 171 172 ¬ 173 174 175
176 177 178 179 180 181 182 • 183 184 185 186 187 188 189 190 191
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
Web colors table
颜色表
Black DarkGreen DarkSlateGray Olive Green Teal Navy Purple
Maroon Indigo MidnightBlue DarkBlue DarkOliveGreen SaddleBrown ForestGreen OliveDrab
SeaGreen DarkGoldenrod DarkSlateBlue Sienna MediumBlue Brown DarkTurquoise DimGray
LightSeaGreen DarkViolet FireBrick MediumVioletRed MediumSeaGreen Chocolate Crimson SteelBlue
Goldenrod MediumSpringGreen LawnGreen CadetBlue DarkOrchid YellowGreen LimeGreen OrangeRed
DarkOrange Orange Gold Yellow Chartreuse Lime SpringGreen Aqua
DeepSkyBlue Blue Magenta Red Gray SlateGray Peru BlueViolet
LightSlateGray DeepPink MediumTurquoise DodgerBlue Turquoise RoyalBlue SlateBlue DarkKhaki
IndianRed MediumOrchid GreenYellow MediumAquamarine DarkSeaGreen Tomato RosyBrown Orchid
MediumPurple PaleVioletRed Coral CornflowerBlue DarkGray SandyBrown MediumSlateBlue Tan
DarkSalmon BurlyWood HotPink Salmon Violet LightCoral SkyBlue LightSalmon
Plum Khaki LightGreen Aquamarine Silver LightSkyBlue LightSteelBlue LightBlue
PaleGreen Thistle PowderBlue PaleGoldenrod PaleTurquoise LightGrey Wheat NavajoWhite
Moccasin LightPink Gainsboro PeachPuff Pink Bisque LightGoldenRod BlanchedAlmond
LemonChiffon Beige AntiqueWhite PapayaWhip Cornsilk LightYellow LightCyan Linen
Lavender MistyRose OldLace WhiteSmoke Seashell Ivory Honeydew AliceBlue
LavenderBlush MintCream Snow White
技术指标调用 [Technical Indicator calls]
double iAC( string symbol, int timeframe, int shift)
计算 Bill Williams' Accelerator/Decelerator oscillator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
示例:
double result=iAC(NULL, 0, 1);
double iAD( string symbol, int timeframe, int shift)
计算 Accumulation/Distribution indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
示例:
double result=iAD(NULL, 0, 1);
double iAlligator( string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int mode, int shift)
计算 Bill Williams' Alligator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
jaw_period – 颚线周期
jaw_shift – 颚线位移
teeth_period – 齿线周期
teeth_shift – 齿线位移
lips_period – 唇线周期
lips_shift – 唇线位移
ma_method – 移动平均线种类
applied_price – 应用价格类型
mode – 来源模式,MODE_GATORJAW,MODE_GATORTEETH 或MODE_GATORLIPS
shift – 位移数
double jaw_val=iAlligator(NULl, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA, PRICE_MEDIAN, MODE_GATORJAW, 1);
double iADX( string symbol, int timeframe, int period, int applied_price, int mode, int shift)
计算 Movement directional index 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
applied_price – 应用价格类型
mode – 来源模式,参见指标线分类枚举
shift – 位移数
if(iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,0)>iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,0)) return(0);
double iATR( string symbol, int timeframe, int period, int shift)
计算 Indicator of the average true range 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
shift – 位移数
if(iATR(NULL,0,12,0)>iATR(NULL,0,20,0)) return(0);
double iAO( string symbol, int timeframe, int shift)
计算 Bill Williams' Awesome oscillator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
double val=iAO(NULL, 0, 2);
double iBearsPower( string symbol, int timeframe, int period, int applied_price, int shift)
计算 Bears Power indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
applied_price – 应用价格类型
shift – 位移数
double val=iBearsPower(NULL, 0, 13,PRICE_CLOSE,0);
double iBands( string symbol, int timeframe, int period, int deviation, int bands_shift, int applied_price, int mode, int shift)
计算 Bollinger bands indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
deviation – 背离
bands_shift – Bands位移
applied_price – 应用价格类型
mode – 来源模式,参见指标线分类枚举
shift – 位移数
if(iBands(NULL,0,20,2,0,PRICE_LOW,MODE_LOWER,0)>Low[0]) return(0);
double iBandsOnArray( double array[], int total, int period, double deviation, int bands_shift, int mode, int shift)
从数组中计算 Bollinger bands indicator 的值
:: 输入参数
array[] – 数组数据
total – 总数据数量
period – 周期
deviation – 背离
bands_shift – Bands位移
applied_price – 应用价格类型
mode – 来源模式,参见指标线分类枚举
shift – 位移数
if(iBands(NULL,0,20,2,0,PRICE_LOW,MODE_LOWER,0)>Low[0]) return(0);
double iBullsPower( string symbol, int timeframe, int period, int applied_price, int shift)
计算 Bulls Power indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
applied_price – 应用价格类型
shift – 位移数
double val=iBullsPower(NULL, 0, 13,PRICE_CLOSE,0);
double iCCI( string symbol, int timeframe, int period, int applied_price, int shift)
计算 Commodity channel index 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
applied_price – 应用价格类型
shift – 位移数
if(iCCI(NULL,0,12,0)>iCCI(NULL,0,20,0)) return(0);
double iCCIOnArray( double array[], int total, int period, int shift)
从数组中计算 Commodity channel index 的值
:: 输入参数
array[] – 数组数据
total – 总数据数量
period – 周期
shift – 位移数
if(iCCIOnArray(ExtBuffer,total,12,0)>iCCI(NULL,0,20,PRICE_OPEN, 0)) return(0);
double iCustom( string symbol, int timeframe, string name, … , int mode, int shift)
计算 自定义指标 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
name – 自定义指标名称
… – 自定义指标参数
mode – 来源模式,参见指标线分类枚举
shift – 位移数
double val=iCustom(NULL, 0, "SampleInd",13,1,0);
double iDeMarker( string symbol, int timeframe, int period, int shift)
计算 DeMarker indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
shift – 位移数
double val=iDeMarker(NULL, 0, 13, 1);
double iEnvelopes( string symbol, int timeframe, int ma_period, int ma_method, int ma_shift, int applied_price, double deviation, int mode, int shift)
计算 Envelopes indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
ma_period – 移动平均线周期
ma_method – 移动平均线模式
ma_shift – 移动平均线位移
applied_price – 应用价格类型
deviation – 背离
mode – 来源模式,参见指标线分类枚举
shift – 位移数
double val=iEnvelopes(NULL, 0, 13,MODE_SMA,10,PRICE_CLOSE,0.2,MODE_UPPER,0);
double iEnvelopesOnArray( double array[], int total, int ma_period, int ma_method, int ma_shift, double deviation, int mode, int shift)
从数组中计算 Envelopes indicator 的值
:: 输入参数
array[] – 数组数据
total – 总数据数量
ma_period – 移动平均线周期
ma_method – 移动平均线模式
ma_shift – 移动平均线位移
deviation – 背离
mode – 来源模式,参见指标线分类枚举
shift – 位移数
double val=iEnvelopesOnArray(ExtBuffer, 0, 13, MODE_SMA, 0.2, MODE_UPPER,0 );
double iForce( string symbol, int timeframe, int period, int ma_method, int applied_price, int shift)
计算 Force index 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
ma_method – 移动平均线模式
applied_price – 应用价格类型
shift – 位移数
double val=iForce(NULL, 0, 13,MODE_SMA,PRICE_CLOSE,0);
double iFractals( string symbol, int timeframe, int mode, int shift)
计算 Fractals 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
mode – 来源模式,参见指标线分类枚举
shift – 位移数
double val=iFractals(NULL, 0, MODE_UPPER,0);
double iGator( string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int mode, int shift)
计算 Fractals 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
jaw_period – 颚线周期
jaw_shift – 颚线位移
teeth_period – 齿线周期
teeth_shift – 齿线位移
lips_period – 唇线周期
lips_shift – 唇线位移
ma_method – 移动平均线种类
applied_price – 应用价格类型
mode – 来源模式,参见指标线分类枚举
shift – 位移数
double jaw_val=iGator(NULL, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA, PRICE_MEDIAN, MODE_UPPER, 1);
double iIchimoku( string symbol, int timeframe, int tenkan_sen, int kijun_sen, int senkou_span_b, int mode, int shift)
计算 Ichimoku Kinko Hyo 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
tenkan_sen – 转换线
jkijun_sen – 基准线
senkou_span_b – 参考范围b
mode – 来源模式,参见指标线分类枚举
shift – 位移数
double tenkan_sen=iIchimoku(NULL, 0, 9, 26, 52, MODE_TENKANSEN, 1);
double iBWMFI( string symbol, int timeframe, int shift)
计算 Bill Williams Market Facilitation index 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
double val=iBWMFI(NULL, 0, 0);
double iMomentum( string symbol, int timeframe, int period, int applied_price, int shift)
计算 Momentum indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
applied_price – 应用价格类型
shift – 位移数
if(iMomentum(NULL,0,12,PRICE_CLOSE,0)>iMomentum(NULL,0,20,PRICE_CLOSE,0)) return(0);
double iMomentumOnArray( double array[], int total, int period, int shift)
从数组中计算 Momentum indicator 的值
:: 输入参数
array[] – 数组数据
total – 总数据数量
period – 周期
shift – 位移数
if(iMomentumOnArray(mybuffer,100,12,0)>iMomentumOnArray(mubuffer,100,20,0)) return(0);
double iMFI( string symbol, int timeframe, int period, int shift)
计算 Money flow index 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
shift – 位移数
if(iMFI(NULL,0,14,0)>iMFI(NULL,0,14,1)) return(0);
double iMA( string symbol, int timeframe, int period, int ma_shift, int ma_method, int applied_price, int shift)
计算 Moving average indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
ma_shift – 移动平均线位移
ma_method – 移动平均线模式
applied_price – 应用价格类型
shift – 位移数
AlligatorJawsBuffer=iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i);
double iMAOnArray( double array[], int total, int period, int ma_shift, int ma_method, int shift)
从数组中计算 Moving average indicator 的值
:: 输入参数
array[] – 数组数据
total – 总数据数量
period – 周期
ma_shift – 移动平均线位移
ma_method – 移动平均线模式
shift – 位移数
double macurrent=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,0);
double macurrentslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,0);
double maprev=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,1);
double maprevslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,1);
//—-
if(maprev=macurrentslow)
Alert("crossing up");
double iOsMA( string symbol, int timeframe, int fast_ema_period, int slow_ema_period, int signal_period, int applied_price, int shift)
计算 Moving Average of Oscillator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
fast_ema_period – 快均线周期
slow_ema_period – 慢均线周期
signal_period – 信号周期
applied_price – 应用价格类型
shift – 位移数
if(iOsMA(NULL,0,12,26,9,PRICE_OPEN,1)>iOsMA(NULL,0,12,26,9,PRICE_OPEN,0)) return(0);
double iMACD( string symbol, int timeframe, int fast_ema_period, int slow_ema_period, int signal_period, int applied_price, int mode, int shift)
计算 Moving averages convergence/divergence 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
fast_ema_period – 快均线周期
slow_ema_period – 慢均线周期
signal_period – 信号周期
applied_price – 应用价格类型
mode – 来源模式,参见指标线分类枚举
shift – 位移数
if(iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0)>iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0)) return(0);
double iOBV( string symbol, int timeframe, int applied_price, int shift)
计算 On Balance Volume indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
shift – 位移数
double val=iOBV(NULL, 0, PRICE_CLOSE, 1);
double iSAR( string symbol, int timeframe, double step, double maximum, int shift)
计算 On Balance Volume indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
step – 步幅
maximum – 最大值
shift – 位移数
if(iSAR(NULL,0,0.02,0.2,0)>Close[0]) return(0);
double iRSI( string symbol, void timeframe, int period, int applied_price, int shift)
计算 Relative strength index 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
applied_price – 应用价格类型
shift – 位移数
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>iRSI(NULL,0,14,PRICE_CLOSE,1)) return(0);
double iRSIOnArray( double array[], int total, int period, int shift)
从数组中计算 Relative strength index 的值
:: 输入参数
array[] – 数组数据
total – 总数据数量
period – 周期
shift – 位移数
if(iRSIOnBuffer(ExtBuffer,1000,14,0)>iRSI(NULL,0,14,PRICE_CLOSE,1)) return(0);
double iRVI( string symbol, int timeframe, int period, int mode, int shift)
计算 Relative Vigor index 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
mode – 来源模式,参见指标线分类枚举
shift – 位移数
double val=iRVI(NULL, 0, 10,MODE_MAIN,0);
double iStdDev( string symbol, int timeframe, int ma_period, int ma_method, int ma_shift, int applied_price, int shift)
计算 Standard Deviation indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
ma_period – 移动平均线周期
ma_method – 移动平均线模式
ma_shift – 移动平均线位移
applied_price – 应用价格类型
shift – 位移数
double val=iStdDev(NULL,0,10,MODE_EMA,0,PRICE_CLOSE,0);
double iStdDevOnArray( double array[], int total, int ma_period, int ma_method, int ma_shift, int shift)
从数组中计算 Standard Deviation indicator 的值
:: 输入参数
array[] – 数组数据
total – 总数据数量
ma_period – 移动平均线周期
ma_method – 移动平均线模式
ma_shift – 移动平均线位移
shift – 位移数
double val=iStdDevOnArray(ExtBuffer,100,10,MODE_EMA,0,0);
double iStochastic( string symbol, int timeframe, int %Kperiod, int %Dperiod, int slowing, int method, int price_field, int mode, int shift)
计算 Stochastic oscillator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
%Kperiod – %K线周期
%Dperiod – %D线周期
slowing – 减速量
method – 移动平均线种类
price_field – 价格领域参数: 0 – Low/High or 1 – Close/Close.
mode – 来源模式,参见指标线分类枚举
shift – 位移数
if(iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0)>iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_SIGNAL,0))
return(0);
double iWPR( string symbol, int timeframe, int period, int shift)
计算 Larry William's percent range indicator 的值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
period – 周期
shift – 位移数
if(iWPR(NULL,0,14,0)>iWPR(NULL,0,14,1)) return(0);
int iBars( string symbol, int timeframe)
返回制定图表的数据数
:: 输入参数
symbol – 通货标识
timeframe – 时间线
Print("Bar count on the 'EUROUSD' symbol with PERIOD_H1 is",iBars("EUROUSD",PERIOD_H1));
int iBarShift( string symbol, int timeframe, datetime time, bool exact=false)
在制定图表中搜索数据
:: 输入参数
symbol – 通货标识
timeframe – 时间线
time – 时间
exact – 是否精确的
datetime some_time=D'2004.03.21 12:00';
int shift=iBarShift("EUROUSD",PERIOD_M1,some_time);
Print("shift of bar with open time ",TimeToStr(some_time)," is ",shift);
double iClose( string symbol, int timeframe, int shift)
返回制定图表的收盘价
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
double iHigh( string symbol, int timeframe, int shift)
返回制定图表的最高价
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
double iLow( string symbol, int timeframe, int shift)
返回制定图表的最低价
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
double iOpen( string symbol, int timeframe, int shift)
返回制定图表的开盘价
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
datetime iTime( string symbol, int timeframe, int shift)
返回制定图表的时间
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
double iVolume( string symbol, int timeframe, int shift)
返回制定图表的成交量
:: 输入参数
symbol – 通货标识
timeframe – 时间线
shift – 位移数
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
int Highest( string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0)
返回制定图表的某段数据的最高值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
type – 数据类型
count – 计算范围
start – 开始点
double val;
// calculating the highest value in the range from 5 element to 25 element
// indicator charts symbol and indicator charts time frame
val=High[Highest(NULL,0,MODE_HIGH,20,4)];
int Lowest( string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0)
返回制定图表的某段数据的最高值
:: 输入参数
symbol – 通货标识
timeframe – 时间线
type – 数据类型
count – 计算范围
start – 开始点
double val=Low[Lowest(NULL,0,MODE_LOW,10,10)];
交易函数 [Trading Functions]
int HistoryTotal( )
返回历史数据的数量
// retrieving info from trade history
int i,hstTotal=HistoryTotal();
for(i=0;i<HSTTOTAL;I++)
{
//—- check selection result
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
{
Print("Access to history failed with error (",GetLastError(),")");
break;
}
// some work with order
}
bool OrderClose( int ticket, double lots, double price, int slippage, color Color=CLR_NONE)
对订单进行平仓操作。
:: 输入参数
ticket – 订单编号
lots – 手数
price – 平仓价格
slippage – 最高划点数
Color – 标记颜色
示例:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderClose(order_id,1,Ask,3,Red);
return(0);
}
bool OrderCloseBy( int ticket, int opposite, color Color=CLR_NONE)
对订单进行平仓操作。
:: 输入参数
ticket – 订单编号
opposite – 相对订单编号
Color – 标记颜色
示例:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderCloseBy(order_id,opposite_id);
return(0);
}
double OrderClosePrice( )
返回订单的平仓价
示例:
if(OrderSelect(ticket,SELECT_BY_POS)==true)
Print("Close price for the order ",ticket," = ",OrderClosePrice());
else
Print("OrderSelect failed error code is",GetLastError());
datetime OrderCloseTime( )
返回订单的平仓时间
示例:
if(OrderSelect(10,SELECT_BY_POS,MODE_HISTORY)==true)
{
datetime ctm=OrderOpenTime();
if(ctm>0) Print("Open time for the order 10 ", ctm);
ctm=OrderCloseTime();
if(ctm>0) Print("Close time for the order 10 ", ctm);
}
else
Print("OrderSelect failed error code is",GetLastError());
string OrderComment( )
返回订单的注释
示例:
string comment;
if(OrderSelect(10,SELECT_BY_TICKET)==false)
{
Print("OrderSelect failed error code is",GetLastError());
return(0);
}
comment = OrderComment();
// …
double OrderCommission( )
返回订单的佣金数
示例:
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("Commission for the order 10 ",OrderCommission());
else
Print("OrderSelect failed error code is",GetLastError());
bool OrderDelete( int ticket)
删除未启用的订单
:: 输入参数
ticket – 订单编号
示例:
if(Ask>var1)
{
OrderDelete(order_ticket);
return(0);
}
datetime OrderExpiration( )
返回代办订单的有效日期
示例:
if(OrderSelect(10, SELECT_BY_TICKET)==true)
Print("Order expiration for the order #10 is ",OrderExpiration());
else
Print("OrderSelect failed error code is",GetLastError());
double OrderLots( )
返回选定订单的手数
示例:
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("lots for the order 10 ",OrderLots());
else
Print("OrderSelect failed error code is",GetLastError());
int OrderMagicNumber( )
返回选定订单的指定编号
示例:
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("Magic number for the order 10 ", OrderMagicNumber());
else
Print("OrderSelect failed error code is",GetLastError());
bool OrderModify( int ticket, double price, double stoploss, double takeprofit, datetime expiration, color arrow_color=CLR_NONE)
对订单进行平仓操作。
:: 输入参数
ticket – 订单编号
price – 平仓价格
stoploss – 止损价
takeprofit – 获利价
expiration – 有效期
Color – 标记颜色
示例:
if(TrailingStop>0)
{
SelectOrder(12345,SELECT_BY_TICKET);
if(Bid-OrderOpenPrice()>oint*TrailingStop)
{
if(OrderStopLoss()<BID-POINT*TRAILINGSTOP)
{
OrderModify(OrderTicket(),Ask-10*Point,Ask-35*Point,OrderTakeProfit(),0,Blue);
return(0);
}
}
}
double OrderOpenPrice( )
返回选定订单的买入价
示例:
if(OrderSelect(10, SELECT_BY_POS)==true)
Print("open price for the order 10 ",OrderOpenPrice());
else
Print("OrderSelect failed error code is",GetLastError());
datetime OrderOpenTime( )
返回选定订单的买入时间
示例:
if(OrderSelect(10, SELECT_BY_POS)==true)
Print("open time for the order 10 ",OrderOpenTime());
else
Print("OrderSelect failed error code is",GetLastError());
void OrderPrint( )
将订单打印到窗口上
示例:
if(OrderSelect(10, SELECT_BY_TICKET)==true)
OrderPrint();
else
Print("OrderSelect failed error code is",GetLastError());
bool OrderSelect( int index, int select, int pool=MODE_TRADES)
选定订单
:: 输入参数
index – 订单索引
select – 选定模式,SELECT_BY_POS,SELECT_BY_TICKET
pool – Optional order pool index. Used when select parameter is SELECT_BY_POS.It can be any of the following values:
MODE_TRADES (default)- order selected from trading pool(opened and pending orders),
MODE_HISTORY – order selected from history pool (closed and canceled order).
示例:
if(OrderSelect(12470, SELECT_BY_TICKET)==true)
{
Print("order #12470 open price is ", OrderOpenPrice());
Print("order #12470 close price is ", OrderClosePrice());
}
else
Print("OrderSelect failed error code is",GetLastError());
int OrderSend( string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)
发送订单
:: 输入参数
symbol – 通货标示
cmd – 购买方式
volume – 购买手数
price – 平仓价格
slippage – 最大允许滑点数
stoploss – 止损价
takeprofit – 获利价
comment – 注释
magic – 自定义编号
expiration – 过期时间(只适用于待处理订单)
arrow_color – 箭头颜色
示例:
int ticket;
if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25)
{
ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,Ask-25*Point,Ask+25*Point,"My order #2",16384,0,Green);
if(ticket<0)
{
Print("OrderSend failed with error #",GetLastError());
return(0);
}
}
double OrderStopLoss( )
返回选定订单的止损
示例:
if(OrderSelect(ticket,SELECT_BY_POS)==true)
Print("Stop loss value for the order 10 ", OrderStopLoss());
else
Print("OrderSelect failed error code is",GetLastError());
int OrdersTotal( )
返回总订单数
示例:
int handle=FileOpen("OrdersReport.csv",FILE_WRITE|FILE_CSV,"t");
if(handle<0) return(0);
// write header
FileWrite(handle,"#","open price","open time","symbol","lots");
int total=OrdersTotal();
// write open orders
for(int pos=0;pos<TOTALOS++)
{
if(OrderSelect(pos,SELECT_BY_POS)==false) continue;
FileWrite(handle,OrderTicket(),OrderOpenPrice(),OrderOpenTime(),OrderSymbol(),OrderLots());
}
FileClose(handle);
int OrdersTotal( )
返回总订单数
示例:
if(OrderSelect(order_id, SELECT_BY_TICKET)==true)
Print("Swap for the order #", order_id, " ",OrderSwap());
else
Print("OrderSelect failed error code is",GetLastError());
double OrderSwap( )
返回指定订单的汇率
示例:
if(OrderSelect(order_id, SELECT_BY_TICKET)==true)
Print("Swap for the order #", order_id, " ",OrderSwap());
else
Print("OrderSelect failed error code is",GetLastError());
string OrderSymbol( )
返回指定订单的通货标识
示例:
if(OrderSelect(12, SELECT_BY_POS)==true)
Print("symbol of order #", OrderTicket(), " is ", OrderSymbol());
else
Print("OrderSelect failed error code is",GetLastError());
double OrderTakeProfit( )
返回指定订单的获利点数
示例:
if(OrderSelect(12, SELECT_BY_POS)==true)
Print("Order #",OrderTicket()," profit: ", OrderTakeProfit());
else
Print("OrderSelect() âåðíóë îøèáêó – ",GetLastError());
int OrderTicket( )
返回指定订单的编号
示例:
if(OrderSelect(12, SELECT_BY_POS)==true)
order=OrderTicket();
else
Print("OrderSelect failed error code is",GetLastError());
int OrderType( )
返回指定订单的类型
示例:
int order_type;
if(OrderSelect(12, SELECT_BY_POS)==true)
{
order_type=OrderType();
// …
}
else
Print("OrderSelect() âåðíóë îøèáêó – ",GetLastError());
窗口函数 [Window Functions]
double PriceOnDropped( )
Returns price part of dropped point where expert or script was dropped. This value is valid when expert or script dropped by mouse.
Note: For custom indicators this value is undefined.
示例:
double drop_price=PriceOnDropped();
datetime drop_time=TimeOnDropped();
//—- may be undefined (zero)
if(drop_time>0)
{
ObjectCreate("Dropped price line", OBJ_HLINE, 0, drop_price);
ObjectCreate("Dropped time line", OBJ_VLINE, 0, drop_time);
}
datetime TimeOnDropped( )
Returns time part of dropped point where expert or script was dropped. This value is valid when expert or script dropped by mouse.
Note: For custom indicators this value is undefined.
示例:
double drop_price=PriceOnDropped();
datetime drop_time=TimeOnDropped();
//—- may be undefined (zero)
if(drop_time>0)
{
ObjectCreate("Dropped price line", OBJ_HLINE, 0, drop_price);
ObjectCreate("Dropped time line", OBJ_VLINE, 0, drop_time);
}
int WindowFind( string name)
返回窗口的索引号
:: 输入参数
name – 指标简称
示例:
int win_idx=WindowFind("MACD(12,26,9)");
int WindowHandle( string symbol, int timeframe)
返回窗口的句柄
:: 输入参数
symbol – 通货标识
timeframe – 时间线
示例:
int win_handle=WindowHandle("USDX",PERIOD_H1);
if(win_handle!=0)
Print("Window with USDX,H1 detected. Rates array will be copied immediately.");
bool WindowIsVisible( int index)
返回窗口是否可见
:: 输入参数
index – 窗口索引号
示例:
int maywin=WindowFind("MyMACD");
if(maywin>-1 && WindowIsVisible(maywin)==true)
Print("window of MyMACD is visible");
else
Print("window of MyMACD not found or is not visible");
int WindowOnDropped( )
Returns window index where expert, custom indicator or script was dropped. This value is valid when expert, custom indicator or script dropped by mouse.
示例:
if(WindowOnDropped()!=0)
{
Print("Indicator 'MyIndicator' must be applied to main chart window!");
return(false);
}
int WindowsTotal( )
返回窗口数
示例:
Print("Windows count = ", WindowsTotal());
int WindowXOnDropped( )
Returns x-axis coordinate in pixels were expert or script dropped to the chart. See also WindowYOnDropped(), WindowOnDropped()
示例:
Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped());/div>
int WindowYOnDropped( )
Returns y-axis coordinate in pixels were expert or script dropped to the chart. See also WindowYOnDropped(), WindowOnDropped()
示例:
Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped());
斑马投诉温馨提示:投资有风险,交易需谨慎!
未经允许不得转载:Eagle Trader » MT4 MQL4编程基础语法学习