System Trading 게시글

Mastering Order Management in MetaTrader 4: Cut Loss or Take Profit with Ease

첨부파일
34194.zip (995 bytes, 다운로드 0회)

Using the EA for Effective Trade Management

Hey fellow traders! Today, we’re diving into an Expert Advisor (EA) that serves as a handy tool for managing your trades in MetaTrader 4. Whether you’re looking to lock in profits or minimize losses, this EA has got your back.

Key Inputs for Your EA

To get started, you’ll need to configure three essential inputs:

  • Profit Target: This is the amount you aim to gain from your trades.
  • Cut Loss: This is the threshold at which you’ll exit a losing trade to prevent further losses.
  • Magic Number: A unique identifier for your trades that allows the EA to manage them effectively.
extern double inTargetProfitMoney = 10; // Target Profit ($)
extern double inCutLossMoney = 0.0; // Cut Loss ($)
extern int inMagicNumber = 0; // Magic Number

Initializing the EA

When you run this EA, it first calls the OnInit() function where it checks your inputs and initializes the necessary variables:

int OnInit()
{
    //---
    if (inTargetProfitMoney <= 0)
    {
        Alert("Invalid input");
        return (INIT_PARAMETERS_INCORRECT);
    }

    inCutLossMoney = MathAbs(inCutLossMoney) * -1;
    //---
    return (INIT_SUCCEEDED);
}

Monitoring Price Movements

Next up, every time there’s a price movement (tick), the OnTick() function is triggered:

void OnTick()
{
    //---
    double tFloating = 0.0;
    int tOrder = OrdersTotal();
    for (int i = tOrder - 1; i >= 0; i--)
    {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            if (OrderMagicNumber() == inMagicNumber)
            {
                tFloating += OrderProfit() + OrderCommission() + OrderSwap();
            }
        }
    }

    if (tFloating >= inTargetProfitMoney || (tFloating <= inCutLossMoney && inCutLossMoney < 0))
    {
        fCloseAllOrders();
    }
}

Closing Orders

The OnTick() function continuously calculates your total profit or loss. Once it hits your target or the maximum loss limit, it triggers the order closure:

void fCloseAllOrders()
{
    double priceClose = 0.0;
    int tOrders = OrdersTotal();
    for (int i = tOrders - 1; i >= 0; i--)
    {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            if (OrderMagicNumber() == inMagicNumber && (OrderType() == OP_BUY || OrderType() == OP_SELL))
            {
                priceClose = (OrderType() == OP_BUY) ? MarketInfo(OrderSymbol(), MODE_BID) : MarketInfo(OrderSymbol(), MODE_ASK);
                if (!OrderClose(OrderTicket(), OrderLots(), priceClose, slippage, clrGold))
                {
                    Print("WARNING: Close Failed");
                }
            }
        }
    }
}

Join the Community!

For more in-depth information and to share your MQL4 coding experiences, feel free to join our Telegram group. We’d love to have you on board!

연관 포스트

댓글 (0)