twodirectionmartin-stylized

Download script
Author:
Profit factor:
0.00

This script is an automated trading system designed to manage market positions dynamically by constantly adjusting pending orders based on price movement and current trade volume. It operates using a sophisticated balancing logic to maintain a specific risk profile.

Core Trading Philosophy

The script utilizes a "dual-sided" approach. At any given time, it attempts to have active positions (or pending orders) in both directions—buying and selling. Rather than simply picking a side, the logic focuses on managing the distance between these sides and the volume assigned to each.

Key Functional Components

1. Dynamic Order Management The system constantly monitors the market price and its own open orders. It calculates the "Spread" (the difference between buying and selling prices) and determines a Take Profit target based on a user-defined percentage of the current price.

2. The "Shrink Range" Mechanism This is the primary engine of the script. Its job is to keep the trading activity compressed near the current market price. It performs the following steps:

  • Loss Calculation: It calculates the potential loss based on the distance between the current price and the existing order targets.
  • Volume Rebalancing: It calculates a new total volume required to maintain the desired risk level.
  • Symmetry Adjustment: It attempts to balance the volume between buy and sell orders. If one side has significantly more weight than the other, it adjusts the numbers so they remain proportional (controlled by a user-defined percentage).
  • Execution: If the current orders are too far away or unbalanced, the script deletes the old orders and places new ones at closer distances to the current price.

3. Safety and Volume Controls To ensure the system remains stable and doesn't execute erratic trades, it includes several safeguards:

  • Volume Limits: There are hard ceilings on how much volume can be placed in a single order to prevent oversized entries.
  • Retry Logic: If a trade request fails due to market "requotes" (common during high volatility), the script will automatically try to resubmit the request several times before giving up.
  • Order Normalization: It automatically rounds down trade volumes and prices to ensure they meet the specific requirements of the broker.

Execution Summary

When you first run the script, it initiates a balanced set of buy and sell orders on both sides of the market. As the price moves, the script evaluates if those orders have become "stale" (too far from the current price) or if one side has become too dominant in volume. When these conditions are met, it automatically wipes out the old positions and replaces them with updated, balanced orders, effectively "shrinking" the trading range to follow the market's pulse.

Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reached
11 Views
1 Downloads
0 Favorites
twodirectionmartin-stylized
//+------------------------------------------------------------------+
//|                                                       My-I28.mq5 |
//+------------------------------------------------------------------+
#property copyright ""
#property link      ""
#property version   "1.28"
#property description "... just for fun"

//--- input parameters
input double KTP=0.35; // Koef. of TakeProfit, as % of Price
input double VolumeToOrder=0.10; // Minimal volume to send(request)
input double VolumeLimitOrder=0.75; // Maximal volume of one order
input double PercentSame=75.0; // Level of Same side (Martingale) = (0,0...100,0%)

                               // Program Global Varible
MqlTick         T; // Tick
MqlTradeRequest R; // Request
MqlTradeResult  D; // Deal (result)
double TP;
double WinPerTrade;
double StopLevel;
double Spread;
int    I;
ulong TicketBuy;
ulong TicketSell;
bool ExistBUY;
bool ExistSELL;
double OldBuyTP;
double OldSellTP;
double OldBuyVol;
double OldSellVol;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ExistOrder() // return some MAIN program varible
  {
   ulong Ticket;
   ExistBUY=false; ExistSELL=false;
   OldSellVol=0.0; OldBuyVol=0.0;
   for(I=0;I<(int)OrdersTotal();I++)
     {
      Ticket=OrderGetTicket(I); // Order selected here
      if(OrderGetString(ORDER_SYMBOL)==_Symbol)
         switch(OrderGetInteger(ORDER_TYPE))
           {
            case ORDER_TYPE_BUY_LIMIT :
              {
               if(OldSellVol<OrderGetDouble(ORDER_VOLUME_CURRENT))
                 {
                  OldSellVol=OrderGetDouble(ORDER_VOLUME_CURRENT);
                  OldSellTP=OrderGetDouble(ORDER_PRICE_OPEN);
                  TicketSell=Ticket;
                  ExistSELL=true; 
                 }
               break; 
              }
            case ORDER_TYPE_SELL_LIMIT :
              {
               if(OldBuyVol<OrderGetDouble(ORDER_VOLUME_CURRENT))
                 {
                  OldBuyVol=OrderGetDouble(ORDER_VOLUME_CURRENT);
                  OldBuyTP=OrderGetDouble(ORDER_PRICE_OPEN);
                  TicketBuy=Ticket;
                  ExistBUY=true; 
                 }
               break; 
              }
            default : {}
           } // end : switch
     } // end : for
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DataForSymbol() // Return Tick valu for Symbol, as program varible
  {
   SymbolInfoTick(_Symbol,T);
   StopLevel=SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL)*_Point;
   Spread=(T.ask-T.bid);
   TP=MathMax(KTP*T.ask/100.0,StopLevel+Spread);
   WinPerTrade=Spread;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DeleteOld() // Remove old pending order ( in wrong direction )
  {
   R.action=TRADE_ACTION_REMOVE;
   R.type_filling=ORDER_FILLING_FOK;
   if(OldBuyVol>0.005)
     {
      R.order=TicketBuy;
      bool Done=OrderSend(R,D); int J=0;
      while(!Done && J<19) { Done=OrderSend(R,D); J++; Sleep(12345); } // REQUOTE
      Print("==> DeleteBuy : Ret.Code=",D.retcode);
     }
   if(OldSellVol>0.005)
     {
      R.order=TicketSell;
      bool Done=OrderSend(R,D); int J=0;
      while(!Done && J<19) { Done=OrderSend(R,D); J++; Sleep(12345); } // REQUOTE
      Print("==> DeleteSell : Ret.Code=",D.retcode);
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void BuyLimitOrderSend(double BLVolume,double BLPrice) // Sene BUY_LIMIT
  {
   R.volume=NormalizeDouble(BLVolume,2);
   R.price=NormalizeDouble(BLPrice,_Digits);
   R.action=TRADE_ACTION_PENDING;
   R.type=ORDER_TYPE_BUY_LIMIT;
   R.type_filling=ORDER_FILLING_RETURN;
   bool Done=OrderSend(R,D); int J=0;
   while(!Done && J<19) { Done=OrderSend(R,D); J++; Sleep(12345); } // REQUOTE
   Print("==> BuyLimit : Ret.Code=",D.retcode);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void SellLimitOrderSend(double SLVolume,double SLPrice) // Send SELL_LIMIT
  {
   R.volume=NormalizeDouble(SLVolume,2);
   R.price=NormalizeDouble(SLPrice,_Digits);
   R.action=TRADE_ACTION_PENDING;
   R.type=ORDER_TYPE_SELL_LIMIT;
   R.type_filling=ORDER_FILLING_RETURN;
   bool Done=OrderSend(R,D); int J=0;
   while(!Done && J<19) { Done=OrderSend(R,D); J++; Sleep(12345); } // REQUOTE
   Print("==> SellLimit : Ret.Code=",D.retcode);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void AddBuySend(double AddVolume) // Send BUY order
  {
   R.volume=NormalizeDouble(AddVolume,2);
   R.action=TRADE_ACTION_DEAL;
   R.type_filling=ORDER_FILLING_FOK;
   R.type=ORDER_TYPE_BUY;
   bool Done=false; int J=0;
   while(!Done && J<19) { DataForSymbol(); R.price=T.ask; Done=OrderSend(R,D); J++; Sleep(12345); } // REQUOTE
   Print("==> AddBuy : Ret.Code=",D.retcode);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void AddSellSend(double AddVolume) // Send SELL order
  {
   R.volume=NormalizeDouble(AddVolume,2);
   R.action=TRADE_ACTION_DEAL;
   R.type_filling=ORDER_FILLING_FOK;
   R.type=ORDER_TYPE_SELL;
   bool Done=false; int J=0;
   while(!Done && J<19) { DataForSymbol(); R.price=T.bid; Done=OrderSend(R,D); J++; Sleep(12345); } // REQUOTE
   Print("==> AddSell : Ret.Code=",D.retcode);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ShrinkRange() // Move orders close to current price 
  {
   DataForSymbol();
   double OldLOSS=((OldBuyTP-T.bid)*OldBuyVol+(T.ask-OldSellTP)*OldSellVol);
   double NewTotalVol=MathMax(2.0*VolumeToOrder,MathCeil(((OldLOSS+WinPerTrade)/TP)*100.0)/100.0);
   double NewBuyVol,NewSellVol,AddVolume;
   if(OldBuyVol>=OldSellVol)
     {
      NewBuyVol=MathMax(VolumeToOrder,MathCeil(NewTotalVol*PercentSame)/100.0);
      NewSellVol=MathMax(VolumeToOrder,MathRound((NewTotalVol-NewBuyVol)*100.0)/100.0); 
     }
   else
     {
      NewSellVol=MathMax(VolumeToOrder,MathCeil(NewTotalVol*PercentSame)/100.0);
      NewBuyVol=MathMax(VolumeToOrder,MathRound((NewTotalVol-NewSellVol)*100.0)/100.0); 
     }
   AddVolume=(NewBuyVol-NewSellVol)-(OldBuyVol-OldSellVol);

   DeleteOld();
   BuyLimitOrder(NewSellVol,T.bid-TP);
   SellLimitOrder(NewBuyVol,T.ask+TP);
   if( AddVolume>+0.005 ) AddBUY(AddVolume);
   if( AddVolume<-0.005 ) AddSELL(-AddVolume);

   Print("===> OldLOSS=",DoubleToString(OldLOSS/VolumeToOrder,_Digits),"  TP=",DoubleToString(TP,_Digits),"  NewTotalVol=",DoubleToString(NewTotalVol,2));
   Print("===> OldBuyVol=",OldBuyVol,"  OldSellVol=",OldSellVol,"  ==> NewBuyVol=",NewBuyVol,"  NewSellVol=",NewSellVol);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void AddBUY(double Volume) // Here order BUY send VOLUME is LIMITED !
  {
   while(Volume>VolumeLimitOrder)
     { AddBuySend(VolumeLimitOrder); Volume=Volume-VolumeLimitOrder; }
   AddBuySend(Volume);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void AddSELL(double Volume) // Here order SELL send VOLUME is LIMITED !
  {
   while(Volume>VolumeLimitOrder)
     { AddSellSend(VolumeLimitOrder); Volume=Volume-VolumeLimitOrder; }
   AddSellSend(Volume);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void BuyLimitOrder(double Volume,double Price) // Here order BUY_LIMIT send VOLUME is LIMITED !
  {
   while(Volume>VolumeLimitOrder)
     { BuyLimitOrderSend(VolumeLimitOrder,Price); Volume=Volume-VolumeLimitOrder; Price=Price-Spread; }
   BuyLimitOrderSend(Volume,Price);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void SellLimitOrder(double Volume,double Price) // Here order SELL_LIMIT send VOLUME is LIMITED !
  {
   while(Volume>VolumeLimitOrder)
     { SellLimitOrderSend(VolumeLimitOrder,Price); Volume=Volume-VolumeLimitOrder; Price=Price+Spread; }
   SellLimitOrderSend(Volume,Price);
  }
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  { // OrderSend constant
   R.sl=0;
   R.tp=0;
   R.magic=2012;
   R.deviation=99;
   R.comment="AutoSend";
   R.symbol=_Symbol;
   return(0);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
// Set program varible
   ExistOrder();
   DataForSymbol();

// INIT or RESTART
   if(!ExistBUY && !ExistSELL)
     {
      AddSELL(VolumeToOrder); BuyLimitOrder(VolumeToOrder,T.bid-TP);
      AddBUY(VolumeToOrder);  SellLimitOrder(VolumeToOrder,T.ask+TP);
      return;
     }

// MAIN LOGIC
   if(!ExistBUY || !ExistSELL) { ShrinkRange(); return; }

   if(( OldBuyTP>T.ask+2.0*TP && OldSellTP<T.bid-TP && OldBuyVol<=OldSellVol) || 
      (OldSellTP<T.bid-2.0*TP && OldBuyTP>T.ask+TP && OldBuyVol>=OldSellVol)) ShrinkRange();
  }
//+------------------------------------------------------------------+

Profitability Reports

PERFORMANCE BY SYMBOL

Expected payoff

Average expected payoff across the available backtests for each symbol.

Positive Negative
4 reports
GBP/AUD Jul 2025 - Sep 2025
0.00
Total Trades 0
Won Trades 0
Lost trades 0
Win Rate 0.0 %
Expected payoff 0.00
Gross Profit 0.00
Gross Loss 0.00
Total Net Profit 0.00
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.00
Total Trades 65
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -60.31
Gross Profit 7842.49
Gross Loss -11762.73
Total Net Profit -3920.24
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
0.00
Total Trades 62
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff 1.79
Gross Profit 3982.78
Gross Loss -3871.59
Total Net Profit 111.19
-100%
-50%
0%
50%
100%
GBP/CAD Jul 2025 - Sep 2025
0.00
Total Trades 0
Won Trades 0
Lost trades 0
Win Rate 0.0 %
Expected payoff 0.00
Gross Profit 0.00
Gross Loss 0.00
Total Net Profit 0.00
-100%
-50%
0%
50%
100%

Comments