Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1632

 
amsgif80 #:

This is the code I tried to insert:

At the top of the code throw this:
enum ENUM_DIRECTION{
DIRECTION_BUY = 0, // buy only
DIRECTION_SELL = 1, // sell only
DIRECTION_ANY = 2, // buy & sell
};

input ENUM_DIRECTION inp_direction = DIRECTION_ANY; // allowed trade direction


further find where in code opens buy and where sell. Look inside the start() or OnTick() function
where buy is in the conditions add:
if(inp_direction!=DIRECTION_SELL)
where sell is in the conditions add:
if(inp_direction!=DIRECTION_BUY )

Where did you put it?
 
MakarFX #:
Where did you put it in?
//+------------------------------------------------------------------+
//| Moving Averages.mq5 |
//| Copyright 2009-2013, MetaQuotes Software Corp.
//+------------------------------------------------------------------+





#property copyright "Copyright 2009-2013, MetaQuotes Software Corp.
#property link "https://www.mql5.com"
#property version "1.00"

enum ENUM_DIRECTION{
DIRECTION_BUY = 0, // buy only
DIRECTION_SELL = 1, // sell only
DIRECTION_ANY = 2, // buy & sell
};

input ENUM_DIRECTION inp_direction = DIRECTION_ANY; // allowed trade direction

#include <Trade\Trade.mqh>

input double MaximumRisk = 0.02; // Maximum Risk in percentage
input double DecreaseFactor = 3; // Descrease factor
input int MovingPeriod = 12; // Moving Average period
input int MovingShift = 6; // Moving Average shift



//---
int ExtHandle=0;


//+------------------------------------------------------------------+
//| Expert initialisation function |
//+------------------------------------------------------------------+




int OnInit(void)
{
//---
ExtHandle=iMA(_Symbol,_Period,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE);
if(ExtHandle==INVALID_HANDLE)
{
printf("Error creating MA indicator");
return(INIT_FAILED);
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| expert tick function |
//+------------------------------------------------------------------+
void OnTick(void)
{
//---
if(PositionSelect(_Symbol))
CheckForClose();
else
CheckForOpen();
//---
}
//+------------------------------------------------------------------+
//| Expert deinitialisation function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double TradeSizeOptimized(void)
{
double price=0.0;
double margin=0.0;
//--- calculate 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_FREEMARGIN)*MaximumRisk/margin,2);
//--- calculate the length of a series of uninterrupted losing trades
if(DecreaseFactor>0)
{
//--- request the entire trading history
HistorySelect(0,TimeCurrent());
//--
int orders=HistoryDealsTotal(); //total number of trades
int losses=0; // number of losing trades in the series

for(int i=orders-1;i>=0;i--)
{
ulong ticket=HistoryDealGetTicket(i);
if(ticket==0)
{
Print("HistoryDealGetTicket failed, no trade history");
break;
}
//--- check for trade symbol
if(HistoryDealGetString(ticket,DEAL_SYMBOL)!=_Symbol)
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 for permissible values of trade volume
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 value of trade volume
return(lot);
}


//+------------------------------------------------------------------+
//| Check for open position conditions |
//+------------------------------------------------------------------+
void CheckForOpen(void)
{
MqlRates rt[2];
//--- copy price values
if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
{
Print("CopyRates of ",_Symbol," failed, no history");
return;
}
//---trade only at the first tick of the new bar
if(rt[1].tick_volume>1)
return;
//--- get current value of Moving Average indicator
double ma[1];
if(CopyBuffer(ExtHandle,0,0,1,ma)!=1)
{
Print("CopyBuffer from iMA failed, no data");
return;
}
//--- signal check
ENUM_ORDER_TYPE signal=WRONG_VALUE;

if(rt[0].open>ma[0] && rt[0].close<ma[0])
signal=ORDER_TYPE_SELL; // condition to sell if(inp_direction!=DIRECTION_BUY)
else
{
if(rt[0].open<ma[0] && rt[0].close>ma[0])
signal=ORDER_TYPE_BUY; // condition to buy if(inp_direction!=DIRECTION_SELL)
}
//--- additional checks
if(signal!=WRONG_VALUE)
if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
if(Bars(_Symbol,_Period)>100)
{
CTrade trade;
trade.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];
//--- copy price values
if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
{
Print("CopyRates of ",_Symbol," failed, no history");
return;
}
//---trade only at the first tick of the new bar
if(rt[1].tick_volume>1)
return;
//--- get current value of Moving Average indicator
double ma[1];
if(CopyBuffer(ExtHandle,0,0,1,ma)!=1)
{
Print("CopyBuffer from iMA failed, no data");
return;
}
//--- get the type of the position, selected earlier through the PositionSelect().
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 checks
if(signal)
if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
if(Bars(_Symbol,_Period)>100)
{
CTrade trade;
trade.PositionClose(_Symbol,3);
}
//---
}
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
  • www.mql5.com
MQL5: язык торговых стратегий для MetaTrader 5, позволяет писать собственные торговые роботы, технические индикаторы, скрипты и библиотеки функций
 

This section should be like this

 //--- проверка сигналов
   ENUM_ORDER_TYPE signal=WRONG_VALUE;

   if(rt[0].open>ma[0] && rt[0].close<ma[0])
     {
      if(inp_direction!=DIRECTION_BUY)
         signal=ORDER_TYPE_SELL;
     }
   else
     {
      if(rt[0].open<ma[0] && rt[0].close>ma[0])
        {
         if(inp_direction!=DIRECTION_SELL)
            signal=ORDER_TYPE_BUY;
        }
     }
 //--- дополнительные проверки 
 
MakarFX #:

This section should be like this.

Makar, this one.

      if(inp_direction==DIRECTION_SELL||inp_direction==DIRECTION_ANY)

is better replaced by this.

      if(inp_direction!=DIRECTION_BUY)
 
Alexey Viktorov #:

Makar, this one

is better replaced by this.

Substituted)
 
MakarFX #:

This section should be like this

Thank you from the bottom of my heart! It all worked at once, it's working. And I've already racked my brains as to how to do it))

 
Can I ask you the same question again, but about my own simple editor-generated EA? I thought that now I will manage to do it myself, but I don't know where to put this Buy/Sell code. I don't know where to paste this Buy/Sell code.
 
amsgif80 #:
Can I ask you the same question again, but about my own simple editor-generated Expert Advisor? I thought that now I will manage to do it myself, but I don't know where to put this Buy/Sell code. I cannot figure out where to paste this Buy/Sell code.
Show me
 
amsgif80 #:

I have shown you how to insert the code in the forum


 
MakarFX #:

You haven't changed anything.

your appeal

is inside.

Makar thanks for the tip

Reason: