Understanding Opposite Trades with Expert Advisors
Are you looking to enhance your trading strategy with MetaTrader 5? One effective method is utilizing an Expert Advisor (EA) that automatically opens a position opposite to your recently closed trade. This nifty little tool is compatible with any trading symbol and magic number, making it versatile for all your trading needs.
How Does It Work?
Let’s break it down. Suppose you have an open AUDUSD BUY position of 0.01 lots. Once you decide to close this position—whether manually or through another method—the Opposite Trade EA will swiftly open a new AUDUSD position, but this time as a SELL. It's like having a trusty sidekick that’s always ready to act!
Digging into the Code
The magic happens within the OnTradeTransaction function. Here’s a sneak peek at how it’s structured:
//+------------------------------------------------------------------+//| TradeTransaction function |//+------------------------------------------------------------------+voidOnTradeTransaction(constMqlTradeTransaction &trans, constMqlTradeRequest &request, constMqlTradeResult &result) { //--- get transaction type as enumeration value ENUM_TRADE_TRANSACTION_TYPE type=trans.type; //--- if transaction is result of addition of the transaction in history if(type==TRADE_TRANSACTION_DEAL_ADD) { long deal_type =-1; long deal_entry =-1; double deal_volume =0.0; string deal_symbol =""; if(HistoryDealSelect(trans.deal)) { deal_type =HistoryDealGetInteger(trans.deal,DEAL_TYPE); deal_entry =HistoryDealGetInteger(trans.deal,DEAL_ENTRY); deal_volume =HistoryDealGetDouble(trans.deal,DEAL_VOLUME); deal_symbol =HistoryDealGetString(trans.deal,DEAL_SYMBOL); } else return; if(deal_entry==DEAL_ENTRY_OUT) { switch((int)deal_type) { case DEAL_TYPE_BUY: m_trade.Buy(deal_volume,deal_symbol); break; case DEAL_TYPE_SELL: m_trade.Sell(deal_volume,deal_symbol); break; default: break; } } } }
Wrapping It Up
In essence, this EA patiently awaits the closing of your trade (noted as DEAL_ENTRY_OUT). As soon as this deal appears, it checks the type of deal you just closed—if it was a BUY, it opens a SELL, and vice versa. This automated approach can save you time and help you maintain your trading momentum.
Happy trading!

Comments 0