SMARTASS-Original

Profit factor:
0.50

This script is designed to automatically trade on the Metatrader platform. It aims to identify potential buying and selling opportunities based on a series of technical indicators, and then execute trades according to pre-defined risk parameters. Here's a breakdown of the script's logic:

  1. Settings: The script starts with a set of customizable settings that allow the user to control how it operates. These include:

    • Trade Size: The amount of currency to trade in each transaction.
    • Profit Target: The desired profit in points for each trade.
    • Trailing Stop: A mechanism to automatically adjust the stop-loss order as the trade moves in a profitable direction, helping to lock in gains.
    • Stop Loss: The maximum acceptable loss in points for each trade.
    • Slippage: The acceptable difference between the requested trade price and the actual execution price.
    • Maximum Risk: The percentage of the trading account that the user is willing to risk on a single trade.
    • Trading Hours: The specific hours of the day during which the script is allowed to open new trades.
    • Money Management: A setting to enable or disable automatic trade size adjustment based on the account balance and risk tolerance.
  2. Initialization: Upon startup, the script prepares the trading environment.

  3. Time Restriction: The script checks the current time. If the current hour is outside the defined StartTrading and EndTrading hours, the script will close any open buy or sell orders and then stop execution. This prevents trading outside of preferred market hours.

  4. Identifying Trading Opportunities: The core of the script involves analyzing market data to identify potential buy or sell signals. It uses several technical indicators for this purpose:

    • Moving Averages: Calculate the average price over recent periods to identify trends.
    • Stochastic Oscillator: Gauges overbought and oversold conditions.
    • MACD (Moving Average Convergence Divergence): Identifies potential trend changes.
    • SAR (Parabolic Stop and Reverse): Helps identify potential price reversals. The script evaluates the relationship between these indicators at the current and previous time periods. Based on whether these indicators align in a way that suggests an upward or downward trend, the script generates buy or sell signals.
  5. Order Management: The script keeps track of open orders. It will not open new orders if an order in the same currency pair exists, identified by its magic number.

  6. Trade Execution: If a buy or sell signal is generated and no order for the same currency pair are open, the script will:

    • Calculate Trade Size: If money management is enabled, the script calculates the appropriate trade size based on the account balance and the maximum risk percentage. Otherwise, it uses the pre-defined trade size.
    • Open Order: Sends a trade order to the Metatrader platform with the specified parameters (trade type, size, stop loss, take profit, etc.). The script retries opening the order multiple times in case of errors (like busy server). If an order is already open and conditions are met, it will close orders.
  7. Order Closing:

    • If a 'close buy' condition is true and the script has a buy order, the script will close all buy orders.
    • If a 'close sell' condition is true and the script has a sell order, the script will close all sell orders.
  8. Trailing Stop Functionality: The script includes a trailing stop feature. If enabled, it automatically adjusts the stop-loss order of open trades as the price moves favorably. This helps to protect profits and limit potential losses.

In summary, this script is an automated trading system that uses technical indicators to generate trading signals and automatically execute trades based on pre-defined risk parameters and a trailing stop mechanism.

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
3 Views
0 Downloads
0 Favorites
SMARTASS-Original
//---- 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,8,0,MODE_LWMA,PRICE_TYPICAL,1);
      double ma2=iMA(NULL,0,21,0,MODE_LWMA,PRICE_TYPICAL,1);
      
      double ma1last=iMA(NULL,0,8,0,MODE_LWMA,PRICE_TYPICAL,2);
      double ma2last=iMA(NULL,0,21,0,MODE_LWMA,PRICE_TYPICAL,2);
      
      double stoch_main = iStochastic(NULL,0,12,12,5,MODE_EMA,0,MODE_MAIN,1);
      double stoch_sig = iStochastic(NULL,0,12,12,5,MODE_EMA,0,MODE_SIGNAL,1);
      double stoch_main1 = iStochastic(NULL,0,12,12,5,MODE_EMA,0,MODE_MAIN,2);
      double stoch_sig1 = iStochastic(NULL,0,12,12,5,MODE_EMA,0,MODE_SIGNAL,2);

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


       
     
        
     if ((ma1>ma2 && stoch_main>stoch_sig && macd_main>macd_sig) && (sar1<Low[1])) up1=true; else up1=false;
     if ((ma1<ma2 && stoch_main<stoch_sig && macd_main<macd_sig) && (sar1>High[1])) down1=true; else down1=false;
  
     if ((ma1last>ma2last && stoch_main1>stoch_sig1 && macd_main1>macd_sig1) && (sar2<Low[2])) up2=true; else up2=false;
     if ((ma1last<ma2last && stoch_main1<stoch_sig1 && macd_main1<macd_sig1) && (sar2>High[2])) 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

NZD/USD Oct 2024 - Jan 2025
0.52
Total Trades 90
Won Trades 30
Lost trades 60
Win Rate 33.33 %
Expected payoff -42.81
Gross Profit 4095.00
Gross Loss -7948.00
Total Net Profit -3853.00
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
0.51
Total Trades 93
Won Trades 19
Lost trades 74
Win Rate 20.43 %
Expected payoff -58.60
Gross Profit 5785.00
Gross Loss -11235.00
Total Net Profit -5450.00
-100%
-50%
0%
50%
100%
AUD/USD Oct 2024 - Jan 2025
0.47
Total Trades 91
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -46.87
Gross Profit 3712.00
Gross Loss -7977.00
Total Net Profit -4265.00
-100%
-50%
0%
50%
100%

Comments