//+------------------------------------------------------------------+ // bestexauto.mq5…
- User
//+------------------------------------------------------------------+ //| best_ex_auto.mq5 | //| Copyright 2024, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00"
const string ID = "-1002113042792"; const string token = "6853490040:AAH2AcCjJ1MVRziJ7BPmM6WveuOi0DBZ6so"; const string IDToLicense = "-1002100526472"; const string IDToTest = "-1002073319919";
int Case;
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- //sendMessage(ID,token); //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //---
} //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- sendMessage(ID,token);
} //+------------------------------------------------------------------+
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void sendMessage(string chatID, string botToken) { string baseUrl = "https://api.telegram.org"; string headers = ""; string requestURL = ""; string requestHeaders = ""; char resultData[]; char posData[]; int timeout = 200;
string result[]; string sep = ","; ushort sep_u = StringGetCharacter(sep,0); string searchPattern = ("text");
string sep2 = " "; ushort sep2_u = StringGetCharacter(sep2,0); string result2[];
requestURL = StringFormat("%s/bot%s/getUpdates?chat_id=%s&offset=-1",baseUrl,botToken,chatID); int response = WebRequest("GET",requestURL,headers,timeout,posData,resultData,requestHeaders);
string resultMessage = CharArrayToString(resultData);
int k = (StringSplit(resultMessage,sep_u,result));
if(k>0) { for(int i=0; i<k; i++) {
if(StringFind(result[i], searchPattern) >= 0) { string res = StringSubstr(result[i],8,StringLen(result[i])); int z = StringSplit(res,sep2_u,result2); Case = (int)result2[1]; Print(Case); } } }if(Case == 1) {
}
if(Case == 2) {} if(Case == 3) {
} if(Case == 4) {
} if(Case == 5) {
} if(Case == 6) {
} } //+------------------------------------------------------------------+ //| 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> #include <Controls\Edit.mqh>
const string ID = "-1002113042792"; const string token = "7152618530:AAGJJC3zdkmCce3B7i11Dn2JDMh7GqpamyM"; const string IDToLicense = "-1002100526472";
#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; CLabel m_labelPipsToChange; // Метка для значения PipsToChange CEdit m_editPipsToChange; CLabel m_labelPipsToDownChange; // Метка для значения PipsToChange CLabel m_labelPipsToDownChange2; CEdit m_editPipsToDownChange;
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ class CAppWindowTwoButtons : public CAppDialog {
private: CButton m_button1; // the button object CButton m_button2; // the button object CLabel m_labelProfit; CLabel m_labelLots; CLabel m_labelProfitSell; CLabel m_labelProfitBuy; CLabel m_labelProfitPerc;
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); void UpdateLabelLots(void); void UpdateProfitSell(void); void UpdateProfitBuy(void); void OnPipsToChangeEdit(void); bool CreatePipsToChangeControls(void); void OnPipsToDownChangeEdit(void); bool CreatePipsToDownChangeControls(void); void UpdateProfitLabelPerc(void);
//--- create dependent controls bool CreateButton1(void); bool CreateButton2(void); bool CreateProfitLabel(void); bool CreateLabelLots(void); bool CreateProfitSell(void); bool CreateProfitBuy(void); bool CreateProfitLabelPerc(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) ON_EVENT(ON_CHANGE,m_editPipsToChange,OnPipsToChangeEdit) ON_EVENT(ON_CHANGE,m_editPipsToDownChange,OnPipsToDownChangeEdit) ON_EVENT(ON_CHANGE,m_editPipsToChange,OnPipsToChangeEdit) 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() || !CreateButton2() || !CreateProfitLabel() || !CreatePipsToChangeControls() || !CreatePipsToDownChangeControls() || !CreateLabelLots() || !CreateProfitSell() || !CreateProfitBuy() || !CreateProfitLabelPerc()) return(false); //--- succeed return(true); }
//+------------------------------------------------------------------+ //| Global Variable | //+------------------------------------------------------------------+ CAppWindowTwoButtons ExtDialog;
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateProfitLabelPerc(void) { int x1=INDENT_LEFT+150; int y1=INDENT_TOP+165; int x2=x1+INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X; // длина метки может быть больше, чтобы вместить текст int y2=y1+BUTTON_HEIGHT;
if(!m_labelProfitPerc.Create(0, "LabelProfitPerc", 0, x1, y1, x2, y2)) return(false);
double profit = CalculateTotalProfit(); double TrueProfit = profit - g_initialProfit + profitCloseSell + profitCloseBuy;
TrueProfit = NormalizeDouble(((TrueProfit * 100) / AccountInfoDouble(ACCOUNT_BALANCE)),_Digits);
// Обновляем текст метки с прибылью string profitText = StringFormat("Прибыль в процентах: %.2f", TrueProfit); m_labelProfitPerc.Text(profitText);
if(!Add(m_labelProfitPerc)) return(false);
return(true); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::UpdateProfitLabelPerc(void) { // Вычисляем текущую прибыль со всех открытых позиций double profit = CalculateTotalProfit(); double TrueProfit = profit - g_initialProfit + profitCloseSell + profitCloseBuy;
TrueProfit = NormalizeDouble(((TrueProfit * 100) / AccountInfoDouble(ACCOUNT_BALANCE)),_Digits);
// Обновляем текст метки с прибылью string profitText = StringFormat("Прибыль в процентах: %.2f", TrueProfit); m_labelProfitPerc.Text(profitText); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateProfitSell(void) { int x1=INDENT_LEFT; int y1=INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X+5; int x2=x1+INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X; // длина метки может быть больше, чтобы вместить текст int y2=y1+BUTTON_HEIGHT+10;
if(!m_labelProfitSell.Create(0, "Label lots Sell", 0, x1, y1, x2, y2)) return(false);
double profitSell = 0; for(int i=PositionsTotal()-1; i>=0; i--) {
string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue; if(m_position.SelectByIndex(i)) if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_SELL) continue; profitSell += m_position.Profit(); }string ProfitSellText = StringFormat("Прибыль по sell: %.2f", profitSell); m_labelProfitSell.Text(ProfitSellText);
if(!Add(m_labelProfitSell)) return(false);
return(true); }
////+------------------------------------------------------------------+ ////| | // ////+------------------------------------------------------------------+ void CAppWindowTwoButtons::UpdateProfitSell(void) { double profitSell = 0; for(int i=PositionsTotal()-1; i>=0; i--) {
string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue; if(m_position.SelectByIndex(i)) if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_SELL) continue; profitSell += m_position.Profit(); }string ProfitSellText = StringFormat("Прибыль по sell: %.2f", profitSell + profitCloseSell); m_labelProfitSell.Text(ProfitSellText); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateProfitBuy(void) { int x1=INDENT_LEFT+190; int y1=INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X+5; int x2=x1+INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X; // длина метки может быть больше, чтобы вместить текст int y2=y1+BUTTON_HEIGHT+10;
if(!m_labelProfitBuy.Create(0, "Label lots Buy", 0, x1, y1, x2, y2)) return(false);
double profitBuy = 0; for(int i=PositionsTotal()-1; i>=0; i--) {
string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue; if(m_position.SelectByIndex(i)) if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_BUY) continue; profitBuy += m_position.Profit(); }string ProfitBuyText = StringFormat("Прибыль по buy: %.2f", profitBuy); m_labelProfitBuy.Text(ProfitBuyText);
if(!Add(m_labelProfitBuy)) return(false);
return(true); }
////+------------------------------------------------------------------+ ////| | // ////+------------------------------------------------------------------+ void CAppWindowTwoButtons::UpdateProfitBuy(void) { double profitBuy = 0; for(int i=PositionsTotal()-1; i>=0; i--) {
string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue; if(m_position.SelectByIndex(i)) if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_BUY) continue; profitBuy += m_position.Profit(); }string ProfitBuyText = StringFormat("Прибыль по buy: %.2f", profitBuy + profitCloseBuy); m_labelProfitBuy.Text(ProfitBuyText); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateLabelLots(void) { int x1=INDENT_LEFT; int y1=INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X+150; int x2=x1+INDENT_TOP+BUTTON_HEIGHT+CONTROLS_GAP_X; // длина метки может быть больше, чтобы вместить текст int y2=y1+BUTTON_HEIGHT+10;
if(!m_labelLots.Create(0, "Label lots", 0, x1, y1, x2, y2)) return(false);
double totalLots = 0.0; for(int i = PositionsTotal() - 1; i >= 0; i--) { if(m_position.SelectByIndex(i)) { totalLots += m_position.Volume(); } } string LotsText = StringFormat("Кол-во лотов: %.2f", totalLots); m_labelLots.Text(LotsText);
if(!Add(m_labelLots)) return(false);
return(true); } // ////+------------------------------------------------------------------+ ////| | // ////+------------------------------------------------------------------+ void CAppWindowTwoButtons::UpdateLabelLots(void) { double totalLots = 0.0; for(int i = PositionsTotal() - 1; i >= 0; i--) { if(m_position.SelectByIndex(i)) { totalLots += m_position.Volume(); } } string LotsText = StringFormat("Кол-во лотов: %.2f", totalLots); m_labelLots.Text(LotsText); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreatePipsToDownChangeControls(void) {
// Создание метки для PipsToChange if(!m_labelPipsToDownChange.Create(0,"LabelPipsToDownChange",0,10,115,130,150)) return false;
m_labelPipsToDownChange.Text("Пункты на которые изменится цена"); if(!Add(m_labelPipsToDownChange)) return(false);
if(!m_labelPipsToDownChange2.Create(0,"LabelPipsToDownChange2",0,10,140,130,170)) return false;
m_labelPipsToDownChange2.Text("после безубытка:"); if(!Add(m_labelPipsToDownChange2)) return(false);
// Создание поля для ввода PipsToChange if(!m_editPipsToDownChange.Create(0,"EditPipsToDownChange",0,150,140,200,165)) return false; if(!m_editPipsToDownChange.ReadOnly(false)) return(false); m_editPipsToDownChange.Text(IntegerToString(PercentToDown)); if(!Add(m_editPipsToDownChange)) return(false);
return true; }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::OnPipsToDownChangeEdit(void) { PercentToDown = StringToInteger(m_editPipsToDownChange.Text()); // Дополнительная валидация может потребоваться здесь }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreatePipsToChangeControls(void) {
// Создание метки для PipsToChange if(!m_labelPipsToChange.Create(0,"LabelPipsToChange",0,10,65,100,10)) return false; m_labelPipsToChange.Text("Количество пунктов изменения цены:"); if(!Add(m_labelPipsToChange)) return(false);
// Создание поля для ввода PipsToChange if(!m_editPipsToChange.Create(0,"EditPipsToChange",0,10,85,60,110)) return false; if(!m_editPipsToChange.ReadOnly(false)) return(false); m_editPipsToChange.Text(IntegerToString(PipsToChange)); if(!Add(m_editPipsToChange)) return(false);
return true; }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::OnPipsToChangeEdit(void) { PipsToChange = StringToInteger(m_editPipsToChange.Text()); // Дополнительная валидация может потребоваться здесь }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateProfitLabel(void) { int x1=INDENT_LEFT+180; int y1=INDENT_TOP+185; int x2=x1+INDENT_TOP+BUTTON_HEIGHT+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);
double profit = CalculateTotalProfit(); double TrueProfit = profit - g_initialProfit + profitCloseSell + profitCloseBuy;
// Обновляем текст метки с прибылью string profitText = StringFormat("Прибыль: %.2f", TrueProfit); m_labelProfit.Text(profitText);
if(!Add(m_labelProfit)) return(false);
return(true); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::UpdateProfitLabel(void) { // Вычисляем текущую прибыль со всех открытых позиций double profit = CalculateTotalProfit(); double TrueProfit = profit - g_initialProfit + profitCloseSell + profitCloseBuy;
// Обновляем текст метки с прибылью string profitText = StringFormat("Прибыль: %.2f", TrueProfit); profitToLine = TrueProfit; m_labelProfit.Text(profitText); profitToSend = StringFormat("Прибыль: %.2f", TrueProfit); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool CAppWindowTwoButtons::CreateButton1(void) { //--- coordinates int x1=INDENT_LEFT+15; // 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+195; // 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); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+
input long PipsToChangeint = 500; // Количество пунктов изменения цены input double InitialLots = 0.1; // Количество лотов для начальной сделки input double LotChangePercent = 30.0; // Процент изменения количества лотов ENUM_TIMEFRAMES TimeFrame = Period(); input long PercentToDownInt = 1000; //Пункты изменения цены после безубытка ENUM_TIMEFRAMES TimeLast;
long PipsToChange = PipsToChangeint; long PercentToDown = PercentToDownInt; double PriceDown = 0; double PriceUp = 10000000000; double LineOfBreak = 0; double maxOpenPriceLast = 0; double minOpenPriceLast = 0;
double profitCloseSell = 0.0; double profitCloseBuy = 0.0; double g_initialProfit = 0.0;
double currentLots = InitialLots; double lastPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
bool close_s = false; bool close_b = false; bool start_b = false; bool start_s = false; bool send_b; bool send_s;
string profitToSend; double profitToLine; double priceLine;
bool close_all = false; bool start = false;
datetime lastBarTime = 0;
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int sendMessage(string text, string chatID, string botToken) { string baseUrl = "https://api.telegram.org"; string headers = ""; string requestURL = ""; string requestHeaders = ""; char resultData[]; char posData[]; int timeout = 200;
requestURL = StringFormat("%s/bot%s/sendmessage?chat_id=%s&text=%s",baseUrl,botToken,chatID,text); int response = WebRequest("POST",requestURL,headers,timeout,posData,resultData,requestHeaders);
string resultMessage = CharArrayToString(resultData);
return response; }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int getMessage(string chatID, string botToken) { string baseUrl = "https://api.telegram.org"; string headers = ""; string requestURL = ""; string requestHeaders = ""; char resultData[]; char posData[]; int timeout = 200;
string result[]; string sep = ","; ushort sep_u = StringGetCharacter(sep,0); string searchPattern = ("text");
string sep2 = "n"; ushort sep2_u = StringGetCharacter(sep2,0); string result2[];
long accountNumber = AccountInfoInteger(ACCOUNT_LOGIN);
requestURL = StringFormat("%s/bot%s/getChat?chat_id=%s",baseUrl,botToken,chatID); int response = WebRequest("GET",requestURL,headers,timeout,posData,resultData,requestHeaders);
string resultMessage = CharArrayToString(resultData); int k = (StringSplit(resultMessage,sep_u,result));
if(k>0) { for(int i=0; i<k; i++) {
if(StringFind(result[i], searchPattern) >= 0) { string res = StringSubstr(result[i],8,StringLen(result[i])-10); int z = StringSplit(res,sep2_u,result2); if(z>0) { for(int j=0; j<z; j++) { string finalResult; int g = StringFind(result2[j],"\\",0); if(g != -1) { finalResult = StringSubstr(result2[j],0,StringLen(result2[j])-1); } else { finalResult = result2[j]; } if(finalResult == (string)accountNumber) { return true; } } } } } }string wrongAccess = "Пытались торговать с счёта " + (string)accountNumber; sendMessage(wrongAccess,ID,token); return false; }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ 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() { if(start != true) { g_initialProfit = CalculateTotalProfit(); }
if(!getMessage(IDToLicense,token)) return(INIT_FAILED);
if(!ExtDialog.Create(0,"Закрытие позиций и изменение вводных",0,15,100,420,350)) 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); }
if(start_b == false) { while(send_b != true) { OpenOrder(ORDER_TYPE_BUY, currentLots, "B"); start_b = true; } }
if(start_s == false) { while(send_s != true) { OpenOrder(ORDER_TYPE_SELL, currentLots, "S"); start_s = true; } }
if(start != true) {
ENUM_TIMEFRAMES TimeInt = TimeFrame; if(TimeInt > 16000) { TimeInt = (ENUM_TIMEFRAMES)((TimeInt - 16384) * 60); } int number = 1; string message = StringFormat( "Number: %ld " "PipsToChange: %ld " "InitialLots: %f " "LotChangePercent: %f " "TimeFrame: %d " "PipsToBreak: %ld " "Symbol: %s " "NumberAcc: %lld", number, PipsToChangeint, InitialLots, LotChangePercent, TimeInt, PercentToDownInt, _Symbol, AccountInfoInteger(ACCOUNT_LOGIN)); sendMessage(message,ID,token); start = true; TimeLast = TimeInt; }ObjectCreate(0,"Линия безубытка",OBJ_HLINE,0,0,LineOfBreak); ObjectSetInteger(0, "Линия безубытка", OBJPROP_COLOR, clrLime);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- Comment(""); //--- destroy dialog ExtDialog.Destroy(reason);
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);
// Округление до ближайшего допустимого большего значения double remainder = fmod(lot - min_lot, lot_step); if (remainder > 0) { lot += (lot_step - remainder); // Прибавляем разницу для достижения следующего шага, если остаток больше 0 }
// Подстраивание под максимально допустимое значение 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); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double getLine(double profitTarget, string cl_pos) { profitTarget = MathAbs(profitTarget);
double VolLots = 0; double PriceLots = 0; // Определение ценности пипса (здесь пример для EURUSD с размером контракта 100000) for(int i=PositionsTotal()-1; i>=0; i--) { if(m_position.SelectByIndex(i)) { VolLots += m_position.Volume(); PriceLots += m_position.Volume() / m_position.PriceOpen(); } }
double pipValue = _Point * SymbolInfoDouble(Symbol(),SYMBOL_TRADE_CONTRACT_SIZE); if(cl_pos == "buy") { double currentPrice = VolLots / PriceLots; // Для сделки BUY double priceChange = (profitTarget / (pipValue * VolLots)) * _Point;
ObjectCreate(0,"Линия безубытка",OBJ_HLINE,0,0,currentPrice - priceChange); ObjectSetInteger(0, "Линия безубытка", OBJPROP_COLOR, clrLime); return currentPrice - priceChange; }else { double currentPrice = VolLots / PriceLots; // Для сделки SELL double priceChange = (profitTarget / (pipValue * VolLots)) * _Point;
ObjectCreate(0,"Линия безубытка",OBJ_HLINE,0,0,currentPrice + priceChange); ObjectSetInteger(0, "Линия безубытка", OBJPROP_COLOR, clrLime); return currentPrice + priceChange; }}
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double SubtractPointsDown(double price, long points) { // Получаем количество десятичных знаков и размер пункта int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS); double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Вычисляем изменение цены double change = points * pointSize;
// Возвращаем результат return NormalizeDouble(price - change, digits); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double SubtractPointsUp(double price, long points) { // Получаем количество десятичных знаков и размер пункта int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS); double pointSize = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Вычисляем изменение цены double change = points * pointSize;
// Возвращаем результат return NormalizeDouble(price + change, digits); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::OnClickButton1(void) { for(int i=PositionsTotal()-1; i>=0; i--) {
string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue; if(m_position.SelectByIndex(i)) if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_SELL) continue; profitCloseSell += m_position.Profit(); m_trade.PositionClose(PositionGetInteger(POSITION_TICKET)); close_s = true; }//string messButt1 = "sell закрыты " + (string)AccountInfoInteger(ACCOUNT_LOGIN); int number = 2; string messButt1 = StringFormat("Number: %ld " "sellAndNumbAcc: %lld", number, AccountInfoInteger(ACCOUNT_LOGIN) ); sendMessage(messButt1,ID,token);
if(close_b == true) { close_all = true; int number2 = 6; string CloseAllMess = StringFormat("Number: %ld " "NumberAcc: %lld", number2, AccountInfoInteger(ACCOUNT_LOGIN) ); sendMessage(CloseAllMess,ID,token); sendMessage(profitToSend,ID,token); }
LineOfBreak = getLine(profitCloseSell,"buy"); PriceUp = SubtractPointsUp(LineOfBreak,PercentToDown); }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void CAppWindowTwoButtons::OnClickButton2(void) { int totalPositions = PositionsTotal(); for(int i = totalPositions - 1; i >= 0; i--) { string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue;
if(m_position.SelectByIndex(i)) if(PositionGetInteger(POSITION_TYPE) != ORDER_TYPE_BUY) continue; profitCloseBuy += m_position.Profit(); m_trade.PositionClose(PositionGetInteger(POSITION_TICKET)); close_b = true; }//string messButt2 = "buy закрыты " + (string)AccountInfoInteger(ACCOUNT_LOGIN); int number = 3; string messButt1 = StringFormat("Number: %ld " "buyAndNumbAcc: %lld", number, AccountInfoInteger(ACCOUNT_LOGIN) ); sendMessage(messButt2,ID,token);
if(close_s == true) { close_all = true; int number2 = 6; string CloseAllMess = StringFormat("Number: %ld " "NumberAcc: %lld", number2, AccountInfoInteger(ACCOUNT_LOGIN) ); sendMessage(CloseAllMess,ID,token); sendMessage(profitToSend,ID,token); }
LineOfBreak = getLine(profitCloseBuy,"sell"); PriceDown = SubtractPointsDown(LineOfBreak,PercentToDown); }
#property indicator_chart_window #property indicator_color1 Pink
//±-----------------------------------------------------------------+ //| Expert tick function | //±-----------------------------------------------------------------+ long PipsToChangelast = PipsToChange; long PercentToDownlast = PercentToDown;
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double GetMaxOpenPrice() { double maxPrice = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--) { if(m_position.SelectByIndex(i)) { double openPrice = m_position.PriceOpen(); if(openPrice > maxPrice) maxPrice = openPrice; }
}return maxPrice; }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ double GetMinOpenPrice() { double minPrice = DBL_MAX; for(int i = PositionsTotal() - 1; i >= 0; --i) {
if(m_position.SelectByIndex(i)) { double openPrice = m_position.PriceOpen(); if(openPrice < minPrice) minPrice = openPrice; } }return minPrice; }
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnTick() { send_b = false; send_s = false;
ExtDialog.OnPipsToChangeEdit(); ExtDialog.UpdateProfitLabel(); ExtDialog.UpdateProfitLabelPerc(); ExtDialog.OnPipsToDownChangeEdit(); ExtDialog.UpdateLabelLots();
ExtDialog.UpdateProfitBuy(); ExtDialog.UpdateProfitSell();if(PercentToDownlast != PercentToDown || PipsToChangelast != PipsToChange) {
int number = 4; string messChanges = StringFormat( "Number: %ld " "PipsToChange: %ld " "PipsToBreak: %ld " "Номер счета: %lld", number, PipsToChange, PercentToDown, AccountInfoInteger(ACCOUNT_LOGIN) ); sendMessage(messChanges,ID,token); PipsToChangelast = PipsToChange; PercentToDownlast = PercentToDown; if(close_b == true) { PriceDown = SubtractPointsDown(LineOfBreak,PercentToDown); } else if(close_s == true) { PriceUp = SubtractPointsUp(LineOfBreak,PercentToDown); } }double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
datetime currentTime = TimeCurrent(); ENUM_TIMEFRAMES Time = Period();
if(Time > 16000) { Time = (ENUM_TIMEFRAMES)((Time - 16384) * 60); }
if(Time != TimeLast) {
int number = 5; string messTimeframe = StringFormat( "Number: %ld " "TimeFrame: %d " "Номер счета: %lld", number, Time, AccountInfoInteger(ACCOUNT_LOGIN) ); sendMessage(messTimeframe,ID,token); TimeLast = Time; }if((SymbolInfoDouble(_Symbol, SYMBOL_BID) > PriceUp || SymbolInfoDouble(_Symbol, SYMBOL_ASK) < PriceDown) && close_all != true) { int totalPositions = PositionsTotal(); for(int i = totalPositions - 1; i >= 0; i--) { string symbol = PositionGetSymbol(i); if(!PositionSelect(symbol)) continue;
profitCloseBuy += m_position.Profit(); m_trade.PositionClose(PositionGetInteger(POSITION_TICKET)); } close_b = true; close_s = true; //string closeMessage = "Бот закрыл все сделки " + (string)AccountInfoInteger(ACCOUNT_LOGIN); int number = 6; string closeMessage = StringFormat( "Number: %ld " "Номер счета: %lld", number, AccountInfoInteger(ACCOUNT_LOGIN)) sendMessage(closeMessage,ID,token); sendMessage(profitToSend,ID,token); close_all = true; }double maxOpenPrice = GetMaxOpenPrice(); double minOpenPrice = GetMinOpenPrice();
if(currentTime >= lastBarTime+Time*60) { MqlRates rates[]; if(CopyRates(_Symbol, Time, 0, 1, rates) > 0) { lastBarTime = rates[0].time; }
if(bidPrice - maxOpenPrice > PipsToChange * _Point || minOpenPrice - askPrice > PipsToChange * _Point) { // Подсчитаем новый размер лота CalculateAndSetLotSize(); lastPrice = bidPrice; // Обновление последней цены // Открываем новые ордера с новым размером лота if(close_b == false) { while(send_b != true) { OpenOrder(ORDER_TYPE_BUY, currentLots, "B"); if(close_s == true) { ObjectDelete(0,"Линия безубытка"); LineOfBreak = getLine(profitCloseSell, "buy"); PriceUp = SubtractPointsUp(LineOfBreak,PercentToDown); } } } if(close_s == false) { while(send_s != true) { OpenOrder(ORDER_TYPE_SELL, currentLots, "S"); if(close_b == true) { ObjectDelete(0,"Линия безубытка"); LineOfBreak = getLine(profitCloseBuy,"sell"); PriceDown = SubtractPointsDown(LineOfBreak,PercentToDown); } } } } }}
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ 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.deviation = 1; 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)) { 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); if(request.type == ORDER_TYPE_BUY) { send_b = false; } else if(request.type == ORDER_TYPE_SELL) { send_s = false; } } else if(request.type == ORDER_TYPE_BUY) { send_b = true; } else if(request.type == ORDER_TYPE_SELL) { send_s = true; }
PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order);
} //+------------------------------------------------------------------+
//+------------------------------------------------------------------+ мне нужно объединить эти программы что бы первая следовала сигналам которые даёт вторая
- Assistant
Чтобы обеспечить возможность первой программы (кода экспертного советника в MetaTrader 5) следовать сигналам второй программы, необходимо в первую очередь обеспечить связь между двумя скриптами.
Поскольку первая программа уже содержит функционал для отправки и получения информации через Telegram с использованием API (с функцией
sendMessageиgetMessage), вы можете использовать этот функционал для обмена сигналами между программами.Шаг 1. Реализация функционала приема сигналов
Для приема сигналов от второй программы первая программа должна регулярно проверять наличие новых сообщений в Telegram (или другого выбранного вами канала связи) и реагировать на них соответствующим образом.
В первой программе у вас уже есть функция для получения сообщений из Telegram (
getMessage). Рассмотрим, как можно её использовать для приема и обработки сигналов.Шаг 2. Расширение функции получения сообщений
Вам понадобится расширить функцию
getMessage, чтобы она могла не только регистрировать, что кто-то пытался торговать на данном счете, но и анализировать содержание сообщений для извлечения из них сигналов на торговлю.Это может выглядеть примерно так (псевдокод):
int getMessage(string chatID, string botToken) { // (здесь ваша реализация запроса сообщений в Telegram) // Примерный вариант анализа сообщений if (StringFind(resultMessage, "определенный сигнал") >= 0) { // Вызов функции, реализующей соответствующую торговую операцию } return true; // Или другая логика обработки результатов }Шаг 3. Периодический запрос к Telegram
Чтобы реализовать постоянное получение сигналов, вам нужно периодически вызывать функцию
getMessageв вашей основной программе (OnTickили другой периодический вызов).void OnTick() { // Вызов getMessage() для проверки наличия новых сигналов getMessage(ID, token); // Обработка торговли и т.д. }Шаг 4. Автоматизация отправки сигналов из второй программы
Теперь, когда первая программа умеет принимать и обрабатывать сигналы, вторая программа должна их автоматически генерировать и отправлять. Для этого убедитесь, что в вашей второй программе в нужных местах реализованы вызовы
sendMessageс соответствующим текстом сигналов.Важно
Обработка и анализ текстовых данных из сообщений может потребовать тщательной работы, чтобы извлечь точные команды для выполнения торговых операций. Убедитесь, что вы разработали надежный и безопасный механизм для этого, включая проверку на корректность получаемых данных.
Эти шаги предоставляют базовое представление о том, как можно организовать взаимодействие между двумя программами для автоматической торговли по сигналам. Однако конкретная реализация может сильно зависеть от деталей вашей задачи, логики торговли и форматов сигналов.