OverTrade_BS_03
Download scriptThis trading script is designed to automate market positions by identifying and following price trends. Rather than relying on complex guessing, it uses a systematic approach to manage risk, detect movement directions, and execute trades based on pre-defined mathematical rules.
Core Trading Logic
Trend Detection The script monitors the market using two different "Moving Averages." These are indicators that smooth out price fluctuations to show the general direction of the market.
- It compares a Slow Moving Average (long-term trend) against a Fast Moving Average (short-term momentum).
- A trade signal is generated only when both averages move in the same direction beyond a specific threshold. For example, if both averages are rising significantly, the script identifies an "Up" trend; if both are falling significantly, it identifies a "Down" trend.
Trade Execution
- Entry: When a new trend is confirmed, the script opens a position in the direction of that trend (buying when the trend is up, selling when it is down).
- Exits: The script manages exits in three ways:
- Take Profit/Stop Loss: Every trade has a pre-set "target" (profit) and a "safety net" (loss limit).
- Trend Reversal: If the market direction flips (e.g., from an Up trend to a Down trend), the script immediately closes existing positions to protect capital.
- New Bar Sync: The script only evaluates these conditions at the start of a new candle on a specific timeframe, preventing it from making impulsive decisions during erratic price flickers.
Advanced Account Management
Dynamic Risk & Lot Sizing Unlike simple scripts that trade the same amount every time, this tool calculates an "Optimal Lot Size." It looks at your account balance and evaluates your recent trading history:
- It calculates risk based on a percentage of your available margin.
- It monitors your losing streak; if the script detects a high frequency of losses without a break, it automatically reduces the trade size (the "Decrease Factor") to preserve your remaining capital.
Equity Protection (Drawdown & Profit Taking) The script includes a sophisticated "Safety Valve" to monitor your account's health in real-time:
- Drawdown Protection: If your account equity drops significantly below a certain peak (a specific percentage of loss), the script will automatically close all open positions to prevent further damage.
- Profit Locking: Conversely, if your account reaches a specific profit milestone relative to its base, it clears out current positions to "lock in" those gains and resets the baseline for the next trading cycle.
Summary of Behavior
In short, this is a Trend-Following System with built-in Defensive Scaling. It looks for confirmation from multiple indicators before entering a trade, automatically shrinks its position size when it encounters difficulty, and provides a hard "emergency stop" to protect your balance if the market moves too far against your strategy.
//+------------------------------------------------------------------+
//| OverTrade_BS_03.mq4 |
//+------------------------------------------------------------------+
#property copyright "OnTheRoad"
#include <stdlib.mqh>
#define MAGICPROB 110101011
#define UP 1
#define BUY 1
#define NUTRAL 0
#define SELL -1
#define DOWN -1
extern int TP_BUY = 45;
extern int SL_BUY = 55; //45;
extern int TP_SELL = 45;
extern int SL_SELL = 55; //45;
extern int TF_SEL = 15;
extern int SLIPAGE = 3;
extern int slow_ma_p = 264;
extern int fast_ma_p = 96;
extern int ma_tf = 60;
extern double Lots = 0.1;
extern double MaximumRisk = 0.0002;
extern double DecreaseFactor = 3;
extern double equity_dd_4x = 0.8; //0.8;
extern double equity_gu_4x = 1.2; //1.2;
static double equity_max ;
static int last_trend ;
static double equity_base;
static datetime lastbar = 0;
int init()
{
lastbar = Time[0];//iTime(Symbol(),PERIOD_M5,0); //Time[0];
last_trend = NUTRAL;
equity_base = AccountEquity();
equity_max = 0;
return ;
}
bool NewBar()
{
datetime curbar = iTime(Symbol(),TF_SEL,0);//Time[0];//
if(lastbar!=curbar)
{
lastbar=curbar;
return (true);
}
else
{
return(false);
}
}
//+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double LotsOptimized()
{
double lot=Lots;
int orders=OrdersHistoryTotal(); //HistoryTotal(); // history orders total
int losses=0; // number of losses orders without a break
int dp=1;
if ( Lots < 0.1 ) dp = 2;
//---- select lot size
lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,dp);
//---- calcuulate number of losses orders without a break
if ( orders > 1 )
if(DecreaseFactor>0)
{
for(int i=orders-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
//----
if(OrderProfit()>0) break;
if(OrderProfit()<0) losses++;
}
if(losses/orders > 0.3) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,dp);
}
//---- return lot size
if(lot<Lots) lot=Lots;
return(lot);
}
//+------------------------------------------------------------------+
//| Start function |
//+------------------------------------------------------------------+
void start()
{
int res , trend;
double equitynow = AccountEquity();
if ( equitynow < equity_dd_4x * equity_max )
{
CLOSE_ALL( BUY ) ;
CLOSE_ALL( SELL ) ;
equity_max = 0;
}
else if ( equitynow > equity_gu_4x * equity_base )
{
CLOSE_ALL( BUY ) ;
CLOSE_ALL( SELL ) ;
equity_base = AccountEquity();
}
else if ( equitynow > equity_max ) equity_max = equitynow ;
if(Bars<100 || IsTradeAllowed()==false) return;
if (NewBar() == true)
{
double slowmanow = iMA(NULL, ma_tf , slow_ma_p , 0 , MODE_SMA , PRICE_CLOSE , 0 ) ;
double slowmalast= iMA(NULL, ma_tf , slow_ma_p , 0 , MODE_SMA , PRICE_CLOSE , 2 ) ;
double fastmanow = iMA(NULL, ma_tf , fast_ma_p , 0 , MODE_SMA , PRICE_TYPICAL , 0 ) ;
double fastmalast= iMA(NULL, ma_tf , fast_ma_p , 0 , MODE_SMA , PRICE_TYPICAL , 2 ) ;
trend = NUTRAL ;
if ( slowmanow > slowmalast + 0.75 * Point ) //trend = UP;
if ( fastmanow > fastmalast + 0.6 * Point ) trend = UP;
// if (( Low[0] > fastmanow )&&( Bid > fastmanow )) trend = UP;
if ( slowmanow < slowmalast - 0.75 * Point ) //trend = DOWN;
if ( fastmanow < fastmalast - 0.6 * Point ) trend = DOWN;
// if (( High[0] < fastmanow )&&( Bid < fastmanow )) trend = DOWN;
/*
double ewtrend=iCustom(NULL,240,"EWTREND",34,5,0,0);
if ( ewtrend > 0 ) trend = UP;
if ( ewtrend < 0 ) trend = DOWN;
*/
/*
//double retrace_gravity = iCustom(NULL,60,"retracement_gravity",55,89,55,89,21,24,4,0);
double retrace_gravity = iCustom(NULL,60,"retracement_gravity",21,34,21,34,14,24,4,0);
retrace_gravity = NUTRAL;
if ( retrace_gravity > 0.7 ) trend = UP;
if ( retrace_gravity < -0.7 ) trend = DOWN;
*/
/*
double highmanow = iMA(NULL, ma_tf , 34 , 0 , MODE_SMA , PRICE_HIGH , 0 ) ;
double highmalast= iMA(NULL, ma_tf , 34 , 0 , MODE_SMA , PRICE_HIGH , 2 ) ;
double lowmanow = iMA(NULL, ma_tf , 34 , 0 , MODE_SMA , PRICE_LOW , 0 ) ;
double lowmalast= iMA(NULL, ma_tf , 34 , 0 , MODE_SMA , PRICE_LOW , 2 ) ;
trend = NUTRAL ;
if ( highmanow > highmalast ) //+ 0.5 * Point ) //trend = UP;
if ( lowmanow > lowmalast ) //+ 0.5 * Point ) //trend = UP;
if (( Low[0] > lowmalast )&&( Bid > lowmanow )) trend = UP;
if ( highmanow < highmalast ) //- 0.5 * Point ) //trend = DOWN;
if ( lowmanow < lowmalast ) //- 0.5 * Point ) //trend = DOWN;
if (( High[0] < highmalast )&&( Bid < highmanow )) trend = DOWN;
*/
Comment ( " \n lasttrend= " , last_trend , " ,trend = " , trend );
if (( last_trend != trend )&&( trend != NUTRAL ))
{
last_trend = trend;
CLOSE_ALL( BUY ) ;
CLOSE_ALL( SELL ) ;
}
if ( trend == DOWN ) res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,SLIPAGE,Bid+Point*SL_SELL,Bid-Point*TP_SELL,"",MAGICPROB,0,Red);
if ( trend == UP ) res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,SLIPAGE,Ask-Point*SL_BUY,Ask+Point*TP_BUY,"",MAGICPROB,0,Blue);
}
return;
}
/////////////////////////////////////////////////////////////////////
void CLOSE_ALL( int buysell )
{
int myTyp;
int i;
// return;
for( i=(OrdersTotal()-1); i>=0; i-- )
{
OrderSelect(i, SELECT_BY_POS);
if(OrderMagicNumber()==MAGICPROB)
{
switch( OrderType() )
{
//Close opened long positions
case OP_BUY : if ( buysell == 1 ) CloseBuy("CLOSEEVERYTHING script BUY");
break;
//Close opened short positions
case OP_SELL : if ( buysell == -1 ) CloseSell("CLOSEEVERYTHING script SELL");
break;
}
}//magic
Sleep(500);
} //for
} // closeeverything
void CloseBuy (string myInfo)
{
int gle;
int cnt;
int loopcount=0;
while(true)
{
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),2,White);
gle=GetLastError();
if(gle==0)
{
Print("CLOSE BUY "+myInfo+" Ticket="+OrderTicket()+" SL="+OrderStopLoss()+" TP="+OrderTakeProfit() );
break;
}
else
{
Print("-----ERROR----- CLOSE BUY PROFIT Bid="+MarketInfo(OrderSymbol(),MODE_BID)+" error="+gle+" "+ErrorDescription(gle));
Sleep(500);
RefreshRates();
}
loopcount++;
if(loopcount>25)
{
Alert("Order failed to CLOSE - See Journal for errors");
break;
}
}//while
}//closebuy
void CloseSell (string myInfo)
{
int gle;
int cnt;
int loopcount=0;
while(true)
{
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),2,Red);
gle=GetLastError();
if(gle==0)
{
Print("CLOSE SELL "+myInfo+" Ticket="+OrderTicket()+" SL="+OrderStopLoss()+" TP="+OrderTakeProfit() );
break;
}
else
{
Print("-----ERROR----- CLOSE SELL PROFIT Ask="+MarketInfo(OrderSymbol(),MODE_ASK)+" error="+gle+" "+ErrorDescription(gle));
Sleep(500);
RefreshRates();
}
loopcount++;
if(loopcount>25)
{
Alert("Order failed to CLOSE - See Journal for errors");
break;
}
}//while
}//closesell
//+------------------------------------------------------------------+
Profitability Reports
Expected payoff
Average expected payoff across the available backtests for each symbol.
Comments