先列出需求,創建一條垂直線,價格漲時,顏色為白色,跌時為紅色。這樣這個實例裡會包括創建一條線、if語句、順帶用一下顏色數據類型。
新建一個自定義指標:
名稱:Indicators\telihai-11
作者:Copyright 2012, telihai.
鏈接:http://www.telihai.com/
#property copyright "Copyright 2012, telihai."
#property link "http://www.telihai.com/"
#property version "1.00"
#property indicator_chart_window
// 聲明一個全局變量。
double telihai_last_price = 0;
int OnInit(){
ObjectCreate(0, "telihai_vline", OBJ_VLINE, 0, 0, 0);
return(0);
}
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[]){
// 垂直線的時間坐標為當前時間。
ObjectSetInteger(0, "telihai_vline", OBJPROP_TIME, time[rates_total-1]);
// 當前價是否大於等於“telihai_last_price”。
if(telihai_last_price <= close[rates_total-1]){
ObjectSetInteger(0, "telihai_vline", OBJPROP_COLOR, clrWhite);
} else {
ObjectSetInteger(0, "telihai_vline", OBJPROP_COLOR, clrRed);
}
// 將當前價賦於“telihai_last_price”。
telihai_last_price = close[rates_total-1];
return(rates_total);
}
當“OnCalculate()”函數第一次運行的時候,“telihai_last_price”的值為0,所以物件的顏色一定是白色,然後會把“close[rates_total-1]”(當前價格)的值賦值給“ telihai_last_price”,當下次運行“OnCalculate()”的時候,“close[rates_total-1]”的值已經更新,但是“telihai_last_price”還是前一次的值,所以可以比較出價格是在漲還是在跌。
“telihai_last_price”是一個全局變量,如果給它放到“OnCalculate()”裡聲明,那麼每次運行“OnCalculate()”的時候都會聲明一個,當函數返回的時候這個變量就被釋放了,無法保留上一次的價格。前面講過了。
