Samuray_v52
Download scriptThis automated trading script, named "Samuray," is designed to manage forex trades autonomously by combining several technical analysis filters and risk management protocols. Instead of executing trades based on a single indicator, it uses a multi-layered logic system to verify market conditions before entering or maintaining positions.
Core Trading Logic and Filters
The script evaluates several conditions simultaneously to determine if a trade is viable:
- Trend Identification (EMA): It utilizes two Exponential Moving Averages (Fast and Slow). The script looks for specific relationships between these two lines to determine the direction of the market trend before authorizing a trade.
- Volatility and Price Location (Bollinger Bands): It uses Bollinger Bands to assess price boundaries. This acts as a filter to ensure that trades are only opened when the price is positioned appropriately relative to its recent volatility range.
- Trade Limits: The system monitors how many positions are currently open. If the number of active trades exceeds a pre-defined maximum, it will pause new entries to prevent over-exposure.
Execution and Safety Mechanisms
Beyond just opening trades, the script includes several "safety" behaviors:
- Security Filters: There is a "Secure Orders" feature that prevents the system from opening new positions unless the current trade setup meets a minimum profit threshold or there are no active orders, helping to ensure the account isn't over-leveraged during choppy markets.
- Recycle Profit: The script features a logic gate that can automatically close all open positions if a specific total profit target is met, effectively "recycling" the gains and resetting the trading cycle.
- Auto-Trade Protection: It includes an explicit check to ensure the user has enabled autonomous trading in the settings before it attempts any actions.
Dynamic Trade Management
Once a trade is live, the script actively manages the position to protect capital:
- Break-Even Logic: Once a trade moves into a specific amount of profit (in pips), the script can automatically move the Stop Loss to the entry price (plus a small offset). This effectively removes the risk of the trade turning into a loser once it has reached a certain milestone.
- Trailing Stop: The script can follow the market's movement in real-time. As the price moves in your favor, the Stop Loss "trails" behind it at a set distance, allowing the trade to capture as much profit as possible while locking in gains.
- Dynamic Lot Sizing (Money Management): Rather than using a fixed amount for every trade, the script can calculate position sizes based on the available margin and a user-defined risk factor. It also identifies whether the account is a standard or "micro" account to adjust the minimum allowable trade sizes accordingly.
User Interface
To keep the trader informed, the script displays a real-time dashboard directly on the trading chart. This updates constantly with information regarding:
- The number of currently open positions.
- Total current profit and loss in pips.
- Swap values (overnight holding costs).
- Account leverage and net pip values.
//+------------------------------------------------------------------+
//| Samuray.mq4 |
//| Kokas |
//| http://www.forexforums.org |
//+------------------------------------------------------------------+
#property copyright "Kokas"
#property link "http://www.forexforums.org"
//---- input parameters
extern string ExpertName = "Samuray V.6";
extern bool AutoTrade = true;
extern int MaxTrades = 20;
extern double RecycleProfit = 1000;
extern bool UseLongs = true;
extern bool UseSwap = true;
extern double InitialStop = 1000; // Initial StopLoss
extern double BreakEven = 50; // Profit Lock in pips
extern double BEOffset = 10; // BreakEven profit capture
extern double TrailStop = 250; //
extern bool SecureOrders = true; // If set to true only open orders when in profit MinPip
extern double MinPip = 20; // Min Profit Pips to open another order (read above)
extern bool CloseAll = false; // Set true to close all current Orders
extern int Magic = 5665; // Magic Number of the EA
extern double Lots = 0.01; // Lot size when not using MM
extern bool MoneyManagement = true; // Set to true to use Money Management
extern double MaxLotSize = 100; // Max Lot size when using Money Management
extern double Risk = 10; // Risk factor when using MM
extern bool UseBollinger = true; // Turn to true to filter your orders with Bollinger Bands
extern string Param2 = "Bollinger Band Settings";
extern double Bollinger_Period = 20;
extern double Bollinger_TF = 60;
extern double Bollinger_Dev = 2;
extern bool UseEmaFilter = true; // Turn true to filter orders using EMA's
extern int ShortEma = 20;
extern int LongEma = 100;
int k, digit=0;
double AccountSize,totalPips,totalProfits,SEma,LEma,error;
double pBid, pAsk, pp,valueswap;
bool AccountIsMicro;
bool signal1 = true, signal2 =true, signal3 = true , signal4 = true, signal5 = true, SecureSignal = true;
string comment = "";
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
if (MarketInfo(Symbol(),MODE_LOTSTEP) == 0.01)
{
AccountIsMicro = true;
}
else
{
AccountIsMicro = false;
}
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
void ChartComment()
{
string sComment = "";
string sp = "****************************\n";
string NL = "\n";
sComment = sp;
sComment = sComment + "Open Positions = " + ScanOpenTrades() + NL;
sComment = sComment + "Current Profit(Pip)= " + totalPips + NL;
sComment = sComment + "SWAP Value (Pip) = " + DoubleToStr(valueswap,2) + NL;
if(UseSwap){
sComment = sComment + "SWAP Enabled" + NL;
} else {
sComment = sComment + "SWAP Disabled" + NL;
}
sComment = NL + sComment + "Net Value (Pip) = " + DoubleToStr(totalPips+valueswap,2) + NL;
sComment = NL + sComment + "Account Leverage: " + DoubleToStr(AccountLeverage(),0) + NL;
sComment = sComment + NL + sp;
Comment(sComment);
}
int ScanOpenTrades()
{
int total = OrdersTotal();
int numords = 0;
for(int cnt=0; cnt<=total-1; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
if(OrderType()<=OP_SELL)
{
if(Magic > 0) if(OrderMagicNumber() == Magic) numords++;
if(Magic == 0) numords++;
}
}
return(numords);
}
// Closing of Open Orders
void OpenOrdClose()
{
int total=OrdersTotal();
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
bool res = false;
bool condition = false;
if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
else if ( Magic==0 ) condition = true;
if (condition && ( mode==OP_BUY || mode==OP_SELL ))
{
// - BUY Orders
if(mode==OP_BUY)
{
res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),3,Yellow);
if( !res )
{
Print(" BUY: OrderClose failed with error #",GetLastError());
Print(" Ticket=",OrderTicket());
Sleep(3000);
}
break;
}
else
// - SELL Orders
if( mode == OP_SELL)
{
res = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),3,White);
if( !res )
{
Print(" SELL: OrderClose failed with error #",GetLastError());
Print(" Ticket=",OrderTicket());
Sleep(3000);
}
break;
}
}
}
}
void TotalProfit()
{
int total=OrdersTotal();
totalPips = 0;
totalProfits = 0;
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
bool condition = false;
if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
else if ( Magic==0 ) condition = true;
if (condition)
{
switch (mode)
{
case OP_BUY:
totalPips += MathRound((MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice())/MarketInfo(OrderSymbol(),MODE_POINT));
//totalPips += MathRound((Bid-OrderOpenPrice())/Point);
totalProfits += OrderProfit();
break;
case OP_SELL:
totalPips += MathRound((OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK))/MarketInfo(OrderSymbol(),MODE_POINT));
//totalPips += MathRound((OrderOpenPrice()-Ask)/Point);
totalProfits += OrderProfit();
break;
}
}
if (UseSwap) {
SwapProfit();
totalProfits = totalProfits + valueswap;
}
}
}
// MoneyManagement with Account Leverage Protection
double LotSize()
{
double lotMM = MathCeil(AccountFreeMargin() * Risk / 1000) / AccountLeverage() / 5;
if(AccountIsMicro==false) //normal account
{
if(lotMM < 0.1) lotMM = 0.1;
if((lotMM >= 0.1) && (lotMM < 0.2)) lotMM = 0.2;
if((lotMM >= 0.2) && (lotMM < 0.3)) lotMM = 0.3;
if((lotMM >= 0.3) && (lotMM < 0.4)) lotMM = 0.4;
if((lotMM >= 0.4) && (lotMM < 1)) lotMM = 0.5;
if(lotMM >= 1.0) lotMM = MathCeil(lotMM);
if(lotMM >= MaxLotSize) lotMM = MaxLotSize;
}
else //micro account
{
if(lotMM < 0.01) lotMM = 0.01;
if((lotMM >= 0.01) && (lotMM < 0.02)) lotMM = 0.02;
if((lotMM >= 0.02) && (lotMM < 0.03)) lotMM = 0.03;
if((lotMM >= 0.03) && (lotMM < 0.04)) lotMM = 0.04;
if((lotMM >= 0.05) && (lotMM < 0.06)) lotMM = 0.05;
if((lotMM >= 0.06) && (lotMM < 0.07)) lotMM = 0.06;
if((lotMM >= 0.07) && (lotMM < 0.08)) lotMM = 0.08;
if((lotMM >= 0.08) && (lotMM < 0.09)) lotMM = 0.09;
if((lotMM >= 0.09) && (lotMM < 0.10)) lotMM = 0.1;
if((lotMM >= 0.1) && (lotMM < 0.2)) lotMM = 0.2;
if((lotMM >= 0.2) && (lotMM < 0.3)) lotMM = 0.3;
if((lotMM >= 0.3) && (lotMM < 0.4)) lotMM = 0.4;
if((lotMM >= 0.4) && (lotMM < 1)) lotMM = 0.5;
if(lotMM >= 1.0) lotMM = MathCeil(lotMM);
if(lotMM >= MaxLotSize) lotMM = MaxLotSize;
}
if(AccountIsMicro) {
AccountSize=2;
} else {
AccountSize=1;
}
lotMM = NormalizeDouble(lotMM,AccountSize);
return (lotMM);
}
void SwapProfit()
{
int total=OrdersTotal();
valueswap = 0;
for (int cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS);
int mode=OrderType();
bool condition = false;
if ( Magic>0 && OrderMagicNumber()==Magic ) condition = true;
else if ( Magic==0 ) condition = true;
if (condition && OrderSwap()!=0)
{
valueswap = valueswap + OrderSwap()/PipCost(OrderSymbol()); // ERROOOOOOOOOOOOOOOOOOOOOOOOOOO
}
}
}
//+--------- --------- --------- --------- --------- --------- ----+
//+ Calculate cost in USD of 1pip of given symbol
//+--------- --------- --------- --------- --------- --------- ----+
double PipCost (string TradeSymbol) {
double Base, Cost;
string TS_13, TS_46, TS_4L;
TS_13 = StringSubstr (TradeSymbol, 0, 3);
TS_46 = StringSubstr (TradeSymbol, 3, 3);
TS_4L = StringSubstr (TradeSymbol, 3, StringLen(TradeSymbol)-3);
Base = MarketInfo (TradeSymbol, MODE_LOTSIZE) * MarketInfo (TradeSymbol,MODE_POINT);
if ( TS_46 == "USD" )
Cost = Base;
else if ( TS_13 == "USD" )
Cost = Base / MarketInfo (TradeSymbol, MODE_BID);
else if ( PairExists ("USD"+TS_4L) )
Cost = Base / MarketInfo ("USD"+TS_4L, MODE_BID);
else
Cost = Base * MarketInfo (TS_46+"USD" , MODE_BID);
return(Cost) ;
}
//+--------- --------- --------- --------- --------- --------- ----+
//+ Returns true if given symbol exists
//+--------- --------- --------- --------- --------- --------- ----+
bool PairExists (string TradeSymbol) {
return ( MarketInfo (TradeSymbol, MODE_LOTSIZE) > 0 );
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
digit = MarketInfo(Symbol(),MODE_DIGITS);
SEma = iMA(Symbol(),0,ShortEma,0,MODE_EMA,PRICE_CLOSE,0);
LEma = iMA(Symbol(),0,LongEma,0,MODE_EMA,PRICE_CLOSE,0);
double BandsLower = iBands(Symbol(),Bollinger_TF,Bollinger_Period,Bollinger_Dev,0,0,2,0); // Lower Bollinger
double BandsUpper = iBands(Symbol(),Bollinger_TF,Bollinger_Period,Bollinger_Dev,0,0,1,0); // Upper Bollinger
double Bands = (BandsLower + BandsUpper) / 2; // Middle Bollinger
signal1 = false;
signal2 = false;
signal3 = true;
signal4 = true;
if (CloseAll) {
OpenOrdClose();
signal4 = false;
}
TotalProfit();
if (totalPips > RecycleProfit) {
OpenOrdClose();
signal4 = false;
}
if (ScanOpenTrades() < MaxTrades) signal1 = true;
if (ScanOpenTrades() == 0){
signal2 = true;
} else {
if (totalPips > MinPip) {
signal2 = true;
} else {
signal2 = false;
}
}
signal3 = true;
if (UseBollinger){
if (MarketInfo(Symbol(),MODE_ASK) < Bands) {
signal3 = true;
}else{
signal3 = false;
}
}
if (MoneyManagement) Lots = LotSize();
if (SecureOrders){
if (totalPips > MinPip || ScanOpenTrades() == 0){
SecureSignal = true;
} else {
SecureSignal = false;
}
} else {
SecureSignal = true;
}
if ((SEma > LEma) && (SEma != LEma)){
signal5 = true;
} else {
signal5 = false;
}
comment = "Samuray:" + DoubleToStr(ScanOpenTrades() + 1,0) + " / " + MaxTrades;
//+------------------------------------------------------------------+
if (!signal1) Print("Max trades Reached");
if (!signal2) Print("Not enougth Margin");
if (!signal3) Print("Bollinger does not allow");
if (!signal4) Print("Recycling Orders");
if (!signal5) Print("Ask EMA to enter trades!");
if (!AutoTrade) Print("Autotrade disabled on properties");
if (!SecureSignal) Print("Not safe to enter yet");
if (signal1 && signal2 && signal3 && signal4 && AutoTrade && SecureSignal){
// signal1 - Control the number of open orders
// signal2 - Check Margin (INACTIVE)
// signal3 - Bollinger Bands Filter
// signal4 - Control Recycle Profits
// signal5 - Check EMA's before place trades
if (UseLongs && signal5) {
error = 1;
while (error != 0) {
if (InitialStop > 0){
OrderSend(Symbol(),OP_BUY,Lots,MarketInfo(Symbol(),MODE_ASK),3,Ask-InitialStop*Point,0,comment,Magic,0,Blue);
error = GetLastError();
} else {
OrderSend(Symbol(),OP_BUY,Lots,MarketInfo(Symbol(),MODE_ASK),3,0,0,comment,Magic,0,Blue);
}
if (error !=0 ) Print(error); }
}
if (!UseLongs && !signal5){
error = 1;
while (error != 0) {
if (InitialStop > 0){
OrderSend(Symbol(),OP_SELL,Lots,MarketInfo(Symbol(),MODE_BID),3,Bid+InitialStop*Point,0,comment,Magic,0,Red);
} else {
OrderSend(Symbol(),OP_SELL,Lots,MarketInfo(Symbol(),MODE_BID),3,0,0,comment,Magic,0,Red);
}
error = GetLastError();
if (error !=0 ) Print(error); }
}
}
ChartComment();
if (TrailStop > 0)
{
TrailIt(TrailStop);
}
if (BreakEven > 0)
{
DoBE(BreakEven);
}
return(0);
}
//+------------------------------------------------------------------+
void TrailIt(int byPips)
{
if (byPips >= 5)
{
for (int i = 0; i < OrdersTotal(); i++)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol() == Symbol() && (OrderMagicNumber() == Magic))
{
if (OrderType() == OP_BUY)
{
if (MarketInfo(OrderSymbol(),MODE_BID) - OrderOpenPrice() > (byPips * MarketInfo(OrderSymbol(), MODE_POINT)))
{
if (OrderStopLoss() < MarketInfo(OrderSymbol(),MODE_BID) - (byPips * MarketInfo(OrderSymbol(), MODE_POINT)))
{
OrderModify(OrderTicket(), OrderOpenPrice(), MarketInfo(OrderSymbol(),MODE_BID) - byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
}
}
}
else
{
if (OrderType() == OP_SELL)
{
if (OrderOpenPrice() - MarketInfo(OrderSymbol(),MODE_ASK) > byPips * MarketInfo(OrderSymbol(), MODE_POINT))
{
if ((OrderStopLoss() > MarketInfo(OrderSymbol(),MODE_ASK) + byPips * MarketInfo(OrderSymbol(), MODE_POINT)) || (OrderStopLoss() == 0))
{
OrderModify(OrderTicket(), OrderOpenPrice(),MarketInfo(OrderSymbol(),MODE_ASK) + byPips * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
}
}
}
}
}
}
}
} // proc TrailIt()
void DoBE(int byPips)
{
for(int i = 0;i < OrdersTotal(); i++)
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic))
{
if (OrderType() == OP_BUY)
{
if (MarketInfo(OrderSymbol(),MODE_BID) - OrderOpenPrice() >= (byPips * MarketInfo(OrderSymbol(), MODE_POINT)))
{
if (OrderStopLoss() != (OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT) * BEOffset) && (OrderStopLoss() == 0))
{
OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() + MarketInfo(OrderSymbol(), MODE_POINT) * BEOffset, OrderTakeProfit(), Red);
}
}
}
if (OrderType() == OP_SELL)
{
if (OrderOpenPrice() - MarketInfo(OrderSymbol(),MODE_ASK) >= byPips * MarketInfo(OrderSymbol(), MODE_POINT))
{
if (OrderStopLoss() != (OrderOpenPrice() - MarketInfo(OrderSymbol(), MODE_POINT) * BEOffset) && (OrderStopLoss() == 0))
{
OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() - MarketInfo(OrderSymbol(), MODE_POINT) * BEOffset, OrderTakeProfit(), Red);
}
}
}
}
}
}
Profitability Reports
Expected payoff
Average expected payoff across the available backtests for each symbol.
Comments