pnn_system_for_demo

Author:
Price Data Components
Series array that contains the lowest prices of each barSeries array that contains the highest prices of each bar
Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reached
Miscellaneous
Uses files from the file systemIt writes information to fileIt reads information from a file
0 Views
0 Downloads
0 Favorites
pnn_system_for_demo
//+------------------------------------------------------------------+
//| Example system using trained probabilistic neural network (PNN)  |
//|                                                                  |
//|                                                 PNN System 1.mq4 |
//|                                             Paco Hernández Gómez |
//|                                    http://www.hernandezgomez.com |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Modified to enable auto training by Pasupathi                    |
//| Creator of self adapting EAs, Dhananjay and PrecisionTypeA       |
//|                                                                  |
//|                                                                  |
//|                                    http://private.thefxcode.com  |
//+------------------------------------------------------------------+

#property copyright ""
#property link      ""

extern int TestRange = 50;       //number of bars to be trained

double pnn1[0][61];
double data[0][63];

extern double SIGMA1 = 0.01;       

static int prevtime = 0;

extern int LIMIT = 20;
extern int STOP_LOSS = 50;       

extern double Lots =0.1;

int init() 
{
}

///////////////////////////////////////////////////////////

int start() 
{        
   int total;
   total = OrdersTotal();
                      
   //Trades are only opened at the beginning of Bar
   
   if (Time[0] == prevtime) return(0);      
   prevtime = Time[0];
   
   //if there is an open trade, exit
   
   if(total!=0)return(0);
   
   //Initiate the array      
         
   PNN1Init();  
   ArrayResize(data, 0);
   
   //
   
   //Start auto training
            
   for(int cnt=10;cnt<=TestRange;cnt++)
   {      
      StartTraining1(cnt);
   }

   //
      
   //Save the auto trained results
            
   PNN1Save();

   //

   //Load the auto trained results
            
   PNN1Load();
   
   //
   
   //Get the current date to be compared with past datas, in this example difference between 2 close prices
   
      double dataR[60];

      for (int i = 0; i < 60; i++) 
      {
         dataR[i] = Close[i+1]-Close[i+2];                                   
                     
      }

      //Classify the data
            
      int class1 = PNN1ClassifyVector(dataR);                           
                        
      if (class1 == 0) 
      {         
         OrderSend(Symbol(), OP_BUY, Lots, Ask, 3, Ask - STOP_LOSS * Point, Ask + LIMIT * Point, NULL, 16384, 0, Green);
      }

      if (class1 == 1) 
      {
         OrderSend(Symbol(), OP_SELL, Lots, Bid, 3, Bid + STOP_LOSS * Point, Bid - LIMIT * Point, NULL, 16384, 0, Red);
      }

   return(0);
}

//Starts autotraining, shift of bars is feeded from earlier loop

int StartTraining1(int shift) 
{      
      //See the original Paco Hernández Gómez description
      
      static int length;
      length = ArrayRange(data, 0);
      ArrayResize(data, length + 2);
   
   for (int i = 0; i <60; i++) 
   {  
      //Stores the difference in close prices between shift of bars feeded
      
      data[length][i] = Close[shift+i]-Close[shift+i+1];         
      data[length+1][i] = data[length][i];
   }
   
      data[length][60] = 0; // Compra
      data[length][61] = Close[shift]; // Open position with Ask price (at market)
      data[length][62] = 0; // 0 indicates that this position is opened, 1 indicates that this position is closed
   
      data[length+1][60] = 1; // Venta
      data[length+1][61] = Close[shift]; // Open position with Bid price (at market)
      data[length+1][62] = 0; // 0 indicates that this position is opened, 1 indicates that this position is closed

   for (i = 0; i < length; i++) 
   {
      
      if (data[i][62] == 0) 
      {
         
         double vector[60];
               
         // If position is a buying position
         if (data[i][60] == 0) 
         {

            // If position is a winner position
            
            //if TP reached earlier (bigger shift) than SL in that particular shift
            
            if(SLLReached(data[i][61],shift,STOP_LOSS)<TPLReached(data[i][61],shift,LIMIT))  
            {
                                                            
               for (int j = 0; j < 60; j++) 
               {
                  vector[j] = data[i][j];
               }

               // Add position to the PNN training vectors set and classify it as a buying position
               PNN1AddVector(0, vector);

               // Mark the position as closed position
               data[i][62] = 1;
            }

            // If position is a loser position

            //if SL reached earlier than TP in that particular shift
            
            else if (SLLReached(data[i][61],shift,STOP_LOSS)>=TPLReached(data[i][61],shift,LIMIT)) 
            {
                                                          
               // Discard position and mark as closed
               data[i][62] = 1;
            }
         }
         
         // If position is a selling position
         else if (data[i][60] == 1) 
         {
         
            // If position is a winner position

            //if TP reached earlier (bigger shift) than SL in that particular shift
            
            if (SLSReached(data[i][61],shift,STOP_LOSS)<TPSReached(data[i][61],shift,LIMIT)) 
            {
                                                          
               for (j = 0; j < 60; j++) 
               {
                  vector[j] = data[i][j];
               }

               // Add position to the PNN training vectors set and classify it as a selling position
               PNN1AddVector(1, vector);

               // Mark the position as closed position
               data[i][62] = 1;
            }

            // If position is a loser position

            //if SL reached earlier than TP in that particular shift
            
            else if (SLSReached(data[i][61],shift,STOP_LOSS)>=TPSReached(data[i][61],shift,LIMIT)) 
            {
                                                         
               // Discard position and mark as closed
               data[i][62] = 1;
            }
         }
      }
  }
  
return(1);
}

///////////////////////See original Paco Hernández Gómez description

void PNN1Init() 
{
   ArrayResize(pnn1, 0);
}

void PNN1AddVector(int class, double vector[]) {
   // Create a new position in the array to store the new training vector and its associated class.
   
   int length = ArrayRange(pnn1, 0);
   ArrayResize(pnn1, length + 1);
   
   // Store the new training vector class
   pnn1[length][0] = class;

   // Store the new training vector
   for (int i = 0; i < ArrayRange(vector, 0); i++) 
   {
      pnn1[length][i + 1] = vector[i];
   }
}

double euclideanScalarProduct1(double p[], double q[]) {
	double euclideanScalarProduct = 0;
	
   int length = ArrayRange(p, 0);
	
	for (int i = 0; i < length; i++) {
		euclideanScalarProduct += MathPow(p[i] - q[i], 2);
	}

	return (euclideanScalarProduct);
}

int PNN1ClassifyVector(double vector[]) {
   double length = ArrayRange(vector, 0);

	double result = -99999999999999999999;
	int resultClass = -1;

   double fx[2] = {0, 0};
   double classVectorCount[2] = {0, 0};
                                                                        
   for (int i = 0; i < ArrayRange(pnn1, 0); i++) 
   {
	
      int class = pnn1[i][0];

      double classVector[60];
      for (int j = 0; j < length; j++) 
      {
         classVector[j] = pnn1[i][j + 1];
      }

      classVectorCount[class]++;
	
      fx[class] += MathExp((-1) * euclideanScalarProduct1(vector, classVector) / (2 * MathPow(SIGMA1, 2)));
   }

   for (i = 0; i < ArrayRange(fx, 0); i++) 
   {
      if(classVectorCount[i]==0)continue;       //To prevent zero divide                  
      
      fx[i] *= 1 / (MathPow(2 * 3.14159265, length / 2) * MathPow(SIGMA1, length)) * (1 / classVectorCount[i]);

      if (fx[i] > result) {
         result = fx[i];
         resultClass = i;
      }
   }
   
   if(resultClass!=0 && resultClass!=1)resultClass=-1;               
   
	return (resultClass);
}

void PNN1Save() {
   int handle;
   
   handle = FileOpen("pnn1.dat", FILE_WRITE | FILE_BIN);

   int vectorSize = ArrayRange(pnn1, 1);

   for (int i = 0; i < ArraySize(pnn1); i++) 
   {
      FileWriteDouble(handle, pnn1[i / vectorSize][i % vectorSize]);
      
   }
   
   FileClose(handle);
}

void PNN1Load() {
   int handle;
   
   handle = FileOpen("pnn1.dat", FILE_READ | FILE_BIN);

   int fileSize = FileSize(handle);

   ArrayResize(pnn1, fileSize / (61 * 8));
   int vectorSize = ArrayRange(pnn1, 1);

   for (int i = 0; i < fileSize; i++) 
   {
      pnn1[i / vectorSize][i % vectorSize] = FileReadDouble(handle);
   }
   
   FileClose(handle);
}

///////////////////////PNN End

//Shift when SL is reached (SLL=Stop Loss Long), when the lowest of subsequent candles after shift exceeds size of SL value

int SLLReached(double Price,int count,int SL) ///if SL long is reached
{
   int reached;
   for(int begin = count; begin>0; begin--)
   {
      if(iLow(NULL, 0, begin)<=Price-SL*Point)
      break;
      reached=begin;
   }
   if(iLow(NULL, 0, iLowest(NULL,0,MODE_LOW,count,1))>Price-SL*Point)
   reached=-1;
   
return(reached);      
}

//Shift when SL is reached (SLS=Stop Loss Short), when the highest of subsequent candles after shift exceeds size of SL value

int SLSReached(double Price,int count,int SL) ///if SL short is reached
{
   int reached;
   for(int begin = count; begin>0; begin--)
   {
   if(iHigh(NULL, 0, begin)>=Price+SL*Point)
   break;
   reached=begin;
   }
   if(iHigh(NULL, 0, iHighest(NULL,0,MODE_HIGH,count,1))<Price+SL*Point)
   reached=-1;
   
return(reached);      
}

//Shift when TP is reached (TPL=Take profit long), when the highest of subsequent candles after shift exceeds size of TP value

int TPLReached(double Price,int count,int TP) ///if TP long is reached
{
   int reached;
   for(int begin = count; begin>0; begin--)
   {
   if(iHigh(NULL, 0, begin)>=Price+TP*Point)
   break;
   reached=begin;
   }
   if(iHigh(NULL, 0, iHighest(NULL,0,MODE_HIGH,count,1))<Price+TP*Point)
   reached=-1;

return(reached);      
}

//Shift when TP is reached (TPL=Take profit short), when the lowest of subsequent candles after shift exceeds size of TP value

int TPSReached(double Price,int count,int TP) ///if TP short is reached
{
   int reached;
   for(int begin = count; begin>0; begin--)
   {
   if(iLow(NULL, 0, begin)<=Price-TP*Point)
   break;
   reached=begin;
   }
   if(iLow(NULL, 0, iLowest(NULL,0,MODE_LOW,count,1))>Price-TP*Point)
   reached=-1;

return(reached);      
}

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---