Mql5: Pnl calculation last 24 hour
//+------------------------------------------------------------------+
//| order pnl today history.mq5 |
//| Copyright 2023, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
double add = Today_Closed_Profit()+CalculateCurrentRunningPnL();
Comment("Pnl1: "+Today_Closed_Profit()+"\n\nCalculateCurrentRunningPnL: "+CalculateCurrentRunningPnL()+"\n\nTotal: "+add);
}
//+------------------------------------------------------------------+
double Today_Closed_Profit()
{
MqlDateTime SDateTime;
TimeToStruct(TimeCurrent(),SDateTime);
SDateTime.hour=0;
SDateTime.min=0;
SDateTime.sec=0;
datetime from_date=StructToTime(SDateTime); // From date
SDateTime.hour=23;
SDateTime.min=59;
SDateTime.sec=59;
datetime to_date=StructToTime(SDateTime); // To date
to_date+=60*60*24;
HistorySelect(from_date,to_date);
int trades_of_day=0;
double wining_trade=0.0;
double losing_trade=0.0;
double total_profit=0.0;
uint total=HistoryDealsTotal();
ulong ticket=0;
//--- for all deals
for(uint i=0; i<total; i++)
{
//--- try to get deals ticket
if((ticket=HistoryDealGetTicket(i))>0)
{
long entry=HistoryDealGetInteger(ticket,DEAL_ENTRY);
if(entry==DEAL_ENTRY_IN)
continue;
//--- get deals properties
trades_of_day++;
double deal_commission=HistoryDealGetDouble(ticket,DEAL_COMMISSION);
double deal_swap=HistoryDealGetDouble(ticket,DEAL_SWAP);
double deal_profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);
double profit=deal_commission+deal_swap+deal_profit;
if(profit>0.0)
wining_trade+=profit;
if(profit<0.0)
losing_trade+=profit;
total_profit+=profit;
}
}
return total_profit;
}
double CalculateCurrentRunningPnL()
{
double runningPnL = 0;
int totalPositions = PositionsTotal(); // Get the total number of open positions
for(int i = 0; i < totalPositions; i++)
{
// Get the symbol of the position at index i
string symbol = PositionGetSymbol(i);
// Select the position by its symbol
if(PositionSelect(symbol))
{
// Accumulate the profit for the position
runningPnL += PositionGetDouble(POSITION_PROFIT);
}
}
return runningPnL;
}
Comments
Post a Comment