//+------------------------------------------------------------------+ // ProjectName //…
- User
//+------------------------------------------------------------------+ //| ProjectName | //| Copyright 2020, CompanyName | //| http://www.companyname.net | //+------------------------------------------------------------------+ #include <Controls\Dialog.mqh> #include <Controls\Button.mqh> #include <Trade\PositionInfo.mqh> #include <Trade\Trade.mqh> #include <Trade\SymbolInfo.mqh> #include <Controls\Label.mqh>
#define INDENT_LEFT (11) #define INDENT_TOP (11) #define CONTROLS_GAP_X (5)
#define BUTTON_WIDTH (100) #define BUTTON_HEIGHT (20)
CPositionInfo m_position; CTrade m_trade; CSymbolInfo m_symbol;
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ class CAppWindowTwoButtons : public CAppDialog {
private: CButton m_button1; // the button object CButton m_button2; // the button object CLabel m_labelProfit;
public: CAppWindowTwoButtons(void); ~CAppWindowTwoButtons(void); //--- create virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2); //--- chart event handler virtual bool OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);
void UpdateProfitLabel(void);
protected: //--- create dependent controls bool CreateButton1(void); bool CreateButton2(void); bool CreateProfitLabel(void); //--- handlers of the dependent controls events void OnClickButton1(void); void OnClickButton2(void);
}; //+------------------------------------------------------------------+ //| Event Handling | //+------------------------------------------------------------------+ EVENT_MAP_BEGIN(CAppWindowTwoButtons) ON_EVENT(ON_CLICK,m_button1,OnClickButton1) ON_EVENT(ON_CLICK,m_button2,OnClickButton2) EVENT_MAP_END(CAppDialog) //+------------------------------------------------------------------+ //| Constructor | //+------------------------------------------------------------------+ CAppWindowTwoButtons::CAppWindowTwoButtons(void) { } //+------------------------------------------------------------------+ //| Destructor | //+------------------------------------------------------------------+ CAppWindowTwoButtons::~CAppWindowTwoButtons(void) { } //+------------------------------------------------------------------+ //| Create | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2) { if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2)) return(false); //--- create dependent controls if(!CreateButton1()) return(false); if(!CreateButton2()) return(false); if(!CreateProfitLabel()) return(false); //--- succeed return(true); } //+------------------------------------------------------------------+ //| Global Variable | //+------------------------------------------------------------------+ CAppWindowTwoButtons ExtDialog; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateProfitLabel(void) { int x1=INDENT_LEFT; int y1=INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X; int x2=x1+BUTTON_WIDTH*2+CONTROLS_GAP_X; // длина метки может быть больше, чтобы вместить текст int y2=y1+BUTTON_HEIGHT;
if(!m_labelProfit.Create(0, "LabelProfit", 0, x1, y1, x2, y2)) return(false);
m_labelProfit.FontSize(10); m_labelProfit.Text("Текущая прибыль: 0");
if(!Add(m_labelProfit)) return(false);
return(true); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateButton1(void) { //--- coordinates int x1=INDENT_LEFT; // x1 = 11 pixels int y1=INDENT_TOP; // y1 = 11 pixels int x2=x1+BUTTON_WIDTH; // x2 = 11 + 100 = 111 pixels int y2=y1+BUTTON_HEIGHT; // y2 = 11 + 20 = 32 pixels //--- create if(!m_button1.Create(0,"Button1",0,x1,y1,x2,y2)) return(false); if(!m_button1.Text("Закрыть sell")) return(false); if(!Add(m_button1)) return(false);
//--- succeed return(true); } //+------------------------------------------------------------------+ //| Create the "Button2" | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateButton2(void) { //--- coordinates int x1=INDENT_LEFT+120; // x1 = 11 + 2 * (100 + 5) = 221 pixels int y1=INDENT_TOP; // y1 = 11 pixels int x2=x1+BUTTON_WIDTH; // x2 = 221 + 100 = 321 pixels int y2=y1+BUTTON_HEIGHT; // y2 = 11 + 20 = 31 pixels //--- create if(!m_button2.Create(0,"Button2",0,x1,y1,x2,y2)) return(false); if(!m_button2.Text("Закрыть buy")) return(false); if(!Add(m_button2)) return(false); //--- succeed return(true); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::UpdateProfitLabel(void) { // Вычисляем текущую прибыль со всех открытых позиций double profit = CalculateTotalProfit(); double TrueProfit = profit - g_initialProfit + g_closedTradesProfit + profitCloseSell + profitCloseBuy;
// Обновляем текст метки с прибылью string profitText = StringFormat("Profit: %.2f", TrueProfit); m_labelProfit.Text(profitText); }
input double BelowCurrentPriceLevel = 1.0809; // Уровень ниже текущей цены для алерта input double AboveCurrentPriceLevel = 2; // Уровень выше текущей цены для алерта input int PipsToChange = 5; // Количество пунктов изменения цены input double InitialLots = 0.1; // Количество лотов для начальной сделки input double LotChangePercent = 10.0; // Процент изменения количества лотов input ENUM_TIMEFRAMES TimeFrame = PERIOD_H1;
double profitCloseSell = 0.0; double profitCloseBuy = 0.0; double g_closedTradesProfit = 0.0; double g_initialProfit = 0.0; double currentLots = InitialLots; // Текущее количество лотов double lastPrice; // Последняя цена для отслеживания изменения на N пунктов bool belowLevelAlerted = false; // Флаг отправки алерта для нижнего уровня bool aboveLevelAlerted = false; // Флаг отправки алерта для верхнего уровня
datetime lastBarTime = 0;
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double CalculateTotalProfit() { double totalProfit = 0.0; for(int i = PositionsTotal() - 1; i >= 0; i--) { if(m_position.SelectByIndex(i)) { totalProfit += m_position.Profit(); } } return totalProfit; }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int OnInit() {
g_initialProfit = CalculateTotalProfit();
if(!ExtDialog.Create(0,"Закрытие позиций",0,15,100,270,220)) return(INIT_FAILED); //--- run application ExtDialog.Run();
MqlRates rates[]; if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0) { lastBarTime = rates[0].time; } else { Print("Ошибка при получении информации о барах: ", GetLastError()); return (INIT_FAILED); }
OpenOrder(ORDER_TYPE_BUY, currentLots, "B"); OpenOrder(ORDER_TYPE_SELL, currentLots, "S");
ObjectCreate(0,"Линия поддержки",OBJ_HLINE,0,0,BelowCurrentPriceLevel); ObjectSetInteger(0, "Линия поддержки", OBJPROP_COLOR, clrBlue); ObjectCreate(0,"Линия сопротивления",OBJ_HLINE,0,0,AboveCurrentPriceLevel);
lastPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);; return(INIT_SUCCEEDED); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- Comment(""); //--- destroy dialog ExtDialog.Destroy(reason);
ObjectDelete(0,"Линия поддержки"); ObjectDelete(0,"Линия сопротивления"); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnChartEvent(const int id, // event ID const long& lparam, // event parameter of the long type const double& dparam, // event parameter of the double type const string& sparam) // event parameter of the string type { ExtDialog.ChartEvent(id,lparam,dparam,sparam); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double NormalizeLot(double lot, double min_lot, double max_lot, double lot_step) { // Округление до ближайшего допустимого значения lot = MathMax(min_lot, lot); lot -= fmod(lot - min_lot, lot_step); lot = MathMin(max_lot, lot); return NormalizeDouble(lot, _Digits); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CalculateAndSetLotSize() { double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
// Увеличение текущего размера лота на заданный процент currentLots *= (1 + LotChangePercent / 100.0);
// Округление до ближайшего допустимого значения currentLots = NormalizeLot(currentLots, min_lot, max_lot, lot_step); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::OnClickButton1(void) { Print("Button 1 clicked!");
for(int i=PositionsTotal()-1; i>=0; i--) {
Print(i); string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue; if(m_position.SelectByIndex(i)) Print(m_position.PositionType()); if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_SELL) continue; profitCloseSell += m_position.Profit(); m_trade.PositionClose(PositionGetInteger(POSITION_TICKET)); }}
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::OnClickButton2(void) { Print("Button 2 clicked!"); int totalPositions = PositionsTotal(); for(int i = totalPositions - 1; i >= 0; i--) { string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue;
if(m_position.SelectByIndex(i)) Print(m_position.PositionType()); if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_BUY) continue; profitCloseBuy += m_position.Profit(); m_trade.PositionClose(PositionGetInteger(POSITION_TICKET)); }}
#property indicator_chart_window #property indicator_color1 Pink //±-----------------------------------------------------------------+ //| Expert tick function | //±-----------------------------------------------------------------+ void OnTick() { ExtDialog.UpdateProfitLabel();
double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// Отправляем алерты при достижении указанных уровней if(!belowLevelAlerted && bidPrice <= BelowCurrentPriceLevel) { Alert("Цена достигла уровня BelowCurrentPriceLevel"); belowLevelAlerted = true; // Отмечаем, что алерт был отправлен }
if(!aboveLevelAlerted && askPrice >= AboveCurrentPriceLevel) { Alert("Цена достигла уровня AboveCurrentPriceLevel"); aboveLevelAlerted = true; // Отмечаем, что алерт был отправлен }
datetime currentTime = TimeCurrent(); // Текущее время сервера MqlRates rates[]; if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0) // Получаем последний бар для H1 { datetime newBarTime = rates[0].time; // Время начала последнего бара
if(newBarTime != lastBarTime) { if(MathAbs(bidPrice - lastPrice) > PipsToChange * _Point) { // Подсчитаем новый размер лота CalculateAndSetLotSize(); lastPrice = bidPrice; // Обновление последней цены // Открываем новые ордера с новым размером лота OpenOrder(ORDER_TYPE_BUY, currentLots, "B"); OpenOrder(ORDER_TYPE_SELL, currentLots, "S"); } lastBarTime = newBarTime; // Обновляем время начала последнего бара } }}
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OpenOrder(ENUM_ORDER_TYPE type, double lots, string orderMagic) {
MqlTradeRequest request = {}; MqlTradeResult result = {};
// Заполнение полей структуры запроса на сделку request.action = TRADE_ACTION_DEAL; request.symbol = _Symbol; request.volume = lots; request.type = type; request.sl = 0.0; // Уровень стоп-лосс не задан request.tp = 0.0; // Уровень тейк-профит не задан request.deviation = 0; request.magic = StringToInteger(orderMagic + IntegerToString(GetTickCount()));
//request.comment = "Auto trade order";
if(type == ORDER_TYPE_BUY) request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); else if(type == ORDER_TYPE_SELL) request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(!OrderSend(request,result)) PrintFormat("OrderSend error %d",GetLastError()); // Попытка отправить торговый запрос } //+------------------------------------------------------------------+ у меня есть такая программа но почему она не всегда отправляет ордер?
- Assistant
Ваша программа использует MQL5, язык программирования используемый для разработки скриптов, индикаторов, советников и утилит для платформы MetaTrader 5. Функция
OrderSendявляется основной функцией для отправки торговых запросов в терминале MetaTrader. Если функцияOrderSendне отправляет ордер (заявку на сделку), это может происходить по нескольким причинам:-
Неверные параметры запроса: Проверьте все поля структуры
MqlTradeRequestперед отправкой. Это включает проверку правильностиsymbol,volumeиprice. -
Неверный тип ордера для текущих условий рынка: Например, попытка купить выше рыночной цены или продать ниже рыночной цены с типом
TRADE_ACTION_DEALне пройдет для маркет-ордеров. -
Слиппаж (расхождение цен): Параметр
deviationопределяет максимально допустимое отклонение от запрашиваемой цены. Если рыночная цена отклоняется за это время больше, чем разрешено отклонением, сделка может быть отклонена. -
Настройки терминала или счета: Некоторые счета могут иметь ограничения на торговлю, такие как допустимые объемы торгов, минимальное расстояние до текущей цены для ордеров stop-loss и take-profit, разрешенные временные рамки и т.д.
-
Технические проблемы с подключением на сервер: Проверьте, подключен ли терминал к серверу брокера и достаточно ли у вас сетевого соединения.
-
Нехватка средств: У торгового счета могут не хватить средств для открытия новой позиции.
-
Ошибки в исполнении запроса на сервере брокера: Сервер может отклонить заказы по своим собственным правилам.
Чтобы понять, почему не отправлен ордер, нужно логировать ошибки. Уже имеется строка кода для этого:
if(!OrderSend(request,result)) PrintFormat("OrderSend error %d", GetLastError());Тем не менее, лучше использовать более подробное логирование, которое также покажет значения параметров, с которыми была сделана попытка отправить ордер. Например:
if(!OrderSend(request, result)) { Print("OrderSend failed with error #", GetLastError()); Print("Details: symbol=", request.symbol, ", volume=", request.volume, ", type=", (request.type==ORDER_TYPE_BUY?"BUY":"SELL"), ", price=", request.price); }Иногда причину отказа могут прояснить дополнительные детали из структуры
MqlTradeResult, напримерresult.commentилиresult.retcode.Всегда стоит проверять код на наличие возможных ошибок и быть готовым к обработке любых исключительных ситуаций, связанных с отправкой торговых запросов.
-