Opposite Trading - MetaTrader 5 Expert | MT5 EA Download - MetaTrader 5 Resources
Opening a position is the opposite of closing a position and the trading volume is the same. It works with any symbol and any magic number.
For example, we have a BUY 0.01 position in AUDUSD. Once the position is closed (eg we close it manually) the Counter Trade Expert Advisor will immediately open a new AUDUSD position, now a SELL position.
The entire code is contained in the OnTradeTransaction function:
//+------------------------------------------------------------------+ //| TradeTransaction function | //+------------------------------------------------------------------+ Blank OnlineTrade ( const MqlTrade transaction & trans, Constant Mql Transaction Requests & Requirements, Constant Mql Transaction Result &Result) { //--- Get the transaction type as enumeration value ENUM_TRADE_TRANSACTION_TYPE type = trans.type; //--- If the transaction is the result of adding a historical transaction if (type == TRADE_TRANSACTION_DEAL_ADD ) { long deal_type =- 1 ; long deal_entry =- 1 ; Double volume = 0.0 ; string deal_symbol = ”” ; if ( Historical Transaction Select (Transaction)) { deal_type = historical transaction acquisition integer (cross-transaction, transaction type ); deal_entry = historical transaction acquisition integer (cross-transaction, DEAL_ENTRY ); Transaction volume = historical transactions get double (cross transaction, transaction volume ); deal_symbol = historical transaction acquisition string (cross-transaction, DEAL_SYMBOL ); } Others return ; if (transaction entry == DEAL_ENTRY_OUT ) { transform (( integer )transactiontype) { Case DEAL_TYPE_BUY : m_trade.Buy(deal_volume,deal_symbol); rest ; Case Transaction Type_Sell : m_trade.Sell(deal_volume,deal_symbol); rest ; default : rest ; } } } }
Here we are waiting for the closing transaction (DEAL_ENTRY_OUT). As soon as this trade occurs, we check the trading position (if we closed the buy position, this would be a sell trade and vice versa) and open a new position.
Attachment download
📎opposite_trade.mq5 (6.19 KB)
Source: MQL5 #18904
💡 Featured Recommendations
✍️ Latest by the author
- •
- •
- •
- •
- •
- •
📌 Popular topics
- •
- •
- •
- •
- •
- •
- •
- •
🔗 You May Be Interested In
- •
- •
- •
- •
- •
- •