stop_and_reverse
Download scriptThis script is designed as an automated "Stop and Reverse" tool for MetaTrader 4. Its primary purpose is to instantly neutralize your current market position on a specific currency pair and flip it into the opposite direction in one seamless action.
How the Logic Works
1. Automated Position Auditing The script begins by scanning your active trading account. It specifically looks for any open positions tied to the chart you are currently viewing. It identifies whether you are currently in a "Buy" position or a "Sell" position.
2. Intelligent Trade Sizing (Risk Management) Before making any moves, the script performs a series of background calculations to determine your trade size. Rather than using a fixed number, it looks at:
- Your current account balance (free margin).
- The specific currency pair's market value.
- The broker's minimum and maximum allowed lot sizes.
It aims to standardize your risk so that the value of a "pip" move is consistent. It then calculates the appropriate number of lots to trade based on a user-defined dollar amount, ensuring that the new trade fits within your account's limits and the broker's rules.
3. The Execution Phase Once it identifies your current position, the script performs a two-step "flip":
- Closure: If you have an open "Buy" order, the script closes it immediately. If you have an open "Sell" order, it closes that instead.
- Reversal: Immediately after closing the old position, the script opens a new trade in the opposite direction. For example, if your current position was a Buy, it will replace it with a Sell; conversely, it replaces a Sell with a Buy.
4. Error Handling and Notifications The script includes a safety net to keep you informed of its actions:
- Success: If a trade is successfully reversed, it logs the price and details in the system terminal.
- Failure: If the trade cannot be opened (due to market conditions or account issues), it will trigger an alert box on your screen explaining the specific error.
- No Action: If there are no active trades to reverse, the script will notify you that there was nothing to perform.
Summary of Use
This tool is built for traders who need to react instantly to a change in market sentiment. Instead of manually closing a losing or stagnant trade and then opening a new one—which can result in price fluctuations between those two actions—this script handles both steps simultaneously to ensure you are positioned correctly as fast as possible.
//+------------------------------------------------------------------+
//| stop_and_reverse.mq4 |
//| Copyright © 2008, Silas Palmer. |
//| http://www.silaspalmer.com/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, Silas Palmer."
#property link "http://www.silaspalmer.com"
#include <stderror.mqh>
#include <stdlib.mqh>
// #property show_confirm
// Uncomment to enable confirmation
//+------------------------------------------------------------------+
//| script "close all orders on a chart, place one in opposite direction to last opened order" |
//+------------------------------------------------------------------+
int start()
{
// Change these amounts to suit your needs
int lotbucks = 50000; // 1 lot for every x dollars in your account.
int Slippage = 3; // Standard amount
// Note script auto-detects minimum lot size
// It also automatically scales lots based on currency pair
// (so that a 1 pip move will be $1 per lotbuck regardless of the pair chosen)
//----
int cmd = -1; // Nothing (buy=0 sell=1)
int i;
double lots,minl,maxl,pipbucks,step;
// Calculate lots
pipbucks = MarketInfo(Symbol(),MODE_TICKVALUE);
minl = MarketInfo(Symbol(),MODE_MINLOT);
maxl = MarketInfo(Symbol(),MODE_MAXLOT);
step = MarketInfo(Symbol(),MODE_LOTSTEP);
// Scale lots so 1 pip = $1 at 1 lot
lots = MathFloor( (((10 / pipbucks) * AccountFreeMargin()) / lotbucks) / step) * step;
if (lots < minl) lots = minl;
if (lots > maxl) lots = maxl;
for ( i=0; i<OrdersTotal(); i++ ) // Loop through orders
if ( OrderSelect ( i, SELECT_BY_POS, MODE_TRADES ) ) {
if ( OrderSymbol() == Symbol() ) {
if (OrderType() == OP_BUY) {
cmd = OP_SELL; // sell
// Close buy Order
OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Blue);
}
if (OrderType() == OP_SELL ) {
cmd = OP_BUY; // buy
// Close sell order
OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Blue);
}
}
}
if(cmd==OP_BUY) {
// buy
if ( OrderSend( Symbol(), OP_BUY, lots, Ask, Slippage, 0, 0, "Opened Buy Order", 0, 0, Orange ) > 0 )
Print ( "Opened Buy Order at ", Ask );
else
Alert ( "Could not open Buy order for ", Symbol(), " ", lots, " at ", Ask, " Error=", ErrorDescription(GetLastError()) );
}
if (cmd==OP_SELL) {
// sell
if ( OrderSend( Symbol(), OP_SELL, lots, Bid, Slippage, 0, 0, "Opened Buy Order", 0, 0, Yellow ) > 0 )
Print ( "Opened Sell Order at ",Bid );
else
Alert ( "Could not open Sell order for ", Symbol(), " ", lots, " at ", Bid, " Error=", ErrorDescription(GetLastError()) );
}
if (cmd==-1) {
Alert ( "Cannot stop and reverse. No orders open.");
}
//----
return(0);
}
//+------------------------------------------------------------------+
Profitability Reports
Expected payoff
Average expected payoff across the available backtests for each symbol.
Comments