Profit factor:
1.26

Here's a breakdown of how this trading script works, explained in a way that's easy to understand without needing technical programming knowledge.

Overall Goal

This script is designed to automatically open, manage, and close trading positions (buying or selling) based on a specific set of rules and indicators. It's like having a robot trader that follows a pre-defined strategy.

Initial Setup (the "extern" variables)

Before the script starts making decisions, it needs some basic information. These "extern" variables act like settings that you, the user, can adjust:

  • Lots: This determines the size of each trade. Think of it as the amount of currency you're willing to risk on a single trade.
  • TakeProfit: This is the profit level at which the script will automatically close a winning trade. It's a target for how much profit you want to make.
  • TrailingStop: This is a clever tool that automatically adjusts the stop-loss order (see below) as the price moves in your favor. It helps to lock in profits.
  • StopLoss: This is the maximum amount you're willing to lose on a trade. If the price moves against you and hits this level, the script will automatically close the trade to prevent further losses.
  • Slippage: This allows a little bit of flexibility in the price at which a trade is executed. Sometimes the market moves so fast that the price changes slightly between when you place the order and when it's filled.
  • MaximumRisk: If "UseMM" is set to true, this defines the maximum percentage of your account balance that the script will risk on any single trade. This helps manage overall risk.
  • StartTrading/EndTrading: These set the hours of the day during which the script is allowed to trade.
  • UseMM: If set to "true", the script will use money management, dynamically adjusting the "Lots" size based on your account balance and the "MaximumRisk" setting.
  • MagicNumber: A unique identifier for the script's trades, preventing it from interfering with trades opened manually or by other scripts.
  • ExpertComment: This is simply a comment that will be attached to each trade opened by the script, for identification purposes.

The Trading Logic

  1. Time Check: The script first checks if the current time is within the specified trading hours (StartTrading and EndTrading). If not, it closes any open positions and does nothing.

  2. Indicator Calculations: The script uses a combination of technical indicators to analyze the market. These indicators provide clues about potential price movements. Specifically, it uses:

    • Moving Averages (MA): These smooth out price data to identify trends.
    • Stochastic Oscillator: This measures the momentum of price, helping to identify overbought and oversold conditions.
    • MACD (Moving Average Convergence Divergence): This indicator helps identify changes in the strength, direction, momentum, and duration of a trend in a stock's price.
    • Parabolic SAR (SAR): This places dots on the chart and if the dots are below price, it indicates an uptrend and if the dots are above price, it indicates a downtrend.
  3. Buy/Sell Conditions: Based on the values of these indicators, the script determines whether to buy, sell, or close existing positions.

    • It looks for specific patterns or "signals" in the indicator values to decide if the price is likely to go up (buy) or down (sell).
    • It also checks for conditions that suggest an existing trade should be closed, either to take profits or limit losses.
  4. Order Management:

    • Opening Orders: If the script detects a buy or sell signal and there are no open orders for the current symbol, it sends an order to the broker to open a new trade. It retries a few times if the order fails initially (due to market conditions).
    • Closing Orders: If the script detects a condition to close an existing trade, it sends an order to the broker to close the trade.
    • Trailing Stop: This is a dynamic stop-loss order. As the price moves in a favorable direction (profit), the stop-loss level is automatically adjusted to lock in profits.
  5. Money Management (Optional): If the UseMM setting is enabled, the script calculates the appropriate trade size (Lots) based on the account balance and the MaximumRisk setting. This helps to control the amount of capital at risk on each trade.

In Plain Language

Imagine this script as a weather forecaster and a farmer working together. The indicators are like the weather forecast ? they give the script an idea of which way the "price winds" are blowing. Based on this forecast, the script (the farmer) decides whether to plant a seed (open a trade ? buy or sell) or harvest a crop (close a trade). The stop-loss is like an insurance policy ? it protects the farmer (you) in case of a sudden storm (unexpected price movement). The trailing stop is like a way to move the harvest (take profit) closer as the crop grows (price moves in your favor), ensuring a good yield.

Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategy
Indicators Used
Moving average indicatorStochastic oscillatorMACD HistogramParabolic Stop and Reverse system
11 Views
0 Downloads
0 Favorites
SMARTASS2
//---- Trades limits
extern   double    Lots = 1;
extern   double    TakeProfit = 1500;
extern   double    TrailingStop = 2000; 
extern   double    StopLoss = 200;
extern   int       Slippage = 5;
extern   double    MaximumRisk        = 0.3;
extern   int       StartTrading = 0;
extern   int       EndTrading   = 24;
extern   bool      UseMM=false;


//--- Global variables
extern int      MagicNumber = 655321;
string   ExpertComment = "SMARTASS";
int      NumberOfTries = 5;

//+------------------------------------------------------------------
int init()
{
   return(0);
}

int deinit() 
{
   return(0);
}
//+------------------------------------------------------------------

bool isNewSymbol(string current_symbol)
  {
   //loop through all the opened order and compare the symbols
   int total  = OrdersTotal();
   for(int cnt = 0 ; cnt < total ; cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      string selected_symbol = OrderSymbol();
      if (current_symbol == selected_symbol && OrderMagicNumber()==MagicNumber)
      return (False);
    }
    return (True);
}

//+------------------------------------------------------------------+
int start()
  {
   
    if (Hour()< StartTrading || Hour()>(EndTrading-1))
   {
     CloseOrder(OP_BUY);
     CloseOrder(OP_SELL);

      return(0);
   }
   
   int cnt, ticket, total,n,trend;
   bool up1,up2,down1,down2,up3,down3;
   bool BuyCondition = false , SellCondition = false , CloseBuyCondition = false , CloseSellCondition = false ;
   double signal,signal1,signal2;
   if(Bars<50) {Print("bars less than 50"); return(0);}

   //Symbo settings:
   RefreshRates();
   Slippage = MarketInfo(Symbol(),MODE_SPREAD);
      
      
      
      double ma1=iMA(NULL,0,5,0,MODE_EMA,PRICE_TYPICAL,1);
      double ma2=iMA(NULL,0,12,0,MODE_EMA,PRICE_TYPICAL,1);
      
      double ma1last=iMA(NULL,0,5,0,MODE_EMA,PRICE_TYPICAL,2);
      double ma2last=iMA(NULL,0,12,0,MODE_EMA,PRICE_TYPICAL,2);
      
      double stoch_main = iStochastic(NULL,0,20,6,16,MODE_EMA,0,MODE_MAIN,1);
      double stoch_sig = iStochastic(NULL,0,20,6,16,MODE_EMA,0,MODE_SIGNAL,1);
      double stoch_main1 = iStochastic(NULL,0,20,6,16,MODE_EMA,0,MODE_MAIN,2);
      double stoch_sig1 = iStochastic(NULL,0,20,6,16,MODE_EMA,0,MODE_SIGNAL,2);

      
      double macd_main=iMACD(NULL,0,13,21,8,PRICE_CLOSE,MODE_MAIN,1); 
      double macd_sig=iMACD(NULL,0,13,21,8,PRICE_CLOSE,MODE_SIGNAL,1); 
      double macd_main1=iMACD(NULL,0,13,21,8,PRICE_CLOSE,MODE_MAIN,2); 
      double macd_sig1=iMACD(NULL,0,13,21,8,PRICE_CLOSE,MODE_SIGNAL,2); 
      
      double sar1=iSAR(NULL,0,0.0026,0.5,1);
      double sar2=iSAR(NULL,0,0.0026,0.5,2);

     if ((stoch_main>stoch_sig && macd_main>macd_sig)) up1=true; else up1=false;
     if ((stoch_main<stoch_sig && macd_main<macd_sig)) down1=true; else down1=false;
  
     if ((stoch_main1>stoch_sig1 && macd_main1>macd_sig1)) up2=true; else up2=false;
     if ((stoch_main1<stoch_sig1 && macd_main1<macd_sig1)) down2=true; else down2=false;
      

     static int arrow;
      if ((up1==true && up2!=true))
       {signal=1;}
     
   
      else if ((down1==true && down2!=true))
      {signal=-1;}
      
      if ((up2==true && up1!=true)) CloseBuyCondition=true;
      if (down2==true && down1!=true) CloseSellCondition=true;
      
   
   //Print(signal);
   //--- Trading conditions
/*   bool BuyCondition = false , SellCondition = false , CloseBuyCondition = false , CloseSellCondition = false ; */
   
   if (signal==1)
       BuyCondition = true;
       
   if (signal==-1)
      SellCondition = true;
   
   if (BuyCondition)
      CloseSellCondition = true;
   
   if (SellCondition)
      CloseBuyCondition = true;
      
      
   
   total  = OrdersTotal();
   
   if (UseMM)
   Lots=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
   
      
   if(total < 1 || isNewSymbol(Symbol())) 
     {
       if(BuyCondition) //<-- BUY condition
         {
           ticket = OpenOrder(OP_BUY); //<-- Open BUY order
            return(0);
         }
         if(SellCondition) //<-- SELL condition
         {
            ticket = OpenOrder(OP_SELL); //<-- Open SELL order
            return(0);
         }
         return(0);
     }
     
      for(cnt=0;cnt<total;cnt++) 
      {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

         if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
         {
            if(OrderType()==OP_BUY)   //<-- Long position is opened
            {
                  if(CloseBuyCondition) //<-- Close the order and exit! 
                  {
                     CloseOrder(OrderType()); 
                  } 
               
               TrailOrder(OrderType()); //<-- Trailling the order
            }
            if(OrderType()==OP_SELL) //<-- Go to short position
            {
                 if(CloseSellCondition) //<-- Close the order and exit! 
                  {
                     CloseOrder(OP_SELL);
                  } 
               TrailOrder(OrderType()); //<-- Trailling the order
            }
         }
      }

   return(0);
  }
//+------------------------------------------------------------------+

int OpenOrder(int type)
{
   int ticket=0;
   int err=0;
   int c = 0;
   
   if(type==OP_BUY)
   {
      for(c = 0 ; c < NumberOfTries ; c++)
      {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,Ask-StopLoss*Point,Ask+TakeProfit*Point,ExpertComment,MagicNumber,0,Green);
         err=GetLastError();
         if(err==0)
         { 
            break;
         }
         else
         {
            if(err==4 || err==137 ||err==146 || err==136) //Busy errors
            {
               Sleep(5000);
               continue;
            }
            else //normal error
            {
               break;
            }  
         }
      }   
   }
   if(type==OP_SELL)
   {   
      for(c = 0 ; c < NumberOfTries ; c++)
      {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,Bid+StopLoss*Point,Bid-TakeProfit*Point,ExpertComment,MagicNumber,0,Red);
         err=GetLastError();
         if(err==0)
         { 
            break;
         }
         else
         {
            if(err==4 || err==137 ||err==146 || err==136) //Busy errors
            {
               Sleep(5000);
               continue;
            }
            else //normal error
            {
               break;
            }  
         }
      }   
   }  
   return(ticket);
}

bool CloseOrder(int type)
{
   if(OrderMagicNumber() == MagicNumber)
   {
      if(type==OP_BUY)
         return (OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Violet));
      if(type==OP_SELL)   
         return (OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Violet));
   }
}
void TrailOrder(int type)
{
   if(TrailingStop>0)
   {
      if(OrderMagicNumber() == MagicNumber)
      {
         if(type==OP_BUY)
         {
            if(Bid-OrderOpenPrice()>Point*TrailingStop)
            {
               if(OrderStopLoss()<Bid-Point*TrailingStop)
               {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
               }
            }
         }
         if(type==OP_SELL)
         {
            if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
            {
               if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
               {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
               }
            }
         }
      }
   }
}


Profitability Reports

USD/CHF Jul 2025 - Sep 2025
0.72
Total Trades 112
Won Trades 34
Lost trades 78
Win Rate 30.36 %
Expected payoff -30.14
Gross Profit 8636.65
Gross Loss -12012.43
Total Net Profit -3375.78
-100%
-50%
0%
50%
100%
USD/CAD Jul 2025 - Sep 2025
0.45
Total Trades 123
Won Trades 29
Lost trades 94
Win Rate 23.58 %
Expected payoff -39.91
Gross Profit 4009.56
Gross Loss -8917.94
Total Net Profit -4908.38
-100%
-50%
0%
50%
100%
NZD/USD Jul 2025 - Sep 2025
0.29
Total Trades 110
Won Trades 18
Lost trades 92
Win Rate 16.36 %
Expected payoff -89.89
Gross Profit 4111.00
Gross Loss -13999.00
Total Net Profit -9888.00
-100%
-50%
0%
50%
100%
GBP/USD Jul 2025 - Sep 2025
0.89
Total Trades 123
Won Trades 34
Lost trades 89
Win Rate 27.64 %
Expected payoff -12.08
Gross Profit 11622.00
Gross Loss -13108.00
Total Net Profit -1486.00
-100%
-50%
0%
50%
100%
GBP/CAD Jul 2025 - Sep 2025
0.56
Total Trades 133
Won Trades 29
Lost trades 104
Win Rate 21.80 %
Expected payoff -42.85
Gross Profit 7120.09
Gross Loss -12819.40
Total Net Profit -5699.31
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.48
Total Trades 167
Won Trades 36
Lost trades 131
Win Rate 21.56 %
Expected payoff -46.87
Gross Profit 7327.26
Gross Loss -15153.72
Total Net Profit -7826.46
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
6.74
Total Trades 835
Won Trades 402
Lost trades 433
Win Rate 48.14 %
Expected payoff 564.81
Gross Profit 553842.00
Gross Loss -82228.00
Total Net Profit 471614.00
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.70
Total Trades 110
Won Trades 31
Lost trades 79
Win Rate 28.18 %
Expected payoff -22.64
Gross Profit 5783.00
Gross Loss -8273.00
Total Net Profit -2490.00
-100%
-50%
0%
50%
100%
USD/JPY Jan 2025 - Jul 2025
1.08
Total Trades 311
Won Trades 71
Lost trades 240
Win Rate 22.83 %
Expected payoff 7.59
Gross Profit 31655.36
Gross Loss -29296.03
Total Net Profit 2359.33
-100%
-50%
0%
50%
100%
USD/CHF Jan 2025 - Jul 2025
1.00
Total Trades 256
Won Trades 78
Lost trades 178
Win Rate 30.47 %
Expected payoff -0.18
Gross Profit 28937.69
Gross Loss -28982.93
Total Net Profit -45.24
-100%
-50%
0%
50%
100%

Comments