Multi_EA_1[1].5.1
Download scriptThis automated trading script is designed to manage and execute currency trades by analyzing specific market indicators and dynamically adjusting trade sizes based on your account's performance. Below is a detailed breakdown of how the logic functions:
Core Trading Logic
The system operates by monitoring a custom "Buy/Sell Indicator" (BSI). It gathers data from multiple currency pairs (specifically GBPUSD, EURUSD, USDCHF, and USDJPY) to determine the overall market sentiment. By aggregating these signals, the script calculates a trigger value:
- Buy Signal: Triggered when the indicators suggest strong upward momentum.
- Sell Signal: Triggered when the indicators suggest strong downward momentum.
The script is designed to be reactive; if it detects a significant shift in market direction that opposes your current open position, it will automatically close the existing trade and look for a new opportunity based on the updated signal.
Dynamic Position Sizing
One of the primary features of this script is its intelligent lot size calculation. Rather than trading the same amount every time, it evaluates two factors:
- Risk Management: It calculates a starting volume based on a percentage of your available account margin to ensure you are not over-leveraged.
- Loss Protection (Decrease Factor): The script reviews your trading history. If it detects a string of consecutive losses, it automatically reduces the trade size (using a "Decrease Factor"). This is intended to protect your capital during losing streaks by lowering your exposure until the account stabilizes.
Trade Management Features
- Trailing Stop: To lock in profits while a trade is moving in your favor, the script includes a trailing stop mechanism. As the price moves further into profit, the stop-loss order "follows" the price at a set distance. If the price reverses, the trade is closed automatically to preserve your gains.
- Time Filters: The script allows for specific "Trading Hours." You can configure the system to only open new positions during certain times of the day (e.g., during high-volume sessions) and remain inactive during low-liquidity periods.
- Automatic Execution: The script monitors the market continuously. When it identifies a signal and finds no active trades, it opens a position automatically. If a trade is already open, it focuses on monitoring that position for profit protection or signal reversals.
Visual Feedback
For the user, the script provides real-time updates directly on the trading chart. It displays your starting balance versus your current balance, equity, and total profit. It also shows the current market "Trigger" and "BSI" status, allowing you to see exactly what the logic is thinking at any given moment.
//+------------------------------------------------------------------+
//| Multi_EA.mq4 |
//| hellkkas |
//| mailto:helderkastro@gmail.com |
//+------------------------------------------------------------------+
// Version 0.0.1
// Last Modified Date: Apr. 29th, 2007
#property copyright "hellkkas"
#property link "mailto:hellkkas@gmail.com"
#define MAGICMA 162429
//---- input parameters
extern int UsePct=0;
extern int MaxLots=100;
extern int Slippage=2;
extern double Lots=1;
extern double MaximumRisk=0.05;
extern double DecreaseFactor=6;
extern double MinLot=0.1;
extern double TrailingStop=30;
double StartBalance,StartEquity;
extern bool UseHourTrade = false;
extern int FromHourTrade = 6;
extern int ToHourTrade = 18;
//---- global variables
int bsi=0;
int dir=0;
int vTrig=0;
int openorders=0;
int cnt;
string pair;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
pair = Symbol();
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate open positions |
//+------------------------------------------------------------------+
int GetCurrentOrders()
{
//---- calc open OrderSelect
openorders=0;
dir=0;
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
//if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
if(OrderSymbol()==Symbol())
{
openorders+=1;
if(OrderType()==OP_BUY) dir=1;
if(OrderType()==OP_SELL) dir=-1;
}
}
}
//+-------------------End Calculate open positions-------------------+
//+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double LotsOptimized()
{
double lot=Lots;
int orders=HistoryTotal(); // history orders total
int losses=0; // number of losses orders without a break
//---- select lot size
lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/500.0,1);
//---- calcuulate number of losses orders without a break
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>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
}
//---- return lot size
if(lot<0.1) lot=0.1;
return(lot);
}
//+-------------------End Calculate optimal lot size-----------------+
//+------------------------------------------------------------------+
//| Close Open Position |
//+------------------------------------------------------------------+
int CloseTrade()
{
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
//if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
if(OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY) OrderClose(OrderTicket(),OrderLots(),Bid,3,Yellow);
if(OrderType()==OP_SELL) OrderClose(OrderTicket(),OrderLots(),Ask,3,Yellow);
}
}
}
//+----------------------End Close Open Position---------------------+
//+------------------------------------------------------------------+
//| Open Trade Position |
//+------------------------------------------------------------------+
int OpenTrade()
{
int vLots=LotsOptimized();
if (bsi>0) OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,Slippage,0,0,NULL,MAGICMA,0,Green);
if (bsi<0) OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,Slippage,0,0,NULL,MAGICMA,0,Red);
}
//+----------------------End Open Trade Position---------------------+
//+------------------------------------------------------------------+
//| Buy/Sell Indicator |
//+------------------------------------------------------------------+
int CalcBSI()
{
//---- calc current indicators
int GU_Trig=1,EU_Trig=1,UC_Trig=1,UJ_Trig=1;
if (iCustom("GBPUSD",0,"JRSX",3,0,0)<50)GU_Trig=-1;
if (iCustom("EURUSD",0,"JRSX",3,0,0)<50)EU_Trig=-1;
if (iCustom("USDCHF",0,"JRSX",3,0,0)<50)UC_Trig=-1;
vTrig=GU_Trig+EU_Trig-UC_Trig;
bsi=0;
if (vTrig>2) bsi=1;
if (vTrig<-2) bsi=-1;
if (pair>"USD") bsi=bsi*(-1);
}
//+-----------------------End Buy/Sell Indicator---------------------+
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && // check for opened position
OrderSymbol()==Symbol()) // check for symbol
{
if(OrderType()==OP_BUY) // long position is opened
{
// check for trailing stop
if(TrailingStop>0)
{
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}
else // go to short position
{
// check for trailing stop
if(TrailingStop>0)
{
if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
{
if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
}
}
//+--------------------End TrailingStop & BreakEven------------------+
if (UseHourTrade)
{
if (!((Hour() >= FromHourTrade) && (Hour() <= ToHourTrade)))
{
Comment("Non-Trading Hours!");
return(0);
}
}
GetCurrentOrders();
CalcBSI();
Comment("\nStart Balance= ",StartBalance,",","Start Equity= ",StartEquity,
"\nBalance: ",AccountBalance(),","," Equity: ",AccountEquity(),","," TotalProfit: ",AccountProfit(),
"\nDir: ",dir,"\nBSI: ",bsi,"\nTrig: ",vTrig);
//---- exit trades
if (openorders!=0) {
if ((bsi>0) && (dir<0)) CloseTrade();
if ((bsi<0) && (dir>0)) CloseTrade();
}
//---- open trades
else {
if (bsi!=0) OpenTrade();
}
}
//+---------------------End Expert Start Function--------------------+
Profitability Reports
Expected payoff
Average expected payoff across the available backtests for each symbol.
Comments