_auto_BUY
Download scriptThis script is designed for the MetaTrader 4 platform to automate the process of opening "Buy" (long) positions on a financial market. It handles everything from determining how much money to risk on a trade to identifying the optimal price points for safety and profit.
Here is a breakdown of how the logic works in plain English:
Smart Lot Sizing (Risk Management)
The script features a sophisticated "Aggression" system to decide how many units (lots) to buy. It doesn't just use a static number; it looks at your current account balance and free margin:
- Fixed Mode: If you prefer a steady approach, it uses a pre-set amount. If your account doesn't have enough money to cover that specific amount, it automatically scales down to the minimum possible size.
- Auto-Selection Mode: The script calculates how many positions your balance can safely handle. It offers two levels of "aggression." One mode grows the trade size more quickly as capital allows, while the other uses a "soft" growth curve (mathematically calculated) to be more conservative with your funds.
Price Action Analysis
To decide where to place a trade, the script scans recent price history:
- It looks back at a specific number of previous candles (up to 15 by default).
- It searches for "local minimums"—points where the price bottomed out recently.
- Depending on the timeframe you are viewing, it uses different logic to identify these lows to ensure it isn't buying at an unfavorable price point.
Automatic Safety Nets (Stop Loss & Take Profit)
Once the script identifies a low point, it calculates the distance needed for your safety buffers:
- Dynamic Distance: It measures the gap between the current market price and the identified low point.
- Safety Minimums: It ensures that these gaps are never too small by comparing them against your minimum requirements (e.g., ensuring a Stop Loss is at least a certain number of pips away).
- Execution: If you have enabled "Stop Loss" or "Take Profit" in the settings, the script automatically attaches these prices to the trade the moment it is opened.
Operational Features
- Slip Page Handling: It includes a buffer for price fluctuations (slippage) to ensure orders are filled even during volatile market movements.
- Visual Logging: There is an optional feature that allows the script to take a "screenshot" of the chart and save it as an image file in your platform's folder immediately after a trade is opened, providing a visual record of the entry.
- Error Reporting: If the script fails to open a trade (due to lack of funds, market conditions, or other issues), it will trigger an alert on your screen to notify you of the specific error code.
//+------------------------------------------------------------------+
//| _auto_BUY.mq4 |
//| "ÑÊÐÈÏÒÛ ÄËß ËÅÍÈÂÎÃÎ" |
//| Ñêðèïò îòêðûâàåò BUY â àêòèâíîì îêíå. |
//| Ïðè CreateGif=true àêòèâíîå îêíî ïîñëå |
//| îòêðûòèÿ ïîçèöèè ñîõðàíÿåòñÿ êàê ðèñóíîê â |
//| ...\<Òåðìèíàë>\exsperts\files\<FileName>.gif |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, Bookkeeper"
#property link "yuzefovich@gmail.com"
#property show_inputs // Åñëè åñòü æåëàíèå ìåíÿòü ýêñòåðíû â ïðîöåññå
//+------------------------------------------------------------------+
extern int Aggression = 1; // = 0 - ôèêñèðîâàííûì ëîòîì
// = 1 èëè 2 àâòîâûáîð
extern double FixLot = 0.1;
extern int DistSLmin = 35; // StopLoss â ïóíêòàõ - íå ìåíüøå.
// Åñëè àâòîìàòîì áóäåò ìåíüøå - áóäåò
// óñòàíîâëåí íà DistSLmin ïóíêòîâ
extern int NBarsMax = 15; // Ìàêñèìàëüíîå ÷èñëî áàðîâ, ñðåäè
// êîòîðûõ èñêàòü ëîêàëüíûé ìèíèìóì.
// Åñëè íàéäåí íå áóäåò, áóäåò âçÿò
// ìåíüøèé èç Low â ýòîì äèàïàçîíå
// èëè ïî DistSLmin
extern int SlipPage = 7; // Ïðîñêàëüçûâàíèå â ïóíêòàõ
extern bool StopLoss = true; // Ñòàâèòü èëè íåò StopLoss
extern bool TakeProfit = true; // Ñòàâèòü èëè íåò TakeProfit=StopLoss
extern bool CreateGif = false; // Ñîçäàòü èëè íåò ðèñóíîê
//+------------------------------------------------------------------+
double CalcLotsAuto() // Ìÿãêî-àãðåññèâíûé ñïîñîá óïðàâëåíèÿ äåíþøêîé.
{
double lots;
// Ìèíèìàëüíûé è ìàêñèìàëüíûé ðàçìåðû ëîòîâ
double MinLot=MarketInfo(Symbol(),MODE_MINLOT);
int MinLotDgts;
if(MinLot<0.1) MinLotDgts=2; // ðàçìåðíîñòü ìèíëîòà
else
{
if(MinLot<1.0) MinLotDgts=1;
else MinLotDgts=0;
}
double MaxLot=MarketInfo(Symbol(),MODE_MAXLOT);
// íóæåí çàëîã íà ìèíëîò
double MarginLot=MarketInfo(Symbol(),MODE_MARGINREQUIRED)*MinLot;
// èìååì ñâîáîäíûõ ñðåäñòâ
double FreeMargin=AccountFreeMargin();
// åñëè èõ íå èìååì :(
if(MarginLot>FreeMargin) return(-1.0);
// à åñëè èìååì, òî ñêîëüêî ëîòîâ ìîæåì ñåáå ïîçâîëèòü íà ïîçó
double LotStep=MarketInfo(Symbol(),MODE_LOTSTEP);
int LotStepDgts;
if(LotStep<0.1) LotStepDgts=2; // ðàçìåðíîñòü
else
{
if(LotStep<1.0) LotStepDgts=1;
else LotStepDgts=0;
}
FixLot=NormalizeDouble(FixLot,LotStepDgts);
if(Aggression==0)
{
if(FixLot>0)
{
MarginLot=MarketInfo(Symbol(),MODE_MARGINREQUIRED)*FixLot;
if(MarginLot>FreeMargin) lots=NormalizeDouble(MinLot,MinLotDgts);
else lots=NormalizeDouble(FixLot,LotStepDgts);
return(lots);
}
else
{
lots=NormalizeDouble(MinLot,MinLotDgts);
return(lots);
}
}
int n=1;
int m=NormalizeDouble(MaxLot/MinLot,0);
double level=MarginLot*2;
while(level<=FreeMargin && n<=m)
{
n++;
if(Aggression==1)
level=level+MarginLot*n; // Ìåíåå àãðåññèâíî
else level=level+MarginLot*MathSqrt(n);
}
n--;
lots=NormalizeDouble((MinLot*n),MinLotDgts);
return(lots);
}
//+------------------------------------------------------------------+
void start()
{
double SL, TP;
int ticket, i;
string FileName, str;
//----
// Äîïóñê óðîâíåé ñòîïîâ (äîáàâëÿþ ïðîñêàëüçûâàíèå)
double MinDistForStops=
(MarketInfo(Symbol(),MODE_STOPLEVEL)+SlipPage)*Point;
double lots=CalcLotsAuto();
if(lots<=0)
{
Alert("Open_BUY: My finance sing romances");
return;
}
int N=0, m=0;
bool b=true;
while(b && N<NBarsMax)
{
N++;
if((Period()<1440 && Low[N]<=Low[N+1] && Low[N]<=Low[N-1] && Low[N]<Low[N+2] && Low[N]<Low[N-2])
|| (Period()>240 && Low[N]<=Low[N+1] && Low[N]<=Low[N-1]))
{
b=false;
m=N;
}
else m=iLowest(NULL,0,MODE_LOW,N,0);
}
RefreshRates();
double DistStops=Bid-Low[m]+MarketInfo(Symbol(),MODE_SPREAD)*Point;
DistStops=MathMax((DistSLmin*Point),DistStops);
DistStops=MathMax(MinDistForStops,DistStops);
if(StopLoss==true) SL=Bid-DistStops;
else SL=0;
if(TakeProfit==true) TP=Ask+DistStops;
else TP=0;
ticket=OrderSend(Symbol(),OP_BUY,
lots,
NormalizeDouble(MarketInfo(Symbol(),MODE_ASK),Digits),
SlipPage,
NormalizeDouble(SL,Digits),
NormalizeDouble(TP,Digits),
"",0,0,CLR_NONE);
if(ticket<0) Alert("Open_BUY LastError: ",GetLastError());
else
{
if(CreateGif==true)
{
// ðèñóåì, åñëè çàêàçàíî
datetime curdate=TimeCurrent();
FileName=Symbol()+"_BUY_"+TimeYear(curdate);
i=TimeMonth(curdate);
if(i<10)
{
str="0"+i;
FileName=FileName+str;
}
else FileName=FileName+i;
i=TimeSeconds(curdate)+
100*TimeMinute(curdate)+
10000*TimeHour(curdate)+
1000000*TimeDay(curdate);
if(TimeDay(curdate)<10)
{
str="0"+i;
FileName=FileName+str;
}
else FileName=FileName+i;
FileName=FileName+".gif";
WindowScreenShot(FileName,400,300);
}
}
return;
}
//+------------------------------------------------------------------+
Profitability Reports
Expected payoff
Average expected payoff across the available backtests for each symbol.
Comments