I have tried those but it is still not creating the file as expected. Updated code is as follows:
#property copyright "Copyright 2023, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" //////////////////////////////////////////////////////////////////////// // Included Classes //////////////////////////////////////////////////////////////////////// #include <Trade\Trade.mqh> #include <Trade\PositionInfo.mqh> MqlTick cT; CTrade trade; CPositionInfo m_position; // object of CPositionInfo class COrderInfo m_order; //////////////////////////////////////////////////////////////////////// // Inputs Menu //////////////////////////////////////////////////////////////////////// static long InpMagicNumber = 876251; // Magic number input double InpLotSize = 1; // Lot Size Per Positions input double MaxInpLotSize = 10; // Max Lots input int MaxInpPositions = 5; // Max Positions Open // User input variables input int InpMaPeriod1 = 21; // EMA PERIOD 1 input int InpMaPeriod2 = 50; // EMA PERIOD 2 input int InpMaPeriod3 = 100; // EMA PERIOD 3 input int shift = 0; // Number to shift candle high/low // Ema indicator handles int ma_handle1; int ma_handle2; int ma_handle3; // Excel handle int excel_handle; // Indicator Buffers double ma_prices1[]; double ma_prices2[]; double ma_prices3[]; double ma_value1; double ma_value2; double ma_value3; //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int OnInit() { //--- correct way of working in the "file sandbox" ResetLastError(); excel_handle = FileOpen("EMA_Price_Deviation_Data.csv",FILE_CSV|FILE_READ|FILE_WRITE|FILE_SHARE_READ|FILE_SHARE_WRITE); if(excel_handle != INVALID_HANDLE) { FileWrite(excel_handle,"Symbol","EMA PRICE","CANDLE HIGH","DEVIATION"); Print("File Open OK"); } else { Print("Operation File Open failed, error ",GetLastError()); } ma_handle1 = iMA(_Symbol,PERIOD_CURRENT,InpMaPeriod1,0,MODE_EMA,PRICE_CLOSE); if(ma_handle1 == INVALID_HANDLE) { Alert("Failed to create indicator EMA 1 Handle"); return INIT_FAILED; } ma_handle2 = iMA(_Symbol,PERIOD_CURRENT,InpMaPeriod2,0,MODE_EMA,PRICE_CLOSE); if(ma_handle2 == INVALID_HANDLE) { Alert("Failed to create indicator EMA 2 Handle"); return INIT_FAILED; } ma_handle3 = iMA(_Symbol,PERIOD_CURRENT,InpMaPeriod3,0,MODE_EMA,PRICE_CLOSE); if(ma_handle3 == INVALID_HANDLE) { Alert("Failed to create indicator EMA 3 Handle"); return INIT_FAILED; } ArraySetAsSeries(ma_prices1,true); ArraySetAsSeries(ma_prices2,true); ArraySetAsSeries(ma_prices3,true); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { CopyBuffer(ma_handle1,0,0,3,ma_prices1); CopyBuffer(ma_handle2,0,0,3,ma_prices2); CopyBuffer(ma_handle3,0,0,3,ma_prices3); if(ArraySize(ma_prices1) < 1 || ArraySize(ma_prices2) < 1 || ArraySize(ma_prices3) < 1) { return; } ma_value1 = ma_prices1[0]; ma_value2 = ma_prices2[0]; ma_value3 = ma_prices3[0]; // Grab the candle OHL to add to the spread sheet double open = iOpen(Symbol(),Period(),shift); double high = iHigh(Symbol(),Period(),shift); double low = iLow(Symbol(),Period(),shift); if(low > ma_value1) { CreateExcelData(high,ma_value1,ma_value2,ma_value3); } else if(high < ma_value1) { CreateExcelData(low,ma_value1,ma_value2,ma_value3); } } void CreateExcelData(double candle_high_low, double chosen_band_value,double band2, double band3) { double price_difference; if(candle_high_low > chosen_band_value) { price_difference = candle_high_low - chosen_band_value; } else if(candle_high_low < chosen_band_value) { price_difference = chosen_band_value - candle_high_low; } if(excel_handle > 0) { FileWrite(excel_handle, _Symbol, DoubleToString(chosen_band_value),DoubleToString(candle_high_low),DoubleToString(price_difference)); Print("Writing to file - line 258"); } }
I close the file on the DeOnit section. Just removed that function for less clutter. Regarding specifying ANSI or unicode. That I am not sure where or how to do that tbh. I am not even sure if I am doing this correctly as I am attempting to use it as part of an EA, which I am not sure if you are supposed to do or not.
Regarding the expert log. I did do that. Everything appears to be working correctly and no errors are generated. Hence why I am uncertain.When attempting to print the pathway I receive this:
2023.06.26 13:42:27.102 2023.06.01 00:00:00 File path: C:\Users\user\AppData\Roaming\MetaQuotes\Tester\9B101088254A9C260A9790D5079A7B11\Agent-127.0.0.1-3000
I was under the impression that would provide the pathway to the current directory but obviously not.
Here is the full code:
//+------------------------------------------------------------------+ //| Output_CSV_Excel.mq5 | //| Copyright 2023, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2023, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" //////////////////////////////////////////////////////////////////////// // Included Classes //////////////////////////////////////////////////////////////////////// #include <Trade\Trade.mqh> #include <Trade\PositionInfo.mqh> MqlTick cT; CTrade trade; CPositionInfo m_position; // object of CPositionInfo class COrderInfo m_order; //////////////////////////////////////////////////////////////////////// // Inputs Menu //////////////////////////////////////////////////////////////////////// static long InpMagicNumber = 876251; // Magic number input double InpLotSize = 1; // Lot Size Per Positions input double MaxInpLotSize = 10; // Max Lots input int MaxInpPositions = 5; // Max Positions Open // User input variables input int InpMaPeriod1 = 21; // EMA PERIOD 1 input int InpMaPeriod2 = 50; // EMA PERIOD 2 input int InpMaPeriod3 = 100; // EMA PERIOD 3 input int shift = 0; // Number to shift candle high/low // Ema indicator handles int ma_handle1; int ma_handle2; int ma_handle3; // Excel handle int excel_handle; // Indicator Buffers double ma_prices1[]; double ma_prices2[]; double ma_prices3[]; // Arrays used to calculate the price deviation from each inputed ema band value double candle_high_prices[]; // Arrays used to calculate the price deviation from each inputed ema band value double price_deviation1[]; double price_deviation2[]; double price_deviation3[]; // double ma_value1; double ma_value2; double ma_value3; //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int OnInit() { //--- correct way of working in the "file sandbox" ResetLastError(); string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH); Print("---------------------------------------------------------------------------------------------------------"); Print("---------------------------------------------------------------------------------------------------------"); Print("File path: ",terminal_data_path); Print("---------------------------------------------------------------------------------------------------------"); Print("---------------------------------------------------------------------------------------------------------"); excel_handle = FileOpen("EMA_Price_Deviation_Data.csv",FILE_CSV|FILE_READ|FILE_WRITE|FILE_SHARE_READ|FILE_SHARE_WRITE); if(excel_handle != INVALID_HANDLE) { FileWrite(excel_handle,"Symbol","EMA PRICE","CANDLE HIGH","DEVIATION"); Print("File Open OK"); } else { Print("Operation File Open failed, error ",GetLastError()); } ma_handle1 = iMA(_Symbol,PERIOD_CURRENT,InpMaPeriod1,0,MODE_EMA,PRICE_CLOSE); if(ma_handle1 == INVALID_HANDLE) { Alert("Failed to create indicator EMA 1 Handle"); return INIT_FAILED; } ma_handle2 = iMA(_Symbol,PERIOD_CURRENT,InpMaPeriod2,0,MODE_EMA,PRICE_CLOSE); if(ma_handle2 == INVALID_HANDLE) { Alert("Failed to create indicator EMA 2 Handle"); return INIT_FAILED; } ma_handle3 = iMA(_Symbol,PERIOD_CURRENT,InpMaPeriod3,0,MODE_EMA,PRICE_CLOSE); if(ma_handle3 == INVALID_HANDLE) { Alert("Failed to create indicator EMA 3 Handle"); return INIT_FAILED; } ArraySetAsSeries(ma_prices1,true); ArraySetAsSeries(ma_prices2,true); ArraySetAsSeries(ma_prices3,true); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { if(ma_handle1 != INVALID_HANDLE) { IndicatorRelease(ma_handle1); } if(ma_handle2 != INVALID_HANDLE) { IndicatorRelease(ma_handle2); } if(ma_handle3 != INVALID_HANDLE) { IndicatorRelease(ma_handle3); } if(excel_handle != INVALID_HANDLE) { FileClose(excel_handle); IndicatorRelease(excel_handle); } } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //////////////////////////////////////////////////////////////////////// // Check if trading is allowed //////////////////////////////////////////////////////////////////////// if(!IsMarketOpen(_Symbol,TimeCurrent())) return; if(!IsTradeAllowed()) return; // Verify if user inputted parameters are valid if(!CheckInputs()) { return; } //////////////////////////////////////////////////////////////////////// // Check if current tick is a bar open tick //////////////////////////////////////////////////////////////////////// if(!IsNewBar()) { return; } if(!SymbolInfoTick(_Symbol,cT)) { Print("Failed to get tick"); return; } CopyBuffer(ma_handle1,0,0,3,ma_prices1); CopyBuffer(ma_handle2,0,0,3,ma_prices2); CopyBuffer(ma_handle3,0,0,3,ma_prices3); if(ArraySize(ma_prices1) < 1 || ArraySize(ma_prices2) < 1 || ArraySize(ma_prices3) < 1) { return; } ma_value1 = ma_prices1[0]; ma_value2 = ma_prices2[0]; ma_value3 = ma_prices3[0]; // Grab the candle OHL to add to the spread sheet double open = iOpen(Symbol(),Period(),shift); double high = iHigh(Symbol(),Period(),shift); double low = iLow(Symbol(),Period(),shift); // Check if it is the starting tick to add the Spread sheet column headings if(low > ma_value1) { CreateExcelData(high,ma_value1,ma_value2,ma_value3); } else if(high < ma_value1) { CreateExcelData(low,ma_value1,ma_value2,ma_value3); } } //////////////////////////////////////////////////////////////////////// // Function to upload data to excel sheet //////////////////////////////////////////////////////////////////////// void CreateExcelData(double candle_high_low, double chosen_band_value,double band2, double band3) { double price_difference; if(candle_high_low > chosen_band_value) { price_difference = candle_high_low - chosen_band_value; } else if(candle_high_low < chosen_band_value) { price_difference = chosen_band_value - candle_high_low; } if(excel_handle > 0) { FileWrite(excel_handle, _Symbol, DoubleToString(chosen_band_value),DoubleToString(candle_high_low),DoubleToString(price_difference)); Print("Writing to file - line 258"); } Print("Candle High Low Value - line 260: ", candle_high_low); Print("Chosen Band Value - line 261: ",chosen_band_value); Print("Band 2 Value - line 262: ", band2); Print("Band 3 Value - line 263: ", band3); } //////////////////////////////////////////////////////////////////////// // Function to verify if the auto trading is allowed. //////////////////////////////////////////////////////////////////////// //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool IsTradeAllowed() { return ((bool)MQLInfoInteger(MQL_TRADE_ALLOWED) // Trading allowed in input dialog && (bool)TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) // Trading allowed in terminal && (bool)AccountInfoInteger(ACCOUNT_TRADE_ALLOWED) // Is account able to trade, not locked out && (bool)AccountInfoInteger(ACCOUNT_TRADE_EXPERT) // Is account able to auto trade ); } //////////////////////////////////////////////////////////////////////// // Function to verify if the market is open //////////////////////////////////////////////////////////////////////// //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool IsMarketOpen(string symbol, datetime time) { static string lastSymbol = ""; static bool isOpen = false; static datetime sessionStart = 0; static datetime sessionEnd = 0; if(lastSymbol == symbol && sessionEnd > sessionStart) { if((isOpen && time >= sessionStart && time <= sessionEnd) || (!isOpen && time > sessionStart && time < sessionEnd)) return isOpen; } lastSymbol = symbol; MqlDateTime mtime; TimeToStruct(time, mtime); datetime seconds = mtime.hour * 3600 + mtime.min * 60 + mtime.sec; mtime.hour = 0; mtime.min = 0; mtime.sec = 0; datetime dayStart = StructToTime(mtime); datetime dayEnd = dayStart + 86400; datetime fromTime; datetime toTime; sessionStart = dayStart; sessionEnd = dayEnd; for(int session = 0;; session++) { if(!SymbolInfoSessionTrade(symbol, (ENUM_DAY_OF_WEEK)mtime.day_of_week, session, fromTime, toTime)) { sessionEnd = dayEnd; isOpen = false; return isOpen; } if(seconds < fromTime) // not inside a session { sessionEnd = dayStart + fromTime; isOpen = false; return isOpen; } if(seconds > toTime) // maybe a later session { sessionStart = dayStart + toTime; continue; } // at this point must be inside a session sessionStart = dayStart + fromTime; sessionEnd = dayStart + toTime; isOpen = true; return isOpen; } return false; } //////////////////////////////////////////////////////////////////////// // Confirm if the current bar is definitely a new bar //////////////////////////////////////////////////////////////////////// //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool IsNewBar() { static datetime previousTime = 0; datetime currentTime = iTime(_Symbol,PERIOD_CURRENT,0); if(previousTime != currentTime) { previousTime = currentTime; return true; } return false; } //////////////////////////////////////////////////////////////////////// // Function to validate user inputs //////////////////////////////////////////////////////////////////////// //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CheckInputs() { if(InpMagicNumber <= 0) { Alert("Wrong input: Magic number <= 0"); return false; } if(InpLotSize <= 0 || InpLotSize > MaxInpLotSize) { Alert("Wrong input: Lot Size <= 0 OR Lot Size exceeds Max Size"); return false; } if(InpMaPeriod1 < 0) { Alert("Wrong input: EMA Period 1 < 0"); return false; } if(InpMaPeriod2 < 0) { Alert("Wrong input: EMA Period 2 < 0"); return false; } if(InpMaPeriod3 < 0) { Alert("Wrong input: EMA Period 3 < 0"); return false; } return true; } //+------------------------------------------------------------------+
![MQL5 - Language of trade strategies built-in the MetaTrader 5 client terminal](https://c.mql5.com/i/registerlandings/logo-2.png)
You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
Hi,
Could someone please help me figure out why my code is not generating an excel spread sheet as intended.
The rest of the code I will correct later, however i need to generate an excel doc first before proceeding further.
Thanks