//+------------------------------------------------------------------+ //| SPH45 TP-SL Synchronizer Script.mq4 | //| Copyright © 2010, David Moser | //| http://www.ForexMT4.com/mt_yahoo/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2010, David Moser" #property link "http://www.ForexMT4.com/mt_yahoo/" #property show_inputs #include #include extern int MagicNumber= 222777; int myDigits; //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { //---- myDigits=MarketInfo(Symbol(),MODE_DIGITS); double BuyTP = CalcTakeProfit(OP_BUY); double BuySL = CalcStopLoss(OP_BUY); double SellTP = CalcTakeProfit(OP_SELL); double SellSL = CalcStopLoss(OP_SELL); if (BuyTP != 0 && BuySL !=0) ModifyOrders(BuyTP, BuySL, OP_BUY); if (SellTP != 0 && SellSL !=0) ModifyOrders(SellTP, SellSL, OP_SELL); //---- return(0); } //+------------------------------------------------------------------+ void ModifyOrders(double newTP, double newSL, int op) { int cnt=0, err=0; bool result; int OrderCount=0; int TicketArray[100]; // first, we retrieve all ticket IDs for existing orders to modify for(cnt = 0; cnt < OrdersTotal(); cnt++) { if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && op==OrderType()) { TicketArray[OrderCount]=OrderTicket(); OrderCount++; } } } // second, if there is more than 1 order, then we will modify orders, otherwise no need if (OrderCount>1) for(cnt=0;cnt 1) Print("LastError = (", err, "): ", ErrorDescription(err)); else OrderPrint(); } } } } double CalcStopLoss(int op) { int ticket; double HighestBuy, LowestSell; double HighestBuySL, LowestSellSL; double newSL; //---- HighestBuy = 0; LowestSell = 9999; HighestBuySL = 0; LowestSellSL = 0; newSL = 0; for(int i=0;i HighestBuy) { HighestBuy = OrderOpenPrice(); HighestBuySL = OrderStopLoss(); } } if (op == OP_SELL && OrderType() == OP_SELL) { if (OrderOpenPrice() < LowestSell) { LowestSell = OrderOpenPrice(); LowestSellSL = OrderStopLoss(); } } } switch (op) { case OP_BUY: newSL = HighestBuySL; break; case OP_SELL: newSL = LowestSellSL; break; default: break; } return (newSL); } double CalcTakeProfit(int op) { int ticket; double LowestBuy, HighestSell; double LowestBuyTP, HighestSellTP; double newTP; //---- LowestBuy = 9999; HighestSell = 0; LowestBuyTP = 0; HighestSellTP = 0; newTP = 0; for(int i=0;i HighestSell) { HighestSell = OrderOpenPrice(); HighestSellTP = OrderTakeProfit(); } } } switch (op) { case OP_BUY: newTP = LowestBuyTP; break; case OP_SELL: newTP = HighestSellTP; break; default: break; } return (newTP); } bool GetTradeContext() { bool hadToWait=false; while(!IsTradeAllowed()) { Sleep(5000); hadToWait=true; } while(IsTradeContextBusy()) { Sleep(200); hadToWait=true; } return(hadToWait); }