TSD_MT4_MR_Trade_0_10

Author: Copyright � 2005 Bob O'Brien / Barcode
Profit factor:
2.02

This script is designed to automatically place and manage trades in the MetaTrader platform, focusing on "breakout" entries. Here's how it works:

1. Core Idea:

The script aims to identify potential breakout trading opportunities. A "breakout" is when the price of an asset moves above a previous high or below a previous low, suggesting the start of a new trend. It does this for a rotating set of currency pairs.

2. Key Steps:

  • Initialization: When the script starts, it sets up initial values for things like which currency pairs to trade, how much risk to take per trade, take profit and trailing stop levels.
  • Currency Pair Selection: The script cycles through a predefined list of currency pairs (e.g., EURUSD, GBPJPY) one by one. It focuses on one pair at a time before moving to the next, ensuring it dedicates its attention effectively.
  • Determining Trade Direction (Buy or Sell): It uses technical indicators ? either MACD or OSMA ? on a longer timeframe (e.g., weekly) to determine the overall trend direction. If the indicator suggests an upward trend, it looks for buy opportunities; if it indicates a downward trend, it seeks sell opportunities.
  • Trade Confirmation (Filtering): Before placing a trade, it uses another indicator ? either WPR or Force Index ? on a shorter timeframe (e.g., daily) to confirm whether the price is in a condition where a breakout trade would be favorable. This acts as a filter to avoid entering trades randomly.
  • Placing a "Pending Order": If the trend direction and filter align, the script places a "pending order" ? a Buy Stop or Sell Stop order. This means the order isn't immediately executed. Instead, it's placed at a specific price above the current price (for a Buy Stop) or below the current price (for a Sell Stop). The idea is that if the price reaches that level, it confirms the breakout, and the order gets automatically triggered.
  • Managing Existing Orders:
    • Adjusting Pending Orders: If the market conditions change slightly, the script can modify the price levels of these pending orders, ensuring they remain aligned with the current price action.
    • Deleting Pending Orders: If the initial trend direction changes, the script will automatically delete the pending order that's no longer aligned with the prevailing trend.
    • Trailing Stop Loss: For open (already executed) trades, the script implements a "trailing stop loss." This is a stop-loss order that automatically adjusts as the price moves in a favorable direction. This helps to lock in profits and limit potential losses if the price reverses.
  • Risk Management: The script calculates the trade size (number of lots) based on either a fixed amount or a percentage of the account balance. This helps to manage risk and prevent excessive losses.

3. Key Concepts:

  • Technical Indicators: These are mathematical calculations based on historical price and volume data, used to identify patterns and predict future price movements.
  • Timeframes: The script uses different timeframes (weekly, daily, hourly) to analyze trends at different levels of detail.
  • Pending Orders (Buy Stop, Sell Stop): Orders placed at a specific price, which are only executed if the price reaches that level.
  • Stop Loss: An order placed to limit the potential loss on a trade.
  • Take Profit: An order placed to automatically close a trade when a specific profit level is reached.
  • Trailing Stop: A stop loss order that automatically adjusts as the price moves in a favorable direction.

In essence, this script automates a breakout trading strategy by identifying potential breakouts, placing pending orders, and then managing those orders with trailing stop losses to maximize profits while limiting risks.

Price Data Components
Series array that contains the highest prices of each barSeries array that contains the lowest prices of each bar
Orders Execution
Checks for the total of open orders
Indicators Used
Larry William percent range indicator
3 Views
0 Downloads
0 Favorites
TSD_MT4_MR_Trade_0_10
/*-----------------------------+
|			       |
| Shared by www.Aptrafx.com    |
|			       |
+------------------------------*/

//+------------------------------------------------------------------+
//|                                   TSD_MR_Trade_MACD_WPR_0_10.mq4 |
//|                           Copyright ® 2005 Bob O'Brien / Barcode |
//|             TSD v1.2 rewritten to MQL4 and enhanced by Mindaugas |
//|                                           TSD Trade version 0.10 |
//+------------------------------------------------------------------+
#property copyright "Copyright ® 2005 Bob O'Brien / Barcode"

#include <stdlib.mqh>

#define  DIRECTION_MACD 1
#define  DIRECTION_OSMA 2

#define  FILTER_WPR     1
#define  FILTER_FORCE   2

// which indicators to use
int DirectionMode = DIRECTION_MACD, FilterMode = FILTER_WPR;
// trading periods
int PeriodDirection = PERIOD_W1, PeriodTrade = PERIOD_D1, PeriodTrailing = PERIOD_H4, CandlesTrailing = 3;
// currency pairs to trade
string pairs[] = { "AUDUSD", "EURCHF", "EURGBP", "EURJPY", "EURUSD", "GBPCHF", "GBPJPY", "GBPUSD",
                   "USDCAD", "USDCHF", "USDJPY" };

// parameters for iWPR and iForce indicators
int WilliamsP = 24, WilliamsL = -75, WilliamsH = -25;
int ForceP = 2;

int TakeProfit = 100, TrailingStop = 60;
int Slippage = 5, LotsMax = 50;
double Lots = 0.1;
int MM = 0, Leverage = 1, MarginChoke = 200;

string TradeSymbol;
int Pair = 0;
datetime LastTrade = 0;
double Spread, SPoint;

//+------------------------------------------------------------------+

int init()   { return(0); }
int deinit() { return(0); }

//+------------------------------------------------------------------+

int start() {
   int TradesThisSymbol, Direction;
   int i, ticket;
   
   bool okSell, okBuy;
   
   double PriceOpen, Buy_Sl, Buy_Tp, LotMM, WilliamsValue;
   string ValueComment;
   
   if ( (LastTrade + 15) > CurTime() )  return(0);
   
   Pair = (Pair+1) % ArraySize(pairs);
   TradeSymbol = pairs[Pair];
   
   Spread = MarketInfo (TradeSymbol, MODE_ASK) - MarketInfo (TradeSymbol, MODE_BID);
   SPoint = MarketInfo (TradeSymbol, MODE_POINT);
   
   TradesThisSymbol = TotalTradesThisSymbol (TradeSymbol);
   
   Direction = Direction (TradeSymbol, PeriodDirection, DirectionMode);
   ValueComment = Filter(TradeSymbol, PeriodTrade, FilterMode, okBuy, okSell);
   
   Comment ("\nSymbol: ", TradeSymbol, "\nMACD Direction: ", Direction, "\n", ValueComment);

   /////////////////////////////////////////////////
   //  Place new order
   /////////////////////////////////////////////////
   if ( TradesThisSymbol < 1 ) {

      LotMM = CalcMM(MM);
      if ( LotMM < 0 )  return(0);

      ticket = 0;

      if ( Direction == 1 && okBuy ) {
         MarkTrade();
	      Print ("TSD BuyStop: ", TradeSymbol, " ", LotMM, " ", CalcOpenBuy(), " ", CalcSlBuy(), " ", CalcTpBuy());
         ticket = OrderSend (TradeSymbol, OP_BUYSTOP, LotMM, CalcOpenBuy(), Slippage, CalcSlBuy(), CalcTpBuy(),
		                       "TSD BuyStop", 0, 0, Blue);
		}
		   
      if ( Direction == -1 && okSell ) {
         MarkTrade();
	      Print ("TSD SellStop: ", TradeSymbol, " ", LotMM, " ", CalcOpenSell(), " ", CalcSlSell(), " ", CalcTpSell());
	      ticket = OrderSend (TradeSymbol, OP_SELLSTOP, LotMM, CalcOpenSell(), Slippage, CalcSlSell(), CalcTpSell(),
	                          "TSD SellStop", 0, 0, Red);
	   }
 
	   if ( ticket == -1 )  ReportError ();
	   if ( ticket != 0 )   return(0);
	} // End of TradesThisSymbol < 1
		
   /////////////////////////////////////////////////
   //  Pending Order Management
   /////////////////////////////////////////////////
   for (i = 0; i < OrdersTotal(); i++) {
      if ( OrderSelect (i, SELECT_BY_POS) == false )  continue;
      if ( OrderSymbol() != TradeSymbol )  continue;

      if ( OrderType () == OP_BUYSTOP ) {
         if ( Direction != 1 ) {
            MarkTrade();
            OrderDelete ( OrderTicket() );
            return(0);
         }
         if ( iHigh(TradeSymbol, PeriodTrade, 1) < iHigh(TradeSymbol, PeriodTrade, 2) &&
              ( !CompareDoubles (CalcSlBuy(), OrderStopLoss()) ||
                !CompareDoubles (CalcTpBuy(), OrderTakeProfit()) ) ) {
            MarkTrade();
     		   OrderModify (OrderTicket(), CalcOpenBuy(), CalcSlBuy(), CalcTpBuy(), 0, White);
            return(0);
         }
      }

      if ( OrderType () == OP_SELLSTOP ) {
         if ( Direction != -1 ) {
            MarkTrade();
            OrderDelete ( OrderTicket() );
            return(0);
         }
         if ( iLow(TradeSymbol, PeriodTrade, 1) > iLow(TradeSymbol, PeriodTrade, 2) &&
              ( !CompareDoubles (CalcSlSell(), OrderStopLoss()) ||
                !CompareDoubles (CalcTpSell(), OrderTakeProfit()) ) ) {
            MarkTrade();
     		   OrderModify (OrderTicket(), CalcOpenSell(), CalcSlSell(), CalcTpSell(), 0, Gold);
            return(0);
         }
      }
   } // End of Pending Order Management
   
   /////////////////////////////////////////////////
   //  Stop Loss Management
   /////////////////////////////////////////////////
   if ( TrailingStop > 0 ) {
      for (i = 0; i < OrdersTotal(); i++) {
         if ( OrderSelect (i, SELECT_BY_POS) == false )  continue;
         if ( OrderSymbol() != TradeSymbol )  continue;
         if ( TrailStop (i, TrailingStop) )  return(0);
      }
   }

   return(0);
}
//+------------------------------------------------------------------+
double CalcOpenBuy  () { return (dMax (iHigh(TradeSymbol, PeriodTrade, 1) + 1*SPoint + Spread,
                                       MarketInfo(TradeSymbol, MODE_ASK) + 16*SPoint)); }
double CalcOpenSell () { return (dMin (iLow(TradeSymbol, PeriodTrade, 1) - 1*SPoint,
                                       MarketInfo(TradeSymbol, MODE_BID) - 16*SPoint)); }
double CalcSlBuy  () { return (iLow (TradeSymbol, PeriodTrade, 1) - 1*SPoint); }
double CalcSlSell () { return (iHigh(TradeSymbol, PeriodTrade, 1) + 1*SPoint + Spread); }
double CalcTpBuy  () {
   double PriceOpen = CalcOpenBuy(), SL = CalcSlBuy();
   return (PriceOpen + dMax(TakeProfit*SPoint, (PriceOpen - SL)*2));
}
double CalcTpSell  () {
   double PriceOpen = CalcOpenSell(), SL = CalcSlSell();
   return (PriceOpen - dMax(TakeProfit*SPoint, (SL - PriceOpen)*2));
}
//+------------------------------------------------------------------+
bool TrailStop (int i, int TrailingStop) {
   double StopLoss;

   if ( OrderType() == OP_BUY ) {
      if ( MarketInfo (TradeSymbol, MODE_BID) < OrderOpenPrice () )  return;
      StopLoss = iLow(TradeSymbol, PeriodTrailing, Lowest (TradeSymbol, PeriodTrailing, MODE_LOW, CandlesTrailing+1, 0)) - 1*Point;
      StopLoss = dMin (MarketInfo (TradeSymbol, MODE_BID)-TrailingStop*SPoint, StopLoss);
      if ( StopLoss > OrderStopLoss() ) {
         MarkTrade();
         OrderModify (OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, White);
         return(true);
      }
   }
   
   if ( OrderType() == OP_SELL ) {
      if ( MarketInfo (TradeSymbol, MODE_ASK) > OrderOpenPrice () )  return;
      StopLoss = iHigh(TradeSymbol, PeriodTrailing, Highest (TradeSymbol, PeriodTrailing, MODE_HIGH, CandlesTrailing+1, 0)) + 1*Point
                 + Spread;
      StopLoss = dMax (MarketInfo (TradeSymbol, MODE_ASK)+TrailingStop*SPoint, StopLoss);
      if ( StopLoss < OrderStopLoss() ) {
         MarkTrade();
         OrderModify (OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Gold);
         return(true);
      }
   }
}
//+------------------------------------------------------------------+
int Direction (string TradeSymbol, int PeriodDirection, int Mode) {
   double Previous, Previous2;

   if (Mode == DIRECTION_MACD ) {
	   Previous  = iMACD (TradeSymbol, PeriodDirection, 5, 34, 5, PRICE_MEDIAN, MODE_MAIN, 1);
	   Previous2 = iMACD (TradeSymbol, PeriodDirection, 5, 34, 5, PRICE_MEDIAN, MODE_MAIN, 2);
	}
	else {
	   Previous  = iOsMA (TradeSymbol, PeriodDirection, 5, 34, 5, PRICE_MEDIAN, 1);
	   Previous2 = iOsMA (TradeSymbol, PeriodDirection, 5, 34, 5, PRICE_MEDIAN, 2);
	}

   if ( Previous > Previous2 )
      return(1);
   if ( Previous < Previous2 )
      return(-1);
   return(0);
}
//+------------------------------------------------------------------+
string Filter (string TradeSymbol, int PeriodTrade, int Mode, bool &okBuy, bool &okSell) {
   double Value;
   
   okBuy = false; okSell = false;
   
   if (Mode == FILTER_WPR) {
      Value = iWPR(TradeSymbol, PeriodTrade, WilliamsP, 1);
	   if (Value < WilliamsH)  okBuy = true;
   	if (Value > WilliamsL)  okSell = true;
   	return ("iWPR: " + DoubleToStr(Value, 2));
   }
   else if (Mode == FILTER_FORCE) {
      Value = iForce (TradeSymbol, PeriodTrade, ForceP, MODE_EMA, PRICE_CLOSE, 1);
      if (Value < 0)  okBuy = true;
      if (Value > 0)  okSell = true;
   	return ("iForce: " + DoubleToStr(Value, 2));
   }
}
//+------------------------------------------------------------------+
double CalcMM (int MM) {
   double LotMM;

   if ( MM < -1) {
      if ( AccountFreeMargin () < 5 )  return(-1);
		LotMM = MathFloor (AccountBalance()*Leverage/1000);
		if ( LotMM < 1 )  LotMM = 1;
		LotMM = LotMM/100;
   }
	if ( MM == -1 ) {
		if ( AccountFreeMargin() < 50 )  return(-1);
		LotMM = MathFloor(AccountBalance()*Leverage/10000);
		if ( LotMM < 1 )  LotMM = 1;
		LotMM = LotMM/10;
   }
	if ( MM == 0 ) {
		if ( AccountFreeMargin() < MarginChoke ) return(-1); 
		LotMM = Lots;
	}
	if ( MM > 0 ) {
      if ( AccountFreeMargin() < 500 )  return(-1);
		LotMM = MathFloor(AccountBalance()*Leverage/100000);
 		if ( LotMM < 1 )  LotMM = 1;
	}
	if ( LotMM > LotsMax )  LotMM = LotsMax;
	return(LotMM);
}
//+------------------------------------------------------------------+
int TotalTradesThisSymbol (string TradeSymbol) {
   int i, TradesThisSymbol = 0;
   
   for (i = 0; i < OrdersTotal(); i++)
      if ( OrderSelect (i, SELECT_BY_POS) )
         if ( OrderSymbol() == TradeSymbol )
            TradesThisSymbol++;

   return (TradesThisSymbol);
}
//+------------------------------------------------------------------+
void ReportError () {
   int err = GetLastError();
   Print("Error(",err,"): ", ErrorDescription(err));
}
//+------------------------------------------------------------------+
double dMax (double val1, double val2) {
  if (val1 > val2)  return(val1);
  return(val2);
}
//+------------------------------------------------------------------+
double dMin (double val1, double val2) {
  if (val1 < val2)  return(val1);
  return(val2);
}
//+------------------------------------------------------------------+
void MarkTrade () {
   LastTrade = CurTime();
}

Profitability Reports

GBP/USD Oct 2024 - Jan 2025
2.02
Total Trades 12
Won Trades 6
Lost trades 6
Win Rate 50.00 %
Expected payoff 21.61
Gross Profit 513.80
Gross Loss -254.50
Total Net Profit 259.30
-100%
-50%
0%
50%
100%

Comments