Questions from Beginners MQL5 MT5 MetaTrader 5 - page 480

 
Hello dear friends!

Please help translate the algorithm for finding the coordinates of the intersection point of two segments

From the article:

It's very simple!
x1,y1 and x2,y2 are coordinates of vertices of the first segment;
x3,y3 and x4,y4 are coordinates of the vertices of the second segment;

to find the intersection we make the equations of the lines:
first equation:
(x-x1)/(x2-x1)=(y-y1)/(y2-y1);
second equation
(x-x3)/(x4-x3)=(y-y3)/(y4-y3);
these equations define a line passing through two points, which is what we need.
From these equations we find x and y by the following formulas:
x:=((x1*y2-x2*y1)*(x4-x3)-(x3*y4-x4*y3)*(x2-x1))/((y1-y2)*(x4-x3)-(y3-y4)*(x2-x1));
y:=((y3-y4)*x-(x3*y4-x4*y3))/(x4-x3);
since our lines intersect, they have a common intersection point with the coordinates (x,y), which we need to find.
For the intersection to belong to our line segments, we need to constrain it, i.e. check the condition:
if
(((x1<=x)and(x2>=x)and(x3<=x)and(x4 >=x))or((y1<=y)and(y2>=y)and(y3<=y) and(y4>=y))
then there is an intersection point of these segments, and if there is not, there is no intersection point.
You should also check the parallelism of these segments using angle coefficients:
k1:=(x2-x1)/(y2-y1);
k2:=(x4-x3)/(y4-y3);
where k1 and k2 are the tangents of the angles of the segments to the positive direction of the OX axis, if k1=k2, then the segments are parallel and therefore have no points of intersection.

Готовая функция.
Код:

POINT Point_X(POINT a1,POINT a2,POINT a3,POINT a4){
        POINT T;
        if(((a1.x<=T.x)&&(a2.x>=T.x)&&(a3.x<=T.x)&&(a4.x >=T.x))||((a1.y<=T.y)&&(a2.y>=T.y)&&(a3.y<=T.y)&&(a4.y>=T.y))){
                float x1=a1.x,x2=a2.x,x3=a3.x,x4=a4.x,y1=a1.y,y2=a2.y,y3=a3.y,y4=a4.y;
                float k1,k2;
                if(y2-y1!=0){
                        k1=(x2-x1)/(y2-y1);
                        if(y4-y3!=0){
                                k2=(x4-x3)/(y4-y3);
                                if(k1!=k2){
                                        T.x=((a1.x*a2.y-a2.x*a1.y)*(a4.x-a3.x)-(a3.x*a4.y-a4.x*a3.y)*(a2.x-a1.x))/((a1.y-a2.y)*(a4.x-a3.x)-(a3.y-a4.y)*(a2.x-a1.x));
                                        T.y=((a3.y-a4.y)*T.x-(a3.x*a4.y-a4.x*a3.y))/(a4.x-a3.x);
                                        T.x*=-1;
                                        return T;
                                }else{
                                        T.x=969; T.y=969;
                                        //text2("Паралельны");
                                }
                        }else{
                                T.x=969; T.y=969;
                                //text2("Паралельны");
                        }
                }else{
                        T.x=969; T.y=969;
                        //text2("Паралельны");
                }
        }else{
                //text2("Пересечение вне отрезка");
                T.x=979; T.y=979;
                return T;
        }

}

Maybe someone has a ready-made one in the archives?
 
Leo59:
Hello dear friends!

Please help translate the algorithm for finding the coordinates of intersection point of two line segments

From the article:

It's very simple!
x1,y1 and x2,y2 are the coordinates of the vertices of the first segment;
x3,y3 and x4,y4 are coordinates of the vertices of the second segment;

to find the intersection we make the equations of the lines:
first equation:
(x-x1)/(x2-x1)=(y-y1)/(y2-y1);
second equation
(x-x3)/(x4-x3)=(y-y3)/(y4-y3);
these equations define a line passing through two points, which is what we need.
From these equations we find x and y by the following formulas:
x:=((x1*y2-x2*y1)*(x4-x3)-(x3*y4-x4*y3)*(x2-x1))/((y1-y2)*(x4-x3)-(y3-y4)*(x2-x1));
y:=((y3-y4)*x-(x3*y4-x4*y3))/(x4-x3);
since our lines intersect, they have a common intersection point with the coordinates (x,y), which we need to find.
For the intersection to belong to our line segments, we need to constrain it, i.e. check the condition:
if
(((x1<=x)and(x2>=x)and(x3<=x)and(x4 >=x))or((y1<=y)and(y2>=y)and(y3<=y) and(y4>=y))
then there is an intersection point of these segments, and if there is not, there is no intersection point.
You should also check the parallelism of these segments using angle coefficients:
k1:=(x2-x1)/(y2-y1);
k2:=(x4-x3)/(y4-y3);
where k1 and k2 are the tangents of the angles of the segments to the positive direction of the OX axis, if k1=k2, then the segments are parallel and therefore have no points of intersection.

Maybe someone has a ready one in the archives?

It's a bit complicated... I wrote the definition of the intersection of the lines, one at 2m highs and the other at 2m lows, further than the next bar or not. I wrote it using tangent, the ratio of the price difference in pips to the number of bars between the Haijs on which the line is drawn. Correspondingly, it is the tangent of the angle of the second line at lowes. And then I use the tangent to find the number of points on the next bar, i.e. I use the inverse formula with the changed value of one cathetus (the number of bars). We obtain the price value at the tested point of these lines. And accordingly if the price value of the straight bar is less, the crossing has occurred.

But so far I can't find this indicator.

 
Leo59:

...

Or maybe someone has a ready-made one in the archives?

Kim posted a function. The function returns the price of the point of the ray drawn from the line to the right.

//+----------------------------------------------------------------------------+
double EquationDirect(double x1, double y1, double x2, double y2, double x) {
  return((x2==x1)?y1:(y2-y1)/(x2-x1)*(x-x1)+y1);
}
//+----------------------------------------------------------------------------+

x1 - bar of the first line coordinate, y1 - price of the first line coordinate. x2 - bar of the second line coordinate, y2 - price of the second line coordinate, x - the bar for which the price is returned.

You can find the prices for each of the two lines and see if they overlap...

 
Thank you very much Alexey and Artem for your attention to my question!

I've written here sort of..., something counts and is drawn, but not at every intersection. There's something wrong with my writing. I don't understand what it is.



#property indicator_separate_window
#property indicator_buffers 4

#property indicator_color1  Aqua                 // Массив 
#property indicator_width1  1
#property indicator_color2  Blue                 // Массив 
#property indicator_width2  1

#property indicator_color3  Lime                 // 
#property indicator_color4  Red                  // 


double   Buf0[];                                 // Массив
double   Buf1[];                                 // Массив

double   y1=0;                                   // Координата Значения буфера Buf0[] на баре с индексом i=2
double   y2=0;                                   // Координата Значения буфера Buf0[] на баре с индексом i=1
double   y3=0;                                   // Координата Значения буфера Buf1[] на баре с индексом i=2
double   y4=0;                                   // Координата Значения буфера Buf1[] на баре с индексом i=1

double   x1=2;                                   // Координата Времени Buf0[] на баре с индексом i=2
double   x2=1;                                   // Координата Времени Buf0[] на баре с индексом i=1
double   x3=2;                                   // Координата Времени Buf1[] на баре с индексом i=2
double   x4=1;                                   // Координата Времени Buf1[] на баре с индексом i=1

double   X=0;                                    // Точка пересечения. Координата по оси Времени
double   Y=0;                                    // Точка пересечения. Координата по оси Значения

double   k1=0;                                   // Тангенс угла наклона 1-первого отрезка
double   k2=0;                                   // Тангенс угла наклона 2-второго отрезка

double   PointX=0;                               // Значение индикатора в точке пересечения отрезков

double   UpArrow[];                              // Зелёные стрелки внизу индикаторного окна
double   DnArrow[];                              // Красные стрелки вверху индикаторного окна

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
   {
    SetIndexBuffer(0,Buf0);       
    SetIndexStyle(0,DRAW_LINE);

    SetIndexBuffer(1,Buf1); 
    SetIndexStyle(1,DRAW_LINE);
   
    SetIndexBuffer(2,UpArrow);                   // Зелёные стрелки внизу индикаторного окна
    SetIndexStyle(2,DRAW_ARROW);
    SetIndexArrow(2,233);

    SetIndexBuffer(3,DnArrow);                   // Красные стрелки вверху индикаторного окна
    SetIndexStyle(3,DRAW_ARROW);
    SetIndexArrow(3,234);
  
    return(0);
   }
//+------------------------------------------------------------------+
//| Moving Averages Convergence/Divergence                           |
//+------------------------------------------------------------------+
int start()
   {
    int i; 
    int limit;
    int counted_bars=IndicatorCounted();
    if(counted_bars<0) return(-1);
    if(counted_bars>0) counted_bars--;
    limit=Bars-counted_bars;

    for(i=limit; i>=0; i--)
         Buf0[i] = ....;

    for(i=limit; i>=0; i--)
         Buf1[i] = ....;

    Fun_New_Bar();
    if (New_Bar==true)
        {
         y1=Buf0_[2];
         y2=Buf0_[1];
         y3=Buf1_[2];
         y4=Buf1_[1];
         
         X=((x1*y2-x2*y1)*(x4-x3)-(x3*y4-x4*y3)*(x2-x1))/((y1-y2)*(x4-x3)-(y3-y4)*(x2-x1));
         Y=((y3-y4)*X-(x3*y4-x4*y3))/(x4-x3);

         if( ((x1<=X)&&(x2>=X)&&(x3<=X)&&(x4 >=X)) || ((y1<=Y)&&(y2>=Y)&&(y3<=Y)&&(y4>=Y)) )       // Проверка на "Пересечение линий вне отрезков"
             {
              if(y2-y1 != 0)                                                                       // Проверка 1-первого отрезка на вырождение в точку
                  {
                   k1=(x2-x1)/(y2-y1);                                                             // Тангенс угла наклона 1-первого отрезка
                   if(y4-y3 != 0)                                                                  // Проверка 2-второго отрезка на вырождение в точку
                       {
                        k2=(x4-x3)/(y4-y3);                                                        // Тангенс угла наклона 2-второго отрезка
                        if(k1 != k2)                                                               // Проверка прямых(отрезков) на параллельность
                            {
                             PointX=Y;                                                             // Значение индикатора в точке пересечения отрезков
                             if(PointX>=0) UpArrow[1]=-0.001;
                             if(PointX< 0) DnArrow[1]= 0.001;
                            }
                        //else              // Alert("Прямые(отрезки) параллельны");
                       }
                   //else              // Alert("2-второй отрезок выродился в точку");
                  }
              //else              // Alert("1-первый отрезок выродился в точку");
             }
         //else              // Alert("Пересечение вне, хотя бы одного, отрезка");
        }
    return(0);
   }
//+------------------------------------------------------------------+
void Fun_New_Bar()
   { 
    static datetime New_Time=0;
    New_Bar=false;
    if(New_Time!=Time[0])
        {
         New_Time=Time[0];
         New_Bar=true;
        }
   }
 
Leo59:
Thank you very much Alexey and Artem for your attention to my question!

I've written here sort of..., something counts and is drawn, but not at every intersection. There's something wrong with my writing. I don't know what it is.

At the moment, I'm not able to understand anything in programming, it's my beloved wife's birthday today. She is 18 years and 384 months old.

But!!! Note that the crossing of the lines can happen IN or OUT of the bars, and the price (Y coordinate) can only be obtained on the bar. Either before or after, but the crossover point cannot always be determined. I'd say that's rare. Considering the above, revise your code with this in mind, maybe it will work.

 

Alexey Viktorov 2015.12.12 17:33 RU

She's turned 18.

Alexei, so now you can do anything! Happy you.... Congratulations!
 
TanFX:
Please advise what kind of commands should be inserted into the Expert Advisor so that it automatically corrects the already set takeprofits in the open positions when recalculating them. Or maybe there is a script that corrects all of the stops on the last set?
about position maintenance here https://www.mql5.com/ru/articles/231
Мастер MQL5: Как написать свой модуль сопровождения открытых позиций
Мастер MQL5: Как написать свой модуль сопровождения открытых позиций
  • 2011.01.20
  • MetaQuotes Software Corp.
  • www.mql5.com
Генератор торговых стратегий Мастера MQL5 значительно упрощает проверку торговых идей. В статье рассказывается о том, как написать и подключить в Мастер MQL5 свой собственный модуль управления открытыми позициями, устанавливающий уровень Stop Loss в безубыток при движении цены в благоприятном направлении, что позволяет защитить прибыль и уменьшить потери. Рассматривается структура и формат описания созданного класса для Мастера MQL5.
 

Please advise how to add code so that in the strategy tester you can change-fit weights of patterns. m_pattern_0(90) replace input variables

I'm not very good with OOP, I get errors"member function not defined" or the code simply doesn't work.

Similar unanswered question here https://www.mql5.com/ru/forum/13484

p.s.: With CiCustom I can change weights for models, but with standard indicators that have standard classes (like CSignalEnvelopes etc.) where are the methods for setting values for each model, but they are not yet available inthe Wizard?
Or maybe it was already suggested somewhere?

о значимости моделей
о значимости моделей
  • www.mql5.com
Значимость каждой рыночной модели, заложенной с сигнал, задаётся в конструкторе класса. - - Категория: общее обсуждение
 
I want to save an archive of quotes longer than the default one (2048 candlesticks) in MT4 (Alpari-Demo). I delete what was there and press "Load".
Something will be loaded from MetaQuotes site and I get the following picture:

Top : Database 2049/12358 records.
The penultimate one is from 17.10.2014, the last one is from 14.07.1993.
Where are the missing ones?
 
Press "Load". Only the last 2048 bars are automatically loaded, the rest must be kicked.
Reason: