Advisors on neural networks, sharing experiences. - page 6

 

It's an interesting topic. I have an idea, but a simpler one. I'll ask questions for now :)

It's clear how to determine the entry point - we take a zig-zag, but we need to know what was before the point to predict the entry. What window in the bars is used to analyse the preceding data?

Have you tried to separate the input and output functions? Or is a reversal - the arrival of the opposite signal usually used? What would be the result if different ways of profit/loss fixing were used instead of an exit to a flip?

 
Started the neuroner on the demo yesterday https://www.mql5.com/ru/signals/129790 Seems to be OK so far.
 
-Aleks-:

It's an interesting topic. I have an idea, but a simpler one. I'll ask questions for now :)

It's clear how to determine the entry point - we take a zig-zag, but we need to know what was before the point to predict the entry. What window in the bars is used to analyse the preceding data?

Have you tried to separate the input and output functions? Or is the reversal - the arrival of the opposite signal - usually used? What would be the result if different ways of profit/loss fixing were used instead of an exit to a flip?

I tried 1 bar forward forecasting, that is a shift of 1 bar back. But the problem is that the zigzag on the last bars needs to be filled with values and it is overdrawn, so everything is not so clear... I'm still using reversal signals to open/reopen, or I'm screwing with martin... But the field of research is very large, it's hard to say how to do it right...
 
Anton Govorukhin:
Started up the neuroner in the demo yesterday https://www.mql5.com/ru/signals/129790 Seems to be ok so far.
Cool, let's see... what's the basis of it?
 
Maxim Dmitrievsky:
Прикольно, понаблюдаемс.. а что в основу заложено?
Объемы, открытый интерес, баланс сил на рынке.
 

So far, nothing interesting is coming out. There may be errors in the code and logic. I'm writing just to develop the topic, so to speak, maybe someone will change it for himself or correct my mistakes.

I've fixed the main moments in code. Prognosis bars - prediction depth, how many bars to look forward. Then length of array for grid training and number of training epochs. 30 neurons, you can change it in the code.

//+------------------------------------------------------------------+
//|                                                      zzNeuro.mq5 |
//|                                                 max dmitrievsky  |
//|                        https://www.mql5.com/ru/users/dmitrievsky |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#include <Trade\Trade.mqh>        
#include <Trade\PositionInfo.mqh> 
#include <Trade\AccountInfo.mqh>
#include "class_mlp.mqh"
CTrade            m_Trade;
CPositionInfo     m_Position;
CNetMLP *net;

input double MaximumRisk=0.01;
input int ZZperiod = 300;
input int PrognozBars = 30;

input int vectorLength = 1000;
input int epoch = 10000;

int    zz_handle, RSI_handle, MA1_handle, MA2_handle; //хендлы индикаторов
double a1[],a2[],a3[],a4[],a5[],ma1[],ma2[],MAbuff[],zzH[],zzL[]; //массивы индикаторов
double inputs[], outputs[]; //массивы для нейросети
bool   learn;
double in[6],out[1]; //количество входов и выходов нейросети
int    snn[]={70,1}; // параметры нейросети

double min,max, minMA, maxMA; //переменные для нормировки данных входящих векторов

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- инициализируем хендлы индикаторов
   learn=false;
   zz_handle=iCustom(Symbol(),0,"zz",ZZperiod);
   RSI_handle=iRSI(Symbol(),0,14,PRICE_CLOSE);
   MA1_handle=iMA(Symbol(),0,200,0,MODE_SMA,PRICE_CLOSE);
   MA2_handle=iMA(Symbol(),0,20,0,MODE_SMA,PRICE_CLOSE);
   
//---
   return(INIT_SUCCEEDED);
  }
  
void FillZZarray(double &a[]) //заполняем массив выходов для нейросети с индикатора зигзаг. Присваиваем значения зигзага каждому бару.
{                             //1 растущий, -1 падающий.
  ArrayResize(a,vectorLength); 
    
   int lastcountbar = 0;
   for(int i=0;i<vectorLength;i++)
     {
      if(zzH[i]>0)  
       {
        a[i]=1; lastcountbar = 1;
       }    
      if(zzL[i]>0) 
       {
        a[i]=-1; lastcountbar = -1;  
       } 
      if(zzH[i]==0 && zzL[i]==0) a[i] = lastcountbar;
     }
}
 
void NormalizeArrays(double &a[]) //нормируем входные данные для рси
  {
   double d1=-1.0;
   double d2=1.0;

   double x_min=a[ArrayMinimum(a)];
   double x_max=a[ArrayMaximum(a)];
   min = x_min;
   max=x_max;

   for(int i=0;i<ArraySize(a);i++)
     {
      a[i]=(((a[i]-x_min)*(d2-d1))/(x_max-x_min))+d1;
     }
  }
  
void NormalizeArraysMA(double &a[]) //нормируем входные данные для МА
  {
   double d1=-1.0;
   double d2=1.0;

   double x_min=a[ArrayMinimum(a)];
   double x_max=a[ArrayMaximum(a)];
   minMA = x_min;
   maxMA=x_max;

   for(int i=0;i<ArraySize(a);i++)
     {
      a[i]=(((a[i]-x_min)*(d2-d1))/(x_max-x_min))+d1;
     }
  }
  
void NormalizeArrays2(double &a[]) //нормируем для рси на каждом новом баре
  {
   double d1=-1.0;
   double d2=1.0;

   for(int i=0;i<ArraySize(a);i++)
     {
      a[i]=(((a[i]-min)*(d2-d1))/(max-min))+d1;
     }
  }
  
void NormalizeArrays2MA(double &a[]) //нормируем для МА на каждом новом баре
  {
   double d1=-1.0;
   double d2=1.0;

   for(int i=0;i<ArraySize(a);i++)
     {
      a[i]=(((a[i]-minMA)*(d2-d1))/(maxMA-minMA))+d1;
     }
  }
   
void learnWeb()
  {
   CopyBuffer(zz_handle,0,PrognozBars,vectorLength,zzH);
   CopyBuffer(zz_handle,1,PrognozBars,vectorLength,zzL);
   FillZZarray(outputs); //заполняем массив выходов, предварительно скопировав хай и лоу зигзага.
   
   CopyBuffer(RSI_handle,0,PrognozBars*2+1,vectorLength,a1);
   CopyBuffer(RSI_handle,0,PrognozBars*2+5,vectorLength,a2);
   CopyBuffer(RSI_handle,0,PrognozBars*2+10,vectorLength,a3);
   CopyBuffer(RSI_handle,0,PrognozBars*2+15,vectorLength,a4);
   CopyBuffer(RSI_handle,0,PrognozBars*2+20,vectorLength,a5);
   CopyBuffer(MA1_handle,0,PrognozBars*2+1,vectorLength,ma1);
   CopyBuffer(MA2_handle,0,PrognozBars*2+1,vectorLength,ma2);
   
   ArrayResize(MAbuff,vectorLength);
   for(int i=0;i<ArraySize(ma1);i++) //вычисляем разницу между двумя МА
     {
      MAbuff[i]=ma1[i]-ma2[i];
     }
    NormalizeArrays(a1);
     NormalizeArrays(a2);
      NormalizeArrays(a3);
       NormalizeArrays(a4);
        NormalizeArrays(a5);
         NormalizeArraysMA(MAbuff); //нормируем все входы
   
   int j = 0;
   for(int i=0;i<vectorLength*6;i=i+6) //компануем массив входов для нейросети
     {
       ArrayCopy(inputs,MAbuff,i,j,1);
       ArrayCopy(inputs,a5,i+1,j,1);
       ArrayCopy(inputs,a4,i+2,j,1);
       ArrayCopy(inputs,a3,i+3,j,1);
       ArrayCopy(inputs,a2,i+4,j,1);
       ArrayCopy(inputs,a1,i+5,j,1);      
       j++;
     }      
   ArraySetAsSeries(inputs,true);
   ArraySetAsSeries(outputs,true);
   
  //+------------------------------------------------------------------+
  //| Neuro Learn                                                      |
  //+------------------------------------------------------------------+     
   net=new CNetMLP(ArraySize(snn),snn,ArraySize(in),1);
   net.Learn(vectorLength,inputs,outputs,epoch,1.0 e-8); Print("MSE=",net.mse,"  Epoch=",net.epoch);
  //--- сохранение сети в файл и удаление сети
   int h=FileOpen("test.net",FILE_BIN|FILE_WRITE);
   net.Save(h);
   FileClose(h);
   
   learn=true;
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   delete net;
   FileDelete("test.net");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
  if(learn==false) learnWeb();
//---
   
   if(fn_NEW_BAR()) //запускаем сеть на каждом новом баре, получаем выходы. Торгуем.
   {  
      ArrayResize(a1,1);
      ArrayResize(a2,1);
      ArrayResize(a3,1);
      ArrayResize(a4,1);
      ArrayResize(a5,1);
      ArrayResize(ma1,1);
      ArrayResize(ma2,1);
      ArrayResize(MAbuff,1);
      
      CopyBuffer(RSI_handle,0,1,1,a1);
      CopyBuffer(RSI_handle,0,5,1,a2);
      CopyBuffer(RSI_handle,0,10,1,a3);
      CopyBuffer(RSI_handle,0,15,1,a4);
      CopyBuffer(RSI_handle,0,20,1,a5);
      CopyBuffer(MA1_handle,0,1,1,ma1);
      CopyBuffer(MA2_handle,0,1,1,ma2);
      
      for(int i=0;i<ArraySize(ma1);i++)
      {
       MAbuff[i]=ma1[i]-ma2[i];
      }
       
      NormalizeArrays2(a1);
       NormalizeArrays2(a2);
        NormalizeArrays2(a3);
         NormalizeArrays2(a4);
          NormalizeArrays2(a5);
           NormalizeArrays2MA(MAbuff);
           
      in[0] = MAbuff[0];
      in[1] = a5[0];
      in[2] = a4[0];
      in[3] = a3[0];
      in[4] = a2[0];
      in[5] = a1[0];
      
          
      net.Calculate(in,out); //подаем на вход данные индикаторов на текущем баре, получаем результат на выходе.
     
//+------------------------------------------------------------------+
//| Expert trade function                                            |
//+------------------------------------------------------------------+         
   if(out[0]>0.9) //если на выходе больше этого значения, то покупаем
     {
      double Lot=LotsOptimized();
      double priceBuy=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
      if(m_Position.Select(Symbol()))
        {
         if(m_Position.PositionType()==POSITION_TYPE_SELL) m_Trade.PositionClose(Symbol());
        }
      if(CountPosBuy()==0) m_Trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,Lot,priceBuy,0,0,NULL);
     }
       
   if(out[0]<-0.9) //если ниже, то продаем
     {
      double Lot=LotsOptimized();
      double priceSell=SymbolInfoDouble(Symbol(),SYMBOL_BID);
      if(m_Position.Select(Symbol()))
        {
         if(m_Position.PositionType()==POSITION_TYPE_BUY) m_Trade.PositionClose(Symbol());
        }
      if(CountPosSell()==0) m_Trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,Lot,priceSell,0,0,NULL);
     }
   } 
  }
//+------------------------------------------------------------------+
//| Custom Functions                                                 |
//+------------------------------------------------------------------+
bool fn_NEW_BAR()
  {
   static int nBars=0;
   if(nBars!=Bars(Symbol(),0))
     {
      nBars=Bars(Symbol(),0);
      return(true);
     }
   return(false);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+  
double LotsOptimized()
  {
   CAccountInfo myaccount;
   double lot;
//---- select lot size
   lot=NormalizeDouble(myaccount.FreeMargin()*MaximumRisk/1000.0,1);
//---- return lot size
   if(lot<0.01) lot=0.01;
   if(lot>50) lot=50;
   return(lot);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int CountPosBuy()
  {
   CPositionInfo myposition;
   int result=0;
   for(int k=0; k<PositionsTotal(); k++)
     {
      if(myposition.Select(_Symbol)==true)
        {
         if(myposition.PositionType()==POSITION_TYPE_BUY)
           {result++;}
         else
           {}
           }
        }
      return(result);
     }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
   int CountPosSell()
     {
      CPositionInfo myposition;
      int result=0;
      for(int k=0; k<PositionsTotal(); k++)
        {
         if(myposition.Select(_Symbol)==true)
           {
            if(myposition.PositionType()==POSITION_TYPE_SELL)
              {result++;}
            else
              {}
              }
           }
         return(result);
        }
 
Gentlemen, if your Expert Advisors do not take the fundamentals into account, then the probability of profit/loss = 50/50 - spread! And no neurons in the Expert Advisor will help, neither their own nor anyone else's:)
 
Rustam Karpunin:
Gentlemen, if your Expert Advisors do not take into account the foundation, then the probability of profit/loss = 50/50 - the spread! And no neurons in the Expert Advisor will help, neither their own nor anyone else's:)
Who says so?
 
Rustam Karpunin:
Gentlemen, if your Expert Advisors don't learn the fundamentals, the probability of profit/loss = 50/50 - spread! And no neurons in the Expert Advisor will help, neither their own nor anyone else's:)
This is very cool, I've started to buy some features of working with them, I've already got interesting results, I'll post them later. I just need to spend a lot of time to think out a strategy.
 
what is it
Advisors on neural networks?
Reason: