Drag and drop SL and TP in the tester. - page 12

 
Andrey Khatimlianskii:

Bragging? )

Either show the code or close the thread.

The code is scattered. Part of it is in the Expert Advisor, part of it is in the indicator. I will not post the entire Expert Advisor and indicator. If you are interested in a certain part, I can post it. Please refer to what you need.
 
khorosh:
The code is scattered. Part of it is in the Expert Advisor, part of it is in the indicator. I will not post the entire Expert Advisor and indicator. If you are interested in a certain part, I can lay it out. Please advise what exactly you need.

I just don't understand why you need to maintain a thread if your issue has already been resolved and the rest of us get nothing out of the discussion.

Suggested to add constructive )

 
Andrey Khatimlianskii:

I just don't understand why you need to maintain a thread if your issue has already been resolved and the rest of us get nothing out of the discussion.

Suggested to add some constructiveness )

Ok, you got it ) I'm posting everything about dragging and dropping SL. For TP, I have not done so far, not particularly need it yet. But it is not a problem to do it by analogy. I am pasting the indicator in its entirety. I have pulled everything concerning the dragging of SL from the EA. I have not studied the innovations of the language, I do many things the old-fashioned way, so do not judge.

Code of indicator:

//+------------------------------------------------------------------+
//|                                      Test_ChartXYToTimePrice.mq4 |
//|                        Copyright 2016, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "khorosh"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_chart_window
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
if(!GlobalVariableCheck(GetNameTF(Period())+" "+Symbol()+" ModifySL"))
  {  
   GlobalVariableSet(GetNameTF(Period())+" "+Symbol()+" ModifySL", 0.0);
  }
   ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,1);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---
   if(id==CHARTEVENT_MOUSE_MOVE && IsTesting())
     {
      if(MouseState((uint)sparam)=="DN")
        {
      //--- подготовим переменные
      int      x     =(int)lparam;
      int      y     =(int)dparam;
      datetime dt    =0;
      double   price =0;
      int      window=0;
      //--- преобразуем координаты X и Y  в терминах дата/время
      if(ChartXYToTimePrice(0,x,y,window,dt,price))
         //--- сделаем обратное преобразование: (X,Y) => (Time,Price)
         if(ChartTimePriceToXY(0,window,dt,price,x,y))
           {
            GlobalVariableSet(GetNameTF(Period())+" "+Symbol()+" ModifySL", StringToDouble(price));
           }   
         else
            Print("ChartTimePriceToXY return error code: ",GetLastError());
        }
      else
         Print("ChartXYToTimePrice return error code: ",GetLastError());
      Print("+--------------------------------------------------------------+");
    }
   if(MouseState((uint)sparam)=="UP") {GlobalVariableSet(GetNameTF(Period())+" "+Symbol()+" ModifySL", 0.0);} 
  }  
}
string MouseState(uint state) 
  { 
    string res; 
   res+=(((state& 1)== 1)?"DN":"UP");   // mouse left 
   return(res); 
  } 
 //+----------------------------------------------------------------------------+
//|  Возвращает наименование таймфрейма                                        |
//+----------------------------------------------------------------------------+
string GetNameTF(int TimeFrame) {
        switch (TimeFrame) {
                case PERIOD_M1:  return("M1");
                case PERIOD_M5:  return("M5");
                case PERIOD_M15: return("M15");
                case PERIOD_M30: return("M30");
                case PERIOD_H1:  return("H1");
                case PERIOD_H4:  return("H4");
                case PERIOD_D1:  return("Daily");
                case PERIOD_W1:  return("Weekly");
                case PERIOD_MN1: return("Monthly");
                default:                     return("UnknownPeriod");
        }
} 

Pieces from EA:

double PriceModifySL   = 0.0;
int TicketModifSlOrder = 0;
int StopLevel = 0;
void OnTick()
 {
//---
StopLevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
if(IsTesting()) {PriceModifySL = GlobalVariableGet(GetNameTF(Period())+" "+Symbol()+" ModifySL");}
else {PriceModifySL=0;}
if(PriceModifySL==0.0) {TicketModifSlOrder=0;}
if(IsTesting() && PriceModifySL>0.0001) {ModifYSL(PriceModifySL);}
 
//---
  }
//================================================================================================================================+
//                                                         ФУНКЦИИ                                                                |
//================================================================================================================================+
void ModifYSL(double priceModifySL=0)
 {
  double sl=0;
  if(TicketModifSlOrder==0)
    {  
     for(int i=0; i<OrdersTotal(); i++) 
      { 
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
         { 
          if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber) 
            {
             if(MathAbs(OrderStopLoss()-priceModifySL)<20*Point) 
               { 
                TicketModifSlOrder=OrderTicket(); break;
               }
            }
         }  
      }
    }
   if(TicketModifSlOrder==0)
     {
      for(int i=0; i<OrdersTotal(); i++) 
      { 
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
         { 
          if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber) 
            {
             if(MathAbs(OrderOpenPrice()-priceModifySL)<30*Point) 
               { 
                TicketModifSlOrder=OrderTicket(); break;
               }
            }
         }  
      }
     }     
   if(OrderSelect(TicketModifSlOrder, SELECT_BY_TICKET))
     {
      sl=priceModifySL;                                
      if(MathAbs(sl-Ask)>StopLevel*Point() && MathAbs(sl-Bid)>StopLevel*Point())
        { 
         ModifyOrder1(-1, sl, -1, 0);
        }           
     }
 }
//=================================================================================================================================
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 28.11.2006                                                     |
//|  Описание : Модификация одного предварительно выбранного ордера.           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    pp - цена установки ордера                                              |
//|    sl - ценовой уровень стопа                                              |
//|    tp - ценовой уровень тейка                                              |
//|    ex - дата истечения                                                     |
//+----------------------------------------------------------------------------+
void ModifyOrder1(double pp=-1, double sl=0, double tp=0, datetime ex=0) {
  bool   fm;
  color  cl=IIFc(OrderType()==OP_BUY
              || OrderType()==OP_BUYLIMIT
              || OrderType()==OP_BUYSTOP, clModifyBuy, clModifySell);
  double op, pa, pb, os, ot;
  int    dg=MarketInfo(OrderSymbol(), MODE_DIGITS), er, it;

  if (pp<=0) pp=OrderOpenPrice();
  if (sl<0 ) sl=OrderStopLoss();
  if (tp<0 ) tp=OrderTakeProfit();
  
  pp=NormalizeDouble(pp, dg);
  sl=NormalizeDouble(sl, dg);
  tp=NormalizeDouble(tp, dg);
  op=NormalizeDouble(OrderOpenPrice() , dg);
  os=NormalizeDouble(OrderStopLoss()  , dg);
  ot=NormalizeDouble(OrderTakeProfit(), dg);

  if (pp!=op || sl!=os || tp!=ot) {
    for (it=1; it<=NumberOfTry; it++) {
      if (!IsTesting() && (!IsExpertEnabled() || IsStopped())) break;
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      fm=OrderModify(OrderTicket(), pp, sl, tp, ex, cl);
      if (fm) {
        PlaySound("wait.wav"); break;
      } else {
        er=GetLastError();
        PlaySound("timeout.wav");
        pa=MarketInfo(OrderSymbol(), MODE_ASK);
        pb=MarketInfo(OrderSymbol(), MODE_BID);
        Print("Error(",er,") modifying order: ",ErrorDescription(er),", try ",it);
        Print("Ask=",pa,"  Bid=",pb,"  sy=",OrderSymbol(),
              "  op="+GetNameOP(OrderType()),"  pp=",pp,"  sl=",sl,"  tp=",tp);
        Sleep(1000*10);
      }
    }
  }
}
 
khorosh:

I haven't done a TP yet, I don't particularly need it yet.

That's why it's possible to pull the opening price up and put a SL in profit ;)

Thanks for the constructive feedback.

 
Andrey Khatimlianskii:

Hence the opportunity to pull the opening price up and put the SL in profit ;)

Thanks for the constructive feedback.

What does this have to do with takeprofit?
 
khorosh:
What does this have to do with takeprofit?
And how will we understand exactly what to modify when the same is added for TP?
 

You should also add one condition to the ModifYSL(double priceModifySL=0) function just in case. As they say, you can't spoil a lot of porridge with butter).

...
if(TicketModifSlOrder>0) // Вот это!!!
  {
   if(OrderSelect(TicketModifSlOrder, SELECT_BY_TICKET))
     {
      sl=priceModifySL;                                
      if(MathAbs(sl-Ask)>StopLevel*Point() && MathAbs(sl-Bid)>StopLevel*Point())
        { 
         ModifyOrder1(-1, sl, -1, 0);
        }           
     }
  }



 
khorosh:
We need to introduce another global variable to modify the TR. I called the global variable"ModifySL" for a reason. And then there's the GV "ModifyTP".
It's understandable. What I mean is this: if the order has no stop, we can drag the line of the order itself and the stop will be set where we "drag" the line to. This is the case if we don't have takeout processing. And if we have processing of both stops and toes, but the order has neither, then if we draw the order line, what should we set? A take or a stop?
 
Artyom Trishkin:
Yes, I can see that. What I mean is this: if the order has no stop, we can drag the line of the order itself, and the stop will be placed where we "drag" the line to. This is the case if we don't have takeout processing. And if we have processing of both stops and toes, but the order has neither, then if we draw the order line, what should we set? A Take or a Stop?
I see. Then we should either add buttons to set the modification type or use the method we have in the real chart. We should set the initial direction of order price movement to determine what should be taken by TP or SL. I did not think about it at first because it is of less importance to me and in my EA for manual testing of strategies, SL and TP are set immediately when placing orders. You have made a good point. Thank you, I will keep this in mind.
 
khorosh:
Got it. Then either make additional buttons to set the modification type, or do it the way it is done on the real chart. The initial direction of movement from the order price to determine what the TP or SL should pull.
Or we can combine it with keypad buttons ;)