How To make some Risk Management on mt5 Expert Advisor

 

Please help, i still do not understand how to do that,

Here example of Risk management pending order Buy on MQL4 language, it is work...., but how to make such that coding on MQL5 language ?

Help me please, thanks

 

 

 #include <stdlib.mqh>

#include <WinUser32.mqh>


// exported variables

extern int BuyStoploss2 = 20;

extern int BuyTakeprofit2 = 30;

extern int PriceOffset2 = 20;

extern double BalanceRiskPercent2 = 5;



// local variables

double PipValue=1;    // this variable is here to support 5-digit brokers

bool Terminated = false;

string LF = "\n";  // use this in custom or utility blocks where you need line feeds

int NDigits = 4;   // used mostly for NormalizeDouble in Flex type blocks

int ObjCount = 0;  // count of all objects created on the chart, allows creation of objects with unique names

int current = 0;




int init()

{

    NDigits = Digits;

    

    if (false) ObjectsDeleteAll();      // clear the chart

    

    

    Comment("");    // clear the chart

}


// Expert start

int start()

{

    if (Bars < 10)

    {

        Comment("Not enough bars");

        return (0);

    }

    if (Terminated == true)

    {

        Comment("EA Terminated.");

        return (0);

    }

    

    OnEveryTick1();

    

}


void OnEveryTick1()

{

    if (true == false && true) PipValue = 10;

    if (true && (NDigits == 3 || NDigits == 5)) PipValue = 10;

    

    BuyPendingRiskFixed2();

    

}


void BuyPendingRiskFixed2()

{

    double lotsize = MarketInfo(Symbol(),MODE_LOTSIZE) / AccountLeverage();

    double pipsize = 1 * 10;

    double maxlots = AccountBalance() / 100 * BalanceRiskPercent2 / lotsize * pipsize;

    if (BuyStoploss2 == 0) Print("OrderSend() error - stoploss can not be zero");

    double lots = maxlots / BuyStoploss2 * 10;

    

    // calculate lot size based on current risk

    double lotvalue = 0.001;

    double minilot = MarketInfo(Symbol(), MODE_MINLOT);

    int powerscount = 0;

    while (minilot < 1)

    {

        minilot = minilot * MathPow(10, powerscount);

        powerscount++;

    }

    lotvalue = NormalizeDouble(lots, powerscount - 1);

    

    if (lotvalue < MarketInfo(Symbol(), MODE_MINLOT))    // make sure lot is not smaller than allowed value

    {

        lotvalue = MarketInfo(Symbol(), MODE_MINLOT);

    }

    if (lotvalue > MarketInfo(Symbol(), MODE_MAXLOT))    // make sure lot is not greater than allowed value

    {

        lotvalue = MarketInfo(Symbol(), MODE_MAXLOT);

    }

    

    int expire = TimeCurrent() + 60 * 60;

    double price = NormalizeDouble(Ask, NDigits) + PriceOffset2*PipValue*Point;

    double SL = price - BuyStoploss2*PipValue*Point;

    if (BuyStoploss2 == 0) SL = 0;

    double TP = price + BuyTakeprofit2*PipValue*Point;

    if (BuyTakeprofit2 == 0) TP = 0;

    if (60 == 0) expire = 0;

    int ticket = OrderSend(Symbol(), OP_BUYSTOP, lotvalue, price, 4, SL, TP, "EA sederhana", 1, expire, Blue);

    if (ticket == -1)

    {

        Print("OrderSend() error - ", ErrorDescription(GetLastError()));

    }

    

}




int deinit()

{

    if (false) ObjectsDeleteAll();

    

    

}

Documentation on MQL5: Standard Constants, Enumerations and Structures / Trade Constants / Order Properties
Documentation on MQL5: Standard Constants, Enumerations and Structures / Trade Constants / Order Properties
  • www.mql5.com
Standard Constants, Enumerations and Structures / Trade Constants / Order Properties - Documentation on MQL5
 
akhmadfx:

Please help, i still do not understand how to do that,

Here example of Risk management pending order Buy on MQL4 language, it is work...., but how to make such that coding on MQL5 language ?

Help me please, thanks

 

 <CODE REMOVED>

When you post code . . .    please use the   SRC   button to post code: How to use the   SRC   button.
 
akhmadfx:

Please help, i still do not understand how to do that,

Here example of Risk management pending order Buy on MQL4 language, it is work...., but how to make such that coding on MQL5 language ?

This is mql4 code,  do you need help with mql4 or mql5 ?  if mql4 use the mql4 Forum
MQL4: automated trading forum
  • www.mql5.com
MQL4: automated trading forum
 
RaptorUK:
This is mql4 code,  do you need help with mql4 or mql5 ?  if mql4 use the mql4 Forum

i need mql5 code , please help me

i need to add MoneyFixedRisk code on this simple pending buy EA,

 

#include <Trade\Trade.mqh>

// exported variables
input double Lots2 = 1;
input int Stoploss2 = 5;
input int Takeprofit2 = 100;
input int PriceOffset2 = 3;


// local variables
double PipValue=1;    // this variable is here to support 5-digit brokers
bool Terminated = false;
string LF = "\n";  // use this in custom or utility blocks where you need line feeds
int NDigits = 4;   // used mostly for NormalizeDouble in Flex type blocks
int ObjCount = 0;  // count of all objects created on the chart, allows creation of objects with unique names
int current = 0;



//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    //---
    NDigits = Digits();
    if (NDigits == 3 || NDigits == 5) PipValue = 10;
    
    if (AccountInfoInteger(ACCOUNT_TRADE_EXPERT) == false)
    {
        Print("Check terminal options because EA trade option is set to not allowed.");
        Comment("Check terminal options because EA trade option is set to not allowed.");
    }
    
    if (false) ObjectsDeleteAll(0);      // clear the chart
    
    
    Comment("");    // clear the chart
    //---
    return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    //---
    if (false) ObjectsDeleteAll(0);
    
    
}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    //---
    if (Terminated == true)
    {
        Comment("EA Terminated.");
    }
    
    OnEveryTick1();
}

//+------------------------------------------------------------------+
//| Get Low for specified bar index                                  |
//+------------------------------------------------------------------+
double Low(int index)
{
    double arr[];
    double low = 0;
    ArraySetAsSeries(arr, true);
    int copied = CopyLow(Symbol(), PERIOD_CURRENT, 0, Bars(Symbol(), PERIOD_CURRENT), arr);
    if (copied>0 && index<copied) low = arr[index];
    return (low);
}
//+------------------------------------------------------------------+
//| Get the High for specified bar index                             |
//+------------------------------------------------------------------+
double High(int index)
{
    double arr[];
    double high = 0;
    ArraySetAsSeries(arr, true);
    int copied = CopyHigh(Symbol(), PERIOD_CURRENT, 0, Bars(Symbol(), PERIOD_CURRENT), arr);
    if (copied>0 && index<copied) high=arr[index];
    return(high);
}
//+------------------------------------------------------------------+
//| Get Close for specified bar index                                |
//+------------------------------------------------------------------+
double Close(int index)
{
    double arr[];
    double close = 0;
    ArraySetAsSeries(arr, true);
    int copied = CopyClose(Symbol(), PERIOD_CURRENT, 0, Bars(Symbol(), PERIOD_CURRENT), arr);
    if (copied>0 && index<copied) close = arr[index];
    return (close);
}
//+------------------------------------------------------------------+
//| Get Open for specified bar index                                 |
//+------------------------------------------------------------------+
double Open(int index)
{
    double arr[];
    double open = 0;
    ArraySetAsSeries(arr, true);
    int copied = CopyOpen(Symbol(), PERIOD_CURRENT, 0, Bars(Symbol(), PERIOD_CURRENT), arr);
    if (copied>0 && index<copied) open = arr[index];
    return (open);
}
//+------------------------------------------------------------------+
//| Get current bid value                                            |
//+------------------------------------------------------------------+
double Bid()
{
    return (SymbolInfoDouble(Symbol(), SYMBOL_BID));
}

//+------------------------------------------------------------------+
//| Get current ask value                                            |
//+------------------------------------------------------------------+
double Ask()
{
    return (SymbolInfoDouble(Symbol(), SYMBOL_ASK));
}

//+------------------------------------------------------------------+
//| Is there an error                                                |
//+------------------------------------------------------------------+
bool IsError(MqlTradeResult& result, string function)
{
    if (result.retcode != 0 && result.retcode != TRADE_RETCODE_DONE && result.retcode != TRADE_RETCODE_PLACED)
    {
        Print("Function: ", function, " Error: ", result.retcode, " ", result.comment);
        return (true);
    }
    else
    Print("> Executed: [", function, "]");
    return (false);
}

bool IsError(CTrade& trade, string function)
{
    if (trade.ResultRetcode() != 0 && trade.ResultRetcode() != TRADE_RETCODE_DONE && trade.ResultRetcode() != TRADE_RETCODE_PLACED)
    {
        Print("Function: ", function, " Error: ", trade.ResultRetcode(), " ", trade.ResultRetcodeDescription());
        return (true);
    }
    else
    Print("> Executed: [", function, "]");
    return (false);
}

//+------------------------------------------------------------------+
//| Get indicator value back                                         |
//+------------------------------------------------------------------+
double GetIndicator(int handle, int buffer_num, int index)
{
    //--- array for the indicator values
    double arr[];    
    //--- obtain the indicator value in the last two bars
    if (CopyBuffer(handle, buffer_num, 0, index+1, arr) <= 0)
    {        
        Sleep(200);
        for(int i=0; i<100; i++)
        {
            if (BarsCalculated(handle) > 0)
            break;
            Sleep(50);
        }
        int copied = CopyBuffer(handle, buffer_num, 0, index+1, arr);
        if (copied <= 0)
        {
            Print("CopyBuffer failed. Maybe history has not download yet? Error = ", GetLastError());
            return -1;
        }
        else
        return (arr[index]);
    }
    else
    {
        return (arr[index]);
    }
    
    return 0;
}

//+------------------------------------------------------------------+
//| Building blocks                                                  |
//+------------------------------------------------------------------+
void OnEveryTick1()
{
    
    if (NDigits == 3 || NDigits == 5) PipValue = 10;
    
    OncePerBar3();
    
}

void OncePerBar3()
{
    static datetime Old_Time;
    datetime New_Time[1];
    // copying the last bar time to the element New_Time[0]
    int copied = CopyTime(Symbol(), Period(), 0, 1, New_Time);
    if (copied > 0)     // ok, the data has been copied successfully
    {
        if (Old_Time != New_Time[0]) // if old time isn't equal to new bar time
        {
            Old_Time=New_Time[0];            // saving bar time
            BuyPendingOrder22();
            
        }
        else
        {
            return;     // still the same bar
        }
    }
    else
    {
        Alert("Error in copying historical times data, error =",GetLastError());
        ResetLastError();
        return;
    }
}

void BuyPendingOrder22()
{
    
    double price = NormalizeDouble(High(2), NDigits) - PriceOffset2*PipValue*Point();
    double SL = price - Stoploss2*PipValue*Point();
    if (Stoploss2 == 0) SL = 0;
    double TP = price + Takeprofit2*PipValue*Point();
    if (Takeprofit2 == 0) TP = 0;
    
    //--- prepare a request
    MqlTradeRequest request;
    ZeroMemory(request);
    request.action=TRADE_ACTION_PENDING;         // setting a pending order
    request.magic = 1;                  // ORDER_MAGIC
    request.symbol = Symbol();                      // symbol
    request.volume = Lots2;                          // volume in 0.1 lots
    request.sl = SL;                                // Stop Loss is not specified
    request.tp = TP;                                // Take Profit is not specified
    request.deviation = 3;                         // deviation in 5 points
    request.price = price;
    request.type_time = ORDER_TIME_SPECIFIED;
    request.expiration = TimeTradeServer()+PeriodSeconds(PERIOD_D1)-2;
    //--- form the order type
    request.type = ORDER_TYPE_BUY_STOP;           // order type ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_LIMIT, ORDER_TYPE_BUY_STOP, ORDER_TYPE_SELL_STOP
    //--- form the price for the pending order
    MqlTradeResult result;
    ZeroMemory(result);
    OrderSend(request,result);
    // check the result
    if (!IsError(result, __FUNCTION__))
    {
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}




Files:
 
akhmadfx:
i need mql5 code , please help me
You can learn to do it or ask someone to do it for you.
Reason: