MQL5中“类型转换可能导致数据丢失”警告的解决方法
解决MQL5中iAMA句柄赋值的“类型转换可能导致数据丢失”警告
问题
编写MQL5指标代码时,调用内置函数iAMA并将返回值赋值给int类型变量,编译器始终提示“类型转换可能导致数据丢失”警告。代码可正常编译运行,但希望消除该警告以规范代码。
原因
MQL5中所有指标/函数的句柄(包括iAMA的返回值)实际为long类型,而非int类型。当将long类型值赋值给int类型变量时,若句柄数值超出int的取值范围(-2147483648 到 2147483647),会导致高位数据丢失,因此编译器触发警告。
解决方案
- 将存储句柄的变量类型从
int改为long,与iAMA的返回值类型匹配 - 确保所有使用该句柄的函数调用参数类型一致,避免隐式类型转换
修改后的代码
// --- Information Properties #property description "Adaptive Moving Average Function Test" //--- Core Properties #property indicator_chart_window #property indicator_buffers 1 #property indicator_plots 1 // --- Styling & Labels Properties #property indicator_type1 DRAW_LINE #property indicator_color1 clrBlack #property indicator_width1 2 #property indicator_label1 "Adaptive Moving Average" //--- Constant Variables const int ama_period = 34; const int ama_fast_ma = 2; const int ama_slow_ma = 34; //--- Global Variables double ama_src = PRICE_MEDIAN; //--- Buffers double ama_buffer[]; //--- Handles long ama_buffer_handle; // 修改:将int改为long //+------------------------------------------------------------------+ //| Indicator Initialization | //+------------------------------------------------------------------+ int OnInit() { //--- Buffers Assignment SetIndexBuffer(0, ama_buffer, INDICATOR_DATA); //--- Accuracy Setting IndicatorSetInteger(INDICATOR_DIGITS, _Digits); //--- First Bar Setting PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, ama_period - 1); //--- Line Shifts Calculations PlotIndexSetInteger(0, PLOT_SHIFT, 0); //--- Labels Calculations PlotIndexSetString(0, PLOT_LABEL, "AMA"); //--- Handles Calculations ama_buffer_handle = iAMA(NULL, 0, ama_period, ama_fast_ma, ama_slow_ma, 0, ama_src); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| OnCalculate function | //+------------------------------------------------------------------+ 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[]) { if(rates_total < ama_period) { return(0); } //--- Troubleshooting: Data Calculation int calculated = BarsCalculated(ama_buffer_handle); if(calculated < rates_total) { Print("Not all data of ama_buffer_handle is calculated (", calculated, " bars). Error ", GetLastError()); return(0); } //--- Troubleshooting: Data Copying int to_copy; if(prev_calculated > rates_total || prev_calculated < 0) { to_copy = rates_total; } else { to_copy = rates_total - prev_calculated; if(prev_calculated > 0) { to_copy++; } } //--- Copy & Validate Buffers if(CopyBuffer(ama_buffer_handle, 0, 0, to_copy, ama_buffer) <= 0) { Print("getting ama_buffer_handle is failed! Error ", GetLastError()); return(0); } if(IsStopped()) { return(0); } return(rates_total); }
内容的提问来源于stack exchange,提问作者Ken
相关产品推荐
相关产品推荐

