How I assemble my advisor by trial and error - page 53

 
Alexsandr San:

#property version "1.012"

Slightly improved the function

when triggered, the Horizontal line SELL opens a position and displays a Horizontal line BUY and vice versa.

Also, the line is set either from "0" and distance is setby Obj: Trailing Step MACD

or from horizontal line"LOW".

FromTimer "LOW Up" "LOW Down" same, onlythe distance is set (input ushort InpObjTrailingStepCS = 5;// Obj: Trailing Step, in pips (1.00045-1.00055=1 pips)

How to know the distance of the horizontal line in the indicatorLow_Macd_Line.mq5 to set in the trail (on each pair, a different distance)

Copy and paste in the Utility settings

in the picture from "0" to Horizontal BUY 0.0064 and when it touches Horizontal LOW, Horizontal SELL will be set (only below"0"-0.0064)

IMPORTANT!!! Do not put minus ( - ) in front of the figures, which we type in the utility.

One of the Variants, how this function works

Changed the Profit and Loss function #property version "1.013"

input string   t="-----  Parameters         -----";              //
input string   Template                     = "ADX";             // Имя шаблона(without '.tpl')
input bool     Inpwithout                   = false;             // Сменить только шаблон (true)
input datetime InpMonday_2                  = D'1970.01.01';     // Dell (00::00 -> off)
input double   TargetTakeProfit             = 1000000;           // Прибыль
input double   TargetStopLoss               = 1000000;           // Убыток
input uint     maxLimits                    = 1;                 // Кол-во Позиции Открыть в одну сторону
input double   InpLots                      = 0.01;              // Lots
input int      InpTakeProfit                = 900;               // Take Profit ("0"-No. 5<100)

if reached, will close and delete everything, and will change all open windows to the specified pattern

Files:
 

The function opens a position, from Profit or Loss

//+------------------------------------------------------------------+
//|                                            Close_Open_Profit.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

#define  InpMagic 0
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
CPositionInfo  m_position; // trade position object
CTrade         m_trade;    // trading object
CSymbolInfo    m_symbol;   // symbol info object
//---
input double InpLots                      = 0.01;  // Lots
input double TargetTakeProfit             = 10000; // Прибыль
input double TargetStopLoss               = 10000; // Убыток
input bool   Acc                          = false; // Open=true; CloseAll=false;
input string t10="- Buy=false><Sell=true  -----";  //
input bool   ObjRevers                    = false; // BUY=false; SELL=true;
//---
double m_adjusted_point; // point value adjusted for 3 or 5 points
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!m_symbol.Name(Symbol())) // sets symbol name
      return(INIT_FAILED);;
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   m_adjusted_point=m_symbol.Point()*digits_adjust;
//--- set default deviation for trading in adjusted points
   m_trade.SetDeviationInPoints(3*digits_adjust);
//---
   ObjectCreate(0,"Buy",OBJ_BUTTON,0,0,0);
   ObjectSetInteger(0,"Buy",OBJPROP_XDISTANCE,ChartGetInteger(0,CHART_WIDTH_IN_PIXELS)-102);
   ObjectSetInteger(0,"Buy",OBJPROP_YDISTANCE,37);
   ObjectSetString(0,"Buy",OBJPROP_TEXT,"Buy");
   ObjectSetInteger(0,"Buy",OBJPROP_BGCOLOR,clrMediumSeaGreen);
//---
   ObjectCreate(0,"Sell",OBJ_BUTTON,0,0,0);
   ObjectSetInteger(0,"Sell",OBJPROP_XDISTANCE,ChartGetInteger(0,CHART_WIDTH_IN_PIXELS)-50);
   ObjectSetInteger(0,"Sell",OBJPROP_YDISTANCE,37);
   ObjectSetString(0,"Sell",OBJPROP_TEXT,"Sell");
   ObjectSetInteger(0,"Sell",OBJPROP_BGCOLOR,clrDarkOrange);
//---
   ObjectCreate(0,"CloseAll",OBJ_BUTTON,0,0,0);
   ObjectSetInteger(0,"CloseAll",OBJPROP_XDISTANCE,ChartGetInteger(0,CHART_WIDTH_IN_PIXELS)-75);
   ObjectSetInteger(0,"CloseAll",OBJPROP_YDISTANCE,57);
   ObjectSetString(0,"CloseAll",OBJPROP_TEXT,"CloseAll");
   ObjectSetInteger(0,"CloseAll",OBJPROP_BGCOLOR,clrMediumVioletRed);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   if(ObjectFind(0,"Buy")==0)
     {
      ObjectDelete(0,"Buy");
     }
   if(ObjectFind(0,"Sell")==0)
     {
      ObjectDelete(0,"Sell");
     }
   if(ObjectFind(0,"CloseAll")==0)
     {
      ObjectDelete(0,"CloseAll");
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(AccountInfoDouble(ACCOUNT_PROFIT)<-TargetStopLoss ||
      AccountInfoDouble(ACCOUNT_PROFIT)>=TargetTakeProfit)
     {
      if(!Acc)
        {
         CloseAll();
        }
      if(Acc)
        {
         if(!ObjRevers)
           {
            CloseAll();
            double price=m_symbol.Ask();
            m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_BUY,InpLots,price,0.0,0.0);
           }
         if(ObjRevers)
           {
            CloseAll();
            double price=m_symbol.Bid();
            m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_SELL,InpLots,price,0.0,0.0);
           }
        }
      PlaySound("ok.wav");
     }
   if(ObjectGetInteger(0,"Buy",OBJPROP_STATE)!=0)
     {
      ObjectSetInteger(0,"Buy",OBJPROP_STATE,0);
      double price=m_symbol.Ask();
      m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_BUY,InpLots,price,0.0,0.0);
     }
   if(ObjectGetInteger(0,"Sell",OBJPROP_STATE)!=0)
     {
      ObjectSetInteger(0,"Sell",OBJPROP_STATE,0);
      double price=m_symbol.Bid();
      m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_SELL,InpLots,price,0.0,0.0);
     }
   if(ObjectGetInteger(0,"CloseAll",OBJPROP_STATE)!=0)
     {
      ObjectSetInteger(0,"CloseAll",OBJPROP_STATE,0);
      CloseAll();
     }
  }
//+------------------------------------------------------------------+
//| start function                                                   |
//+------------------------------------------------------------------+
void CloseAll(void)
  {
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
        {
         ClosePosition(m_position.Symbol()); // close a position by the specified symbo
        }
  }
//+------------------------------------------------------------------+
//| Close selected position                                          |
//+------------------------------------------------------------------+
void ClosePosition(const string symbol)
  {
   if(InitTrade(symbol))
      m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbo
   PlaySound("ok.wav");
  }
//+------------------------------------------------------------------+
//| Init trade object                                                |
//+------------------------------------------------------------------+
bool InitTrade(const string symbol)
  {
   if(!m_symbol.Name(symbol)) // sets symbol name
      return(false);
   if(IsFillingTypeAllowed(symbol,SYMBOL_FILLING_FOK))
      m_trade.SetTypeFilling(ORDER_FILLING_FOK);
   else
      if(IsFillingTypeAllowed(symbol,SYMBOL_FILLING_IOC))
         m_trade.SetTypeFilling(ORDER_FILLING_IOC);
      else
         m_trade.SetTypeFilling(ORDER_FILLING_RETURN);
   return(true);
  }
//+------------------------------------------------------------------+
//| Checks if the specified filling mode is allowed                  |
//+------------------------------------------------------------------+
bool IsFillingTypeAllowed(string symbol,int fill_type)
  {
//--- Obtain the value of the property that describes allowed filling modes
   int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);
//--- Return true, if mode fill_type is allowed
   return((filling & fill_type)==fill_type);
  }
//+------------------------------------------------------------------+
Files:
 
Alexsandr San:

I have made an assistant indicator in UtilityCommand.mq5, lines are moving and it's possible to set commands from them. I built it withSEM


I found https://www.mql5.com/ru/code/16269 It turns out to be an mt4 script I thank the authorAlexey Volchanskiy.

PriceLines
PriceLines
  • www.mql5.com
Стандартная сетка графика имеет ряд особенностей, не позволяющих с одного взгляда определить движение цены котировки: шаг сетки динамически меняется при переключении таймфрейма, шаг не привязан к базовым уровням, например к 1.12000, как на скриншоте ниже. Скрипт Price Lines размечает уровни цен на графике и служит дополнением к...
 
Alexsandr San:

I searched https://www.mql5.com/ru/code/16269 It turns out this script from mt4 Thanks to the authorAlexey Volchanskiy!

There is a script not only for mt4 but also for mt5https://www.mql5.com/ru/code/16262 I have mastered it in the Indicator.I thank the authorAlexey Volchanskiy!

GBPUSDH4

PriceLines
PriceLines
  • www.mql5.com
Стандартная сетка графика имеет ряд особенностей, не позволяющих с одного взгляда определить движение цены котировки: шаг сетки динамически меняется при переключении таймфрейма, шаг не привязан к базовым уровням, например к 1.12000, как на скриншоте ниже. Скрипт Price Lines размечает уровни цен на графике и служит дополнением к сетке графика...
Files:
PriceLines.mq5  11 kb
 
Alexsandr San:

Changed the Profit and Loss function #property version "1.013"

when reached, it will close and delete everything, and change all open windows to the specified pattern

#property version "1.014"

Still, Profit from Balance is a necessary feature - when one Expert Advisor, works on several pairs.

has redesigned Profit and Loss to close on a given pair without affecting other pairs

//+------------------------------------------------------------------+
input string   t="-----  Parameters         -----";              //
input string   Template                     = "ADX";             // Имя шаблона(without '.tpl')
input bool     Inpwithout                   = false;             // Сменить только шаблон (true)
input datetime InpMonday_2                  = D'1970.01.01';     // Dell (00::00 -> off)
input double   TargetProfit                 = 999999.99;         // Цель Баланса(Ваш Баланс + сумма)
input uint     maxLimits                    = 1;                 // Кол-во Позиции Открыть в одну сторону
input double   InpLots                      = 0.01;              // Lots
input int      InpTakeProfit                = 900;               // Take Profit ("0"-No. 5<100)
input double   TargetTakeProfit             = 1000000;           // Прибыль на паре в валюте
input double   TargetStopLoss               = 1000000;           // Убыток на паре в валюте

Profit and Loss, write the amount (for example 1 unit of your currency) in the 1000000 setting - until it takes a million ofyourcurrency, it will not close the position

Files:
 
Alexsandr San:

#property version "1.014"

Still, Profit from Balance is a necessary feature - when one Expert Advisor works on several pairs.

redesigned Profit and Loss to close on this pair and not to affect other pairs

TheP&L function sets the amount (e.g. 1 unit of your currency) to 1000000 - it does not close the position until it takes a million ofyour currency

#property version "1.015"

a little fixed, this function (Profit and Loss) - because on one pair, you can open several positions, one way - now will close the total amount, one position can be in the plus and the other in the negative, but the total amount is equal to the specified amount in the settings.

----------------------

here is a function(Profit & Loss)

//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool ProfitOnTick(void)
  {
   bool res=false;
   double level;
   double PROFIT_BUY=0.00;
   double PROFIT_SELL=0.00;
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name())
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);
               if(PROFIT_BUY<-TargetStopLoss || PROFIT_BUY>=TargetTakeProfit) // if the profit
                  if(FreezeStopsLevels(level))
                     ClosePositions(POSITION_TYPE_BUY,level);
              }
            else
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                 {
                  PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);
                  if(PROFIT_SELL<-TargetStopLoss || PROFIT_SELL>=TargetTakeProfit) // if the profit
                     if(FreezeStopsLevels(level))
                        ClosePositions(POSITION_TYPE_SELL,level);
                 }
            res=true;
           }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
Files:
 
Alexsandr San:

#property version "1.015"

Fixed it (Profit & Loss) - one can open several positions for one currency pair and it will close on total amount, one position may be profitable and another one - negative, but total amount is equal to the specified amount in settings.

----------------------

Here is a function(Profit and Loss)

I tried it on a real account, I wanted a small profit of two opened positions. I had set it to 160 and thought it would close the biggest minus position, but it didn't.

I thought it would close the biggest losing position but it didn't. It closed the one that got 160 profit and closed both positions and I am a sucker. It turns out that I have to calculate from the first open position, adding the minus position

Photo by

Snapshot2

 
Alexsandr San:

#property version "1.015"

Fixed it (Profit & Loss) - one can open several positions for one currency pair and it will close on total amount, one position may be profitable and another one - negative, but total amount is equal to the specified amount in settings.

----------------------

here's the function(Profit & Loss)

#property version "1.016"

I tried different ways but it seems to be the only way. If I set the amount at once, opened a lot of positions - it closes the same amount.

Here's the function, a little differently

//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool ProfitOnTick(void)
  {
   bool res=false;
   double level;
   double PROFIT_BUY=0.00;
   double PROFIT_SELL=0.00;
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name())
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               PROFIT_BUY=PROFIT_BUY+m_position.Commission()+m_position.Swap()+m_position.Profit();
               if(PROFIT_BUY<-TargetStopLoss || PROFIT_BUY>=TargetTakeProfit) // if the profit
                  if(FreezeStopsLevels(level))
                     ClosePositions(POSITION_TYPE_BUY,level);
              }
            else
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                 {
                  PROFIT_SELL=PROFIT_SELL+m_position.Commission()+m_position.Swap()+m_position.Profit();
                  if(PROFIT_SELL<-TargetStopLoss || PROFIT_SELL>=TargetTakeProfit) // if the profit
                     if(FreezeStopsLevels(level))
                        ClosePositions(POSITION_TYPE_SELL,level);
                 }
            res=true;
           }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
Files:
 
Alexsandr San:

#property version "1.016"

I've tried all sorts of things, but it's the only way it should be. If I set the amount at once, opened many positions - it closes exactly that amount.

Here's a function, a little different

I checked this function in the tester - I set a profit of 300, a loss of 10000. Opening came from the indicator (LeMan_BrainTrend1Sig) on the EURUSD H1 with a balance of 100 leverage 100 with 0.01 lot

Snapshot.PNG

Snapshot2

function Profit Loss in currency - BUY and SELL have their own profit on the same pair, (for example, ifBUY has made a profit, it will close their positions, SELL will not close until it has made a profit)

 
Alexsandr San:

I checked this function in the tester - I set profit 300, loss 10000. Opening was performed using indicator (LeMan_BrainTrend1Sig) on EURUSD H1 with balance 100, leverage 100 with 0.01 lot

Function Profit Loss in currency - BUY and SELL have their own profit on one pair, (for example, ifBUY has made a profit, it will close their positions, SELL will not close, until they reach their own profit)

One more function has been added. I just need to check it in real time in the terminal.

input  int     limit_total_symbol           = 3;                 // Кол-во Позиции при Убытке
input double   TargetOpenLot                = 1000000;           // Убыток на Позиции Открыть Позицию

This version is like this - In the Tester

//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool OpenLotBuy(void)
  {
   bool res=false;
   double PROFIT_BUY=0.00;
   CloseTikB=iClose(NULL,Period(),0);
   OpenTikB=iOpen(NULL,Period(),0);
//---
   int total=PositionsTotal(); // количество открытых позиций
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name())
           {
            if(total>0)
              {
               ulong position_ticket=PositionGetTicket(total-1); // тикет позиции
              }
            if(total<limit_total_symbol)// количество открытых позиций
              {
               if(OpenTikB<CloseTikB)
                 {
                  if(m_position.PositionType()==POSITION_TYPE_BUY)
                    {
                     PROFIT_BUY=PROFIT_BUY+m_position.Commission()+m_position.Swap()+m_position.Profit();
                     if(PROFIT_BUY<-TargetOpenLot)
                        ExtNeedOpenBuy=true;
                     if(LongObjOpened())
                        return(res);
                    }
                  res=true;
                 }
              }
           }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool OpenLotSell(void)
  {
   bool res=false;
   double PROFIT_SELL=0.00;
   CloseTikS=iClose(NULL,Period(),0);
   OpenTikS=iOpen(NULL,Period(),0);
//---
   int total=PositionsTotal(); // количество открытых позиций
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name())
           {
            if(total>0)
              {
               ulong position_ticket=PositionGetTicket(total-1); // тикет позиции
              }
            if(total<limit_total_symbol)// количество открытых позиций
              {
               if(OpenTikS>CloseTikS)
                 {
                  if(m_position.PositionType()==POSITION_TYPE_SELL)
                    {
                     PROFIT_SELL=PROFIT_SELL+m_position.Commission()+m_position.Swap()+m_position.Profit();
                     if(PROFIT_SELL<-TargetOpenLot)
                        ExtNeedOpenSell=true;
                     if(ShortObjOpened())
                        return(res);
                    }
                  res=true;
                 }
              }
           }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+

Photo by

Snapshot2

Files: