Écrire des EA gratuites - page 11

 
4p0ssum:
Merci cher gss pour l'intérêt que vous portez à ma demande. Si vous êtes un programmeur MQL4, vous pouvez échanger votre EA avec d'autres programmeurs MQL4. Je pense que le code que j'ai est bon, je l'ai collecté à partir de différents EAs, ou pour être plus précis à partir de l'un d'entre eux, j'ai pris uniquement la fonction Trailing Stop. Le reste, je l'ai inventé moi-même (concernant les commandes en cours). Je voudrais vous demander, ainsi qu'à d'autres gourous, de jeter un coup d'œil à mon code et d'ajouter deux fonctions supplémentaires à ce robot, si vous le voulez bien.
1) Suppression d'un ordre en attente lorsque l'un des deux est déclenché.
2) Augmentation automatique d'un lot (pour chaque 50$ 0.01 i.e. pour 100$ ce sera 0.02).
Merci d'avance.

//+------------------------------------------------------------------+
//|                                                      4p0ssum.mq4 |
//|                        Copyright 2013, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property strict

extern int    TakeProfit     = 100.0;
extern bool   AllPositions   = True; // Управлять всеми позициями
extern bool   ProfitTrailing = True;  // Тралить только профит
extern int    TrailingStop   = 50;    // Фиксированный размер трала
extern int    TrailingStep   = 0;     // Шаг трала
extern bool   Del            = false; // Удалять оппозитный ордер
extern bool   UseSound       = False;  // Использовать звуковой сигнал
extern string NameFileSound  = "expert.wav";  // Наименование звукового файла


//------- Внешние параметры модуля -----------------------------------
extern string _Parameters_b_Lots = "---------- Параметры модуля расчёта лота";
extern int LotsWayChoice  = 0;    // Способ выбора рабочего лота:
                                  //  0-фиксированный,
                                  //  1-процент от депозита,
                                  //  2-фиксированно-пропорциональный,
                                  //  3-фракционно-фиксированный,
extern double Lots        = 0.1;  // Фиксированный размер лота
extern int LotsPercent    = 10;   // Процент от депозита
extern int LotsDeltaDepo  = 500;  // Коэффициент приращения депозита
extern int LotsDepoForOne = 500;  // Размер депозита для одного минилота
extern int LotsMax        = 1000; // Максимальное количество минилотов


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void start() 
{
double TakeProfitLevelB;
double TakeProfitLevelS;

double BuyStart = Ask + 400*_Point;
double SellStart = Bid - 400*_Point;

TakeProfitLevelB = BuyStart + TakeProfit*Point;
TakeProfitLevelS = SellStart - TakeProfit*Point;

if (Open[1]==Close[1]&& OrdersTotal()==0)
{
int BuyTicket = OrderSend(Symbol(),OP_BUYSTOP,GetSizeLot(),BuyStart,3,0,TakeProfitLevelB,NULL,0,0,Green);
int SellTicket = OrderSend(Symbol(),OP_SELLSTOP,GetSizeLot(),SellStart,3,0,TakeProfitLevelS,NULL,0,0,Blue);
}
  for (int i=0; i<OrdersTotal(); i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (AllPositions || OrderSymbol()==Symbol()) {
        TrailingPositions();
      }
    }
  }
 if(Del && ExistPositions(Symbol()))DeleteOrders(Symbol(),-1);
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void TrailingPositions() 
{
  double pBid, pAsk, pp;

  pp = MarketInfo(OrderSymbol(), MODE_POINT);
  if (OrderType()==OP_BUY) {
    pBid = MarketInfo(OrderSymbol(), MODE_BID);
    if (!ProfitTrailing || (pBid-OrderOpenPrice())>TrailingStop*pp) {
      if (OrderStopLoss()<pBid-(TrailingStop+TrailingStep-1)*pp) {
        ModifyStopLoss(pBid-TrailingStop*pp);
        return;
      }
    }
  }
  if (OrderType()==OP_SELL) {
    pAsk = MarketInfo(OrderSymbol(), MODE_ASK);
    if (!ProfitTrailing || OrderOpenPrice()-pAsk>TrailingStop*pp) {
      if (OrderStopLoss()>pAsk+(TrailingStop+TrailingStep-1)*pp || OrderStopLoss()==0) {
        ModifyStopLoss(pAsk+TrailingStop*pp);
        return;
      }
    }
  }
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ModifyStopLoss(double ldStopLoss) 
{
  bool fm;

  fm=OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,CLR_NONE);
  if (fm && UseSound) PlaySound(NameFileSound);
}
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 06.03.2008                                                     |
//|  Описание : Возвращает флаг существования позиций                          |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    ot - время открытия             ( 0   - любое время открытия)           |
//+----------------------------------------------------------------------------+
bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=0) {
  int i, k=OrdersTotal();

  if (sy=="" || sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              if (ot<=OrderOpenTime()) return(True);
            }
          }
        }
      }
    }
  }
  return(False);
}
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия  : 13.06.2007                                                      |
//|  Описание : Удаление ордеров. Версия функции для тестов на истории.        |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ("" или NULL - текущий символ)          |
//|    op - операция                   (    -1      - любая позиция)           |
//|    mn - MagicNumber                (    -1      - любой магик)             |
//+----------------------------------------------------------------------------+
void DeleteOrders(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal(), ot;

  if (sy=="" || sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      ot=OrderType();
      if (ot==OP_BUYLIMIT || ot==OP_BUYSTOP || ot==OP_SELLLIMIT || ot==OP_SELLSTOP) {
        if (OrderSymbol()==sy && (op<0 || ot==op)) {
          if (mn<0 || OrderMagicNumber()==mn) {
            OrderDelete(OrderTicket(), clrRed);
          }
        }
      }
    }
  }
}
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.02.2008                                                     |
//|  Описание : Возвращает одно из двух значений взависимости от условия.      |
//+----------------------------------------------------------------------------+
string IIFs(bool condition, string ifTrue, string ifFalse) {
  if (condition) return(ifTrue); else return(ifFalse);
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Вывод сообщения в коммент и в журнал                           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    m - текст сообщения                                                     |
//+----------------------------------------------------------------------------+
void Message(string m) {
  Comment(m);
  if (StringLen(m)>0) Print(m);
}
//+------------------------------------------------------------------+
//| Главная функция получения размера лота (вызывается из советника) |
//+------------------------------------------------------------------+
double GetSizeLot()
{
  double dLot;

  if (LotsWayChoice==0) dLot=Lots;

  // фиксированный процент от депозита
  if (LotsWayChoice==1)
  {
    dLot=MathCeil(AccountFreeMargin()/100000*LotsPercent)/10;
  }

  // фиксированно-пропорциональный
  if (LotsWayChoice==2)
  {
    int k=LotsDepoForOne;
    for (double i=2; i<=LotsMax; i++)
    {
      k=k+i*LotsDeltaDepo;
      if (k>AccountFreeMargin())
      {
        dLot=(i-1)/10000; break;
      }
    }
  }

  // фракционно-фиксированный
  if (LotsWayChoice==3)
  {
    dLot=MathCeil((AccountFreeMargin()-LotsDepoForOne)/LotsDeltaDepo)/10;
  }
  if (dLot<MarketInfo(Symbol(), MODE_MINLOT)) dLot=MarketInfo(Symbol(), MODE_MINLOT);
  if (dLot<0.01) dLot=0.01;
  return(dLot);
}
//+------------------------------------------------------------------+
 
Bonjour, je me demandais si vous pouviez m'aider à écrire un EA. Voici l'affaire. Après la fermeture d'une bougie avec un grand volume (achat ou vente), un ordre d'achat ou de vente avec un lot et un TP personnalisables est ouvert sur la deuxième bougie. Merci. Si vous pouvez m'aider)) Terminal MT4
 
ilfatiskhakov:
Bonjour, je me demandais si vous pouviez m'aider à rédiger une évaluation environnementale. Voici l'affaire. Après la fermeture d'une bougie avec un grand volume (achat ou vente), un ordre d'achat ou de vente avec un lot et un TP personnalisables est ouvert sur la deuxième bougie. Merci. Si vous pouvez m'aider)) Terminal MT4

https://www.mql5.com/ru/code/mt4/experts

MQL5 Code Base: Советники
MQL5 Code Base: Советники
  • www.mql5.com
Советники для MetaTrader 4 с исходными кодами
 

Bonjour, je vous demande d'écrire un EA basé sur l'indicateur ADX ci-joint. Je vous demande d'écrire un EA pour cet indicateur et non pour un autre, car il en existe de nombreuses variétés.

Le principe de fonctionnement va de flèche en flèche, lorsque la flèche apparaît la transaction est ouverte et lorsque le signal opposé apparaît la transaction est fermée et ouverte dans la direction opposée. Le lot est calculé à l'aide de la formule (Balance x (risque/1000), où le risque est de 0 à 1. Il devrait également y avoir une fonction de lot fixe

Dossiers :
 
SAJSRAh:

Bonjour, je vous demande d'écrire un EA basé sur l'indicateur ADX ci-joint. Je vous demande d'écrire un EA pour cet indicateur et non pour un autre, car il en existe de nombreuses variétés.

Le principe de fonctionnement va de flèche en flèche, lorsque la flèche apparaît la transaction est ouverte et lorsque le signal opposé apparaît la transaction est fermée et ouverte dans la direction opposée. Le lot est calculé à l'aide de la formule (Balance x (risque/1000), où le risque est compris entre 0 et 1. Il devrait également y avoir une fonction de lot constant.

Faux signaux

+ indicateur de l'avenir

 
Iurii Tokman:

Faux signaux solides

+ indicateur de l'avenir

Je trade manuellement sur H4 et c'est pas mal

 

Iurii Tokman:

Faux signaux solides

+ indicateur de l'avenir

Dans MT5, les points d'entrée sont légèrement différents

EURUSDH1

//+------------------------------------------------------------------+
//|                                           Back and forth ADX.mq5 |
//|                               Copyright © 2005, BrainTrading Inc |
//|                                      http://www.braintrading.com |
//+------------------------------------------------------------------+
//---- авторство индикатора
#property copyright "Copyright © 2005, BrainTrading Inc."
//---- ссылка на сайт автора
#property link      "http://www.braintrading.com/"
//---- номер версии индикатора
#property version   "1.00"
//---- отрисовка индикатора в главном окне
#property indicator_chart_window
//---- для расчета и отрисовки индикатора использовано два буфера
#property indicator_buffers 2
//---- использовано всего два графических построения
#property indicator_plots   2
//+----------------------------------------------+
//|  Параметры отрисовки медвежьего индикатора   |
//+----------------------------------------------+
//---- отрисовка индикатора 1 в виде символа
#property indicator_type1   DRAW_ARROW
//---- в качестве цвета медвежьей линии индикатора использован розовый цвет
#property indicator_color1  Wheat
//---- толщина линии индикатора 1 равна 4
#property indicator_width1  2
//---- отображение метки медвежьей линии индикатора
#property indicator_label1  "Back and forth ADX Sell"
//+----------------------------------------------+
//|  Параметры отрисовки бычьго индикатора       |
//+----------------------------------------------+
//---- отрисовка индикатора 2 в виде символа
#property indicator_type2   DRAW_ARROW
//---- в качестве цвета бычей линии индикатора использован зеленый цвет
#property indicator_color2  LightSeaGreen
//---- толщина линии индикатора 2 равна 4
#property indicator_width2  2
//---- отображение метки бычьей линии индикатора
#property indicator_label2 "Back and forth ADX Buy"
//+----------------------------------------------+
//| Входные параметры индикатора                 |
//+----------------------------------------------+
input int adx_period=14;  // период расчета ADX
//---- объявление динамических массивов, которые будут в
//---- дальнейшем использованы в качестве индикаторных буферов
double SellBuffer[];
double BuyBuffer[];
//--- индикаторные буферы
double ADXBuffer[];
double DI_plusBuffer[];
double DI_minusBuffer[];
//---
int OldTrend;
int ADX_Handle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit()
  {
//---- получение хендла индикатора ADX
   ADX_Handle=iADX(Symbol(),Period(),adx_period);
   if(ADX_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора iADX");
//---- превращение динамического массива в индикаторный буфер
   SetIndexBuffer(0,SellBuffer,INDICATOR_DATA);
//---- осуществление сдвига начала отсчета отрисовки индикатора 1
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,0);
//--- создание метки для отображения в DataWindow
   PlotIndexSetString(0,PLOT_LABEL,"Back and forth ADX Sell");
//---- символ для индикатора
   PlotIndexSetInteger(0,PLOT_ARROW,108);
//---- индексация элементов в буфере как в таймсерии
   ArraySetAsSeries(SellBuffer,true);
//---- превращение динамического массива в индикаторный буфер
   SetIndexBuffer(1,BuyBuffer,INDICATOR_DATA);
//---- осуществление сдвига начала отсчета отрисовки индикатора 2
   PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,0);
//--- создание метки для отображения в DataWindow
   PlotIndexSetString(1,PLOT_LABEL,"Back and forth ADX Buy");
//---- символ для индикатора
   PlotIndexSetInteger(1,PLOT_ARROW,108);
//---- индексация элементов в буфере как в таймсерии
   ArraySetAsSeries(BuyBuffer,true);
//--- привязка массивов к индикаторным буферам
   SetIndexBuffer(2,ADXBuffer,INDICATOR_DATA);
   SetIndexBuffer(3,DI_plusBuffer,INDICATOR_DATA);
   SetIndexBuffer(4,DI_minusBuffer,INDICATOR_DATA);
//---- установка формата точности отображения индикатора
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//---- имя для окон данных и лэйба для субъокон
   string short_name="Back and forth ADX";
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//----
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---- проверка количества баров на достаточность для расчета
   if(BarsCalculated(ADX_Handle)<rates_total
      || rates_total<0)
      return(0);
//---- объявления локальных переменных
   int to_copy,limit,bar;
   bool ADXUp,ADXDn;
//---- расчеты необходимого количества копируемых данных и
//стартового номера limit для цикла пересчета баров
   if(prev_calculated>rates_total || prev_calculated<=0)// проверка на первый старт расчета индикатора
     {
      to_copy=rates_total; // расчетное количество всех баров
      limit=rates_total-1; // стартовый номер для расчета всех баров
     }
   else
     {
      to_copy=rates_total-prev_calculated+1; // расчетное количество только новых баров
      limit=rates_total-prev_calculated; // стартовый номер для расчета новых баров
     }
//---- копируем вновь появившиеся данные в массивы
   if(CopyBuffer(ADX_Handle,0,0,to_copy,ADXBuffer)<=0)
      return(0);
   if(CopyBuffer(ADX_Handle,1,0,to_copy,DI_plusBuffer)<=0)
      return(0);
   if(CopyBuffer(ADX_Handle,2,0,to_copy,DI_minusBuffer)<=0)
      return(0);
//---- индексация элементов в массивах как в таймсериях
   ArraySetAsSeries(ADXBuffer,true);
   ArraySetAsSeries(DI_plusBuffer,true);
   ArraySetAsSeries(DI_minusBuffer,true);
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
//---- основной цикл расчета индикатора
   for(bar=limit; bar>=0; bar--)
     {
      SellBuffer[bar]=0.0;
      BuyBuffer[bar]=0.0;
      ADXDn=DI_plusBuffer[bar]<DI_minusBuffer[bar] && ADXBuffer[bar]<DI_minusBuffer[bar];
      ADXUp=DI_plusBuffer[bar]>DI_minusBuffer[bar] && ADXBuffer[bar]>DI_minusBuffer[bar];
      //----
      if(ADXDn)
        {
         if(OldTrend>0)
            SellBuffer[bar]=high[bar];
         if(bar!=0)
            OldTrend=-1;
        }
      if(ADXUp)
        {
         if(OldTrend<0)
            BuyBuffer[bar]=low[bar];
         if(bar!=0)
            OldTrend=+1;
        }
     }
//----
   return(rates_total);
  }
//+------------------------------------------------------------------+

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

J'ai couru pour vérifier l'indicateur - cela semble être un bon début.

tout va bien jusqu'à présent

tout va bien jusqu'à présent 2
 
SAJSRAh:

Je trade manuellement sur H4 et cela semble bon.

résultats d'activités sur le studio

 
SanAlex:

MT5 a des points d'entrée légèrement différents

où est l'avenir ?

    for(int i = 0; i < limit; i++)
      {
        b4plusdi = iADX(NULL, 0, ADXcrossesPeriod, PRICE_CLOSE, MODE_PLUSDI, i - 1);
i - 1
 
Iurii Tokman:

Où est l'avenir ?

Je n'en ai aucune idée - je l'ai fait tel qu'il est ! Je suis autodidacte, tout par méthode scientifique

\\\\\\\\\\\\\ Je suis moi-même surpris - il semble aussi que le résultat soit bon - mon expert est lourd - il faut beaucoup de temps pour le tester

Tout va bien jusqu'à présent 3

Raison: