I need to pick MagicNumbers into an Array, and then make the array distinct ( There are multiple order groups and each has unique MagicNumbers ). But having problem. My code is:
int xxx = OrdersTotal();
int magics[xxx]; // here is an error:
// invalid index value
for ( int i = OrdersTotal() - 1; i >= 0; i-- ){
if ( OrderSelect( i, SELECT_BY_POS ) ){
magics[i] = OrderMagicNumber(); // choosing magics
ArrayResize( magics,
ArraySize( magics ) + 1,
0
);
}
}
ArraySort( magics ); // making distinct
int sorted[];
int x = 0;
for ( int i = 0; i < OrdersTotal() - 1; i++ ){ // duplicates = 0
if ( magics[i] != magics[i+1] ){
sorted[x] = magics[i];
Print( "Sorted array: " + DoubleToStr( sorted[x] ) );
x = x + 1;
}
}
How to pick distinct MagicNumbers into an array?
Try this code. It will create an array, loop through all the orders in the History tab, check if the MagicNumber of the order exists in the array. If it does not exists, adds it to the array. You will end with an array of unique MagicNumbers.
//+------------------------------------------------------------------+
//| UniqueMagic.mq4 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, joseph dot lee at fs dot com dot my"
#property link "https://www.facebook.com/joseph.fhlee"
#property strict
void OnTick() {
int vaiMagicNumbers[]; //Array containing list of MagicNumbers
//Loop through all the Orders (in History tab)
for(int viIndex=OrdersTotal()-1; viIndex>=0; viIndex--) {
if(OrderSelect(viIndex, SELECT_BY_POS, MODE_HISTORY) ){
//Check if the selected Order (in History tab) already exists in the array
if( fniGetElementIndex( vaiMagicNumbers, OrderMagicNumber() ) == -1 ) {
//If not exists, then increase the array by 1, and add the MagicNumber into the array
ArrayResize(vaiMagicNumbers, ArrayRange(vaiMagicNumbers,0)+1);
vaiMagicNumbers[ArrayRange(vaiMagicNumbers,0)-1] = OrderMagicNumber();
}
}
};
Comment( ArrayRange(vaiMagicNumbers,0) ); //Show the number of unique MagicNumbers in the History tab.
}
//Function to return the index (position) of viValue within a given array
int fniGetElementIndex( int &vaiArray[], int viValue ) {
int viElementCount = ArrayRange(vaiArray, 0); //Get the total number of elements within that array.
int viFoundAt = -1; //The element index where viValue is found within the array.
//Loop through every element in vaiArray
for(int viElement=0; viElement<viElementCount; viElement++) {
if( vaiArray[viElement] == viValue ) {
//If the element value is the same as viValue, then FOUND, break the for loop.
viFoundAt = viElement;
break;
}
}
return( viFoundAt );
}