Scalp_8_12_v1_2(ICEedition)
Download scriptThis automated trading script is designed to execute "scalping" trades—meaning it aims to capture small price movements quickly. It operates by analyzing historical price ranges and identifying specific moments when the market moves beyond expected boundaries.
Here is a detailed breakdown of the logic used by the system:
Core Trading Logic
The script functions based on two distinct sets of rules (referred to as "series 8" and "series 12"). Each series monitors the market differently to identify entry points:
- Range Analysis: The system looks back at a specific number of days to calculate the average daily movement of the currency or asset.
- Volatility Filtering: It calculates the current price range (the difference between the highest and lowest prices) over a specific window of time. It will only consider entering a trade if the current price movement is relatively small compared to the historical average (using a user-defined multiplier). This ensures the system avoids entering trades during "crazy" or unpredictable market spikes.
- Price Level Detection: Based on the historical averages, the script mathematically calculates specific "Buy" and "Sell" price levels. It essentially waits for the price to break through these calculated boundaries before taking action.
Trade Management
Once a trade is opened, the system manages it using three primary methods:
- Stop Loss & Profit Targets: Every trade has a pre-calculated exit point. These are based on the historical average ranges. If the price reaches the designated profit or loss target, the script automatically closes the position.
- Time-Based Exits: To prevent holding trades overnight or during low-liquidity periods, the script includes a "Close by Time" feature. It will automatically shut down all active positions at a specific hour of the day (e.g., 9:00 AM).
- Insurance Stops: The script includes an additional safety mechanism called an "Insurance Stop." This is an extra buffer placed on the trade to protect against sudden, extreme movements in the opposite direction.
Risk and Money Management
The script features several layers of risk control to protect the account balance:
- Lot Sizing: It can automatically calculate how much money to risk per trade based on your available account balance.
- Daily Trade Limits: You can set a maximum number of trades allowed per day to prevent the system from over-trading.
- Day-Specific Rules: The script allows for specific behavior on different days—for example, you can choose to double the trade size on a specific day or completely disable trading on another day (like a weekend).
- Error Handling: If the server fails to execute a command (like opening or closing a trade), the script is programmed to retry several times with increasing pauses between attempts.
Operational Constraints
The script follows a strict schedule to ensure it only operates when market conditions are optimal:
- Operating Window: It will only open new trades during a specific "active" window of the day (e.g., between 8:00 AM and 10:00 PM).
- Single Execution: It is designed to run once per candle to prevent multiple simultaneous entries on the same price movement.
//+------------------------------------------------------------------+
//| Scalp_8_12_v1_1.mq4 |
//| Copyright © 2006, Magex |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Dan"
#property link "3172552@gmail.com"
#include <stdlib.mqh>
#define MN_8 8
#define MN_12 12
//---- input parameters
extern int Hours2Check= 8; //êîëè÷åñòâî ÷àñîâ äëÿ èçìåðåíèÿ ïðîáèâàåìîãî äèàïàçîíà
extern int CloseHour= 9; //âðåìÿ çàêðûòèÿ âñåõ ïîçèöèé
extern int EarliestOpenHour=14; //ðàíüøå ýòîãî ÷àñà íå îòêðûâàåìñÿ
extern int Days2Check= 10; //êîëè÷åñòâî ñóòîê äëÿ èçìåðåíèÿ ñðåäíåãî ñóòî÷íîãî äèàïàçîíà
extern double ChannelK= 1.5; //êîýôôèöèåíò ðàññ÷¸òà êàíàëà
extern int CheckHour_8= 8; //âðåìÿ èçìåðåíèÿ ïðîáèâàåìîãî äèàïàçîíà
extern double ProfitK_8= 2; //êîýôôèöèåíò ðàññ÷¸òà ïðîôèòà
extern double LossK_8= 2; //êîýôôèöèåíò ðàññ÷¸òà ëîññà
extern double OffsetK_8= 2; //êîýôôèöèåíò ðàññ÷¸òà ðàññòîÿíèÿ ïðîáîÿ
extern int CheckHour_12= 12; //âðåìÿ èçìåðåíèÿ ïðîáèâàåìîãî äèàïàçîíà
extern double ProfitK_12= 2; //êîýôôèöèåíò ðàññ÷¸òà ïðîôèòà
extern double LossK_12= 1.5; //êîýôôèöèåíò ðàññ÷¸òà ëîññà
extern double OffsetK_12= 2.5; //êîýôôèöèåíò ðàññ÷¸òà ðàññòîÿíèÿ ïðîáîÿ
extern int FilterDay= 4; //â ýòîò äåíü íåäåëè íå òîðãóåì
extern int DoubleDay= 5; //â ýòîò äåíü íåäåëè óäâàèâàåì ëîò
extern bool UseMM= false;
extern int TradesPerDayAllowed= 2; //êîëè÷åñòâî ñäåëîê ðàçðåø¸ííûõ â ñóòêè
//////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//Ïàðàìåòðû äëÿ èñïîëüçîâàíèÿ ÌÌ
int MaxSystemDD=240; //ñþäà ïèñÀòü ìàêñ. äðîóäàóí ñèñòåìû áåç èñïîëüçîâàíèÿ ìì
int SystemTrustK=1;//êîýôôèöèåíò äîâåðèÿ ê ñèñòåìå-
int MaxDD_Allowed=20;// ðàçðåø¸ííûé äðîóäàóí ñèñòåìû â ïðîöåíòàõ îò äåïî
///////////////////////
double Lots=1.0;
int LatestOpenHour=22;//ïîñëå ýòîãî ÷àñà íå îòêðûâàåìñÿ
int PointPrice=10;//öåíà ïóíêòà ïðè ðàáîòå 1-ì ëîòîì, äëÿ åâðî- 10 äîëëàðîâ
/////////////////////////////////////////////////////
//Ïàðàìåòðû îáðàáîòêè îøèáîê ñåðâåðîì
int MaxTries=5;//êîëè÷åñòâî ïîïûòîê îòêðûòü ïîçó
int Pause=1000;//ïåðâîå çíà÷åíèå ïàóçû ïåðåä íîâîé ïîïûòêîé îòêðûòü-çàêðûòü îðäåð
int err;//îøèáêà
int try;//èòåðàöèÿ ïîïûòêè îòêðûòèÿ-çàêðûòèÿ
int ticket;//ðåçóëüòàò îòêðûòèÿ
bool close;//ðåçóëüòàò çàêðûòèÿ
///////////////////////////////////////
int i;//èòåðàöèÿ âûáîðà îðäåðà
int BarsPerDay;//ñâå÷é â ñóòêè
int InsuranceStop;//ñòðàõîâî÷íûé ñòîï, íà ñëó÷àé ñèëüíîãî äâèæåíèÿ ïðîòèâ íàøåé ïîçèöèè
double ISK=1.5;//êîýôôèöèåíò äëÿ ðàññ÷¸òà ñòðàõîâî÷íîãî ñòîïà, êîòîðûé óñòàíàâëèâàåòñÿ â OrderSend()
int bars;//èñïîëüçóåòñÿ äëå òîãî, ÷òîáû ýêñïåðò ðàáîòàë òîëüêî 1 ðàç íà ñâå÷ó
//ìàññèâû
int OpenDay[2];
int Bars2Check[2];
int profit[2];
int loss[2];
int offset[2];
int avrange[2];
double sellprice[2];
double buyprice[2];
double daj[2];
double hh[2];
double ll[2];
double totalrange[2];
double channel[2];
int CheckHour[2];
double ProfitK[2];
double LossK[2];
double OffsetK[2];
int MN[2];
bool first_start;
////////////////////////////////////////////////////////////
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
first_start=true;
CheckHour[0] = CheckHour_8;
ProfitK [0] = ProfitK_8;
LossK [0] = LossK_8;
OffsetK [0] = OffsetK_8;
MN [0] = MN_8;
CheckHour[1] = CheckHour_12;
ProfitK [1] = ProfitK_12;
LossK [1] = LossK_12;
OffsetK [1] = OffsetK_12;
MN [1] = MN_12;
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
/////////////////////////////////////////////////////////////////////
void Levels_Defining(int n)
{ //èíèöèàëèçàöèÿ ìàññèâîâ
// CheckHour[0]=CheckHour_8;
// ProfitK[0]=ProfitK_8;
// LossK[0]=LossK_8;
// OffsetK[0]=OffsetK_8;
// MN[0]=MN_8;
// CheckHour[1]=CheckHour_12;
// ProfitK[1]=ProfitK_12;
// LossK[1]=LossK_12;
// OffsetK[1]=OffsetK_12;
// MN[1]=MN_12;
if ( n==0 ) {Bars2Check[n]=((Hours2Check*60)/Period()); }
else { Bars2Check[n]=(((CheckHour[1]-CheckHour[0])*60)/Period()); }
hh[n]=High[Highest(NULL,0,MODE_HIGH,Bars2Check[n],((Hour()-CheckHour[n])*60)/Period()+1)];
ll[n]=Low[Lowest(NULL,0,MODE_LOW,Bars2Check[n],((Hour()-CheckHour[n])*60)/Period()+1)];
BarsPerDay=((24*60)/Period());
totalrange[n]=0;
channel[n]=hh[n]-ll[n];
for(i=1;i<=Days2Check;i++)
{
daj[n]=(High[Highest(NULL,0,MODE_HIGH,BarsPerDay,BarsPerDay*(i-1)+((Hour()-CheckHour[n])*60)/Period()+1)]
-Low[Lowest(NULL,0,MODE_LOW,BarsPerDay,BarsPerDay*(i-1)+((Hour()-CheckHour[n])*60)/Period()+1)]);
totalrange[n]=totalrange[n]+daj[n];
}
avrange[n]=MathRound((totalrange[n]/Days2Check)/Point);
offset[n]=MathRound(avrange[n]/OffsetK[n]);
sellprice[n]=NormalizeDouble(ll[n]-offset[n]*Point,4);
buyprice[n]=NormalizeDouble(hh[n]+offset[n]*Point,4);
profit[n]=MathRound(avrange[n]/ProfitK[n]);
loss[n]=MathRound(avrange[n]/LossK[n]);
return;
}
//*/*
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////_8
void Close_by_Closetime(int n)
{
for(i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if((OrderMagicNumber()!=MN[n] && OrderMagicNumber()!=MN[n]) || OrderSymbol()!=Symbol() ) continue;
if (OrderType()==OP_BUY)
{
for(int try=1;try<=MaxTries;try++)
{
while (!IsTradeAllowed()) Sleep(1000);
close=false;
RefreshRates();
close=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,4),3,White);
Sleep(Pause);
if (close){Pause=1000; break;}
else
{
err=GetLastError();
Print("OrderClose failed with error #",err," : ",ErrorDescription(err),"Trying Again #",try);
Pause=Pause*2;
if (try==MaxTries)
{
Pause=1000;
Print("Warning!!!Last try failed!");
SendMail("Warning!!!Last try failed! ",OrderType()+" by "+OrderClosePrice()+" Cloing Failed!");
break;
}
}
}
}
if (OrderType()==OP_SELL)
{
for(try=1;try<=MaxTries;try++)
{
while (!IsTradeAllowed()) Sleep(1000);
close=false;
RefreshRates();
close=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,4),3,White);
Sleep(Pause);
if (close){Pause=1000; break;}
else
{
err=GetLastError();
Print("OrderClose failed with error #",err," : ",ErrorDescription(err),"Trying Again #",try);
Pause=Pause*2;
if (try==MaxTries)
{
Pause=1000;
Print("Warning!!!Last try failed!");
SendMail("Warning!!!Last try failed! ",OrderType()+" by "+OrderClosePrice()+" Cloing Failed!");
break;
}
}
}
}
}
}
///////////////////////////////////////////////////////////////*/
///////////////////////////////////////////////////////////////
void Close_by_Stops(int n)
{
for(i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderMagicNumber()!=MN[n] || OrderSymbol()!=Symbol()) continue;
if ((OrderType()==OP_BUY)
&& (((Close[1]-NormalizeDouble(OrderOpenPrice(),4))>=profit[n]*Point)
|| ((NormalizeDouble(OrderOpenPrice(),4)-Close[1])>=loss[n]*Point)))
{
for(int try=1;try<=MaxTries;try++)
{
while (!IsTradeAllowed()) Sleep(5000);
close=false;
RefreshRates();
close=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,4),3,White);
Sleep(Pause);
if (close){Pause=1000;break;}
else
{
err=GetLastError();
Print("OrderClose failed with error #",err," : ",ErrorDescription(err),"Trying Again #",try);
Pause=Pause*2;
if (try==MaxTries)
{
Pause=1000;
Print("Warning!!!Last try failed!");
SendMail("Warning!!!Last try failed! ",OrderType()+" by "+OrderClosePrice()+" Cloing Failed!");
break;
}
}
}
}
if ((OrderType()==OP_SELL)
&& (((Close[1]-NormalizeDouble(OrderOpenPrice(),4))>=loss[n]*Point)
|| ((NormalizeDouble(OrderOpenPrice(),4)-Close[1])>=profit[n]*Point)))
{
for(try=1;try<=MaxTries;try++)
{
while (!IsTradeAllowed()) Sleep(5000);
close=false;
RefreshRates();
close=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,4),3,White);
Sleep(Pause);
if (close){Pause=1000;break;}
else
{
err=GetLastError();
Print("OrderClose failed with error #",err," : ",ErrorDescription(err),"Trying Again #",try);
Pause=Pause*2;
if (try==MaxTries)
{
Pause=1000;
Print("Warning!!!Last try failed!");
SendMail("Warning!!!Last try failed! ",OrderType()+" by "+OrderClosePrice()+" Cloing Failed!");
break;
}
}
}
}
}
}
//////////////////////////////////////////////////*/
double LotSizeCounting(int OpTime)
{
if (UseMM==true)
{
if (OpTime==8)
{
// Lots=NormalizeDouble(((AccountFreeMargin( )/100000)*MarginPercent),1);Print(Lots);
// Lots=NormalizeDouble(MathSqrt(100*channel_8),1);
// Lots=NormalizeDouble(((AccountFreeMargin( )/100)*MaxDD_Allowed )/((loss)*SystemTrustK*PointPrice),1);
Lots=NormalizeDouble(((AccountFreeMargin( )/100)*MaxDD_Allowed )/(MaxSystemDD*SystemTrustK*PointPrice),1);
// Print(Lots);
}
if (OpTime==12)
{
// Lots=NormalizeDouble((AccountFreeMargin( )/100000)*MarginPercent,1);
// Lots=NormalizeDouble(MathSqrt(100*channel_12),1);
// Lots=NormalizeDouble(((AccountFreeMargin( )/100)*MaxDD_Allowed )/((loss)*SystemTrustK*PointPrice),1);
Lots=NormalizeDouble(((AccountFreeMargin( )/100)*MaxDD_Allowed )/(MaxSystemDD*SystemTrustK*PointPrice),1);
}
if (Lots<0.1)
{
Print("Too risky Trade! Add some money to account");
SendMail("Too risky Trade! Add some money to account","Too risky Trade! Add some money to account");
Lots=0.1;
}
}
else Lots=0.1;
if (DayOfWeek()==DoubleDay ){Lots=Lots*2;}
return(Lots);
}
////////////////////////////////////////////////////////////////////////////////
void Opening(int n)
{
InsuranceStop=MathRound(loss[n]*ISK);
Lots=LotSizeCounting(8);
if (Close[1]>=buyprice[n])
{
for (int try=1;try<=MaxTries;try++)
{
while (!IsTradeAllowed()) Sleep(5000);
RefreshRates();
ticket=OrderSend(Symbol(),OP_BUY,Lots,NormalizeDouble(Ask,4),3,NormalizeDouble(Ask-InsuranceStop*Point,4),1.5,"Order 8-series Open",MN[n],Blue);
Sleep(Pause);
if (ticket>0){OpenDay[n]=Day();Pause=1000;break;}
else
{
err=GetLastError();
Print("OrderSend failed with error #",err," : ",ErrorDescription(err),"Trying again #",try);
Pause=Pause*2;
if (try==MaxTries)
{
Pause=1000;
Print("Warning!!!Last try failed!");
SendMail("Warning!!!Last try failed!",OrderType()+" by "+OrderOpenPrice()+" Opening failed!");
break;
}
}
}
}
if (sellprice[n]>=Close[1])
{
for (try=1;try<=MaxTries;try++)
{
while (!IsTradeAllowed()) Sleep(5000);
RefreshRates();
ticket=OrderSend(Symbol(),OP_SELL,Lots,NormalizeDouble(Bid,4),3,NormalizeDouble(Bid+InsuranceStop*Point,4),0.5,"Order 8-series Open",MN[n],Red);
Sleep(Pause);
if (ticket>0){OpenDay[n]=Day();Pause=1000;break;}
else
{
err=GetLastError();
Print("OrderSend failed with error #",err," : ",ErrorDescription(err),"Trying again #",try);
Pause=Pause*2;
if (try==MaxTries)
{
Pause=1000;
Print("Warning!!!Last try failed!");
SendMail("Warning!!!Last try failed!",OrderType()+" by "+OrderOpenPrice()+" Opening failed!");
break;
}
}
}
}
}
/////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
void start()
{
if ( Period()!=60 || Bars==bars ) return;
bars=Bars;
if (first_start)
{
first_start=false;
for(i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) continue;
if(OrderMagicNumber()==MN[0] && OrderSymbol()==Symbol()) OpenDay[0]=TimeDay(OrderOpenTime());
if(OrderMagicNumber()==MN[1] && OrderSymbol()==Symbol()) OpenDay[1]=TimeDay(OrderOpenTime());
}
// Levels_Defining(0);
// Levels_Defining(1);
}
// Comment("p(0)",profit[0], " l(0) ", loss[0],"p(1)", profit[1], "l(1)", loss[1]);
int i;int n;
//----
if (OrdersTotal()>0)
{
Levels_Defining(0);
Close_by_Stops(0);
Levels_Defining(1);
Close_by_Stops(1);
if ((Hour()>=CloseHour) && (Day()!=OpenDay[0]))
Close_by_Closetime(0);
if ((Hour()>=CloseHour) && (Day()!=OpenDay[1]))
Close_by_Closetime(1);
}
if (Hour()>LatestOpenHour || Hour()<EarliestOpenHour) return;
{
if ( DayOfWeek()!=FilterDay )
{
Levels_Defining(0);//Print(offset[1],"--",loss[1],"--",channel[1]);
if ( channel[0]<(avrange[0]/ChannelK)*Point && Day()!=OpenDay[0])
{ Opening(0); }
if (OrdersTotal()==TradesPerDayAllowed) return;
Levels_Defining(1);
if ( channel[1]<(avrange[1]/ChannelK)*Point && Day()!=OpenDay[1])
{ Opening(1); }
}
}
}
/////////////////////////////////////////////////////////
Profitability Reports
Expected payoff
Average expected payoff across the available backtests for each symbol.
Comments