Profit factor:
0.62

This trading script is an automated system designed to manage trades by analyzing market momentum, trend direction, and historical performance. It utilizes a combination of technical indicators to decide when to enter the market, how much risk to take, and how to manage active positions in real-time.

Core Trading Logic

1. Trend and Momentum Analysis The system determines the primary "direction" of the market using the MACD (Moving Average Convergence Divergence) indicator on a weekly timeframe. By comparing recent data points, it identifies whether the overall trend is bullish (upward) or bearish (downward).

To refine these entries, it also uses the Williams Percent Range (WPR) indicator. This helps the script identify specific momentum shifts—looking for moments where the price movement suggests a high probability of continuation in the current trend.

2. Intelligent Entry Mechanism Unlike simple systems that enter a trade immediately at market price, this script uses "Pending Orders" (Buy Stop and Sell Stop).

  • Execution: It places orders at specific price levels based on previous candle highs and lows.
  • Dynamic Adjustment: If the current price is too close to the intended entry point, the script automatically adjusts the order price to ensure a sufficient buffer is maintained for safety.

3. Risk Management and Position Sizing One of the more sophisticated features of this script is its "Optimization" logic:

  • Dynamic Lot Sizing: It calculates trade sizes based on your available account margin and a predefined risk percentage.
  • Loss Mitigation: The script reviews your trading history. If it detects a sequence of consecutive losses, it automatically reduces the lot size for future trades. This is designed to protect your capital during "losing streaks" by decreasing exposure until the system finds a winning rhythm again.

4. Active Trade Management Once a trade is live, the script actively monitors it using several protective layers:

  • Trailing Stop: To lock in profits while allowing for continued growth, the script moves the "Stop Loss" automatically as the price moves in your favor. If the price begins to reverse, the stop loss remains at the highest (for buys) or lowest (for sells) point reached during the move.
  • Auto-Deletion: The script monitors its pending orders. If the market trend shifts against a pending order before it is triggered, the script will automatically delete that order to prevent unnecessary entries in a bad market environment.
  • Take Profit: Every trade is assigned a specific target profit level to ensure that gains are realized systematically.

Summary of Workflow

The script follows a structured hierarchy: it first checks if the market is suitable for trading; then, it identifies the overall trend; next, it evaluates whether to open a new position based on momentum; and finally, it manages all existing trades by moving stops to protect profits and adjusting risk levels based on past performance.

Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategy
Indicators Used
Larry William percent range indicatorMACD Histogram
18 Views
0 Downloads
0 Favorites
TSD_v12
/*-----------------------------+
|			       |
| Shared by www.Aptrafx.com    |
|			       |
+------------------------------*/

// Conversion by MojoFX on Moving Average expert structure

#define MAGICMA  20050610

extern double  Lots               = 0.1;
extern double  MaximumRisk        = 0.02;
extern double  DecreaseFactor     = 3;

extern int     TakeProfit         = 100;
extern int     TrailingStop       = 50;

//---- change here to revert to original version
extern int     WilliamsP          = 24;
extern double  WilliamsL          = -75;
extern double  WilliamsH          = -25;

bool     condBuy,condSell;
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//---- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//---- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         //----
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//---- return lot size
   if(lot<0.1) lot=0.1;
   if(DecreaseFactor<0) lot = Lots;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
   {
   if(Volume[0]>1) return;
   
   int res;
   double WPRs,WPRb;
   double PriceOpen,NewPrice,Buy_Tp,Sell_Tp;
   
   int wDir = getDirection();   

//---- change here to revert to original
	WPRs    = iWPR(NULL,0,WilliamsP,1) > WilliamsL; //-75
	WPRb    = iWPR(NULL,0,WilliamsP,1) < WilliamsH; //-25
   
   condBuy  = (wDir == 1 && WPRb &&
              iWPR(NULL,0,WilliamsP,0) < iWPR(NULL,0,WilliamsP,1) );
   
   condSell = (wDir == -1 && WPRs &&
              iWPR(NULL,0,WilliamsP,0) > iWPR(NULL,0,WilliamsP,1) );   
   
//---- sell conditions
   if (condSell) {
      PriceOpen = Low[1]-1*Point;
      if (PriceOpen > (Bid-16*Point))
         {
         if (TakeProfit > 0)
            { Sell_Tp = PriceOpen-TakeProfit*Point; } else { Sell_Tp = 0; }
            
         res = OrderSend(Symbol(),OP_SELLSTOP,LotsOptimized(),PriceOpen,3,
                        High[1]+1*Point,Sell_Tp,"TSD1",MAGICMA,0,Red);
         
         return;
         
         } else {
         
         NewPrice = Bid-16*Point;
         if (TakeProfit > 0)
            { Sell_Tp = NewPrice-TakeProfit*Point; } else { Sell_Tp = 0; }
            
         res = OrderSend(Symbol(),OP_SELLSTOP,LotsOptimized(),NewPrice,3,
                        High[1]+1*Point,Sell_Tp,"TSD1",MAGICMA,0,Red);
                        
         return;
         } // end if priceopen    
      } // end if condSell

//---- buy conditions
   if (condBuy) {
   
      PriceOpen = High[1]+1*Point;
      if (PriceOpen > (Ask+16*Point))
         {
         if (TakeProfit > 0)
            { Buy_Tp = PriceOpen+TakeProfit*Point; } else { Buy_Tp = 0; }
                     
         res=OrderSend(Symbol(),OP_BUYSTOP,LotsOptimized(),PriceOpen,3,
                        Low[1]-1*Point,Buy_Tp,"TSD1",MAGICMA,0,GreenYellow);
         
         return;         
         } else {         
         NewPrice = Ask + 16 * Point;
         
         if (TakeProfit > 0)
            { Buy_Tp = NewPrice+TakeProfit*Point; } else { Buy_Tp = 0; }
            
         res=OrderSend(Symbol(),OP_BUYSTOP,LotsOptimized(),NewPrice,3,
                        Low[1]-1*Point,Buy_Tp,"TSD1",MAGICMA,0,GreenYellow);
                        
         return;
         }
      } // end CondBuy         
   } // end CheckForOpen()
      
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
   {      
   // trade on fresh bar
   if(Volume[0]>1) return;
  
   double PriceOpen,NewPrice,Buy_Tp,Sell_Tp;
   
   int wDir = getDirection();

   for(int i=0;i<OrdersTotal();i++)
      {
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)        break;
      if (OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
        
      //---- trailing stop  
      if (OrderType() == OP_BUY) {
         if (Bid - OrderOpenPrice() > TrailingStop*MarketInfo(OrderSymbol(),MODE_POINT)) {
            if ((OrderStopLoss() < Bid-TrailingStop*MarketInfo(OrderSymbol(),MODE_POINT)) || (OrderStopLoss() == 0)) {
               OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*MarketInfo(OrderSymbol(),MODE_POINT),OrderTakeProfit(),SteelBlue);
               }
            }
         } else 
      if (OrderType() == OP_SELL) {
         if (OrderOpenPrice() - Ask > TrailingStop * MarketInfo(OrderSymbol(),MODE_POINT)) {
            if ((OrderStopLoss() > Ask+TrailingStop*MarketInfo(OrderSymbol(),MODE_POINT)) || (OrderStopLoss() == 0)) {
               OrderModify(OrderTicket(),OrderOpenPrice(),Ask+TrailingStop*MarketInfo(OrderSymbol(),MODE_POINT),OrderTakeProfit(),Magenta);
               }
            }
         }          

      if (OrderType() == OP_BUYSTOP && wDir == 1)
         {
         if (High[1]<High[2])
            {
            if (High[1]>Ask+16*Point) 
               OrderModify(OrderTicket(),High[1]+1*Point,Low[1]-1*Point,OrderTakeProfit(),0,SteelBlue);
               else 
               OrderModify(OrderTicket(),Ask+16*Point,Low[1]-1*Point,OrderTakeProfit(),0,SteelBlue);               
            }         
         }
      
      if (OrderType() == OP_SELLSTOP && wDir == -1)
         {
         if (Low[1]>Low[2])
            {
            if (Low[1]<Bid-16*Point)
               OrderModify(OrderTicket(),Low[1]-1*Point,High[1]+1*Point,OrderTakeProfit(),0,Magenta);
               else
               OrderModify(OrderTicket(),Bid-16*Point,High[1]+1*Point,OrderTakeProfit(),0,Magenta);
            }            
         }   
      
      //---- pending orders deletion
      if ( OrderType() == OP_BUYSTOP && wDir == -1 ) OrderDelete(OrderTicket());
      if ( OrderType() == OP_SELLSTOP && wDir == 1 ) OrderDelete(OrderTicket());
      
     } // end for
   } // end CheckForClose()

//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
   {

   // check for history and trading
   if (Bars<100 || IsTradeAllowed()==false) return;
   
   // calculate open orders by current symbol
   if (CalculateCurrentOrders(Symbol())==0) CheckForOpen(); else CheckForClose();
   } // end start()
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Get direction                                                    | 
//+------------------------------------------------------------------+
int getDirection()
   {
   double MacdC,MacdP,MacdP2;
   int wDir;
   
	MacdC  = iMACD(NULL,PERIOD_W1,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
	MacdP  = iMACD(NULL,PERIOD_W1,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
	MacdP2 = iMACD(NULL,PERIOD_W1,12,26,9,PRICE_CLOSE,MODE_MAIN,2);
	
	if (MacdP >  MacdP2) wDir =  1;
	if (MacdP <  MacdP2) wDir = -1;
	if (MacdP == MacdP2) wDir = 0;
	
	Comment("Direction = ",wDir);
	
	return(wDir);	
   } // end start()
//+------------------------------------------------------------------+

Profitability Reports

PERFORMANCE BY SYMBOL

Expected payoff

Average expected payoff across the available backtests for each symbol.

Positive Negative
13 reports
EUR/USD Jul 2025 - Sep 2025
0.90
Total Trades 508
Won Trades 202
Lost trades 306
Win Rate 39.76 %
Expected payoff -0.62
Gross Profit 2791.40
Gross Loss -3106.50
Total Net Profit -315.10
-100%
-50%
0%
50%
100%
USD/CAD Oct 2024 - Jan 2025
0.84
Total Trades 253
Won Trades 120
Lost trades 133
Win Rate 47.43 %
Expected payoff -1.02
Gross Profit 1315.97
Gross Loss -1573.94
Total Net Profit -257.97
-100%
-50%
0%
50%
100%
GBP/USD Jul 2025 - Sep 2025
0.80
Total Trades 507
Won Trades 193
Lost trades 314
Win Rate 38.07 %
Expected payoff -1.29
Gross Profit 2618.60
Gross Loss -3272.10
Total Net Profit -653.50
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
0.79
Total Trades 267
Won Trades 83
Lost trades 184
Win Rate 31.09 %
Expected payoff -1.21
Gross Profit 1191.80
Gross Loss -1514.20
Total Net Profit -322.40
-100%
-50%
0%
50%
100%
USD/JPY Jul 2025 - Sep 2025
0.77
Total Trades 461
Won Trades 239
Lost trades 222
Win Rate 51.84 %
Expected payoff -1.61
Gross Profit 2483.06
Gross Loss -3223.56
Total Net Profit -740.50
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
0.76
Total Trades 292
Won Trades 108
Lost trades 184
Win Rate 36.99 %
Expected payoff -1.71
Gross Profit 1555.30
Gross Loss -2053.70
Total Net Profit -498.40
-100%
-50%
0%
50%
100%
EUR/USD Oct 2025 - Feb 2026
0.70
Total Trades 815
Won Trades 250
Lost trades 565
Win Rate 30.67 %
Expected payoff -1.63
Gross Profit 3137.50
Gross Loss -4464.40
Total Net Profit -1326.90
-100%
-50%
0%
50%
100%
USD/CAD Jul 2025 - Sep 2025
0.66
Total Trades 431
Won Trades 156
Lost trades 275
Win Rate 36.19 %
Expected payoff -1.74
Gross Profit 1472.08
Gross Loss -2221.90
Total Net Profit -749.82
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.59
Total Trades 460
Won Trades 132
Lost trades 328
Win Rate 28.70 %
Expected payoff -2.26
Gross Profit 1486.80
Gross Loss -2525.80
Total Net Profit -1039.00
-100%
-50%
0%
50%
100%
GBP/AUD Oct 2025 - Feb 2026
0.45
Total Trades 1323
Won Trades 367
Lost trades 956
Win Rate 27.74 %
Expected payoff -2.88
Gross Profit 3149.49
Gross Loss -6963.32
Total Net Profit -3813.83
-100%
-50%
0%
50%
100%
GBP/CAD Oct 2025 - Feb 2026
0.38
Total Trades 1039
Won Trades 233
Lost trades 806
Win Rate 22.43 %
Expected payoff -3.17
Gross Profit 2013.79
Gross Loss -5311.17
Total Net Profit -3297.38
-100%
-50%
0%
50%
100%
AUD/USD Oct 2025 - Feb 2026
0.30
Total Trades 788
Won Trades 138
Lost trades 650
Win Rate 17.51 %
Expected payoff -4.11
Gross Profit 1418.70
Gross Loss -4655.90
Total Net Profit -3237.20
-100%
-50%
0%
50%
100%
GBP/CAD Jul 2025 - Sep 2025
0.06
Total Trades 592
Won Trades 34
Lost trades 558
Win Rate 5.74 %
Expected payoff -6.69
Gross Profit 240.12
Gross Loss -4200.83
Total Net Profit -3960.71
-100%
-50%
0%
50%
100%

Comments