I will write an advisor free of charge - page 155

 
Oltinbek Sohibov #:

Hello !

Who can help to add SL and TP and time frame trading on this EA !

Thank you so much

//--- additional checking
   double sl   =500;
   double tp   =500;
   if(signal!=WRONG_VALUE)
     {
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
         ExtTrade.PositionOpen(_Symbol,signal,TradeSizeOptimized(),
                               SymbolInfoDouble(_Symbol,signal==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK),
                               SymbolInfoDouble(_Symbol,sl==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK),
                               SymbolInfoDouble(_Symbol,tp==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK));
     }
//---

I need to make some adjustments to the SL and TP

 
Oltinbek Sohibov # :

Hello !

who can help on this adviser will add SL and TP and time interval trading

thanks in advance

here is from the example https://www.mql5.com/ru/docs/constants/structures/mqltraderequest

 //+------------------------------------------------------------------+

//|                                                    MA CCI  1.mq5 |

//|                                  Copyright 2021, MetaQuotes Ltd. |

//|                                             https://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright "Copyright 2021, MetaQuotes Ltd."

#property link        " https://www.mql5.com "

#property version    "1.00"

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

#include <Trade\Trade.mqh>



input double MaximumRisk        = 0.02 ;     // Maximum Risk in percentage

input double DecreaseFactor     = 3 ;       // Descrease factor

input int     MovingPeriod       = 150 ;       // Moving Average period

input int     MovingShift        = 0 ;       // Moving Average shift





input int     ma_period          = 14 ;     // период усреднения

input int     CCI_level_high     = 220 ;

input int     CCI_level_low      = - 220 ;



extern double Max_spread        = 20 ; // максимально допустимый спред при входе

extern int     Sl                = 150 ; // стоплосс - 0-выкл.

extern int     Tp                = 500 ; // тейкпрофит - 0-выкл.

extern double Lots              = 0.01 ; // лот







//---

int     ExtHandle= 0 ;

bool    ExtHedging= false ;

CTrade ExtTrade;



int     CCIHandle= 0 ;





#define MA_MAGIC 1234501

//+------------------------------------------------------------------+

//| Calculate optimal lot size                                       |

//+------------------------------------------------------------------+
double TradeSizeOptimized( void )
  {
   double price= 0.0 ;
   double margin= 0.0 ;
//--- select lot size
   if (! SymbolInfoDouble ( _Symbol , SYMBOL_ASK ,price))
       return ( 0.0 );
   if (! OrderCalcMargin ( ORDER_TYPE_BUY , _Symbol , 1.0 ,price,margin))
       return ( 0.0 );
   if (margin<= 0.0 )
       return ( 0.0 );
   double lot= NormalizeDouble ( AccountInfoDouble ( ACCOUNT_MARGIN_FREE )*MaximumRisk/margin, 2 );
//--- calculate number of losses orders without a break
   if (DecreaseFactor> 0 )
     {
       //--- select history for access
       HistorySelect ( 0 , TimeCurrent ());
       //---
       int     orders= HistoryDealsTotal ();   // total history deals
       int     losses= 0 ;                     // number of losses orders without a break
       for ( int i=orders- 1 ; i>= 0 ; i--)
        {
         ulong ticket= HistoryDealGetTicket (i);
         if (ticket== 0 )
           {
             Print ( "HistoryDealGetTicket failed, no trade history" );
             break ;
           }
         //--- check symbol
         if ( HistoryDealGetString (ticket, DEAL_SYMBOL )!= _Symbol )
             continue ;
         //--- check Expert Magic number
         if ( HistoryDealGetInteger (ticket, DEAL_MAGIC )!=MA_MAGIC)
             continue ;
         //--- check profit
         double profit= HistoryDealGetDouble (ticket, DEAL_PROFIT );
         if (profit> 0.0 )
             break ;
         if (profit< 0.0 )
            losses++;
        }
       //---
       if (losses> 1 )
         lot= NormalizeDouble (lot-lot*losses/DecreaseFactor, 1 );
     }
//--- normalize and check limits
   double stepvol= SymbolInfoDouble ( _Symbol , SYMBOL_VOLUME_STEP );
   lot=stepvol* NormalizeDouble (lot/stepvol, 0 );
   double minvol= SymbolInfoDouble ( _Symbol , SYMBOL_VOLUME_MIN );
   if (lot<minvol)
      lot=minvol;
   double maxvol= SymbolInfoDouble ( _Symbol , SYMBOL_VOLUME_MAX );
   if (lot>maxvol)
      lot=maxvol;
//--- return trading volume
   return (lot);
  }
//+------------------------------------------------------------------+

//| Check for open position conditions                               |

//+------------------------------------------------------------------+
void CheckForOpen( void )

  {
   MqlRates rt[ 2 ];
//--- go trading only for first ticks of new bar
   if ( CopyRates ( _Symbol , _Period , 0 , 2 ,rt)!= 2 )
     {
       Print ( "CopyRates of " , _Symbol , " failed, no history" );
       return ;
     }
   if (rt[ 1 ].tick_volume> 1 )
       return ;
//--- get current Moving Average
   double    ma[ 1 ];
   if ( CopyBuffer (ExtHandle, 0 , 0 , 1 ,ma)!= 1 )
     {
       Print ( "CopyBuffer from iMA failed, no data" );
       return ;
     }
//--- check signals
   ENUM_ORDER_TYPE signal= WRONG_VALUE ;
   if (rt[ 0 ].open>ma[ 0 ] && rt[ 0 ].close<ma[ 0 ] && ma_period<CCI_level_high)           // && ma_period>CCI_level_high
      signal= ORDER_TYPE_SELL ;     // sell conditions
   else
     {
       if (rt[ 0 ].open<ma[ 0 ] && rt[ 0 ].close>ma[ 0 ]  &&  ma_period>CCI_level_low)         // &&  ma_period<CCI_level_low
         signal= ORDER_TYPE_BUY ;   // buy conditions
     }
//--- additional checking
   if (signal!= WRONG_VALUE )
     {
       if ( TerminalInfoInteger ( TERMINAL_TRADE_ALLOWED ) && Bars ( _Symbol , _Period )> 100 )
         ExtTrade.PositionOpen( _Symbol ,signal,TradeSizeOptimized(),
                               SymbolInfoDouble ( _Symbol ,signal== ORDER_TYPE_SELL ? SYMBOL_BID : SYMBOL_ASK ),
                               0 , 0 );
     }
//---
  }
//+------------------------------------------------------------------+

//| Check for close position conditions                              |

//+------------------------------------------------------------------+
void CheckForClose( void )

  {
   MqlRates rt[ 2 ];
//--- go trading only for first ticks of new bar
   if ( CopyRates ( _Symbol , _Period , 0 , 2 ,rt)!= 2 )
     {
       Print ( "CopyRates of " , _Symbol , " failed, no history" );
       return ;
     }
   if (rt[ 1 ].tick_volume> 1 )
       return ;
//--- get current Moving Average
   double    ma[ 1 ];
   if ( CopyBuffer (ExtHandle, 0 , 0 , 1 ,ma)!= 1 )
     {
       Print ( "CopyBuffer from iMA failed, no data" );
       return ;
     }
//--- positions already selected before
   bool signal= false ;
   long type= PositionGetInteger ( POSITION_TYPE );
   if (type==( long ) POSITION_TYPE_BUY && rt[ 0 ].open>ma[ 0 ] && rt[ 0 ].close<ma[ 0 ])         //
      signal= true ;
   if (type==( long ) POSITION_TYPE_SELL && rt[ 0 ].open<ma[ 0 ] && rt[ 0 ].close>ma[ 0 ])       //
      signal= true ;
//--- additional checking
   if (signal)
     {
       if ( TerminalInfoInteger ( TERMINAL_TRADE_ALLOWED ) && Bars ( _Symbol , _Period )> 100 )
         ExtTrade.PositionClose( _Symbol , 3 );
     }
//---
  }
//+------------------------------------------------------------------+

//| Position select depending on netting or hedging                  |

//+------------------------------------------------------------------+
bool SelectPosition()

  {
   bool res= false ;
//--- check position in Hedging mode
   if (ExtHedging)
     {
       uint total= PositionsTotal ();
       for ( uint i= 0 ; i<total; i++)
        {
         string position_symbol= PositionGetSymbol (i);
         if ( _Symbol ==position_symbol && MA_MAGIC== PositionGetInteger ( POSITION_MAGIC ))
           {
            res= true ;
             break ;
           }
        }
     }
//--- check position in Netting mode
   else
     {
       if (! PositionSelect ( _Symbol ))
         return ( false );
       else
         return ( PositionGetInteger ( POSITION_MAGIC )==MA_MAGIC); //---check Magic number
     }
//--- result for Hedging mode
   return (res);
  }

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+
int OnInit ( void )

  {
//--- prepare trade class to control positions if hedging mode is active
   ExtHedging=(( ENUM_ACCOUNT_MARGIN_MODE ) AccountInfoInteger ( ACCOUNT_MARGIN_MODE )== ACCOUNT_MARGIN_MODE_RETAIL_HEDGING );
   ExtTrade.SetExpertMagicNumber(MA_MAGIC);
   ExtTrade.SetMarginMode();
   ExtTrade.SetTypeFillingBySymbol( Symbol ());
//--- Moving Average indicator
   ExtHandle= iMA ( _Symbol , _Period ,MovingPeriod,MovingShift, MODE_SMA , PRICE_CLOSE );
   if (ExtHandle== INVALID_HANDLE )
     {
       printf ( "Error creating MA indicator" );
       return ( INIT_FAILED );
     }
//--- индикатора Commodity Channel Index
   CCIHandle= iCCI ( _Symbol , _Period ,ma_period, _AppliedTo );
   if (CCIHandle== INVALID_HANDLE )
     {
       printf ( "Error creating CCI indicator" );
       return ( INIT_FAILED );
     }
//--- ok
   return ( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+
void OnTick ( void )

  {
//---
   if (SelectPosition())
      CheckForClose();
   else
      CheckForOpen();
   OnStartsltp();
//---
  }
//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+
void OnDeinit ( const int reason)

  {
  }
//+------------------------------------------------------------------+
//| Модификация Stop Loss и Take Profit позиции                      |
//+------------------------------------------------------------------+
void OnStartsltp()
  {
//--- объявление запроса и результата
   MqlTradeRequest request;
   MqlTradeResult   result;
   int total= PositionsTotal (); // количество открытых позиций
//--- перебор всех открытых позиций
   for ( int i= 0 ; i<total; i++)
     {
       //--- параметры ордера
       ulong   position_ticket= PositionGetTicket (i); // тикет позиции
       string position_symbol= PositionGetString ( POSITION_SYMBOL ); // символ
       int     digits=( int ) SymbolInfoInteger (position_symbol, SYMBOL_DIGITS ); // количество знаков после запятой
       ulong   magic= PositionGetInteger ( POSITION_MAGIC ); // MagicNumber позиции
       double volume= PositionGetDouble ( POSITION_VOLUME );     // объем позиции
       double sl= PositionGetDouble ( POSITION_SL );   // Stop Loss позиции
       double tp= PositionGetDouble ( POSITION_TP );   // Take Profit позиции
       ENUM_POSITION_TYPE type=( ENUM_POSITION_TYPE ) PositionGetInteger ( POSITION_TYPE );   // тип позиции
       //--- вывод информации о позиции
       PrintFormat ( "#%I64u %s  %s  %.2f  %s  sl: %s  tp: %s  [%I64d]" ,
                  position_ticket,
                  position_symbol,
                   EnumToString (type),
                  volume,
                   DoubleToString ( PositionGetDouble ( POSITION_PRICE_OPEN ),digits),
                   DoubleToString (sl,digits),
                   DoubleToString (tp,digits),
                  magic);
       //--- если MagicNumber совпадает, Stop Loss и Take Profit не заданы
       if (magic==MA_MAGIC && sl== 0 && tp== 0 )
        {
         //--- вычисление текущих ценовых уровней
         double price= PositionGetDouble ( POSITION_PRICE_OPEN );
         double bid= SymbolInfoDouble (position_symbol, SYMBOL_BID );
         double ask= SymbolInfoDouble (position_symbol, SYMBOL_ASK );
         int     stop_level=( int ) SymbolInfoInteger (position_symbol, SYMBOL_TRADE_STOPS_LEVEL );
         double price_level;
         //--- если уровень минимально допустимого отступа в пунктах от текущей цены закрытия не задан
         if (stop_level<= 0 )
            stop_level= 150 ; // зададим отступ в 150 пунктов от текущей цены закрытия
         else
            stop_level+= 50 ; // уровень отступа возьмем равным (SYMBOL_TRADE_STOPS_LEVEL + 50) пунктов для надежности
         //--- вычисление и округление значений Stop Loss и Take Profit
         price_level=stop_level* SymbolInfoDouble (position_symbol, SYMBOL_POINT );
         if (type== POSITION_TYPE_BUY )
           {
            sl= NormalizeDouble (bid-price_level,digits);
            tp= NormalizeDouble (bid+price_level,digits);
           }
         else
           {
            sl= NormalizeDouble (ask+price_level,digits);
            tp= NormalizeDouble (ask-price_level,digits);
           }
         //--- обнуление значений запроса и результата
         ZeroMemory (request);
         ZeroMemory (result);
         //--- установка параметров операции
         request.action  = TRADE_ACTION_SLTP ; // тип торговой операции
         request.position=position_ticket;   // тикет позиции
         request.symbol=position_symbol;     // символ
         request.sl      =sl;                 // Stop Loss позиции
         request.tp      =tp;                 // Take Profit позиции
         request.magic=MA_MAGIC;         // MagicNumber позиции
         //--- вывод информации о модификации
         PrintFormat ( "Modify #%I64d %s %s" ,position_ticket,position_symbol, EnumToString (type));
         //--- отправка запроса
         if (! OrderSend (request,result))
             PrintFormat ( "OrderSend error %d" , GetLastError ());   // если отправить запрос не удалось, вывести код ошибки
         //--- информация об операции
         PrintFormat ( "retcode=%u  deal=%I64u  order=%I64u" ,result.retcode,result.deal,result.order);
        }
     }
  }
//+------------------------------------------------------------------+

Screenshot_2021-09-03_20-24-38.png 122.9 kB 1366 x 768px

Документация по MQL5: Константы, перечисления и структуры / Структуры данных / Структура торгового запроса
Документация по MQL5: Константы, перечисления и структуры / Структуры данных / Структура торгового запроса
  • www.mql5.com
Структура торгового запроса - Структуры данных - Константы, перечисления и структуры - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Anton Yakovlev:
If you have a good strategy and are willing to share it, I can write an EA. I invite you to discuss it publicly
Hello,is it possible to write an indicator based on candlestick patterns(patterns,movements I don't know what else to call them),with certain candlestick movements and then write an EA for this indicator with the following amendments?
 

Hello !

Thank you very much can you add more trading time for example from 12 to 20 he traded

Thank you

 

Good day!

Please write or send (if there is an analogue) a simple Expert Advisor.

Condition:

At a given time puts the limit orders in both directions. Everything))

I want to use in a tester, so please add parameters for optimization:

- time of Limiters setting (only hours are enough, whole numbers)
- time to delete all Limiters (including those in the market - forced closing)
- number of Limiters set from both sides (i.e. if you set 3, 3 Limiters will be set at both sides)
- distance from the price to the first Limiters
- step between Limits (the rest, i.e. between 1, 2, 3...... )
- SL and TP

It would be greatly appreciated.

 
Ivan Butko #:

Good day!

Please write or download (if there is an analogue) a simple Expert Advisor.

Condition:

At a given time puts the limit orders in both directions. Everything))

I want to use in a tester, so please add parameters for optimization:

- time of Limiters setting (only hours are enough, whole numbers)
- time to delete all Limiters (including those in the market - forced closure)
- number of Limiters set on both sides (i.e., if you set 3, 3 Limiters will be set on both sides)
- distance from the price to the first Limiters
- step between Limiters (the rest, i.e. between 1, 2, 3...... )
- SL and TP

It would be much appreciated.

Only one order on both sides. And a trawl afterwards.

Files:
 
Valeriy Yastremskiy #:

Only one warrant on both sides. And a trawl afterwards.

The idea there is to pick up all the flat overnight movement and so several limits are placed. Anyway, thanks for the program's analogue.

Unfortunately, when testing and optimizing it, the "2021.09.09 16:39:38.084 2021.01.04 07:00:00 Time_Open_Trail_3_21 EURUSD,H1: Alert: The order opening time is less than the current time. The expert Advisor doesn't work.

I tried to set any time: both past and new, it still says so.


 
Ivan Butko #:

The idea there is to pick up all the flat night movement, and so a few limits are exposed. Anyway, thanks for the program's analogue.

Unfortunately, when testing and optimizing it, the "2021.09.09 16:39:38.084 2021.01.04 07:00:00 Time_Open_Trail_3_21 EURUSD,H1: Alert: The order opening time is less than the current time. The expert Advisor doesn't work.

I tried to set any time: both past and new time, still receives the same message.


Do you consider the difference between terminal time and local time? It says that time is later than the one that is set. I have the test passes.

I have a very good time in the tester, I have just placed pending orders, that's all. It was done for Market.

Zy. (Your date is wrong.) It's April 1. )

ZyZy In the tester it is not possible to set the date forward, in OnInit in the tester the terminal time, not the time tested, which has initially already passed.

 
Valeriy Yastremskiy #:

Do you take into account the difference between the terminal time and the local time? It says that the time is later than the time you set. I check it.

I just place pending orders in the tester, that's all. It was done for market.

Zy. (Your date is wrong.) It's April 1. )

ZyZy In the tester it is not possible to set the date forward, in OnInit in the tester the terminal time, not the time being tested, which initially has already passed.

Apparently a different time format in the terminal, I put the test from January 01, 2021, but it starts and writes 2021.01.04 (from January 4)))


 
Ivan Butko #:

Apparently different time format of the terminal, I set the test from January 01, 2021 and it starts and writes 2021.01.04 (from January 4)))


The good thing is, if you want to watch in the tester, you can remove the test for a time later than the real time. This is in OnInit. And I don't remember exactly if in 4ka in the tester time request timecarrent will return the tester time. I think it will return the current time, so in the tester there are just placing orders at once and that's it. Also requesting local time will give the current local time.

This is in the 5k in the tester a complete environment emulator.