Common functions
Alert()
Comment()
GetLastError()
GetTickCount()
IsDemo()
IsTesting()
IsTradeAllowed()
MarketInfo()
MessageBox()
Period()
PlaySound()
Print()
RefreshRates()
SendMail()
ServerAddress()
Sleep()
SpeechText()
Symbol()
void Alert( / ...)
Displays a dialog box containing a user-defined data. Parameters can be of any type. Arrays cannot be passed to the Alert function. Data of bool, datetime and color types will be printed as it's numeric presentation. To print values of datetime type as string convert it's by TimeToStr() function.
See also: Comment() and Print() functions.
Parameters
... / - / Any values, separated by commas.
Sample
if(Close[0]>SignalLevel)
Alert("Close price coming ", Close[0],"!!!");
void Comment( / ...)
Prints some message to the left top corner of the chart. Parameters can be of any type. Arrays cannot be passed to the Comment function. Arrays should be output elementwise. Data of bool, datetime and color types will be printed as it's numeric presentation. To print values of datetime type as string convert it's by TimeToStr() function.
See also: Alert() and Print() functions.
Parameters
... / - / Any values, separated by commas.
Sample
Comment("Account free margin is ", AccountFreeMargin(),"\n",
"Current time is ", TimeToStr(CurTime));
int GetLastError( / )
Returns last occurred error after an operation and sets internal last error value to zero. Error codes listed at Error Codes page.
Sample
FileWrite(handle, "Bars total = ", Bars);
if(GetLastError()!=0) Alert("Some error message");
int GetTickCount( / )
The GetTickCount function retrieves the number of milliseconds that have elapsed since the system was started. It is limited to the resolution of the system timer.
Sample
int start=GetTickCount();
// do some hard calculation...
Print("Calculation time is ", GetTickCount()-start, " milliseconds.");
bool IsDemo( / )
Returns true if expert runs on demo account, otherwise returns false.
Sample
if(IsDemo()) Print("I am working on demo account");
else Print("I am working on real account");
bool IsTesting( / )
Returns true if expert runs in the testing mode, otherwise returns false.
Sample
if(IsTesting()) Print("I am testing now");
bool IsTradeAllowed( / )
Returns true if trade is allowed for the expert, otherwise returns false.
Sample
if(IsTradeAllowed()) Print("Trade allowed");
double MarketInfo( / stringsymbol, inttype)
Returns value from Market watch window.
Parameters
symbol / - / Instrument symbol.
type / - / Returning data type index. It can be any one of the Market information identifiers value.
Sample
double var;
var=MarketInfo("EURUSD",MODE_BID);
int MessageBox( / stringtext=NULL, stringcaption=NULL, intflags=EMPTY)
The MessageBox function creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons.
If the function succeeds, the return value is one of the MessageBox return code values.
Parameters
text / - / Optional text that contains the message to be displayed.
caption / - / Optional text that contains the dialog box title. If this parameter is NULL, the title will be is name of expert.
flags / - / Specifies the contents and behavior of the dialog box. This optional parameter can be a combination of flags from the following groups of flags.
Sample
#include <WinUser32.h>
if(ObjectCreate("text_object", OBJ_TEXT, 0, T'2004.02.20 12-30', 1.0045)==false)
{
int ret=MessageBox("ObjectCreate() fails with code"+IntToStr(GetLastError())+"\nContinue?", "Question", MB_YESNO|MB_ICONQUESTION);
if(ret==IDNO) return(false);
}
// continue
int Period( / )
Returns the number of minutes defining the used period (chart's timeframe).
Sample
Print("Period is ", Period());
void PlaySound( / stringfilename)
Function plays sound file. File must be located at the terminal_dir\sounds directory or its subdirectory.
Parameters
filename / - / Sound file name.
Sample
if(IsDemo()) PlaySound("alert.wav");
void Print( / ...)
Prints some message to the experts log. Parameters can be of any type. Arrays cannot be passed to the Print function. Arrays should be printed elementwise. Data of bool, datetime and color types will be printed as it's numeric presentation. To print values of datetime type as string convert it's by TimeToStr() function.
See also: Alert() and Comment() functions.
Parameters
... / - / Any values, separated by commas.
Sample
Print("Account free margin is ", AccountFreeMargin());
Print("Current time is ", TimeToStr(CurTime));
// Array printing
for(int i=0;i<10;i++)
Print(Close[i]);
bool RefreshRates( / )
Refreshing data in the built-in variables and series arrays. This function is used when expert advisor calculates in long time and need refreshing data. Returns true if data is refreshed, otherwise false.
Sample
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( / stringsubject, stringsome_text)
Sends mail to address set in the Tools->Options->EMail tab if enabled.
Parameters
subject / - / Subject text.
some_text / - / Mail body.
Sample
double lastclose=Close[0];
if(lastclose<my_signal)
SendMail("from your expert", "Price dropped down to "+DoubleToStr(lastclose));
string ServerAddress( / )
Returns connected server address in form of a text string.
Sample
Print("Server address is ", ServerAddress());
void Sleep( / intmilliseconds)
The Sleep function suspends the execution of the current expert for a specified interval.
Parameters
milliseconds / - / Sleeping interval in milliseconds.
Sample
Sleep(5);
void SpeechText( / stringtext, intlang_mode=SPEECH_ENGLISH)
Computer speaks some text.
Parameters
text / - / Speaking text.
lang_mode / - / SPEECH_ENGLISH (by default) or SPEECH_NATIVE values.
Sample
double lastclose=Close[0];
SpeechText("Price dropped down to "+DoubleToStr(lastclose));
string Symbol( / )
Returns a text string with the name of the current financial instrument.
Sample
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
if(OrderType()>OP_SELL || OrderSymbol()!=Symbol()) continue;
// do some orders processing...
}

公用函数 [Common Functions]

void Alert( ... )
弹出一个显示信息的警告窗口
:: 输入参数
... - 任意值,如有多个可用逗号分割
示例:
if(Close[0]>SignalLevel)
Alert("Close price coming ", Close[0],"!!!");
string ClientTerminalName()
返回客户终端名称
示例:
Print("Terminal name is ",ClientTerminalName());
string CompanyName()
返回公司名称
示例:
Print("Company name is ",CompanyName());
void Comment( ... )
显示信息在走势图左上角
:: 输入参数
... - 任意值,如有多个可用逗号分割
示例:
double free=AccountFreeMargin();
Comment("Account free margin is ",DoubleToStr(free,2),"\n","Current time is ",TimeToStr(CurTime()));
int GetLastError()
取最后错误在错误中的索引位置
示例:
int err;
int handle=FileOpen("somefile.dat", FILE_READ|FILE_BIN);
if(handle<1)
{
err=GetLastError();
Print("error(",err,"): ",ErrorDescription(err));
return(0);
}
int GetTickCount()
取时间标记,函数取回用毫秒标示的时间标记。
示例:
int start=GetTickCount();
// do some hard calculation...
Print("Calculation time is ", GetTickCount()-start, " milliseconds.");
void HideTestIndicators(bool hide)
使用此函数设置一个在Expert Advisor的开关,在测试完成之前指标不回显示在图表上。
:: 输入参数
hide - 是否隐藏 True或者False
示例:
HideTestIndicators(true);
bool IsConnected()
返回客户端是否已连接
示例:
if(!IsConnected())
{
Print("Connection is broken!");
return(0);
}
// Expert body that need opened connection
// ...
bool IsDemo()
返回是否是模拟账户
示例:
if(IsDemo()) Print("I am working on demo account");
else Print("I am working on real account");
bool IsDllsAllowed()
返回是否允许载入Dll文件
示例:
#import "user32.dll"
int MessageBoxA(int hWnd ,string szText, string szCaption,int nType);
...
...
if(IsDllsAllowed()==false)
{
Print("DLL call is not allowed. Experts cannot run.");
return(0);
}
// expert body that calls external DLL functions
MessageBoxA(0,"an message","Message",MB_OK);
bool IsLibrariesAllowed()
返回是否允许载入库文件
示例:
#import "somelibrary.ex4"
int somefunc();
...
...
if(IsLibrariesAllowed()==false)
{
Print("Library call is not allowed. Experts cannot run.");
return(0);
}
// expert body that calls external DLL functions
somefunc();
bool IsStopped()
返回是否处于停止状态
示例:
while(expr!=false)
{
if(IsStopped()==true) return(0);
// long time procesing cycle
// ...
}
bool IsTesting()
返回是否处于测试模式
示例:
if(IsTesting()) Print("I am testing now");
bool IsTradeAllowed()
返回是否允许交易
示例:
if(IsTradeAllowed()) Print("Trade allowed");
double MarketInfo( string symbol, int type)
返回市场当前情况
:: 输入参数
symbol - 通货代码
type - 返回结果的类型
示例:
double var;
var=MarketInfo("EURUSD",MODE_BID);
int MessageBox( string text=NULL, string caption=NULL, int flags=EMPTY)
弹出消息窗口,返回消息窗口的结果
:: 输入参数
text - 窗口显示的文字
caption - 窗口上显示的标题
flags - 窗口选项开关
示例:
#include
if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)==false)
{
int ret=MessageBox("ObjectCreate() fails with code "+GetLastError()+"\nContinue?", "Question", MB_YESNO|MB_ICONQUESTION);
if(ret==IDNO) return(false);
}
// continue
int Period()
返回图表时间线的类型
示例:
Print("Period is ", Period());
void PlaySound( string filename)
播放音乐文件
:: 输入参数
filename - 音频文件名
示例:
if(IsDemo()) PlaySound("alert.wav");
void Print( ... )
将文本打印在结果窗口内
:: 输入参数
... - 任意值,复数用逗号分割
示例:
Print("Account free margin is ", AccountFreeMargin());
Print("Current time is ", TimeToStr(CurTime()));
double pi=3.141592653589793;
Print("PI number is ", DoubleToStr(pi,8));
// Output: PI number is 3.14159265
// Array printing
for(int i=0;i<10;i++)
Print(Close[i]);
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", "Price dropped down to "+DoubleToStr(lastclose));
string ServerAddress()
返回服务器地址
示例:
Print("Server address is ", ServerAddress());
void Sleep( int milliseconds)
设置线程暂停时间
:: 输入参数
milliseconds - 暂停时间 1000 = 1秒
示例:
Sleep(5);
void SpeechText( string text, int lang_mode=SPEECH_ENGLISH)
使用Speech进行语音输出
:: 输入参数
text - 阅读的文字
lang_mode - 语音模式 SPEECH_ENGLISH (默认的) 或 SPEECH_NATIVE
示例:
double lastclose=Close[0];
SpeechText("Price dropped down to "+DoubleToStr(lastclose));
string Symbol()
返回当前当前通货的名称
示例:
int total=OrdersTotal();
for(int pos=0;pos<TOTAL;POS++)
{
// 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
}
//...
}