Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 110
You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
Please help me to write a function that will calculate the number of orders and their total profit closed in the last 60 seconds on the current pair. I can't formulate it correctly.
double ClosingSellProfit=0, ClosingBuyProfit;
for(int i=0; i<OrdersHistoryTotal(); i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) && OrderSymbol()==Symbol())
{
}
}
I think you may understand it:
double GetProfitOldClosePos(string symb="", int type=-1, int mg=-1) {
if(symb=="0") symb=Symbol();
datetime gt=0,ct=0;
double pr=0;
for(int i=OrdersHistoryTotal()-1; i>=0; i--) {
if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
if(OrderSymbol()==symb &&(type<0||OrderType()==type)&& OrderMagicNumber()==mg) {
ct=OrderCloseTime();
// 120 секунд разницы между закрытием первой и последней в сетке
if((gt<=ct && ct<=gt+120) || gt==0) {
gt=ct;
pr+=OrderProfit()+OrderCommission()+OrderSwap();
}}}}
return(pr);
}
Please help me to write a function that will calculate the number of orders and their total profit closed in the last 60 seconds on the current pair. I can't find it on my tongue, I can't formulate it correctly.
double ClosingSellProfit=0, ClosingBuyProfit;
for(int i=0; i<OrdersHistoryTotal(); i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) && OrderSymbol()==Symbol())
{
if(OrderType()==OP_SELL)
{
if(. . .)
{
CountClosedSellOrders++;
ClosingSellProfit+=OrderProfit()+OrderCommission()+OrderSwap();
}
if(OrderType()==OP_BUY)
{
if(. . .)
{
CountClosedBuyOrders++;
ClosingBuyProfit+=OrderProfit()+OrderCommission()+OrderSwap();
}
}
}
}
double ClosingSellProfit=0,ClosingBuyProfit;
//for(int i=0; i<OrdersHistoryTotal(); i++)
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) && OrderSymbol()==Symbol())
{
if(OrderCloseTime()>=TimeCurrent()-60)
{
if(OrderType()==OP_SELL)
{
CountClosedSellOrders++;
ClosingSellProfit+=OrderProfit()+OrderCommission()+OrderSwap();
}
if(OrderType()==OP_BUY)
{
CountClosedBuyOrders++;
ClosingBuyProfit+=OrderProfit()+OrderCommission()+OrderSwap();
}
}
}
}
How do I specify a trailing stop when opening an order?
If the price is zero or is not set , set the line coordinate to the price of the last order. This is fine.
The log is also normal, it drains the account as it should be. I do not watch errors about insufficient deposit.
But the line is still red. I.e. we call the buy line, it is as it is, we pass the parameters but other ones are passed.
This condition definitely should not be written like in your code. You create your own difficulties to "heroically" overcome them ))))
Everything that creates the red line in the code is commented out, hence it is created by someone else. Or it's been hanging on the chart since that part of the code was in the works.
I recommend the same as I've recommended many times before - print all actions and return codes (errors) to the log, it will answer many questions.
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
//---
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);
}
//+------------------------------------------------------------------+
But the basic principle for most indicators is this:
//| 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[])
{
//---
if(rates_total<1) return(0); // проверка достаточности данных для расчёта индикатора, если не достаточно - выходим
// если для расчёта требуются некое количество баров слева от индекса цикла, ...
// ... то проверять нужно это количество, а не 1
//--- Действия для полного перерасчёта индикатора
int limit=rates_total-prev_calculated; // количество посчитанных уже баров
if(limit>1) { // если количество больше 1, значит имеем новые данные, и нужно полностью пересчитать индикатор
limit=rates_total-1; // задаём количество требуемых для расчёта баров равным количеству баров в истории,
// если для расчёта требуются некое количество баров слева от индекса цикла, ...
// ... то это количество тоже нужно вычесть из rates_total чтобы не выйти за пределы массива
// так же тут нужно при необходимости произвести инициализацию буферов индикатора
}
//--- Основной цикл индикатора
for(int i=limit; i>=0; i--) {
// тут выполняем нужные расчёты и записываем их результат в нужные буферы, например:
ExtMapBuffer[i]=(open[i]+high[i]+low[i]+close[i])/4.0; // Выведем на график среднюю цену каждой свечи (OHLC/4.0)
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
This condition should certainly not be written as in your code. You create your own difficulties to "heroically" overcome them ))))
Everything that creates the red line in the code is commented out, hence it is created by someone else. Or it's been hanging on the graph since that part of the code was in the works.
I recommend the same thing I've recommended many times before - print all the actions and return codes (errors) to the log, this will answer many questions.
200 line mystique
:)
You don't have a complete template - you probably haven't set the indicator buffers in the wizard, where the calculated data will be written to.
But the basic principle for most indicators is this:
//| 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[])
{
//---
if(rates_total<1) return(0); // проверка достаточности данных для расчёта индикатора, если не достаточно - выходим
// если для расчёта требуются некое количество баров слева от индекса цикла, ...
// ... то проверять нужно это количество, а не 1
//--- Действия для полного перерасчёта индикатора
int limit=rates_total-prev_calculated; // количество посчитанных уже баров
if(limit>1) { // если количество больше 1, значит имеем новые данные, и нужно полностью пересчитать индикатор
limit=rates_total-1; // задаём количество требуемых для расчёта баров равным количеству баров в истории,
// если для расчёта требуются некое количество баров слева от индекса цикла, ...
// ... то это количество тоже нужно вычесть из rates_total чтобы не выйти за пределы массива
// так же тут нужно при необходимости произвести инициализацию буферов индикатора
}
//--- Основной цикл индикатора
for(int i=limit; i>=0; i--) {
// тут выполняем нужные расчёты и записываем их результат в нужные буферы, например:
ExtMapBuffer[i]=(open[i]+high[i]+low[i]+close[i])/4.0; // Выведем на график среднюю цену каждой свечи (OHLC/4.0)
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
Please help!
There is a string ABCDEF how to split it into 3 strings (save to a variable string):
AB
CD
EF
Please help!
There is a string ABCDEF how to split it into 3 strings (save to a variable string):
AB
CD
EF
string string_value, // строка
int start_pos, // с какой позиции начать
int length=0 // длина извлекаемой строки
);