How to save and read from file multidimensional array
How to save and read from file multidimensional array
28 Oct 2019, 19:03
Hi, How can I save and then read from file multidimensional array e.g [100,4]? I need this to not loose data (in array) when restarting robot. Is there any other way to not loose data when rebooting? Should I use txt or other file to save data from array and then read it by robot and use for trading?
firemyst
17 Aug 2020, 12:43
Serialize it to JSON, save the JSON to a text file.
Then when you restart and restart your bot/indicator, in the OnStart or Initialize methods, you can read the json back in and convert it back to a 2-dimensional array.
Example code:
//In the OnStart method: // read saved file into a string and deserialize JSON to a type RobotInfoClass ric = null; if (System.IO.File.Exists(_savedFilePath)) { ric = JsonConvert.DeserializeObject<RobotInfoClass>(System.IO.File.ReadAllText(_savedFilePath)); System.IO.File.Delete(_savedFilePath); //clean up since we no longer need it } /////////////////////////////////////// //In the OnStop method: using (System.IO.StreamWriter sw = new System.IO.StreamWriter(_savedFilePath)) { using (JsonWriter writer = new JsonTextWriter(sw)) { RobotInfoClass ric = new RobotInfoClass(); ric._positionEntryPricePoints = _positionEntryPricePoints; ric._positionEntryPriceTimes = _positionEntryPriceTimes; ric._breakEvenPoints = _breakEvenPoints; ric._increasePositionSizePoints = _increasePositionSizePoints; //blah blah blah ric._savedTime = DateTime.Now; JsonSerializer serializer = new JsonSerializer(); serializer.Formatting = Formatting.Indented; serializer.Serialize(writer, ric); } }
@firemyst