The provided code is a MetaTrader 4 (MT4) Expert Advisor (EA) script. It seems to be designed for automated trading based on certain market conditions and parameters. Below are some key components and features of the script:
Key Features
-
Initialization and Deinitialization:
init()
: Initializes input parameters like ATR multiplier, EMA periods, number of trades, SL/TP multipliers, etc.deinit()
: Cleans up by deleting objects (indicators) used in the EA.
-
Inputs:
- Various input parameters allow customization:
- ATR Multiplier
- EMA Periods for Entry and Exit signals
- Maximum number of trades
- SL/TP multipliers
- Stop Loss and Take Profit adjustments
- Various input parameters allow customization:
-
Indicators:
- Uses Exponential Moving Average (EMA) and Average True Range (ATR) indicators.
-
Trade Management:
- Manages buy and sell orders based on the signals generated by EMA crossover.
- Calculates entry, stop loss, and take profit levels using ATR values.
-
Order Handling:
- Functions to count open trades and specific types of pending orders (buy/sell stops).
- Deletes existing pending orders before placing new ones if necessary.
-
Comments and Logging:
- Provides detailed comments in the trading chart for better understanding of current market conditions and EA decisions.
-
Magic Number Generation:
- Generates a unique magic number for each symbol and timeframe combination to distinguish between different EAs or strategies on the same platform.
Key Functions
-
start()
: Main function that gets executed every tick. It checks conditions for opening new trades or adjusting existing ones. -
subPrintDetails()
: Logs current market conditions and EA parameters in the chart's comment section. -
Order Management Functions:
subTotalOpenTrade()
subTotalBuyStopTrade()
subTotalSellStopTrade()
-
Price Calculation Functions:
subLastOpenPrice()
subLastSLPrice()
Considerations
-
Risk Management: Ensure that SL/TP settings are appropriate for your risk tolerance.
-
Backtesting: Before live deployment, thoroughly backtest the strategy to understand its performance and potential risks.
-
Customization: Adjust input parameters according to your trading style and market conditions.
This script is a good starting point for automated trading on MT4. However, always ensure you have a solid understanding of how it works before using it in real trading scenarios.
Profitability Reports
//+------------------------------------------------------------------+
//| Ninja Tutle - System2 - (fixed lots) Beta.mq4 |
//| Copyright © 2006, Mikhail Veneracion |
//| |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2006, Mikhail Veneracion"
#property link ""
extern double
Lots = 0.5; // Assign Fixed Lot Size to be traded,AutoLotSize must be false
extern int
MaxUnits = 4, //Maximum units to trade per Currency Pair
MagicNumber = 11282,
EntryLookBack = 55, //Bars to lookback in calculating breakout prices
ExitLookBack = 20, //Bars to lookback in calculating exit points
ATRPeriod = 20;
extern double
SLMultiple = 2.0, //Multiply ATR by this to calculate StopLoss
ReEntryMultiple = 0.5; //Multiple ATR by this to calculate Re Entry Point
extern bool
ATRBreakEven = true; //if set to true SL will be moved to break even level
extern double
BreakEvenMultiple = 2.5;
//-------------------GLOBAL VARS
static int
TimeFrame;
double LastEMAX,
LastEMIN,
LastXMAX,
LastXMIN,
LastOpen,
LastSL;
double
EMAX,
EMIN,
XMAX,
N,
XMIN;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----------------------- GENERATE MAGIC NUMBER AND TICKET COMMENT
//----------------------- SOURCE : PENGIE
MagicNumber = subGenerateMagicNumber(MagicNumber, Symbol(), Period());
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----------------------- PREVENT RE-COUNTING WHILE USER CHANGING TIME FRAME
//----------------------- SOURCE : CODERSGURU
TimeFrame=Period();
return(0);
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//-----------------SET VARIABLE VALUES
//
double Unit = Lots;
int Ehighest_bar=Highest(NULL, 0, MODE_HIGH, EntryLookBack, 1);
EMAX=NormalizeDouble (iHigh(NULL, 0, Ehighest_bar),Digits);
int Elowest_bar=Lowest(NULL, 0, MODE_LOW, EntryLookBack, 1);
EMIN=NormalizeDouble (iLow(NULL, 0, Elowest_bar),Digits);
int Xhighest_bar=Highest(NULL, 0, MODE_HIGH, ExitLookBack, 1);
XMAX=NormalizeDouble (iHigh(NULL, 0, Xhighest_bar),Digits);
int Xlowest_bar=Lowest(NULL, 0, MODE_LOW, ExitLookBack, 1);
XMIN=NormalizeDouble (iLow(NULL, 0, Xlowest_bar),Digits);
N = NormalizeDouble ((iATR(NULL,0,20,1)),Digits);
LastOpen = subLastOpenPrice();
LastSL = subLastSLPrice();
subPrintDetails();
// Unit=(AccountBalance()/100/N/Point*MarketInfo(Symbol(),MODE_TICKVALUE));
int BuyStopOrder = 0, SellStopOrder = 0, BuyOrder = 0, SellOrder = 0;
int _GetLastError = 0, _OrdersTotal = OrdersTotal();
for ( int z = _OrdersTotal - 1; z >= 0; z -- )
{
if ( !OrderSelect( z, SELECT_BY_POS ) )
{
_GetLastError = GetLastError();
Print( "OrderSelect( ", z, ", SELECT_BY_POS ) - Error #", _GetLastError );
continue;
}
if ( OrderSymbol() != Symbol() ) continue;
if ( OrderMagicNumber() != MagicNumber ) continue;
switch ( OrderType() )
{
case OP_BUY: BuyOrder = OrderTicket(); break;
case OP_SELL: SellOrder = OrderTicket(); break;
case OP_BUYSTOP: BuyStopOrder = OrderTicket(); break;
case OP_SELLSTOP: SellStopOrder = OrderTicket(); break;
}
}
//-----------------------PENDING ORDERS PROCESS-----------------+
if(subTotalOpenTrade()<1)
{
LastXMIN = 0;
LastXMAX = 9999999;
double BStopLossLevel, SStopLossLevel;
string Modify1 = "none";
string Modify2 = "none";
BStopLossLevel = NormalizeDouble( EMAX - N*SLMultiple, Digits );
SStopLossLevel = NormalizeDouble( EMIN + N*SLMultiple, Digits );
if((LastEMAX != EMAX)||(BuyStopOrder<1))
{
if (BuyStopOrder>0)
{
int cnt;
int total = subTotalBuyStopTrade();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_BUYSTOP && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
BuyStopOrder = OrderTicket();
}
OrderDelete(BuyStopOrder);
}
BuyStopOrder = 0;
}
if(subTotalBuyStopTrade()<1)
{
if (OrderSend(Symbol(),OP_BUYSTOP,Unit,EMAX,6,BStopLossLevel,0,"TURTLE POWER",MagicNumber,0,Green)<0)
{
Print( "OrderSend Error #", GetLastError() );
return(-1);
}
LastEMAX = EMAX;
double BuyPrice = LastEMAX;
}
}
if((LastEMIN != EMIN)||(SellStopOrder<1))
{
if (SellStopOrder>0)
{
total = subTotalSellStopTrade();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_SELLSTOP && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
SellStopOrder = OrderTicket();
}
OrderDelete(SellStopOrder);
}
SellStopOrder = 0;
}
if(subTotalSellStopTrade()<1)
{
if (OrderSend(Symbol(),OP_SELLSTOP,Unit,EMIN,6,SStopLossLevel,0,"TURTLE POWER",MagicNumber,0,Green)<0)
{
Alert( "OrderSend Error #", GetLastError() );
return(-1);
}
LastEMIN = EMIN;
double SellPrice = LastEMIN;
}
}
}
//-----------------------------------------------------+
//$$$$$$$$$$$$$$$$(OPEN BUY PROCESS)$$$$$$$$$$$$$$$$$$$+
//-----------------------------------------------------+
if(BuyOrder>0)
{
if (SellStopOrder>0)
{
if ( !OrderDelete( SellStopOrder ) )
{
Alert( "OrderDelete Error #", GetLastError() );
return(-1);
}
}
LastOpen = subLastOpenPrice();
//-------------PENDING REENTRY PROCESS
total = subTotalOpenTrade();
if(total<MaxUnits)
{
double PendingTotal = subTotalBuyStopTrade();
if(PendingTotal<1)
{
BuyPrice = NormalizeDouble((LastOpen+N*ReEntryMultiple),Digits);
if(BuyPrice>Bid){
if (OrderSend(Symbol(),OP_BUYSTOP,Unit,BuyPrice,6,0,0,"TURTLE POWER",MagicNumber,0,Green)<0)
{
Print( BuyPrice+"OrderSend Error #", GetLastError() );
return(-1);
}
LastOpen = subLastOpenPrice();
}
}
}
//-----------MODIFY STOPS AFTER REENTRY
if((total>1)&&(XMIN<LastOpen))
{
BStopLossLevel = NormalizeDouble(LastOpen - N*SLMultiple, Digits );
total = subTotalOpenTrade();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
if ( BStopLossLevel > OrderStopLoss()|| OrderStopLoss() <= 0.0 )
{
if ( !OrderModify( OrderTicket(), OrderOpenPrice(), BStopLossLevel,OrderTakeProfit(), OrderExpiration() ) )
{
Print( "OrderModify Error #", GetLastError() );
return(-1);
}
}
}
}
}
//-----------BREAK EVEN AFTER PIPS PROCESS
if((ATRBreakEven)&&(XMIN<LastOpen))
{
double BreakEvenPrice = NormalizeDouble(LastOpen + N*BreakEvenMultiple,Digits);
if(Bid > BreakEvenPrice){
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
if ( LastOpen > OrderStopLoss()|| OrderStopLoss() <= 0.0 )
{
if ( !OrderModify( OrderTicket(), OrderOpenPrice(), LastOpen,OrderTakeProfit(), OrderExpiration() ) )
{
Print( "OrderModify Error #", GetLastError() );
return(-1);
}
}
}
}
Modify2="done";
}
}
//-----------TRAILING STOP PROCESS
LastSL = subLastSLPrice();
if(XMIN>=LastOpen)
{
if(LastSL < XMIN)
{
total = subTotalOpenTrade();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
if ( !OrderModify( OrderTicket(), OrderOpenPrice(), XMIN,OrderTakeProfit(), OrderExpiration() ) )
{
Print( "OrderModify Error #", GetLastError() );
return(-1);
}
}
}
LastSL = subLastSLPrice();
}
}
//+----------END OF TRAILING STOP PROCESS
}
//-----------------------------------------------------+
//$$$$$$$$$$$$$$$(OPEN SELL PROCESS)$$$$$$$$$$$$$$$$$$$+
//-----------------------------------------------------+
if(SellOrder>0)
{
if (BuyStopOrder>0)
{
if ( !OrderDelete( BuyStopOrder ) )
{
Alert( "OrderDelete Error #", GetLastError() );
return(-1);
}
}
LastOpen = subLastOpenPrice();
//-------------PENDING REENTRY PROCESS
total = subTotalOpenTrade();
if(total<MaxUnits)
{
PendingTotal = subTotalSellStopTrade();
if(PendingTotal<1)
{
SellPrice = NormalizeDouble((LastOpen-N*ReEntryMultiple),Digits);
if(SellPrice<Bid){
if (OrderSend(Symbol(),OP_SELLSTOP,Unit,SellPrice,6,0,0,"TURTLE POWER",MagicNumber,0,Green)<0)
{
Print( BuyPrice+"OrderSend Error #", GetLastError() );
return(-1);
}
LastOpen = subLastOpenPrice();
}
}
}
//-----------MODIFY STOPS AFTER REENTRY
if((total>1)&&(XMAX>LastOpen))
{
SStopLossLevel = NormalizeDouble(LastOpen + N*SLMultiple, Digits );
total = subTotalOpenTrade();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
if ( SStopLossLevel < OrderStopLoss()|| OrderStopLoss() <= 0.0 )
{
if ( !OrderModify( OrderTicket(), OrderOpenPrice(), SStopLossLevel,OrderTakeProfit(), OrderExpiration() ) )
{
Print( "OrderModify Error #", GetLastError() );
return(-1);
}
}
}
}
}
//-----------BREAK EVEN AFTER PIPS PROCESS
if((ATRBreakEven)&&(XMAX>LastOpen)&&(total==MaxUnits))
{
BreakEvenPrice = NormalizeDouble(LastOpen - N*BreakEvenMultiple,Digits);
if(Bid < BreakEvenPrice){
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
if ( LastOpen < OrderStopLoss()|| OrderStopLoss() <= 0.0 )
{
if ( !OrderModify( OrderTicket(), OrderOpenPrice(), LastOpen,OrderTakeProfit(), OrderExpiration() ) )
{
Print( "OrderModify Error #", GetLastError() );
return(-1);
}
}
}
}
}
}
//-----------TRAILING STOP PROCESS
LastSL = subLastSLPrice();
if(XMAX<=LastOpen)
{
if(LastSL > XMAX)
{
total = subTotalOpenTrade();
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
{
if ( !OrderModify( OrderTicket(), OrderOpenPrice(), XMAX,OrderTakeProfit(), OrderExpiration() ) )
{
Print( "OrderModify Error #", GetLastError() );
return(-1);
}
}
}
LastSL = subLastSLPrice();
}
}
//+----------END OF TRAILING STOP PROCESS
}
//----
return(0);
}
//+--------------------------END OF PROGRAM--------------------------+
//----------------------- GENERATE MAGIC NUMBER BASE ON SYMBOL AND TIME FRAME FUNCTION
//----------------------- SOURCE : PENGIE
int subGenerateMagicNumber(int MagicNumber, string symbol, int timeFrame)
{
int isymbol = 0;
if (symbol == "EURUSD") isymbol = 1;
else if (symbol == "GBPUSD") isymbol = 2;
else if (symbol == "USDJPY") isymbol = 3;
else if (symbol == "USDCHF") isymbol = 4;
else if (symbol == "AUDUSD") isymbol = 5;
else if (symbol == "USDCAD") isymbol = 6;
else if (symbol == "EURGBP") isymbol = 7;
else if (symbol == "EURJPY") isymbol = 8;
else if (symbol == "EURCHF") isymbol = 9;
else if (symbol == "EURAUD") isymbol = 10;
else if (symbol == "EURCAD") isymbol = 11;
else if (symbol == "GBPUSD") isymbol = 12;
else if (symbol == "GBPJPY") isymbol = 13;
else if (symbol == "GBPCHF") isymbol = 14;
else if (symbol == "GBPAUD") isymbol = 15;
else if (symbol == "GBPCAD") isymbol = 16;
else isymbol = 17;
if(isymbol<10) MagicNumber = MagicNumber * 10;
return (StrToInteger(StringConcatenate(MagicNumber, isymbol, timeFrame)));
}
//----------------------- PRINT COMMENT FUNCTION
//----------------------- SOURCE : CODERSGURU
void subPrintDetails()
{
string sComment = "";
string sp = "-------------------------------------------------------------\n";
string NL = "\n";
sComment = sp;
sComment = sComment + sp;
sComment = sComment + "Entry HIGH= " + DoubleToStr(EMAX,4) + " | ";
sComment = sComment + "Entry LOW= " + DoubleToStr(EMIN,4) + " | ";
sComment = sComment + NL;
sComment = sComment + sp;
sComment = sComment + "ATR =" + DoubleToStr(N,4) + " | ";
sComment = sComment + "OpenPrice =" + DoubleToStr(LastOpen,4) + " | ";
sComment = sComment + "SL =" + DoubleToStr(LastSL,4) + " | ";
sComment = sComment + NL;
sComment = sComment + sp;
sComment = sComment + "EXIT HIGH= " + DoubleToStr(XMAX,4) + " | ";
sComment = sComment + "EXIT LOW= " + DoubleToStr(XMIN,4) + " | ";
sComment = sComment + NL;
sComment = sComment + sp;
Comment(sComment);
}
//----------COUNT OPEN TRADES------------------+
int subTotalOpenTrade()
{
int
cnt,
total = 0;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if((OrderType()==OP_SELL||OrderType()==OP_BUY) &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==MagicNumber) total++;
}
return(total);
}
//----------GET LASt OPENED PRICE------------------+
double subLastOpenPrice()
{
int
cnt,
total = 0;
double OpenPrice;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if((OrderType()==OP_SELL||OrderType()==OP_BUY) &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==MagicNumber)
OpenPrice = OrderOpenPrice();
}
return(OpenPrice);
}
//----------GET LASt SL PRICE------------------+
double subLastSLPrice()
{
int
cnt,
total = 0;
double SLPrice;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if((OrderType()==OP_SELL||OrderType()==OP_BUY) &&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==MagicNumber)
SLPrice = OrderStopLoss();
}
return(SLPrice);
}
//----------COUNT BUYSTOP ORDERS---------------+
int subTotalBuyStopTrade()
{
int
cnt,
total = 0;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderType()==OP_BUYSTOP&&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==MagicNumber) total++;
}
return(total);
}
//-----------COUNT SELLSTOP ORDERS-------------+
int subTotalSellStopTrade()
{
int
cnt,
total = 0;
for(cnt=0;cnt<OrdersTotal();cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderType()==OP_SELLSTOP&&
OrderSymbol()==Symbol() &&
OrderMagicNumber()==MagicNumber) total++;
}
return(total);
}
Comments
Markdown Formatting Guide
# H1
## H2
### H3
**bold text**
*italicized text*
[title](https://www.example.com)

`code`
```
code block
```
> blockquote
- Item 1
- Item 2
1. First item
2. Second item
---