Keep order details in arrays? - arrays

could you please help me.
1) Is it better to keep orders in the EA's arrays rather than querying the system with the Order.. commands in mql4? Keeping data in arrays means that you have to query the system less and that internet reliability may be less of an issue. However, the coding required to keep an accurate order book is quite cumbersome.
2) How do you keep track of orders that is on the same Symbol but has come from two different EA's?
Thank you very much

It depends on your needs and ideas, without that it could be quite difficult to tell anything.
you can keep an array of ticket numbers (or CArrayObj) but need to check that ticket exists before doing other operations (like trail). if you have problems with internet - change vps and do not try to solve it with coding.
Each ea keeps a book of its own deals.
Cannot imagine sence of keeping just numbers of tickets, but maybe it exists. If you need to store some data in addition to what can be achieved from Order...() then use classes or structures, some fields might be filled with osl,tp,oop,lot,magic, symbol etc once and do not call Order.() functions later except OrderProfit(),OrderClosePrice() and OrderCloseTime()-such functions would be called all the time.
Example of how to store data is below: instances of CTrade are added to CArrayObj
#include <Object.mqh>
#include <Arrays\ArrayObj.mqh>
class CTrade : public CObject
{
private:
int m_ticketId;
double m_oop,m_osl,m_otp,m_lot;//OrderOpenPrice() and sl, tp, lot-add more
public:
CTrade(const int ticket){
m_ticketId=ticket;
}
bool isTicketExist(){
if(OrderSelect(m_ticketId,SELECT_BY_TICKET))
return(OrderCloseTime()==0);
else return(false);//or GetLastError()!=4108
}
};
CArrayObj* listOfTrades=NULL;
int OnInit(void){
listOfTrades=new CArrayObj;
}
void OnDeinit(const int reason){
if(CheckPointer(listOfTrades)==POINTER_DYNAMIC)
delete(listOfTrades);
}
void OnTick(){
for(int i=listOfTrades.Total()-1;i>=0;i--){
CTrade *trade=listOfTrades.At(i);
if(!trade.isTicketExist())
{listOfTrades.Delete(i);continue;}
//do trail or what you need
} // - loop over the array when necessary but clean it first
}
listOfTrades.Add(new CTrade(ticket));// - way to add elements to the list

Related

Appending values to DataSet in Apache Flink

I am currently writing an (simple) analytisis code to sum time connected powerreadings. With the data being assumingly raw (e.g. disturbances from the measuring device have not been calculated out) I have to account for disturbances by calculation the mean of the first one thousand samples. The calculation of the mean itself is not a problem. I only am unsure of how to generate the appropriate DataSet.
For now it looks about like this:
DataSet<Tupel2<long,double>>Gyrotron_1=ECRH.includeFields('11000000000'); // obviously the line to declare the first gyrotron, continues for the next ten lines, assuming separattion of not occupied space
DataSet<Tupel2<long,double>>Gyrotron_2=ECRH.includeFields('10100000000');
DataSet<Tupel2<long,double>>Gyrotron_3=ECRH.includeFields('10010000000');
DataSet<Tupel2<long,double>>Gyrotron_4=ECRH.includeFields('10001000000');
DataSet<Tupel2<long,double>>Gyrotron_5=ECRH.includeFields('10000100000');
DataSet<Tupel2<long,double>>Gyrotron_6=ECRH.includeFields('10000010000');
DataSet<Tupel2<long,double>>Gyrotron_7=ECRH.includeFields('10000001000');
DataSet<Tupel2<long,double>>Gyrotron_8=ECRH.includeFields('10000000100');
DataSet<Tupel2<long,double>>Gyrotron_9=ECRH.includeFields('10000000010');
DataSet<Tupel2<long,double>>Gyrotron_10=ECRH.includeFields('10000000001');
for (int=1,i<=10;i++) {
DataSet<double> offset=Gyroton_'+i+'.groupBy(1).first(1000).sum()/1000;
}
It's the part in the for-loop I'm unsure of. Does anybody know if it is possible to append values to DataSets and if so how?
In case of doubt, I could always put the values into an array but I do not know if that is the wise thing to do.
This code will not work for many reasons. I'd recommend looking into the fundamentals of Java and the basic data structures and also in Flink.
It's really hard to understand what you actually try to achieve but this is the closest that I came up with
String[] codes = { "11000000000", ..., "10000000001" };
DataSet<Tuple2<Long, Double>> result = env.fromElements();
for (final String code : codes) {
DataSet<Tuple2<Long, Double>> codeResult = ECRH.includeFields(code)
.groupBy(1)
.first(1000)
.sum(0)
.map(sum -> new Tuple2<>(sum.f0, sum.f1 / 1000d));
result = codeResult.union(result);
}
result.print();
But please take the time and understand the basics before delving deeper. I also recommend to use an IDE like IntelliJ that would point to at least 6 issues in your code.

How to use Collections.binarySearch() in a CodenameOne project

I am used to being able to perform a binary search of a sorted list of, say, Strings or Integers, with code along the lines of:
Vector<String> vstr = new Vector<String>();
// etc...
int index = Collections.binarySearch (vstr, "abcd");
I'm not clear on how codenameone handles standard java methods and classes, but it looks like this could be fixed easily if classes like Integer and String (or the codenameone versions of these) implemented the Comparable interface.
Edit: I now see that code along the lines of the following will do the job.
int index = Collections.binarySearch(vstr, "abcd", new Comparator<String>() {
#Override
public int compare(String object1, String object2) {
return object1.compareTo(object2);
}
});
Adding the Comparable interface (to the various primitive "wrappers") would also would also make it easier to use Collections.sort (another very useful method :-))
You can also sort with a comparator but I agree, this is one of the important enhancements we need to provide in the native VM's on the various platforms personally this is my biggest peeve in our current VM.
Can you file an RFE on that and mention it as a comment in the Number issue?
If we are doing that change might as well do both.

How to make the program work this way?

So i have a program that does these calculations with numbers. The program is threaded, and the number of threads are specified from the user.
I will give a close example
static void *program_thread(void *thread)
{
bool somevar = true;
if(somevar)
{
work = getwork();
}
dowork(work);
if(condition1 blah blah)
somevar = false; /* disable getwork */
if(condition2)
somevar = true; /* condition was either met or not met, so we request
new work either way */
}
Then with pthreads(and i will skip some code) i do
int main(blah)
{
if (pthread_create(&thr->pth, NULL, program_thread, thread_number)) {
printf("%s","program thread create failed");
return 1;
}
}
Now i will start explaining. The number of threads created are specified from the user, so i do a for loop and create as many threads as i need.
Each thread calls
work = getwork();
Thus getting independant work to do, however the CPU is slow for this kind of job. It tries to compute something by trying 2^32 numbers(which is from 1 to 4 294 967 296)
But my CPU can only do around 3 million numbers per second, and by the time it reaches 4 billion numbers, it's restarted(for new work).
So i then thought of a better method. Instead of each thread getting totally different work, all the threads should get the same work and split the numbers they need to try.
The problem is, that i can't controll what work it get's, so i must fetch
work = getwork();
Before initiating the threads. The question is HOW? Using pthread_create obviously...but then what?
You get more than one way to do it:
split your work package into smaller parts (thus, your getWork returns a new, smaller work)
store your work in a common place, that you access from your thread using a reader-writer pattern
from the pthread API, the 4th parameter is given to your thread, you can do something like the following code :
Work = getWork();
if (pthread_create(&thr->pth, NULL, program_thread, (void*) &work))
...
And your program_thread function would be like that
static void *program_thread(void *pxThread)
{
Work* pWork = (Work*) pxThread;
...
Of course, you need to check the validaty of the pointer and common stuff (in my example, I created it on stack which is most probably a bad idea). Note that your code is givig a thread_number as a pointer, which is usually a bad idea. If you want to have more information transfered to your thread, simply hide it into a structure.
I'm not sure I fully understood your issue, but this could give you some hints most probably. Please note also that when doing multithreading, you need to take into account specific issues like race conditions, concurrent access and more complex lifecycle of objects...

multithreads process data from the same file

can anyone in this forum give an example in C how two threads process data from one textfile.
As an example, I have one textfile that contains a paragraph. I have two threads that will process the data in the said file. One thread will count the number of lines in the paragraph. The second thread will count the numeric characters.
thanks
If you asked in C++ I could give you a code example, but I havent done ANSI C in a very long time so I will give you the design and pseudo code.
Please keep in mind this is really bad pseudo code that is meant to give an example. I'm not questioning WHY you would want to do this. For all I know it could be an excercise with threads or because you "feel like it".
Example 1
int integerCount = 0;
int lineCount = 0;
numericThread()
{
// By flagging the file as readonly you should
// be able to open it as many times as you wish
handle h = openfile ("textfile.txt". readonly);
while (!eof(h)) {
String word = readWord (h);
int outInteger
if (stringToInteger(word, outInteger)) {
++integerCount;
}
}
}
lineThread()
{
// By flagging the file as readonly you should
// be able to open it as many times as you wish
handle h = openfile ("textfile.txt". readonly);
while (!eof(h)) {
String word = readWord (h);
if (word.equals("\n") {
++lineCount ;
}
}
}
If for some reason you aren't able to open the file twice in readonly you will need to maintain a queue for each thread, having the main thread put words into each threads queue. The threads will then pull from the queue.
Example 2
int integerCount = 0;
int lineCount = 0;
queue numericQueue;
queue lineQueue;
numericThread()
{
while (!numericQueue.closed()) {
String word = numericQueue.pop();
int outInteger
if (stringToInteger(word, outInteger)) {
++integerCount;
}
}
}
lineThread()
{
while (!lineQueue.closed()) {
String word = lineQueue.pop();
if (word.equals("\n") {
++lineCount ;
}
}
}
mainThread()
{
handle h = openfile ("textfile.txt". readonly);
while (!eof(h)) {
String word = readWord(h);
numericQueue.push(word);
lineQueue.push(word);
}
numericQueue.close();
lineQueue.close();
}
There are lots of ways to do this. You can make different design decisions depending on how fast or simple or elegant or overengineered you want this to be. One way, as posted by Andrew Finnell is to have each thread open the file and read it completely independently. In theory this isn't great because you are doing expensive IO twice but in practice it's probably fine because the OS has likely cached the contents of whichever read executes first. Double IO is still more expensive than average because it involves a lot of needless system calls, but again in practice it will be irrelevant unless you have a very large file.
Another model of how to do this would be for each thread to have an input queue, or a shared global queue. The main thread reads the file and places each line in turn on the queue(s), and perhaps main doubles as one of your worker threads. This is more complicated because access to the queue(s) must be synchronized, or some lockless queue implementation must be used. In the case of a shared global queue, there is less duplication of data but now the lifecycle of that data is more complicated.
Just to point out how many ways such a simple thing can be done, you could go the overengineering route and make each thread generic. Instead of placing data on the queue(s) you place both data (or pointers to data) and function pointers and let each thread execute the callback. This kind of model might might sense if you plan on adding lots more kind of things to compute but want to limit the number of threads you will use.
I don't think you will see much performance difference in using 2 threads over one. Either way, you don't want both threads to read the file. Read the file first, then pass a COPY of the stream to the methods you want and process both. The threads will not have access to the same stream of data at the same time so you'll need to use 2 copies of the textfile.
P.S. It's possible that depending on the size of the file, you will actually loose performance using 2 threads.

How do you link two arrays?

I'm in a basic programming class, and everything is done in pseudo code.
My question is this: How do you link two arrays?
I have a single-dimensional array that lists students names, and I have a two-dimensional array that lists the top eight scores of each student...this is all fine and dandy, but now I need to sort the arrays by the students name. I'm poked around online and read through the books chapter twice, it only briefly mentions linking two arrays but shows no examples.
If it's any help, we are using bubble-sorting, and that is what I am fairly familiar with...I can sort the names, that's the easy part, but I don't know how to sort the grades so they do not go out of order.
Thanks for the input!
Sidenote: I got it figured out! I ended up doing how Greg Hewgill had mentioned. As I put in my comment to his suggestion, I started randomly throwing in lines of code until that idea hit me...it doesn't look pretty (one module swapped the names, another to swap the grades, and a third even then to swap the individual students grades earlier on in a multidimensional array), but it indeed seemed to work...no way to test it in a language as I have no compiler nor have I enough knowledge to make the pseudo code into actual code if I were to download one, but it sounds really good on the paper I typed it out on!
As I also mentioned in the note, I do thank everyone for their speedy and helpful insight, I actually didn't even think I'd get a reply tonight, thank you everyone again for all your help!
Jeffrey
Define a simple Student class like this:
public class Student : IComparable<Student>
{
public string Name { get; set; }
public int[] Scores { get; set; }
#region IComparable<Student> Members
public int CompareTo(Student other)
{
// Assume Name cannot be null
return this.Name.CompareTo(other.Name);
}
#endregion
}
then even simpler
var students = new[] {
new Student(){ Name = "B", Scores = new [] { 1,2,3 } },
new Student(){ Name = "C", Scores = new [] { 3,4,5 } },
new Student(){ Name = "A", Scores = new [] { 5,6,7 } }
};
Array.Sort(students);
will do the work for you.
What you may want to do is the following: As you're sorting the names and you have to swap two positions, do the same swap in the array of scores. That way, all changes that you make to the names array will be reflected in the scores array. When you're done, the scores will be in the same sorted order as the names are.
There are more effective ways of doing this with different data structures, as other comments will show.
Your premise is wrong. You shouldn't have two array in the first place.
You should have one array of objects, each of which holds a student's name and his scores:
public class Record
{
public string Student;
public int[] Scores;
}
Two approaches: first, when sorting the names, each time you exchange two names, exchange the rows (or columns or whatever you want to call them) of scores in the same positions. At the end, the scores should still be in sync with the names.
Second, instead of sorting the names, create a third array that will contain the indexes into either of the other two arrays, initially 0 through n-1, but then sorted, comparing name[a] and name[b], instead of sorting the names array itself.

Resources