Author: Copyright � 2014 Bill Jones
Profit factor:
0.00

System Overview

The Order_EA is a specialized management tool designed to oversee and automate the lifecycle of trading orders on a specific currency pair. Rather than acting as a standard "set-and-forget" bot, this script acts as an intelligent coordinator that monitors visual indicators (lines) placed on your trading chart. It bridges the gap between manual visual planning and automated execution by watching where you place your targets and triggers, then taking action based on price movement.

Core Logic & Functional Modules

1. Visual Trigger Recognition

The system is built to "read" your chart. It identifies specific types of lines you create or drop onto the graph, including Buy/Sell entries, Take Profit (TP) targets, and Stop Loss (SL) limits.

  • Dynamic Tracking: The script automatically organizes these lines into internal lists. If you add more lines than the system is configured to handle, it intelligently manages the oldest ones to keep your workspace clean.
  • Validation: It ensures that your planned moves make sense. For example, if you try to place a Buy line while the system is already in "Sell mode," or if a Stop Loss is placed in an impossible direction relative to the market price, the script will identify the error and prevent incorrect execution.

2. Automated Order Execution

Once the system recognizes a valid line on the chart, it monitors the live market price against that line:

  • Entry Execution: If the market price crosses your designated Buy or Sell line, the EA automatically opens the trade for you at the best available price.
  • Conflict Prevention: To maintain strategy integrity, the system enforces a rule where it will not allow conflicting positions (e.g., it prevents opening a Buy if you already have an active Sell position).

3. Intelligent Exit Management

The EA doesn't just open trades; it actively manages how they close based on your visual targets:

  • Take Profit (TP): The script monitors the price relative to your TP lines. If the price hits a target, it executes the closing order. It is also smart enough to distinguish between closing just one specific position or clearing all positions depending on the setup.
  • Stop Loss (SL): Similarly, if the market moves against you and touches a Stop Loss line, the EA triggers an immediate exit to preserve your capital.
  • Clean-up: Once a target is hit and an order is closed, the script automatically removes that specific line from its tracking list.

4. Advanced Protection Features

The script includes two sophisticated "active" management tools:

  • Trailing Stop (TS): This is a dynamic protection layer. If enabled, the system can create a "moving" safety net. As your trade moves into profit, the script automatically shifts this line forward to "lock in" gains while maintaining a set distance from the current price. If the market retraces and hits this moving line, the position is closed automatically.
  • Global Status Sync: The EA communicates with other scripts via global variables. If you use a separate "Close All" command, this EA recognizes that signal instantly and wipes all active lines and trailing stops from the chart to keep your workspace synchronized with your actions.

Summary of Workflow

  1. Identify: The EA looks at your chart and identifies Buy, Sell, TP, SL, and Trailing Stop lines.
  2. Monitor: It constantly watches the live "Bid" and "Ask" prices.
  3. Act:
    • Price hits an Entry Line $\rightarrow$ Open a new trade.
    • Price hits a TP/SL Line $\rightarrow$ Close the existing trade.
    • Price moves in favor of a trade $\rightarrow$ Move the Trailing Stop forward.
  4. Report: It provides a real-time text summary on your chart, showing you exactly how many orders are active and where your safety levels currently sit.
Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt Closes Orders by itself
5 Views
0 Downloads
0 Favorites
Order_EA
//+------------------------------------------------------------------+
//+ Order_EA - Order Processing Expert Adviser
//+   Keeps track of all orders for a given currency pair
//+   Responds to lines generated by the following scripts:
//+      Order_Close_All - Close all open orders and delete all control lines
//+      Order_Close_Old - Close the oldest open order
//+      Order_Immediate - Create an instant buy/sell plus StopLoss & TakeProfit
//+      Order_Pending   - Create a Buy/Sell line where dropped plus StopLoss & TakeProfit
//+      Order_SL        - Create a StopLoss line where dropped
//+      Order_TP        - Create a TakeProfit line where dropped
//+      Order_Fill_21   - Fill the space between the Buy/Sell line and the TakeProfit line with orders
//+                           This will also move the StopLoss lines as each order is processed
//+      Order_Waypoint  - Mark way points between current price and Take Profit
//+
//+   Ask if the value the broker is willing to sell a position (a buy on our side)
//+   Bid is the value the broker is willing to pay for your trade (a sell)
//+
//+------------------------------------------------------------------+

#property copyright "Copyright © 2014 Bill Jones"
#property version "1.00"
#property description "Use the Order_xxx scripts to control order processing."


#define OP_ALL    10       // Used to delete all open orders
#define Array_Max 20       // Number of lines of each type

// Input parameters
input double    MagicNumber        = 1125;      // Magic Number
input double    Lot                = 0.05;      // Lot size
input double    TakeProfitPip      = 100;       // Take Profit (in pips)
input double    StopLossPip        = 30;        // Stop Loss (in pips)
input bool      EnableTS           = True;      // Enable Trailing Stop

// Global names for this iteration (currency pair)
string   GLots       = "GLots"+Symbol();
string   GTP         = "GTP"+Symbol();
string   GSL         = "GSL"+Symbol();
string   GMaxSlip    = "GMaxSlip"+Symbol();
string   GMagic      = "GMagic"+Symbol();
string   GStatus     = "GStatus"+Symbol();

// Order Parameters
double   CurrPriceLine;          // Current (0) value of the line
double   lots;                   // Number of lots to trade
int      MaxSlippage=3;
double   PipValue;
double   TPBarrier;              // Let us know when close to TP Line
double   TPDiff;                 // Difference between TPLine & current Bid/Ask
int      ticket;
int      TypeOrder;

// Order processing arrays - Current Max of 20 items allowed
int      Order_Count=0;       // Number of orders open
int      Order_Buy_Count  = 0;
int      Order_Sell_Count = 0;
int      Buy_Max=0;       // Current Buy Order count
string   Buy_Name[Array_Max];
int      Sell_Max=0;       // Current Sell Order count
string   Sell_Name[Array_Max];
int      SL_Max=0;       // Current Stop Loss count
string   SL_Name[Array_Max];
int      TP_Max=0;       // Current Take Profit count
string   TP_Name[Array_Max];
double   TS_BidLast     =0.0;
string   TS_Name="TrailingStop"; // Name of Trailing Stop line
double   TS_Value=0.0;
int      Index;                    // Array process index
int      LineCnt        = 0;       // Counter to make unique lines on chart
datetime Temp;

// Program Flow Parameters
bool     openedBuy      = false;
bool     openedSell     = false;
double   StatusChange   = 0.0;         // Script Order_Immediate sets to 1.0 when an order has been added 
                                       // Script Order_Close_Old sets to 2.0 when one order has been deleted
// Script Order_Close_All sets to 3.0 when all orders have been deleted

// Error messages & debug
string   comm;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---   

   if(Digits==5 || Digits==3) // Adjust for five (5) digit brokers.
     {
      MaxSlippage=MaxSlippage*10;
      PipValue=Point*10;
     }
   else
      PipValue=Point;

   lots=Lot;

   if(lots<MarketInfo(Symbol(),MODE_MINLOT))
      lots=MarketInfo(Symbol(),MODE_MINLOT);
   if(lots>MarketInfo(Symbol(),MODE_MAXLOT))
      lots=MarketInfo(Symbol(),MODE_MAXLOT);

// Set GLOBAL variables
   if(GlobalVariableTemp(GLots))   Temp = GlobalVariableSet(GLots, lots);
   if(GlobalVariableTemp(GTP))     Temp = GlobalVariableSet(GTP, (TakeProfitPip*PipValue));
   if(GlobalVariableTemp(GSL))     Temp = GlobalVariableSet(GSL, (StopLossPip*PipValue));
   if(GlobalVariableTemp(GMaxSlip)) Temp= GlobalVariableSet(GMaxSlip,MaxSlippage);
   if(GlobalVariableTemp(GMagic))  Temp = GlobalVariableSet(GMagic, MagicNumber);
   if(GlobalVariableTemp(GStatus)) Temp = GlobalVariableSet(GStatus, StatusChange);

// Find the number of open orders - Pending orders are not counted
   CheckOpenOrders();

// Find all Order_EA lines on the chart
   int    obj_total=ObjectsTotal();
   string name,holdname;

   for(int i=0;i<obj_total;i++)
     {
      name=ObjectName(i);
      if(BuildLineArray(name)) continue;

      if(StringSubstr(name,0,3)=="Buy")
        {
         if(Buy_Max>Array_Max)
            DeleteLine(name);
         else
           {
            holdname=StringSubstr(name,0,3)+IntegerToString(LineCnt++,5,'-');
            ObjectSetString(0,name,OBJPROP_NAME,holdname);
            Buy_Name[Buy_Max++]=holdname;
           }
        }
      else
      if(StringSubstr(name,0,4)=="Sell")
        {
         if(Sell_Max>Array_Max)
            DeleteLine(name);
         else
           {
            holdname=StringSubstr(name,0,4)+IntegerToString(LineCnt++,5,'-');
            ObjectSetString(0,name,OBJPROP_NAME,holdname);
            Sell_Name[Sell_Max++]=holdname;
           }
        }
      else
      if(StringSubstr(name,0,10)=="TakeProfit")
        {
         if(TP_Max>Array_Max)
            DeleteLine(name);
         else
           {
            holdname=StringSubstr(name,0,10)+IntegerToString(LineCnt++,5,'-');
            ObjectSetString(0,name,OBJPROP_NAME,holdname);
            TP_Name[TP_Max++]=holdname;
           }
        }
      else
      if(StringSubstr(name,0,8)=="StopLoss")
        {
         if(SL_Max>Array_Max)
            DeleteLine(name);
         else
           {
            holdname=StringSubstr(name,0,8)+IntegerToString(LineCnt++,5,'-');
            ObjectSetString(0,name,OBJPROP_NAME,holdname);
            SL_Name[SL_Max++]=holdname;
           }
        }
      else
      if(name==TS_Name) // Trailing Stop
      if(openedBuy)
        {
         TS_BidLast   = Bid;
         TS_Value     = ObjectGetValueByShift(name,0);
        }
      else
      if(openedSell)
        {
         TS_BidLast   = Ask;
         TS_Value     = ObjectGetValueByShift(name,0);
        }
      else
         ResetTS();

     }

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   GlobalVariableDel(GLots);
   GlobalVariableDel(GTP);
   GlobalVariableDel(GSL);
   GlobalVariableDel(GMaxSlip);
   GlobalVariableDel(GMagic);
   GlobalVariableDel(GStatus);
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| BuildLineArray - Add each line to proper array                   |
//+------------------------------------------------------------------+
bool BuildLineArray(string name)
  {
   if(name=="Buy")
     {
      if(Buy_Max>Array_Max) {DeleteLine(name); return(false); }
      ObjectSetString(0,name,OBJPROP_NAME,name+IntegerToString(LineCnt,5,'-'));
      Buy_Name[Buy_Max++]=name+IntegerToString(LineCnt++,5,'-');
      return(true);
     }

   if(name=="Sell")
     {
      if(Sell_Max>Array_Max) {DeleteLine(name); return(false); }
      ObjectSetString(0,name,OBJPROP_NAME,name+IntegerToString(LineCnt,5,'-'));
      Sell_Name[Sell_Max++]=name+IntegerToString(LineCnt,5,'-');
      return(true);
     }

   if(name=="TakeProfit")
     {
      if(TP_Max>Array_Max) {DeleteLine(name); return(false); }
      ObjectSetString(0,name,OBJPROP_NAME,name+IntegerToString(LineCnt,5,'-'));
      TP_Name[TP_Max++]=name+IntegerToString(LineCnt++,5,'-');
      return(true);
     }

   if(name=="StopLoss")
     {
      if(SL_Max>Array_Max) {DeleteLine(name); return(false); }
      ObjectSetString(0,name,OBJPROP_NAME,name+IntegerToString(LineCnt,5,'-'));
      SL_Name[SL_Max++]=name+IntegerToString(LineCnt++,5,'-');
      return(true);
     }
   return(false);
  }
//+------------------------------------------------------------------+
//| ResetTS - Clear the Trailing Stop information                    |
//+------------------------------------------------------------------+
void ResetTS()
  {
   TS_BidLast   = 0.0;
   TS_Value     = 0.0;
   if(ObjectFind(0,TS_Name)>=0)
      DeleteLine(TS_Name);
  }
//+------------------------------------------------------------------+
//| DeleteBuy - delete each line after it is used                    |
//+------------------------------------------------------------------+
bool DeleteBuy(int i,bool DelLine=true)
  {
   if(DelLine) DeleteLine(Buy_Name[i]);          // Delete the line
   Buy_Max--;
   if(i== Buy_Max) return(true);   // Done
   int j=i;                        // Else, compress the array
   while(j<=Buy_Max)
     {
      Buy_Name[j]=Buy_Name[j+1];   // Move everything Left
      j++;
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| DeleteSell - delete each line after it is used                   |
//+------------------------------------------------------------------+
bool DeleteSell(int i,bool DelLine=true)
  {
   if(DelLine) DeleteLine(Sell_Name[i]);         // Delete the line
   Sell_Max--;
   if(i== Sell_Max) return(true);  // Done
   int j=i;                        // Else, compress the array
   while(j<=Sell_Max)
     {
      Sell_Name[j]=Sell_Name[j+1]; // Move everything Left
      j++;
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| DeleteSL - delete each line after it is used                     |
//+------------------------------------------------------------------+
bool DeleteSL(int i,bool DelLine=true)
  {
   if(DelLine) DeleteLine(SL_Name[i]);          // Delete the line
   SL_Max--;
   if(i==SL_Max) return(true);   // Done
   int j=i;                        // Else, compress the array
   while(j<=SL_Max)
     {
      SL_Name[j]=SL_Name[j+1];   // Move everything Left
      j++;
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| DeleteSLAbove - delete all Stop Losses above value               |
//+------------------------------------------------------------------+
bool DeleteSLAbove(double Price)
  {
   int i=SL_Max;
   double LinePrice;
   while(i>0)
     {
      i--;
      LinePrice=ObjectGetValueByShift(SL_Name[i],0);
      if(LinePrice>=Price)
        {
         DeleteLine(SL_Name[i]);          // Delete the line
         SL_Max--;
         if(i== SL_Max) continue;       // Done
         int j=i;                       // Else, compress the array
         while(j<=SL_Max)
           {
            SL_Name[j]=SL_Name[j+1];   // Move everything Left
            j++;
           }
        }
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| DeleteSLBelow - delete all Stop Losses below value               |
//+------------------------------------------------------------------+
bool DeleteSLBelow(double Price)
  {
   int i=SL_Max;
   double LinePrice;
   while(i>0)
     {
      i--;
      LinePrice=ObjectGetValueByShift(SL_Name[i],0);
      if(LinePrice<=Price)
        {
         DeleteLine(SL_Name[i]);          // Delete the line
         SL_Max--;
         if(i== SL_Max) continue;       // Done
         int j=i;                       // Else, compress the array
         while(j<=SL_Max)
           {
            SL_Name[j]=SL_Name[j+1];   // Move everything Left
            j++;
           }
        }
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| DeleteTP - delete each line after it is used                     |
//+------------------------------------------------------------------+
bool DeleteTP(int i,bool DelLine=true)
  {
   if(DelLine) DeleteLine(TP_Name[i]);           // Delete the line
   TP_Max--;
   if(i== TP_Max) return(true);    // Done
   int j=i;                        // Else, compress the array
   while(j<=TP_Max)
     {
      TP_Name[j]=TP_Name[j+1];     // Move everything Left
      j++;
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| DeleteTPAbove - delete all Take Profit above value               |
//+------------------------------------------------------------------+
bool DeleteTPAbove(double Price)
  {
   int i=TP_Max;
   double LinePrice;
   while(i>0)
     {
      i--;
      LinePrice=ObjectGetValueByShift(TP_Name[i],0);
      if(LinePrice>=Price)
        {
         DeleteLine(TP_Name[i]);          // Delete the line
         TP_Max--;
         if(i== TP_Max) continue;       // Done
         int j=i;                       // Else, compress the array
         while(j<=TP_Max)
           {
            TP_Name[j]=TP_Name[j+1];   // Move everything Left
            j++;
           }
        }
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| DeleteTPBelow - delete all Take Profit below value               |
//+------------------------------------------------------------------+
bool DeleteTPBelow(double Price)
  {
   int i=TP_Max;
   double LinePrice;
   while(i>0)
     {
      i--;
      LinePrice=ObjectGetValueByShift(TP_Name[i],0);
      if(LinePrice<=Price)
        {
         DeleteLine(TP_Name[i]);          // Delete the line
         TP_Max--;
         if(i== TP_Max) continue;       // Done
         int j=i;                       // Else, compress the array
         while(j<=TP_Max)
           {
            TP_Name[j]=TP_Name[j+1];   // Move everything Left
            j++;
           }
        }
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| DeleteLine - delete each line after it is used                   |
//+------------------------------------------------------------------+
bool DeleteLine(string name)
  {
   if(!ObjectDelete(0,name)) // Try to delete the line so that it does not get hit again.
     {
      ObjectSetString(0,name,OBJPROP_NAME,"ReallyBad"+IntegerToString(LineCnt++,5,'-'));
      comm=comm+"\n Could not DELETE "+name+" Line - Abort";
      Comment(comm);
      return (false);
     }
   return (true);
  }
//////////////////////////////////////////////////////////////////////////////////////////////////
//+ Check for latest count of open orders for this symbol
void CheckOpenOrders()
  {
   Order_Buy_Count  = 0;
   Order_Count      = 0;
   Order_Sell_Count = 0;
   openedBuy        = false;
   openedSell       = false;

   int total=OrdersTotal();

   for(int pos=0; pos<total; pos++)
     {
      if(OrderSelect(pos,SELECT_BY_POS,MODE_TRADES)==false) continue;

      if(OrderSymbol()==Symbol())
        {
         if(OrderType()==OP_BUY)
           {
            Order_Count++;
            Order_Buy_Count++;
           }
         if(OrderType()==OP_SELL)
           {
            Order_Count++;
            Order_Sell_Count++;
           }
        }
     }
   if(Order_Count>0)
      if(Order_Buy_Count>Order_Sell_Count) // U.S.A. Rules: can only buy or sell - not both
         openedBuy=true;
   else
      openedSell=true;
  }
//+ ======================== MAIN PROGRAM ===========================+
//+------------------------------------------------------------------+
//| expert start function - executed for every tic                   |
//+------------------------------------------------------------------+
int start()
  {
// Find all of our lines and check against current price
   comm="Order_EA";              // Identify comment stack

   if(!IsTradeAllowed()) // Why bother if we cannot trade now...
     {
      comm=comm+"\n Trading is not allowed - will wait!";
      Comment(comm);
      return (0);
     }

   if(OrdersTotal()<=0) // Unfortunately, this counts all orders open in system
     {
      openedBuy  = false;
      openedSell = false;
      Order_Buy_Count   = 0;
      Order_Count       = 0;
      Order_Sell_Count  = 0;
     }
   else
      if(Order_Count==0 && (openedBuy || openedSell)) CheckOpenOrders();

// Did a Script change the orders?
   StatusChange=GlobalVariableGet(GStatus);

   if(StatusChange<0.1) {}    // If still zero - do nothing
   else
     {
      if(StatusChange<2.1)
        {}                      // TP & SL lines are not deleted here
      else                       // All orders must have been deleted.
        {
         DeleteTPAbove(0.0);     // Delete ALL Take Profit lines
         DeleteSLAbove(0.0);     // Delete All Stop Loss lines
         ResetTS();
         Index=Buy_Max;
         while(Index>0)
           {
            Index--;
            DeleteBuy(Index);
           }
         Buy_Max=0;
         Index=Sell_Max;
         while(Index>0)
           {
            Index--;
            DeleteSell(Index);
           }
         Sell_Max=0;
        }
      CheckOpenOrders();
      StatusChange=0.0;
      Temp=GlobalVariableSet(GStatus,StatusChange);
     }

// Search for new drag-drop lines on chart

   if(ObjectFind("Buy")>=0) // Look for Buy
      if(openedSell) // Cannot have both buy & sell open
        {
         DeleteLine("Buy");
         comm=comm+"\n Cannot have BUY in sell mode!";
        }
   else
      BuildLineArray("Buy");

   if(ObjectFind("Sell")>=0) // Look for Sell
      if(openedBuy) // Cannot have both buy & sell open
        {
         DeleteLine("Sell");
         comm=comm+"\n Cannot have SELL in buy mode!";
        }
   else
      BuildLineArray("Sell");

   if(ObjectFind("StopLoss")>=0) // Look for StopLoss
      if(openedBuy)
         if(ObjectGetValueByShift("StopLoss",0)>Bid) // Cannot have line out of place
            DeleteLine("StopLoss");
   else
      BuildLineArray("StopLoss");
   else
   if(openedSell)
   if(ObjectGetValueByShift("StopLoss",0)<Ask)
      DeleteLine("StopLoss");
   else
      BuildLineArray("StopLoss");
   else
      BuildLineArray("StopLoss");

   if(ObjectFind("TakeProfit")>=0) // Look for TakeProfit
      if(openedBuy)
         if(ObjectGetValueByShift("TakeProfit",0)<Ask) // Cannot have line out of place
            DeleteLine("TakeProfit");
   else
      BuildLineArray("TakeProfit");
   else
   if(openedSell)
   if(ObjectGetValueByShift("TakeProfit",0)>Bid)
      DeleteLine("TakeProfit");
   else
      BuildLineArray("TakeProfit");
   else
      BuildLineArray("TakeProfit");       // No orders open - put the TP anywhere

// Search for new orders to open
   Index=Buy_Max;
   if(openedSell) // Cannot have buy orders in during a sale order
     {
      while(Index>0)
        {
         Index--;
         DeleteBuy(Index);
        }
      Buy_Max=0;
     }
   else
   while(Index>0) // Start at the back & go to zero
     {
      Index--;             // Buy_Max is always 1 greater than number of orders
      if(ObjectFind(Buy_Name[Index])<0) // Has this object been deleted?
        {
         Print("Not Found: "+IntegerToString(long(Index))+" "+Buy_Name[Index]);
         DeleteBuy(Index,false);             // Yes, cleanup
         continue;
        }
      CurrPriceLine=ObjectGetValueByShift(Buy_Name[Index],0);

      if(CurrPriceLine<Ask) // Has the Ask crossed above our line?
         if(OpenOrder(OP_BUY))
           {
            DeleteBuy(Index);
            DeleteSLAbove(Ask);
            DeleteTPBelow(Ask);
            comm=comm+"\n Buy Order created";
            openedBuy=true;
           }
     }

   Index=Sell_Max;
   if(openedBuy) // Cannot have Sell orders in during a Buy order
     {
      while(Index>0)
        {
         Index--;
         DeleteSell(Index);
        }
      Sell_Max=0;
     }
   else
   while(Index>0) // Start at the back & go to zero
     {
      Index--;             // Buy_Max is always 1 greater than number of orders
      if(ObjectFind(Sell_Name[Index])<0) // Has this object been deleted?
        {
         Print("Not Found: "+IntegerToString(long(Index))+" "+Sell_Name[Index]);
         DeleteSell(Index,false);
         continue;
        }
      CurrPriceLine=ObjectGetValueByShift(Sell_Name[Index],0);

      if(CurrPriceLine>Bid) // Has the Bid crossed below our line?
         if(OpenOrder(OP_SELL))
           {
            DeleteSell(Index);
            DeleteSLBelow(Bid);
            DeleteTPAbove(Bid);
            comm=comm+"\n Sell Order created";
            openedSell=true;
           }
     }

// Search for orders to close with Take Profit line
   if(openedBuy || openedSell) // Don't bother if no order is open
     {
      Index=TP_Max;
      while(Index>0) // Search for Take Profit to close
        {
         Index--;                // Start at the back & go to zero
         if(ObjectFind(TP_Name[Index])<0) // Has this object been deleted?
           {
            Print("Not Found: "+IntegerToString(long(Index))+" "+TP_Name[Index]);
            DeleteTP(Index,false);
            continue;
           }
         CurrPriceLine=ObjectGetValueByShift(TP_Name[Index],0);    // Find current value of TP Line

         if(openedBuy) // Looking for a Buy to close 
           {
            if(EnableTS) // Are we processing a Trailing Stop?
              {
               if(TS_Value<PipValue) // Yes, check if we should create one.
                 {
                  if((CurrPriceLine -(10*PipValue))<Bid) // Are we within 10 pips?
                    {
                     TS_BidLast  = Bid;               // Keep track of how far we have moved
                     TS_Value = Bid - (20*PipValue);  // Back TS line 20 pips above current price
                     if(!ObjectCreate(TS_Name,OBJ_TREND,0,Time[10],TS_Value,Time[0],TS_Value))
                       {
                        Print("Error: can't create Trailing Stop! code #",GetLastError());
                        continue;
                       }
                     DeleteTP(Index);     // Don't use this TP line again.
                     ObjectSetInteger(0,TS_Name,OBJPROP_COLOR,clrPlum);
                     ObjectSetInteger(0,TS_Name,OBJPROP_STYLE,STYLE_DASH);
                     ObjectSetInteger(0,TS_Name,OBJPROP_WIDTH,1);
                     ObjectSetInteger(0,TS_Name,OBJPROP_BACK,false);
                     ObjectSetInteger(0,TS_Name,OBJPROP_SELECTABLE,false);
                     ObjectSetInteger(0,TS_Name,OBJPROP_SELECTED,false);
                     ObjectSetInteger(0,TS_Name,OBJPROP_RAY_LEFT,false);
                     ObjectSetInteger(0,TS_Name,OBJPROP_RAY_RIGHT,true);
                     continue;
                    }
                  else
                     continue;            // We are not within 10 pips of CurrentPriceLine
                 }
              }
            if(CurrPriceLine<Bid) // Has the Bid crossed above our line?
              {
               if(TP_Max<=1) // Do we need to close all of the orders?
                  TypeOrder=OP_ALL;
               else
                  TypeOrder=OP_SELL;
               if(CloseOrders(Symbol(),TypeOrder))
                  DeleteTP(Index);
              }
           }
         else
         if(openedSell) // Looking for Sell to close 
           {
            if(EnableTS) // Are we processing a Trailing Stop?
              {
               if(TS_Value<PipValue) // Yes, check if we should create one.
                 {
                  if((CurrPriceLine+(10*PipValue))>Ask) // Are we within 10 pips?
                    {
                     TS_BidLast=Ask;
                     TS_Value=Ask+(20*PipValue);  // Back TS line 20 pips above current price
                     if(!ObjectCreate(TS_Name,OBJ_TREND,0,Time[10],TS_Value,Time[0],TS_Value))
                       {
                        Print("Error: can't create Trailing Stop! code #",GetLastError());
                        continue;
                       }
                     DeleteTP(Index);     // Don't use this TP line again.
                     ObjectSetInteger(0,TS_Name,OBJPROP_COLOR,clrPlum);
                     ObjectSetInteger(0,TS_Name,OBJPROP_STYLE,STYLE_DASH);
                     ObjectSetInteger(0,TS_Name,OBJPROP_WIDTH,1);
                     ObjectSetInteger(0,TS_Name,OBJPROP_BACK,false);
                     ObjectSetInteger(0,TS_Name,OBJPROP_SELECTABLE,false);
                     ObjectSetInteger(0,TS_Name,OBJPROP_SELECTED,false);
                     ObjectSetInteger(0,TS_Name,OBJPROP_RAY_LEFT,false);
                     ObjectSetInteger(0,TS_Name,OBJPROP_RAY_RIGHT,true);
                     continue;
                    }
                  else
                     continue;            // We are not within 10 pips of CurrentPriceLine
                 }
              }
            if(CurrPriceLine>Ask) // Has the Ask crossed below our line?
              {
               if(TP_Max<=1) // Do we need to close all of the orders?
                  TypeOrder=OP_ALL;
               else
                  TypeOrder=OP_BUY;
               if(CloseOrders(Symbol(),TypeOrder))
                  DeleteTP(Index);
              }
           }

        }

      // Trailing Stop Processing
      if(TS_Value>PipValue) // Do we have a Trailing Stop?
        {
         CurrPriceLine=ObjectGetValueByShift(TS_Name,0);
         if(openedBuy)
           {
            if(CurrPriceLine>Bid) // Has the Bid crossed below our line?
              {
               if(TP_Max<1) // Do we need to close all of the orders?
                  TypeOrder=OP_ALL;
               else
                  TypeOrder=OP_SELL;
               if(CloseOrders(Symbol(),TypeOrder))
                  ResetTS();
              }
            else                                // Do we need to move the TS line?
            if((TS_BidLast+PipValue)<Bid) // Have we moved more than one pip?
            if((TS_Value+(4*PipValue))<Bid) // Are we more than 4 pips away?
              {
               TS_BidLast  =Bid;
               TS_Value=TS_Value+PipValue+PipValue;   // Move up 2 pips
               ObjectMove(0,TS_Name,0,Time[10],TS_Value);
               ObjectMove(0,TS_Name,1,Time[0],TS_Value);
               ChartRedraw(0);
              }
           }
         else
         if(openedSell)
           {
            if(CurrPriceLine<Ask) // Has the Ask crossed above our line?
              {
               if(TP_Max<1) // Do we need to close all of the orders?
                  TypeOrder=OP_ALL;
               else
                  TypeOrder=OP_BUY;
               if(CloseOrders(Symbol(),TypeOrder))
                  ResetTS();
              }
            else                             // See if we need to move the TS line
            if((TS_BidLast-PipValue)>Ask) // Have we moved more than one pip?
            if((TS_Value-(4*PipValue))>Ask) // Are we more than 4 pips away?
              {
               TS_BidLast  =Ask;
               TS_Value=TS_Value-PipValue-PipValue;   // Move up 2 pips
               ObjectMove(0,TS_Name,0,Time[10],TS_Value);
               ObjectMove(0,TS_Name,1,Time[0],TS_Value);
               ChartRedraw(0);
              }
           }
         else                       // No Order to process
         ResetTS();
        }

      // Stop Loss Processing
      Index=SL_Max;
      while(Index>0) // Search for Stop Loss to close
        {
         Index--;                // Start at the back & go to zero
         if(ObjectFind(SL_Name[Index])<0) // Has this object been deleted?
           {
            Print("Not Found: "+IntegerToString(long(Index))+" "+SL_Name[Index]);
            DeleteSL(Index,false);
            continue;
           }
         CurrPriceLine=ObjectGetValueByShift(SL_Name[Index],0);
         if(openedBuy) // Looking for a sell to close Buy
           {
            if(CurrPriceLine>Bid) // Has the Bid crossed above our line?
              {
               if(SL_Max<=1) // Do we need to close all of the orders?
                  TypeOrder=OP_ALL;
               else
                  TypeOrder=OP_SELL;
               if(CloseOrders(Symbol(),TypeOrder))
                  DeleteSL(Index);
              }
           }
         else
         if(openedSell) // Looking for Buy to close Sell
           {
            if(CurrPriceLine<Ask) // Has the Bid crossed above our line?
              {
               if(SL_Max<=1) // Do we need to close all of the orders?
                  TypeOrder=OP_ALL;
               else
                  TypeOrder=OP_BUY;
               if(CloseOrders(Symbol(),TypeOrder))
                  DeleteSL(Index);
              }
           }
        }
     }
   comm=comm+"\n Buy Orders:  "+IntegerToString(long(Buy_Max),4);
   comm=comm+"\n Sell Orders: "+IntegerToString(long(Sell_Max),4);
   comm=comm+"\n Take Profit: "+IntegerToString(long(TP_Max),4);
   comm=comm+"\n Stop Loss:   "+IntegerToString(long(SL_Max),4);
   comm=comm+"\n Trailing Stop: "+DoubleToString(TS_Value,5);
   if(openedBuy)
      comm=comm+"\n In BUY mode, Orders ="+IntegerToString(long(Order_Buy_Count),4);
   if(openedSell)
      comm=comm+"\n In SELL mode, Orders ="+IntegerToString(long(Order_Sell_Count),4);

   Comment(comm);
//----
   return(0);
  }
//////////////////////////////////////////////////////////////////////////////////////////////////
bool OpenOrder(int orderType)
  {
   if(!IsTradeAllowed()) return(false);

   if(orderType==OP_BUY)
     {
      ticket=OrderSend(Symbol(),OP_BUY,lots,Ask,MaxSlippage,0,0,"",MagicNumber,0,clrGreen);
      if(ticket>0) // Did we create an order?
        {
         Order_Buy_Count++;
         return(true);        // Yes!
        }
     }
   else
   if(orderType==OP_SELL)
     {
      ticket=OrderSend(Symbol(),OP_SELL,lots,Bid,MaxSlippage,0,0,"",MagicNumber,0,clrRed);
      if(ticket>0) // Did we create an order?
        {
         Order_Sell_Count++;
         return(true);        // Yes!
        }
     }

   return(false);            // No order created
  }
// cmd = OP_ALL deletes all orders for this symbol
// cmd = OP_BUY or OP_SELL deletes only the oldest order.
// cmd = OP_BUY to close a sell
// cmd = OP_SELL to close a buy
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool CloseOrders(string symbol,int cmd)
  {
   int total=OrdersTotal();

   if(total<1)
     {
      Print("No orders to delete for ",symbol);
      Order_Buy_Count  = 0;
      Order_Sell_Count = 0;
      openedBuy        = false;
      openedSell       = false;
      return(false);
     }
   for(int pos=0; pos<total; pos++) // Start with oldest
     {
      if(!OrderSelect(pos,SELECT_BY_POS,MODE_TRADES)) continue;    // May not still be valid
      if(OrderSymbol()==symbol)                                    // Is this our trade?
        {
         while(IsTradeContextBusy()) Sleep(100);
         if((cmd==OP_SELL || cmd==OP_ALL) && OrderType()==OP_BUY) // Close One or All
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,MaxSlippage,Violet))
              {
               Print("Error closing "+OrderType()+" order : ",GetLastError());
               return (false);
              }
           }
         else
         if((cmd==OP_BUY || cmd==OP_ALL) && OrderType()==OP_SELL) // Close One or All
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,MaxSlippage,Violet))
              {
               Print("Error closing "+OrderType()+" order : ",GetLastError());
               return (false);
              }
           }
         if(cmd==OP_ALL && (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP || OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT))
            if(!OrderDelete(OrderTicket()))
              {
               Print("Error deleting "+OrderType()+" order : ",GetLastError());
               return (false);
              }
         if(cmd==OP_BUY || cmd==OP_SELL) break;     // Done deleting - exit loop
        }
     }
   CheckOpenOrders();
   return (true);
  }
//+------------------------------------------------------------------+

Comments