Writing free EAs - page 11

 
4p0ssum:
Thank you dear gss for your interest in my request. If you are an MQL4 programmer, you can exchange your EA with other MQL4 programmers. I think that the code I have is good, I have collected it from different EAs, or to be more precise from one of them, I took only Trailing Stop function. The rest I have made up myself (concerning pending orders). I would like to ask you and other gurus to take a look at my code and add two more functions to this robot, if you would not mind.
1) Deletion of a pending order when one of the two is triggered.
2) Automatic increase of a lot (for each 50$ 0.01 i.e. for 100$ it will be 0.02).
Thank you in advance.

//+------------------------------------------------------------------+
//|                                                      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);
}
//+------------------------------------------------------------------+
 
Hello, I was wondering if you could help me write an EA. Here's the deal. After a candle closes with a large volume (Buy or Sell), a Buy or Sell order with a customizable lot and TP is opened on the second one. Thank you. If you could help)) MT4 terminal
 
ilfatiskhakov:
Hi. I was wondering if you could help with writing an EA. Here's the deal. After a candle closes with a large volume (Buy or Sell), a Buy or Sell order with a customizable lot and TP is opened on the second one. Thank you. If you could help)) MT4 terminal

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

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

Hello, I'm asking you to write an EA for the attached ADX indicator. I am asking you to write an EA for this indicator and not for another one, because there are many varieties.

The principle of operation from arrow to arrow, when the arrow appears deal is opened and when the opposite signal appears deal is closed and opened in the opposite direction. The lot is calculated using the formula (Balance x (risk/1000), where the risk is from 0 to 1. There should also be a fixed lot function

Files:
 
SAJSRAh:

Hello, I'm asking you to write an EA for the attached ADX indicator. I am asking you to write an EA for this indicator and not for another one, because there are many varieties.

The principle of operation from arrow to arrow, when the arrow appears deal is opened and when the opposite signal appears deal is closed and opened in the opposite direction. The lot is calculated using the formula (Balance x (risk/1000), where the risk is from 0 to 1. There should also be a constant lot function

False signals

+ indicator of the future

 
Iurii Tokman:

Solid false signals

+ indicator of the future

I trade manually on H4 and it's not bad

 

Iurii Tokman:

Solid false signals

+ indicator of the future

In MT5 slightly different entry points

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

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

ran to check the indicator - seems to be a good start

going well so far

going well so far 2
 
SAJSRAh:

I trade manually on H4 and it looks good.

trading results on the studio

 
SanAlex:

MT5 has slightly different entry points

where is the future ?

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

Where's the future?

I have no idea - I made it as it is! I am self-taught, all by scientific method

\\\\\\\\\\\\\ I am surprised myself - it also seems to be a good result - my expert is heavy - it takes a long time to test

Going well so far 3