TrailingLines1

TrailingLines1

This script is designed to manage and automate specific trade actions on the MetaTrader platform by creating visual indicators and executing automated price protection logic. Here is a breakdown of how it functions:

Trade Detection and Setup

The script begins by scanning your active trades to identify a specific position based on where you interact with the chart. Once a relevant order is identified, the system automatically calculates and draws two distinct visual lines on your screen:

  • Stop Loss Line: Represented in red, this marks the point at which a trade will automatically close to prevent further losses.
  • Take Profit Line: Represented in lime (green), this marks the target price where the trade will close to secure gains.

Automated Trailing Logic

One of the primary features of this script is its ability to "trail" your protection. If the TrailingLine setting is enabled, the script monitors the real-time movement of the market price:

  • It calculates the distance between your entry price and your current Stop Loss.
  • As the market moves in your favor, the script evaluates whether moving the Stop Loss closer to the current price would protect more profit while maintaining that original "buffer" distance.
  • If a better protection level is identified, the script automatically moves the visual line and the actual trade's Stop Loss to that new position.

Real-Time Monitoring and Execution

The script runs in a continuous loop, constantly refreshing its view of the market prices (Bid and Ask). It performs three main tasks during this cycle:

  1. Visual Updates: It updates the on-screen labels and lines so you can see exactly where your current Stop Loss and Take Profit levels are situated.
  2. Status Reporting: It provides a text comment on the screen displaying the trade type, ticket number, and current price levels for quick reference.
  3. Automatic Closure: The script constantly checks if the current market candles have crossed over your set Stop Loss or Take Profit lines. If a crossing is detected, it immediately sends a command to close the position automatically.

Cleanup

To keep your trading chart organized, the script includes a "de-initialization" phase. When the script is removed or turned off, it automatically cleans up after itself by deleting the visual lines and clearing the on-screen comments, leaving your chart in its original state.

Price Data Components
Series array that contains the highest prices of each barSeries array that contains the lowest prices of each bar
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself
11 Views
0 Downloads
0 Favorites
TrailingLines1
//+------------------------------------------------------------------+
//|                                                 TrailingLine.mq4 |
//|                                                            Roger |
//+------------------------------------------------------------------+
#property show_inputs

extern bool TrailingLine=True;
int _OrderTicket;

int start()
{
//+------------------------------------------------------------------+
int Order_Find_Radius = 10;

int Stop_Loss = 14;
int Take_Profit = 30;

int Slippage = 50;

//+------------------------------------------------------------------+
double Open_Price_Level, Stop_Loss_Level, PriceClose, Take_Profit_Level, Take_Profit_Level_new, Stop_Loss_Level_new;
int _break;
double lev;
double DropPrice = WindowPriceOnDropped();
bool mod;
for ( int x = 0; x <= Order_Find_Radius; x ++ )
{
	for ( int z = 0; z < OrdersTotal(); z ++ )
	{
		OrderSelect( z, SELECT_BY_POS, MODE_TRADES );
		if ( OrderSymbol() == Symbol() )
		{
			if ( MathAbs(( DropPrice - OrderOpenPrice() )/Point) <= x )
			{ _break = 1;
			    break;
		   }
		}
	}
	if ( _break == 1 ) break; 
}

string ord;
int _OrderType = OrderType();
if(_OrderType==0)ord="BUY"; else ord="SELL";
_OrderTicket = OrderTicket();
Open_Price_Level = Bid;
if ( Stop_Loss > 0 )
   {
   if(_OrderType==0)Stop_Loss_Level = Open_Price_Level - Stop_Loss*Point; 
   if(_OrderType==1)Stop_Loss_Level = Open_Price_Level + Stop_Loss*Point;
   ObjectCreate( "Stop_Loss_Line"+_OrderTicket, OBJ_HLINE, 0, 0, Stop_Loss_Level, 0, 0, 0, 0 );
   ObjectSet( "Stop_Loss_Line"+_OrderTicket, OBJPROP_COLOR,Red );
   ObjectSetText( "Stop_Loss_Line"+_OrderTicket, "Stop_Loss_Line", 6, "Arial", Red );
   }
else Stop_Loss_Level =0;
if ( Take_Profit >0 )
   {
   if(_OrderType==0)Take_Profit_Level=Open_Price_Level + Take_Profit*Point; 
   if(_OrderType==1)Take_Profit_Level=Open_Price_Level - Take_Profit*Point; 
   ObjectCreate( "Take_Profit_Line"+_OrderTicket, OBJ_HLINE, 0, 0, Take_Profit_Level, 0, 0, 0, 0 );
   ObjectSet( "Take_Profit_Line"+_OrderTicket, OBJPROP_COLOR,Lime );
   ObjectSetText( "Take_Profit_Line"+_OrderTicket, "Take_Profit_Line", 6, "Arial", Lime );
   }   
else Take_Profit_Level=0;
lev=Open_Price_Level-Stop_Loss_Level;
Print("OrderType - ",ord," OrderTicket - ",_OrderTicket," OpenPrice - ",Open_Price_Level," StopLoss - ",Stop_Loss_Level," TakeProfit - ",Take_Profit_Level);
WindowRedraw();

int xx;
while( xx<1)
   {
   RefreshRates();
	if(ObjectFind("Stop_Loss_Line"+_OrderTicket)!=-1)Stop_Loss_Level_new = NormalizeDouble( ObjectGet( "Stop_Loss_Line"+_OrderTicket, OBJPROP_PRICE1 ), MarketInfo( Symbol(), MODE_DIGITS ) ); 
	else 
	  {
	  Stop_Loss_Level=0;
	  Stop_Loss_Level_new =0;
	  }
	if(ObjectFind("Take_Profit_Line"+_OrderTicket)!=-1)Take_Profit_Level = NormalizeDouble( ObjectGet( "Take_Profit_Line"+_OrderTicket, OBJPROP_PRICE1 ), MarketInfo( Symbol(), MODE_DIGITS ) );
	else Take_Profit_Level=0;
   if(Stop_Loss_Level==0&&Take_Profit_Level==0)break;
   if(_OrderType==0)PriceClose=Bid; else PriceClose=Ask;
   if(Stop_Loss_Level!=Stop_Loss_Level_new)lev=Bid-Stop_Loss_Level_new;
   Stop_Loss_Level=Stop_Loss_Level_new;
   if(TrailingLine)
            if(MathAbs(Bid-Stop_Loss_Level)>MathAbs(lev)&&Stop_Loss_Level!=0)
                  {
                  Stop_Loss_Level=Bid-lev;
                  ObjectMove( "Stop_Loss_Line"+_OrderTicket, 0, 10,Stop_Loss_Level );
                 WindowRedraw();            
                  }
              
      Comment("Order ",ord," - ",_OrderTicket, " StopLoss - ",Stop_Loss_Level," TakeProfit - ",Take_Profit_Level);
      if((lev<0&&iHigh(0,1,0)>=Stop_Loss_Level&&Stop_Loss_Level>0)||(lev>0&&iLow(0,1,0)<=Stop_Loss_Level)||
      (iHigh(0,1,1)<Take_Profit_Level&&iHigh(0,1,0)>=Take_Profit_Level)||(iLow(0,1,1)>Take_Profit_Level&&iLow(0,1,0)<=Take_Profit_Level))//óñëîâèÿ ïåðåñå÷åíèÿ ñòîïà èëè ïðîôèòà
            {
            for(int i=0;i<OrdersTotal();i++)
                  {
                  OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
	               if (_OrderTicket == OrderTicket())
                        {
                        if(OrderClose(OrderTicket(),OrderLots(),PriceClose,Slippage,CLR_NONE))
                              {
                              break;
                              }
                        }
                  }
            }
   OrderSelect(_OrderTicket,SELECT_BY_TICKET,MODE_TRADES);
   if(OrderCloseTime( ) !=0)break;
   Sleep(2000);
   }
return(-1);
}

int deinit()
{
ObjectDelete( "Stop_Loss_Line"+_OrderTicket );
ObjectDelete( "Take_Profit_Line"+_OrderTicket );
Comment("");
return(0);
}


Comments