I am saving all the trades done by my EA into a CSV file. When a Trade is closed by the EA, I have to add string "Book Profit" to the end of particular line from the file.
eg:
Below is the line that is saved in the file while trade is open
"Buy GBPJPY 146.28 145.15", I would like to add string "Book Profit" to the end of the above line and save it to the file.
After saving the line should look like
"Buy GBPJPY 146.28 145.15 Book Profit"
int file_handle_dtf=FileOpen("MyTrades.CSV",FILE_READ|FILE_WRITE|FILE_CSV);
if(file_handle_dtf!=INVALID_HANDLE){
while(!FileIsEnding(file_handle_dtf)){
str_size1=FileReadInteger(file_handle_dtf,INT_VALUE);
//--- read the string
str1=FileReadString(file_handle_dtf,str_size1);
strBP=StringConcatenate(str1,",Book Profit");
FileWriteString(file_handle_dtf,strBP+"\n");
}
}
This code just overwrites the file and it is not readable
Seek the end of the file first before writing to it:
if (FileSeek(file_handle_dtf, 0, SEEK_END))
{
// put file writing code here
}
Use the following function with your four parameters (Buy, GBPJPY, 146.28, 145.15):
void func_replaceStringInCSV(string _order,string _symbol,string _SL,string _TP)
{
int handle=FileOpen("MyTrades.CSV",FILE_READ|FILE_WRITE|FILE_CSV);
if(handle!=INVALID_HANDLE)
{
while(!FileIsEnding(handle))
{
int lineStart=(int)FileTell(handle);
string order=FileReadString( handle);
if(FileIsLineEnding(handle))continue;
string symbol=FileReadString(handle);
if(FileIsLineEnding(handle))continue;
string SL=FileReadString(handle);
if(FileIsLineEnding(handle))continue;
string TP=FileReadString(handle);
if(FileIsLineEnding(handle))
{
if(StringConcatenate(order,symbol,SL,TP)==
StringConcatenate(_order,_symbol,_SL,_TP))
{
string blankSpace="";
int lineLen=StringLen(StringConcatenate(order,symbol,SL,TP))+3;
FileSeek(handle,lineStart,SEEK_SET);
for(int l=0;l<=lineLen;l++)
blankSpace+=" ";
FileWrite(handle,order,symbol,SL,TP,"Book Profit");
FileFlush(handle);
}
}
}
}
}
Related
To begin with C++, I prepare a user registration and log-in program.The program I write records the information into the file.But when I open the program again, it wipes out the old record and re-writes it back.
I tried to define string and get input from text but it failed.
using namespace std;
void saveuser() {
string datausername = "test";//User name to save or read from txt
string datapassword = "pass";//password to save or read from txt
string datarealname = "realname";//Real name of the user
ofstream database;
database.open ("userdatabase.txt");
database << datausername.c_str();
database << " , ";
database << datapassword.c_str();
database << " , ";
database << datarealname.c_str();
database.close();
}
I want to store all users information on separate lines.
Like, User1's details : User1 , Pass1 , UserName1
and in other line User2 , Pass2 , UserName2
Sounds like you would like to append to the file.
To append to a file, pass the mode argument of std::ofstream::app into the open function.
Example:
void saveuser() {
....
ofstream database;
database.open ("userdatabase.txt", std::ofstream::out, | std::ofstream::app);
...
}
This will not overwrite the previous contents of the file.
I am using jsonc-libjson to create a json string like below.
{ "author-details": {
"name" : "Joys of Programming",
"Number of Posts" : 10
}
}
My code looks like below
json_object *jobj = json_object_new_object();
json_object *jStr1 = json_object_new_string("Joys of Programming");
json_object *jstr2 = json_object_new_int("10");
json_object_object_add(jobj,"name", jStr1 );
json_object_object_add(jobj,"Number of Posts", jstr2 );
this gives me json string
{
"name" : "Joys of Programming",
"Number of Posts" : 10
}
How do I add the top part associated with author details?
To paraphrase an old advertisement, "libjson users would rather fight than switch."
At least I assume you must like fighting with the library. Using nlohmann's JSON library, you could use code like this:
nlohmann::json j {
{ "author-details", {
{ "name", "Joys of Programming" },
{ "Number of Posts", 10 }
}
}
};
At least to me, this seems somewhat simpler and more readable.
Parsing is about equally straightforward. For example, let's assume we had a file named somefile.json that contained the JSON data shown above. To read and parse it, we could do something like this:
nlohmann::json j;
std::ifstream in("somefile.json");
in >> j; // Read the file and parse it into a json object
// Let's start by retrieving and printing the name.
std::cout << j["author-details"]["name"];
Or, let's assume we found a post, so we want to increment the count of posts. This is one place that things get...less tasteful--we can't increment the value as directly as we'd like; we have to obtain the value, add one, then assign the result (like we would in lesser languages that lack ++):
j["author-details"]["Number of Posts"] = j["author-details"]["Number of Posts"] + 1;
Then we want to write out the result. If we want it "dense" (e.g., we're going to transmit it over a network for some other machine to read it) we can just use <<:
somestream << j;
On the other hand, we might want to pretty-print it so a person can read it more easily. The library respects the width we set with setw, so to have it print out indented with 4-column tab stops, we can do:
somestream << std::setw(4) << j;
Create a new JSON object and add the one you already created as a child.
Just insert code like this after what you've already written:
json_object* root = json_object_new_object();
json_object_object_add(root, "author-details", jobj); // This is the same "jobj" as original code snippet.
Based on the comment from Dominic, I was able to figure out the correct answer.
json_object *jobj = json_object_new_object();
json_object* root = json_object_new_object();
json_object_object_add(jobj, "author-details", root);
json_object *jStr1 = json_object_new_string("Joys of Programming");
json_object *jstr2 = json_object_new_int(10);
json_object_object_add(root,"name", jStr1 );
json_object_object_add(root,"Number of Posts", jstr2 );
I have an xObject Class which basically is a trivial "Person" Class and I want to be able to serialize the whole class to a .json file, and then read that file in order to be able to extract the variables from the file and link those variables to the name of the class.
So for example:
xObject Class Code:
class xObject{
string name;
string lastname;
int age;
public:
string getName(){
return name;
}
string getLastname(){
return lastname;
}
int getAge(){
return age;
}
}
And then I create an object with some attributes on it.
int main(){
xObject homer;
homer.name = "Homer";
homer.lastname = "Simpson";
homer.age = 30;
//SERIALIZATION OF HOMER.
homer.serialExport("File.json")
return 0;
}
So now, my File.json should look like this:
{"homer" :
{"name" : "Homer"
"lastname" : "Simpson"
"age" : 30
}
}
and then, I want to be able to read from the file to extract data from it with something like this:
int main(){
xObject bart;
bart.name = "Bart";
//ACTUAL USE OF THE .JSON FILE HERE
myFile = ("File.json");
bart.lastname = Deserializer(myFile).getLastname(); //It is supossed to assign "Simpson"
//to the lastname reading from the serialized
//homer class file described above.
bart.age = Deserializer(myFile).getAge() - 20; //Sets homer's age minus 20 years.
return 0;
}
So, how can I do that on c++? (Libraries implementation accepted)
And how could I retrieve the class name that has been serialized?
For example Deserialize(myFile).getClassName() should return "homer"
I've done something similar in java with XML serialization, and it was pretty straight forward, but it seems that in C++ this is not very easy to do, and I'm relatively new to C++.
In c++ there is not introspection/reflection, so you can't automatically serialize a class without explicitly write your member variables in your stream. For the same reason, you can't retrieved the class name that have been serialized.
So the solution is to write a function in your class that serializes the member variables you want.
Of course you will not reinvent the wheel to format your file in json. You can use: https://github.com/open-source-parsers/jsoncpp.
For instance you can write:
Json::Value root;
root["homer"]["name"]="Homer";
root["homer"]["lastname"]="Simpson";
//etc
ofstream file;
file.open("File.json");
file << root;
file.close();
However, for the read, you can do as you wanted:
Json::Value root2;
ifstream file2;
file2.open("File.json");
file2 >> root2;
file2.close();
xObject homer;
homer.lastname = root2["homer"]["lastname"].toStyledString();
//etc
Of course your attribute has to be public. Otherwise you need to add a setter function.
I have log file containing somewhere five * in two places. The file can be big.
Log record
*****
Log record
Log record
*****
Log record
I would like to get everything which is between five *. Right, I can read line by line but perhaps there are better solutions like parsing using Regular Expressions in Groovy?
Thank you.
You could also write a custom Reader like:
class DelimitedReader extends BufferedReader {
String delimiterLine
DelimitedReader( String delimiterLine, Reader reader ) {
super( reader )
this.delimiterLine = delimiterLine
scanUntilDelimiter()
}
private scanUntilDelimiter() {
String line = super.readLine()
while( line != null && line != delimiterLine ) {
line = super.readLine()
}
}
String readLine() {
String line = super.readLine()
if( line == delimiterLine ) {
line = null
}
line
}
}
And then, you can do something like this to iterate over them
new File( '/tmp/test.txt' ).withReader { r ->
new DelimitedReader( '*****', r ).eachLine { line ->
println line
}
}
This saves you having the whole file loaded in to a single (potentially huge) string
Try this regex:
(?s)(?<=[*]{5}).+(?=[*]{5})
Demo
http://groovyconsole.appspot.com/script/2405001
This regex matches everything between the first ***** and the next one:
(?<=\*{5})[\s\S]*(?=\*{5})
Is there any simple way to do that? I'm not in Java and I'm new in Python so I would need another way(s). Thanks in advance!
Do you perhaps mean a csv file that ends in .txt? If the data inside the file looks like this:
1,434,2236,5,569,some,value,other,value
4,347,2351,1,232,different,value,than,those
Then it has comma separated values (csv) and Weka has classes and functions which convert a csv file into an arff: http://weka.wikispaces.com/Converting+CSV+to+ARFF You can use these from the command line, like this:
java weka.core.converters.CSVLoader filename.csv > filename.arff
Otherwise, #D3mon-1stVFW 's comment links to great documentation from weka about turning text files (things like blog posts or books or essays) into the arff format. http://weka.wikispaces.com/ARFF+files+from+Text+Collections and this can also be called from the command line, like this:
java weka.core.converters.TextDirectoryLoader /directory/with/your/text/files > output.arff
Missing -dir argument specifier:
java weka.core.converters.TextDirectoryLoader -dir /directory/with/your/text/files > output.arff
This solution assumes you have your data in .csv format - see kaz's solution.
One simple way to do this is in version 3.6.11 (I'm on a mac) is to open up the Explorer and then in the Preprocess tab select "Open file...", just as you would when you want to open a .arff file. Then where it asks for the File Format at the bottom of the dialog box, change it to .csv. You can now load CSV files straight into Weka. If the first line of your CSV file is a header line, these names will be used as the attribute names.
On the right-hand side of the Preprocesses tabs is a "Save..." button. You can click on that and save your data as a .arff file.
This is a bit long-winded to explain, but takes only a few moments to perform and is very intuitive.
package WekaDemo;
public class Txt2Arff {
static ArrayList inList=new ArrayList();
static String colNames[];
static String colTypes[];
static String indata[][];
static ArrayList clsList=new ArrayList();
static ArrayList disCls=new ArrayList();
static String res="";
public String genTrain()
{File fe=new File("input2.txt");
FileInputStream fis=new FileInputStream(fe);
byte bt[]=new byte[fis.available()];
fis.read(bt);
fis.close();
String st=new String(bt);
String s1[]=st.trim().split("\n");
String col[]=s1[0].trim().split("\t");
colNames=col;
colTypes=s1[1].trim().split("\t");
for(int i=2;i<s1.length;i++)
{
inList.add(s1[i]);
}
ArrayList at1=new ArrayList();
for(int i=0;i<inList.size();i++)
{
String g1=inList.get(i).toString();
if(!g1.contains("?"))
{
at1.add(g1);
res=res+g1+"\n";
}
}
indata=new String[at1.size()][colNames.length-1]; // remove cls
for(int i=0;i<at1.size();i++)
{
String s2[]=at1.get(i).toString().trim().split("\t");
for(int j=0;j<s2.length-1;j++)
{
indata[i][j]=s2[j].trim();
}
if(!disCls.contains(s2[s2.length-1].trim()))
disCls.add(s2[s2.length-1].trim());
clsList.add(s2[s2.length-1]);
}
String ar="#relation tra\n";
try
{
for(int i=0;i<colNames.length-1;i++) // all columName which you have split
//and store in Colname
{
//where yor attitude in nominal or you can say character value
if(colTypes[i].equals("con"))
ar=ar+"#attribute "+colNames[i].trim().replace(" ","_")+" real\n";
else
{
ArrayList at1=new ArrayList();
for(int j=0;j<indata.length;j++) //your all numeric data
{
if(!at1.contains(indata[j][i].trim()))
at1.add(indata[j][i].trim());
}
String sg1="{";
for(int j=0;j<at1.size();j++)
{
sg1=sg1+at1.get(j).toString().trim()+",";
}
sg1=sg1.substring(0,sg1.lastIndexOf(","));
sg1=sg1+"}";
ar=ar+"#attribute "+colNames[i].trim().replace(" ", "_")+" "+sg1+"\n";
}
}
//end of attribute
// now adding a class Attribute
ArrayList dis=new ArrayList();
String c1="";
for(int i=0;i<clsList.size();i++)
{
String g=clsList.get(i).toString().trim();
if(!dis.contains(g))
{
dis.add(g);
c1=c1+g+",";
}
}
c1=c1.substring(0, c1.lastIndexOf(","));
ar=ar+"#attribute class {"+c1+"}\n"; //attribute name
//adding class attribute is done
//now data
ar=ar+"#data\n";
for(int i=0;i<indata.length;i++)
{
String g1="";
for(int j=0;j<indata[0].length;j++)
{
g1=g1+indata[i][j]+",";
}
g1=g1+clsList.get(i);
ar=ar+g1+"\n";
}
}
catch(Exception e)
{
e.printStackTrace();
}
return ar;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Txt2Arff T2A=new Txt2Arff();
String ar1=T2A.genTrain();
File fe1=new File("tr.arff");
FileOutputStream fos1=new FileOutputStream(fe1);
fos1.write(ar1.getBytes());
fos1.close();
}}