Okay, here's a breakdown of what this MetaTrader script does, explained in plain language for someone who doesn't code:
Overall Goal:
The script is designed to automatically place pending buy and sell orders (specifically, "Buy Stop" and "Sell Stop" orders) based on the price movement around a calculated "envelope" of values. It then manages these orders by adjusting their stop-loss levels to protect profits or deleting them if they haven't been triggered by the end of the trading day. It also calculates the lot size of the trades depending on a risk percentage and reduces the size of the lots if losses occur.
Here's a step-by-step breakdown:
-
Setting the Stage (Input Parameters):
- The script starts by letting you, the user, define several settings. These are like knobs and dials that control how the script behaves.
- Envelope Period: This tells the script how many past data points to consider when calculating the envelope. Think of it like setting the length of a trend you're trying to identify.
- Envelope Timeframe: Here you chose in which timeframe the envelope will be calculated, you can chose the current chart timeframe, hourly, 4 hours, daily...
- Envelope Method: This determines the type of average to use for drawing the middle line of the envelope (Simple Moving Average, Exponential Moving Average, etc.).
- Envelope Deviation: This controls how far away from the middle line the upper and lower lines of the envelope will be. A higher deviation means a wider envelope.
- Trading Hours: The script will only place new orders during a specific time window you define (e.g., between 0:00 and 23:00 hours).
- Take Profit Levels: The script uses different levels to set take profits for each order.
- Lot Size: You can specify a fixed lot size to use for each trade, but the script will also adjust this based on your risk settings.
- Risk Management: You can define the maximum percentage of your account you're willing to risk on each trade. The script will then automatically calculate the appropriate lot size. It can also decrease the size of future trades if you experience a losing streak.
- Trailing Stop Loss: This feature will automatically adjust the stop-loss levels of your open trades to lock in profits as the price moves in your favor. It can be based on the Moving Average line or the opposite side of the "envelope."
-
Calculating the Envelope:
- The script uses the settings you provided to calculate two lines that form an "envelope" around the current price.
- One line is above the price (the upper envelope), and the other is below (the lower envelope). These lines act as potential areas where the price might reverse direction.
-
Placing Pending Orders:
- The script checks if the current price is within the trading hours you specified and if it�s inside the enveolpe levels.
- If these conditions are met, it places both a "Buy Stop" order above the upper envelope line and a "Sell Stop" order below the lower envelope line.
- "Buy Stop" and "Sell Stop" orders are pending orders that will only be activated if the price reaches those levels.
- The script places up to 3 buy orders, and 3 sell orders.
- The script calculates the lot size of the orders in dependance of the risk that was especified.
-
Managing Existing Orders:
- The script constantly checks all open and pending orders.
- Tracking Orders: It remembers the "ticket number" (a unique identifier) of each order it has placed. This allows it to keep track of them.
- Trailing Stop Loss: If you've enabled the trailing stop loss feature, the script will automatically adjust the stop-loss levels of your open trades to lock in profits as the price moves in your favor.
- Deleting Orders at End of Day: At the end of the trading day (hour 23), the script will automatically delete any pending "Buy Stop" or "Sell Stop" orders that haven't been triggered. This prevents orders from lingering overnight.
In Summary:
This script is an automated trading tool that uses a price "envelope" to identify potential entry points for trades. It then places pending orders, manages risk by adjusting lot sizes, and protects profits by using a trailing stop loss. Finally, it cleans up any unused orders at the end of the day.
Profitability Reports
/*-----------------------------+
| |
| Shared by www.Aptrafx.com |
| |
+------------------------------*/
//+------------------------------------------------------------------+
//| Envelope 2.mq4 |
//| tageiger |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "tageiger"
#property link "http://www.metaquotes.net"
//---- input parameters
extern int EnvelopePeriod =144;
extern int EnvTimeFrame =240; //envelope time frame: 0=chart,60=1hr,240=4hr, etc.
extern int EnvMaMethod =1; //0=sma,1=ema,2=smma,3=lwma.
extern double EnvelopeDeviation =0.85;
extern int TimeOpen =0;
extern int TimeClose =23;
extern double FirstTP =233.0;
extern double SecondTP =377.0;
extern double ThirdTP =610.0;
extern double Lots =0.1;
extern double MaximumRisk =0.02;
extern double DecreaseFactor =3;
extern int MaElineTSL =1;//0=iMA trailing stoploss 1=Opposite Envelope TSL
int b1,b2,b3,s1,s2,s3;
int order_type;
double TSL =0;
//+------------------------------------------------------------------+
//| 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/1000.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);
}
int start()
{
int p=0;p=EnvelopePeriod;
int etf=0;etf=EnvTimeFrame;
int mam=0;mam=EnvMaMethod;
double d=0;d=EnvelopeDeviation;
double btp1,btp2,btp3,stp1,stp2,stp3;
double bline=0,sline=0,ma=0;
int cnt, ticket, total;
ma=iMA(NULL,etf,p,0,mam,PRICE_CLOSE,0);
bline=iEnvelopes(NULL,etf,p,mam,0,PRICE_CLOSE,d,MODE_UPPER,0);
sline=iEnvelopes(NULL,etf,p,mam,0,PRICE_CLOSE,d,MODE_LOWER,0);
total=OrdersTotal();
if(OrdersTotal()==0)
{b1=0;b2=0;b3=0;s1=0;s2=0;s3=0;}
//Print(b1," ",b2," ",b3," ",s1," ",s2," ",s3);
//Print("order type:",OrderType());
if(b1==0)
{
if(Hour()>TimeOpen && Hour()<TimeClose)
{
if(bline>Close[0] && sline<Close[0])
{
btp1=(NormalizeDouble(bline,4))+(FirstTP*Point);
ticket=OrderSend(Symbol(),
OP_BUYSTOP,
LotsOptimized(),
(NormalizeDouble(bline,4)),
0,
(NormalizeDouble(sline,4)),
btp1,
"",
2,
TimeClose,
Aqua);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
{
b1=ticket;
Print(ticket);
}
else Print("Error Opening BuyStop Order: ",GetLastError());
return(0);
}
}
}
}
if(b2==0)
{
if(Hour()>TimeOpen && Hour()<TimeClose)
{
if(bline>Close[0] && sline<Close[0])
{
btp2=(NormalizeDouble(bline,4))+(SecondTP*Point);
ticket=OrderSend(Symbol(),
OP_BUYSTOP,
LotsOptimized(),
(NormalizeDouble(bline,4)),
0,
(NormalizeDouble(sline,4)),
btp2,
"",
4,
TimeClose,
Aqua);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
{
b2=ticket;
Print(ticket);
}
else Print("Error Opening BuyStop Order: ",GetLastError());
return(0);
}
}
}
}
if(b3==0)
{
if(Hour()>TimeOpen && Hour()<TimeClose)
{
if(bline>Close[0] && sline<Close[0])
{
btp3=(NormalizeDouble(bline,4))+(ThirdTP*Point);
ticket=OrderSend(Symbol(),
OP_BUYSTOP,
LotsOptimized(),
(NormalizeDouble(bline,4)),
0,
(NormalizeDouble(sline,4)),
btp3,
"",
6,
TimeClose,
Aqua);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
{
b3=ticket;
Print(ticket);
}
else Print("Error Opening BuyStop Order: ",GetLastError());
return(0);
}
}
}
}
if(s1==0)
{
if(Hour()>TimeOpen && Hour()<TimeClose)
{
if(bline>Close[0] && sline<Close[0])
{
stp1=NormalizeDouble(sline,4)-(FirstTP*Point);
ticket=OrderSend(Symbol(),
OP_SELLSTOP,
LotsOptimized(),
(NormalizeDouble(sline,4)),
0,
(NormalizeDouble(bline,4)),
stp1,
"",
1,
TimeClose,
HotPink);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
{
s1=ticket;
Print(ticket);
}
else Print("Error Opening SellStop Order: ",GetLastError());
return(0);
}
}
}
}
if(s2==0)
{
if(Hour()>TimeOpen && Hour()<TimeClose)
{
if(bline>Close[0] && sline<Close[0])
{
stp2=NormalizeDouble(sline,4)-(SecondTP*Point);
ticket=OrderSend(Symbol(),
OP_SELLSTOP,
LotsOptimized(),
(NormalizeDouble(sline,4)),
0,
(NormalizeDouble(bline,4)),
stp2,
"",
3,
TimeClose,
HotPink);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
{
s2=ticket;
Print(ticket);
}
else Print("Error Opening SellStop Order: ",GetLastError());
return(0);
}
}
}
}
if(s3==0)
{
if(Hour()>TimeOpen && Hour()<TimeClose)
{
if(bline>Close[0] && sline<Close[0])
{
stp3=NormalizeDouble(sline,4)-(ThirdTP*Point);
ticket=OrderSend(Symbol(),
OP_SELLSTOP,
LotsOptimized(),
(NormalizeDouble(sline,4)),
0,
(NormalizeDouble(bline,4)),
stp3,
"",
5,
TimeClose,
HotPink);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
{
s3=ticket;
Print(ticket);
}
else Print("Error Opening SellStop Order: ",GetLastError());
return(0);
}
}
}
}
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderTicket()==b1)
{if(OrderType()!=OP_BUY)
{if(OrderType()!=OP_BUYSTOP)
{b1=0; }}}
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderTicket()==b2)
{if(OrderType()!=OP_BUY)
{if(OrderType()!=OP_BUYSTOP)
{b2=0; }}}
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderTicket()==b3)
{if(OrderType()!=OP_BUY)
{if(OrderType()!=OP_BUYSTOP)
{b3=0; }}}
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderTicket()==s1)
{if(OrderType()!=OP_SELL)
{if(OrderType()!=OP_SELLSTOP)
{s1=0; }}}
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderTicket()==s2)
{if(OrderType()!=OP_SELL)
{if(OrderType()!=OP_SELLSTOP)
{s2=0; }}}
OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderTicket()==s3)
{if(OrderType()!=OP_SELL)
{if(OrderType()!=OP_SELLSTOP)
{s3=0; }}}
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_BUY)
{
if(MaElineTSL==0) {TSL=NormalizeDouble(ma,4); }
if(MaElineTSL==1) {TSL=NormalizeDouble(sline,4); }
if(Close[0]>OrderOpenPrice())
{
if((Close[0]>sline) && (TSL>OrderStopLoss()))
{
double bsl;bsl=TSL;
OrderModify(OrderTicket(),
OrderOpenPrice(),
bsl,
OrderTakeProfit(),
0,//Order expiration server date/time
Green);
Sleep(10000);
}
}
}
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()==OP_SELL)
{
if(MaElineTSL==0) {TSL=NormalizeDouble(ma,4); }
if(MaElineTSL==1) {TSL=NormalizeDouble(bline,4); }
if(Close[0]<OrderOpenPrice())
{
if((Close[0]<bline) && (TSL<OrderStopLoss()))
{
double ssl;ssl=TSL;
OrderModify(OrderTicket(),
OrderOpenPrice(),
ssl,
OrderTakeProfit(),
0,//Order expiration server date/time
Red);
Sleep(10000);
}
}
}
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(Hour()==23 && OrderType()==OP_BUYSTOP)
{
OrderDelete(OrderTicket());
if(OrderTicket()==b1) {b1=0; return;}
if(OrderTicket()==b2) {b2=0; return;}
if(OrderTicket()==b3) {b3=0; return;}
}
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(Hour()==23 && OrderType()==OP_SELLSTOP)
{
OrderDelete(OrderTicket());
if(OrderTicket()==s1) {s1=0; return;}
if(OrderTicket()==s2) {s2=0; return;}
if(OrderTicket()==s3) {s3=0; return;}
}
}
}
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
---