Scriverò un EA gratuitamente - pagina 155

 
Oltinbek Sohibov #:

Ciao!

Chi può aiutare ad aggiungere SL e TP e il time frame trading su questo EA!

Grazie mille

//--- 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));
     }
//---

Ho bisogno di fare alcuni aggiustamenti allo SL e al TP

 
Oltinbek Sohibov # :

Ciao !

chi può aiutare su questo consulente aggiungerà SL e TP e trading a intervalli di tempo

Grazie in anticipo

ecco dall'esempio 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:
Se hai una buona strategia e sei disposto a condividerla, posso scrivere un EA. Ti invito a discuterne pubblicamente
Ciao, è possibile scrivere un indicatore basato su modelli di candele (modelli, movimenti, non so come altro chiamarli), con certi movimenti di candele e poi scrivere un EA per questo indicatore con le seguenti modifiche?
 

Ciao!

Grazie mille si può aggiungere più tempo di trading per esempio dalle 12 alle 20 ha scambiato

Grazie

 

Buona giornata!

Per favore scrivi o invia (se c'è un analogo) un semplice Expert Advisor.

Condizione:

In un dato momento mette gli ordini limite in entrambe le direzioni. Tutto))

Voglio usare in un tester, quindi per favore aggiungi i parametri per l'ottimizzazione:

- tempo di impostazione dei Limiters (solo ore sono sufficienti, numeri interi)
- tempo per cancellare tutti i Limiters (inclusi quelli nel mercato - chiusura forzata)
- numero di Limiters impostati da entrambi i lati (cioè, se si imposta 3, 3 Limiters saranno impostati da entrambi i lati)
- distanza dal prezzo ai primi Limiters
- passo tra i Limits (il resto, cioè tra 1, 2, 3 .... )
- SL e TP

Sarebbe molto apprezzato.

 
Ivan Butko #:

Buona giornata!

Per favore scrivi o invia (se c'è un analogo) un semplice Expert Advisor.

Condizione:

In un dato momento mette gli ordini limite in entrambe le direzioni. Tutto))

Voglio usare in un tester, quindi per favore aggiungi i parametri per l'ottimizzazione:

- tempo di impostazione dei Limiters (solo ore sono sufficienti, numeri interi)
- tempo per cancellare tutti i Limiters (compresi quelli nel mercato - chiusura forzata)
- numero di Limiters impostati da entrambi i lati (cioè, se si imposta 3, 3 Limiters saranno impostati da entrambi i lati)
- distanza dal prezzo ai primi Limiters
- passo tra i Limits (il resto, cioè tra 1, 2, 3 .... )
- SL e TP

Sarebbe molto apprezzato.

Solo un ordine su entrambi i lati. E dopo una pesca a strascico.

File:
 
Valeriy Yastremskiy #:

Solo un mandato su entrambi i lati. E dopo un'indagine a tappeto.

L'idea è quella di raccogliere tutto il movimento notturno piatto e quindi vengono posti diversi limiti. Comunque, grazie per l'analogo del programma.

Purtroppo, quando l'ho testato e ottimizzato, il "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. Il consulente esperto non funziona.

Ho provato a impostare qualsiasi tempo: sia passato che nuovo, dice ancora così.


 
Ivan Butko #:

L'idea è quella di raccogliere tutto il movimento notturno piatto, e quindi alcuni limiti sono esposti. Comunque, grazie per l'analogo del programma.

Purtroppo, quando l'ho testato e ottimizzato, il "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. Il consulente esperto non funziona.

Ho provato a impostare qualsiasi ora: sia l'ora passata che quella nuova, riceve ancora lo stesso messaggio.


Considera la differenza tra l'ora terminale e l'ora locale? Dice che l'orario è più tardivo di quello impostato. Ho i pass per il test.

Mi trovo molto bene nel tester, ho solo fatto degli ordini in sospeso, tutto qui. È stato fatto per il mercato.

Zy. (La tua data è sbagliata.) È il 1° aprile. )

ZyZy Nel tester non è possibile impostare la data in avanti, in OnInit nel tester il tempo terminale, non il tempo testato, che in origine è già passato.

 
Valeriy Yastremskiy #:

Tieni conto della differenza tra l'ora del terminale e l'ora locale? Dice che l'ora è più tardi dell'ora che avete impostato. Controllo.

Metto solo gli ordini in sospeso nel tester, tutto qui. È stato fatto per il mercato.

Zy. (La tua data è sbagliata.) È il 1° aprile. )

ZyZy Nel tester non è possibile impostare la data in avanti, in OnInit nel tester l'ora del terminale, non quella che si sta testando, che inizialmente è già passata.

Apparentemente un formato orario diverso nel terminale, ho messo il test dal 01 gennaio 2021, ma parte e scrive 2021.01.04 (dal 4 gennaio))


 
Ivan Butko #:

Apparentemente il formato orario del terminale è diverso, ho impostato il test dal 01 gennaio 2021 e parte e scrive 2021.01.04 (dal 4 gennaio))


La cosa buona è che se vuoi guardare nel tester, puoi rimuovere il test per un tempo successivo a quello reale. Questo è in OnInit. E non ricordo esattamente se in 4ka nella richiesta di tempo del tester timecarrent restituirà il tempo del tester. Penso che restituisca l'ora corrente, quindi nel tester ci sono solo ordini in una volta e basta. Anche la richiesta dell'ora locale darà l'ora locale corrente.

Questo è nel 5k nel tester un emulatore di ambiente completo.

Motivazione: