В конце концов, я нашел "OBJ_RECTANGLE и OBJ_TEXT ", которые, как мне кажется, я могу использовать вместо " OBJ_LABEL и OBJ_RECTANGLE_LABEL ", которые оба перемещают вместе линию предложения.
Вопрос: Итак, какие объекты очень полезны для перемещения вместе линии предложения, пожалуйста?
Мне очень нужен информативный комментарий. Хороших выходных.
Если вы не тестируете спарэм дальше, этот код срабатывает, когда любой объект перетаскивается.
Мой оригинальный код:
voidOnChartEvent(constint id, constlong& lparam, constdouble& dparam, conststring& sparam) { if(id==CHARTEVENT_OBJECT_DRAG&& sparam=="line") // the chart event of dragging the line
Я уже знаю / читал ваш один из замечательных примеров CrossHair.mq4. Но я борюсь, чтобы дать цену предложения в Label, RectLabel Objects. То есть я пытаюсь, чтобы Label, RectLabel Objects двигались вместе с Bid Line.
Мне нужно только изображение, пожалуйста, найдите прикрепленный файл.
Для объектов фиксированного размера: OBJ_BUTTON, OBJ_RECTANGLE_LABEL и OBJ_EDIT, свойства OBJPROP_XDISTANCE и OBJPROP_YDISTANCE задают положение левой верхней точки объекта относительно угла графика (OBJPROP_CORNER), от которого будут отсчитываться координаты X и Y в пикселях.
} //+------------------------------------------------------------------+ //| Create rectangle by the given coordinates | //+------------------------------------------------------------------+ bool RectangleCreate(constlong chart_ID=0, // chart's ID conststring name="Rectangle", // rectangle name constint sub_window=0, // subwindow index datetime time1=0, // first point time double price1=0, // first point price datetime time2=0, // second point time double price2=0, // second point price constcolor clr=clrRed, // rectangle color constENUM_LINE_STYLE style=STYLE_SOLID, // style of rectangle lines constint width=1, // width of rectangle lines constbool fill=false, // filling rectangle with color constbool back=false, // in the background constbool selection=true, // highlight to move constbool hidden=true, // hidden in the object list constlong z_order=0) // priority for mouse click { //--- set anchor points' coordinates if they are not set ChangeRectangleEmptyPoints(time1,price1,time2,price2); //--- reset the error value ResetLastError(); //--- create a rectangle by the given coordinates if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE,sub_window,time1,price1,time2,price2)) { Print(__FUNCTION__, ": failed to create a rectangle! Error code = ",GetLastError()); return(false); } //--- set rectangle color ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr); //--- set the style of rectangle lines ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style); //--- set width of the rectangle lines ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width); //--- display in the foreground (false) or background (true) ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back); //--- enable (true) or disable (false) the mode of highlighting the rectangle for moving //--- when creating a graphical object using ObjectCreate function, the object cannot be //--- highlighted and moved by default. Inside this method, selection parameter //--- is true by default making it possible to highlight and move the object ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection); ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection); //--- hide (true) or display (false) graphical object name in the object list ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden); //--- set the priority for receiving the event of a mouse click in the chart ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order); //--- successful execution return(true); } //+------------------------------------------------------------------+ //| Move the rectangle anchor point | //+------------------------------------------------------------------+ bool RectanglePointChange(constlong chart_ID=0, // chart's ID conststring name="Rectangle", // rectangle name constint point_index=0, // anchor point index datetime time=0, // anchor point time coordinate double price=0) // anchor point price coordinate { //--- if point position is not set, move it to the current bar having Bid price if(!time) time=TimeCurrent(); if(!price) price=SymbolInfoDouble(Symbol(),SYMBOL_BID); //--- reset the error value ResetLastError(); //--- move the anchor point if(!ObjectMove(chart_ID,name,point_index,time,price)) { Print(__FUNCTION__, ": failed to move the anchor point! Error code = ",GetLastError()); return(false); } //--- successful execution return(true); } //+------------------------------------------------------------------+ //| Check the values of rectangle's anchor points and set default | //| values for empty ones | //+------------------------------------------------------------------+ void ChangeRectangleEmptyPoints(datetime &time1,double &price1, datetime &time2,double &price2) { //--- if the first point's time is not set, it will be on the current bar if(!time1) time1=TimeCurrent(); //--- if the first point's price is not set, it will have Bid value if(!price1) price1=SymbolInfoDouble(Symbol(),SYMBOL_BID); //--- if the second point's time is not set, it is located 9 bars left from the second one if(!time2) { //--- array for receiving the open time of the last 10 bars datetime temp[10]; CopyTime(Symbol(),Period(),time1,10,temp); //--- set the second point 9 bars left from the first one time2=temp[0]; } //--- if the second point's price is not set, move it 300 points lower than the first one if(!price2) price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT); } //+------------------------------------------------------------------+
Если вы не тестируете спарэм дальше, этот код срабатывает, когда любой объект перетаскивается. Мой оригинальный код:
voidOnChartEvent(constint id, constlong& lparam, constdouble& dparam, conststring& sparam) { if(id==CHARTEVENT_OBJECT_DRAG&& sparam=="line") // the chart event of dragging the line
Я уже пробовал нижеприведенный код.
if(id==CHARTEVENT_OBJECT_DRAG && sparam=="#"+IntegerToString(OrderTicket())+"-TP") { // here was my functions }
Это не было ответом мне.
---
Но я использую код, приведенный ниже, который я немного изменил в соответствии с вашим кодом - и он отлично работает, что я и хотел. До сих пор я не сталкивался ни с какой проблемой. Может я делаю что-то не так, пожалуйста?
Для авторизации и пользования сайтом MQL5.com необходимо разрешить использование файлов Сookie.
Пожалуйста, включите в вашем браузере данную настройку, иначе вы не сможете авторизоваться.
Вы вошли в аккаунт. Двухфакторная аутентификация отключена. Настройте её заново и отсканируйте новый QR-код или продолжите с отключённой двухфакторной аутентификацией.
Я пытаюсь после завершения перетаскиванияOBJPROP_SELECTED сделать "false" с помощью нижеприведенного кода, никаких эффектов.
Как я могу решить эту проблему, пожалуйста?
{
SL_TPdrags();
Sleep(1000);
drag_onoff=false; // OBJPROP_SELECTED
}
Заранее спасибо.
Извините, я никогда не использовал CHARTEVENT_OBJECT_DRAG.
В конце концов, я нашел "OBJ_RECTANGLE и OBJ_TEXT ", которые, как мне кажется, я могу использовать вместо " OBJ_LABEL и OBJ_RECTANGLE_LABEL ", которые оба перемещают вместе линию предложения.
Вопрос: Итак, какие объекты очень полезны для перемещения вместе линии предложения, пожалуйста?
Мне очень нужен информативный комментарий.
Хороших выходных.
ID
Описание
OBJ_VLINE
Вертикальная линия
OBJ_HLINE
Горизонтальная линия
OBJ_TREND
Линия тренда
OBJ_TRENDBYANGLE
Линия тренда под углом
OBJ_CYCLES
Линии циклов
OBJ_ARROWED_LINE
Стреловидная линия
OBJ_CHANNEL
Эквидистантный канал
OBJ_STDDEVCHANNEL
Канал стандартного отклонения
OBJ_REGRESSION
Канал линейной регрессии
OBJ_PITCHFORK
Вилы Эндрюса
OBJ_GANNLINE
Линия Ганна
OBJ_GANNFAN
Веер Ганна
OBJ_GANNGRID
Сетка Ганна
OBJ_FIBO
Ретрейсмент Фибоначчи
OBJ_FIBOTIMES
Временные зоны Фибоначчи
OBJ_FIBOFAN
Веер Фибоначчи
OBJ_FIBOARC
Дуги Фибоначчи
OBJ_FIBOCHANNEL
Канал Фибоначчи
OBJ_EXPANSION
Расширение Фибоначчи
OBJ_ELLIOTWAVE5
Волна Эллиотта
OBJ_ELLIOTWAVE3
Коррекционная волна Эллиотта
OBJ_RECTANGLE
Прямоугольник
OBJ_TRIANGLE
Треугольник
OBJ_ELLIPSE
Эллипс
OBJ_ARROW_THUMB_UP
Пальцы вверх
OBJ_ARROW_THUMB_DOWN
Пальцы вниз
OBJ_ARROW_UP
Стрелка вверх
OBJ_ARROW_DOWN
Стрелка вниз
OBJ_ARROW_STOP
Знак остановки
OBJ_ARROW_CHECK
Знак чека
OBJ_ARROW_LEFT_PRICE
Левая наклейка с ценой
OBJ_ARROW_RIGHT_PRICE
Ярлык правой цены
OBJ_ARROW_BUY
Знак покупки
OBJ_ARROW_SELL
Знак продажи
OBJ_ARROW
Стрелка
OBJ_TEXT
Текст
OBJ_LABEL
Ярлык
OBJ_BUTTON
Кнопка
OBJ_CHART
Диаграмма
OBJ_BITMAP
Битовая карта
OBJ_BITMAP_LABEL
Ярлык растровой карты
OBJ_EDIT
Редактирование
OBJ_EVENT
Объект "Событие", соответствующий событию в экономическом календаре
OBJ_RECTANGLE_LABEL
Объект "Прямоугольная метка" для создания и оформления пользовательского графического интерфейса.
Что вы имели в виду под словом "двигаться вместе"?
Я пытаюсь после завершения перетаскиванияOBJPROP_SELECTED сделать "false" с помощью нижеприведенного кода, никаких эффектов.
Как я могу решить эту проблему, пожалуйста?
{
SL_TPdrags();
Sleep(1000);
drag_onoff=false; // OBJPROP_SELECTED
}
Заранее спасибо.
Если вы не тестируете спарэм дальше, этот код срабатывает, когда любой объект перетаскивается.
Мой оригинальный код:
{
if(id==CHARTEVENT_OBJECT_DRAG && sparam=="line") // the chart event of dragging the line
Я уже знаю / читал ваш один из замечательных примеров CrossHair.mq4.
Но я борюсь, чтобы дать цену предложения в Label, RectLabel Objects. То есть я пытаюсь, чтобы Label, RectLabel Objects двигались вместе с Bid Line.
Мне нужно только изображение, пожалуйста, найдите прикрепленный файл.
Всего наилучшего.
Для объектов фиксированного размера: OBJ_BUTTON, OBJ_RECTANGLE_LABEL и OBJ_EDIT, свойства OBJPROP_XDISTANCE и OBJPROP_YDISTANCE задают положение левой верхней точки объекта относительно угла графика (OBJPROP_CORNER), от которого будут отсчитываться координаты X и Y в пикселях.
//| rectangle.mq4 |
//| Copyright 2017, Marco vd Heijden, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, Marco vd Heijden, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create timer
EventSetTimer(1);
//--- create rectangle
RectangleCreate(0,"Rectangle",0,0,0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- destroy timer
EventKillTimer();
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
RectanglePointChange(0,"Rectangle",0,TimeCurrent(),Ask);
}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void OnTimer()
{
//---
}
//+------------------------------------------------------------------+
//| Create rectangle by the given coordinates |
//+------------------------------------------------------------------+
bool RectangleCreate(const long chart_ID=0, // chart's ID
const string name="Rectangle", // rectangle name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // rectangle color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of rectangle lines
const int width=1, // width of rectangle lines
const bool fill=false, // filling rectangle with color
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeRectangleEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a rectangle by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create a rectangle! Error code = ",GetLastError());
return(false);
}
//--- set rectangle color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the style of rectangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the rectangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the rectangle for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the rectangle anchor point |
//+------------------------------------------------------------------+
bool RectanglePointChange(const long chart_ID=0, // chart's ID
const string name="Rectangle", // rectangle name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of rectangle's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeRectangleEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the second one
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first one
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
Если вы не тестируете спарэм дальше, этот код срабатывает, когда любой объект перетаскивается.
Мой оригинальный код:
{
if(id==CHARTEVENT_OBJECT_DRAG && sparam=="line") // the chart event of dragging the line
{
// here was my functions
}
Это не было ответом мне.
---
Но я использую код, приведенный ниже, который я немного изменил в соответствии с вашим кодом - и он отлично работает, что я и хотел. До сих пор я не сталкивался ни с какой проблемой.
Может я делаю что-то не так, пожалуйста?
Всего наилучшего.
Возможно, это поможет.
Добавьте это на график и вы увидите:
#property indicator_chart_window
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
ObjectCreate(0,"MyLine",OBJ_HLINE,0,0,Bid);
ObjectSetInteger(0,"MyLine",OBJPROP_SELECTED,true);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ObjectDelete(0,"MyLine");
}
//+------------------------------------------------------------------+
//| OnChartEvent() |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long& lparam,
const double& dparam,
const string& sparam)
{
if(id==CHARTEVENT_OBJECT_DRAG && sparam=="MyLine")
{
double price=ObjectGetDouble(0,"MyLine",OBJPROP_PRICE,0);
Alert("MyLine moved! New price is " + DoubleToStr(price,_Digits));
}
}
//+------------------------------------------------------------------+
//| 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(rates_total);
}