This expert advisor will scan through new trades and automatically apply a default stop loss to trades that have no stop loss

Click here for the MT5 version

Start by using the wizard to create the expert advisor template. I called my expert AutoStopLoss.

This expert uses a simple point value to set the default stop loss. This needs a single input line

input	int	InpStopLossPoints		=	500;	//	Stop loss in points

No code is required in the OnInit or OnDeinit functions, all the work is done in the OnTick function. Begin by declaring a variable to set a time to look back for new trades. Trades placed earlier than the calculated time will not have a stop loss applied

datetime	checkTime	=	TimeCurrent()-30;							//	Only looking at trades in last 30 seconds

Then a standard loop to scan through trades

	int		cnt			=	OrdersTotal();
	for (int i=cnt-1; i>=0; i--) {
		if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
			if (OrderMagicNumber()==0 && OrderStopLoss()==0
					&& (OrderType()==ORDER_TYPE_BUY || OrderType()==ORDER_TYPE_SELL)) {
					//	magic 0 = manual entry, sl 0 means not set
				if (OrderOpenTime()>checkTime) {							//	lets you override after 30 seconds
					double	stopLoss			=	InpStopLossPoints*SymbolInfoDouble(OrderSymbol(), SYMBOL_POINT);
					double	stopLossPrice	=	(OrderType()==ORDER_TYPE_BUY) ?
														OrderOpenPrice()-stopLoss :
														OrderOpenPrice()+stopLoss;
					stopLossPrice				=	NormalizeDouble(stopLossPrice, (int)SymbolInfoInteger(OrderSymbol(), SYMBOL_DIGITS));
					if (OrderModify(OrderTicket(), OrderOpenPrice(), stopLossPrice, OrderTakeProfit(), OrderExpiration())) {}
				}
			}
		}
	}

Line 1 just captures the total number of orders for the loop

Line 2 is the start of the loop counting down from cnt-1 to zero and line 3 uses OrderSelect to load the order details into memory.

Lines 4-5 check that the selected order has magic number zero which means it was placed manually through the terminal, has no stop loss already applied, and is a buy or sell (ignoring stop and limit orders)

Line 7 then uses the earlier check time to compare open time and avoid any trades placed before the time interval. Without this the expert would repeatedly apply a stop loss if ti is removed. Using the timeout allows you to cancel the stop loss after waiting the selected numebr of seconds and the trade will then be ignored by the expert.

Line 8 calculates the size of the stop loss by converting the points to a price value based on the symbol of the current order

Lines 9-12 then calculate the stop loss price, depending on buy or sell, and ensure that it is a valid normalized price

Finally line 13 applies the updated stop loss price using OrderModify and filling in other arguments with the existing order values. The surrounding if statement is only to suppress a compile warning and does nothing. You may want to include some error checking code here.

 

 

This Post Has 3 Comments

  1. Mahdi Djawadi

    Q?
    when i trying to add EA to any chart dosen’t do any reaction and icon is unhappy face?
    CODE :
    void OnTick()
    {
    datetime checkTime = TimeCurrent()-30; // Only looking at trades in last 30 seconds
    int cnt = OrdersTotal();
    for (int i=cnt-1; i>=0; i–) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
    if (OrderMagicNumber()==0 && OrderStopLoss()==0
    && (OrderType()==ORDER_TYPE_BUY || OrderType()==ORDER_TYPE_SELL)) {
    // magic 0 = manual entry, sl 0 means not set
    if (OrderOpenTime()>checkTime) { // lets you override after 30 seconds
    double stopLoss = InpStopLossPoints*SymbolInfoDouble(OrderSymbol(), SYMBOL_POINT);
    double stopLossPrice = (OrderType()==ORDER_TYPE_BUY) ?
    OrderOpenPrice()-stopLoss :
    OrderOpenPrice()+stopLoss;
    stopLossPrice = NormalizeDouble(stopLossPrice, (int)SymbolInfoInteger(OrderSymbol(), SYMBOL_DIGITS));
    if (OrderModify(OrderTicket(), OrderOpenPrice(), stopLossPrice, OrderTakeProfit(), OrderExpiration() )){}
    }
    }
    }
    }
    }
    —————-
    Please advise me

  2. Mahdi Djawadi

    I think solved it with enabling Allow automated trading in Option box and EA wizard ?!
    because that work as you wrote

Leave a Reply