Sales Analyzer Updates

This commit is contained in:
HojouFotytu 2024-01-17 01:56:52 +09:00
parent ae15f7440f
commit 615e07986b
6 changed files with 659 additions and 215 deletions

View File

@ -440,6 +440,10 @@ namespace Core.Main.DataObjects.PTMagicData
public double FundingThisMonth { get; set; }
public double FundingLastMonth { get; set; }
public double FundingTotal { get; set; }
public double TotalFundingPerc { get; set; }
public double TotalFundingPercYesterday { get; set; }
public double TotalFundingPercWeek { get; set; }
public double TotalFundingPercToday { get; set; }
}
public class DailyPNLData
@ -448,6 +452,13 @@ namespace Core.Main.DataObjects.PTMagicData
public double CumulativeProfitCurrency { get; set; }
public double Order { get; set; }
}
public class DailyTCVData
{
public string Date { get; set; }
public double TCV { get; set; }
public double Order { get; set; }
}
public class MonthlyStatsData
{
@ -455,6 +466,7 @@ namespace Core.Main.DataObjects.PTMagicData
public double TotalProfitCurrency { get; set; }
public double TotalSales { get; set; }
public double AvgGrowth { get; set; }
public double Order { get; set; }
}

View File

@ -19,6 +19,7 @@ namespace Core.Main.DataObjects
private PropertiesData _properties = null;
private StatsData _stats = null;
private List<DailyPNLData> _dailyPNL = new List<DailyPNLData>();
private List<DailyTCVData> _dailyTCV = new List<DailyTCVData>();
private List<MonthlyStatsData> _monthlyStats = new List<MonthlyStatsData>();
private decimal? _totalProfit = null;
public decimal? TotalProfit
@ -39,15 +40,16 @@ namespace Core.Main.DataObjects
private PTMagicConfiguration _systemConfiguration = null;
private TransactionData _transactionData = null;
private DateTime _dailyPNLRefresh = DateTime.UtcNow;
private DateTime _dailyTCVRefresh = DateTime.UtcNow;
private DateTime _monthlyStatsRefresh = DateTime.UtcNow;
private DateTime _statsRefresh = DateTime.UtcNow;
private DateTime _buyLogRefresh = DateTime.UtcNow;
private DateTime _sellLogRefresh = DateTime.UtcNow;
private DateTime _dcaLogRefresh = DateTime.UtcNow;
private DateTime _miscRefresh = DateTime.UtcNow;
private DateTime _propertiesRefresh = DateTime.UtcNow;
private volatile object _dailyStatsLock = new object();
private volatile object _dailyPNLLock = new object();
private DateTime _propertiesRefresh = DateTime.UtcNow;
private volatile object _dailyPNLLock = new object();
private volatile object _dailyTCVLock = new object();
private volatile object _monthlyStatsLock = new object();
private volatile object _statsLock = new object();
private volatile object _buyLock = new object();
@ -221,7 +223,11 @@ namespace Core.Main.DataObjects
FundingWeek = statsDataJson["totalFundingWeek"],
FundingThisMonth = statsDataJson["totalFundingThisMonth"],
FundingLastMonth = statsDataJson["totalFundingLastMonth"],
FundingTotal = statsDataJson["totalFunding"]
FundingTotal = statsDataJson["totalFunding"],
TotalFundingPerc = statsDataJson["totalFundingPerc"],
TotalFundingPercYesterday = statsDataJson["totalFundingPercYesterday"],
TotalFundingPercWeek = statsDataJson["totalFundingPercWeekPerc"],
TotalFundingPercToday = statsDataJson["totalFundingPercTodayPerc"]
};
}
public List<DailyPNLData> DailyPNL
@ -299,6 +305,83 @@ namespace Core.Main.DataObjects
Order = dailyPNLDataJson["order"],
};
}
public List<DailyTCVData> DailyTCV
{
get
{
if (_dailyTCV == null || DateTime.UtcNow > _dailyTCVRefresh)
{
lock (_dailyTCVLock)
{
if (_dailyTCV == null || DateTime.UtcNow > _dailyTCVRefresh)
{
using (var stream = GetDataFromProfitTrailerAsStream("/api/v2/data/stats"))
using (var reader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(reader))
{
JObject basicSection = null;
JObject extraSection = null;
while (jsonReader.Read())
{
if (jsonReader.TokenType == JsonToken.PropertyName)
{
if ((string)jsonReader.Value == "basic")
{
jsonReader.Read(); // Move to the value of the "basic" property
basicSection = JObject.Load(jsonReader);
}
else if ((string)jsonReader.Value == "extra")
{
jsonReader.Read(); // Move to the value of the "extra" property
extraSection = JObject.Load(jsonReader);
}
}
if (basicSection != null && extraSection != null)
{
break;
}
}
if (basicSection != null) // &&
//((_totalProfit == null ||
//!Decimal.Equals(_totalProfit.Value, basicSection["totalProfit"].Value<decimal>())) ||
//(_totalSales == null ||
//!Decimal.Equals(_totalSales.Value, basicSection["totalSales"].Value<decimal>()))))
{
//_totalProfit = basicSection["totalProfit"].Value<decimal>();
//_totalSales = basicSection["totalSales"].Value<decimal>();
if (extraSection != null)
{
JArray dailyTCVSection = (JArray)extraSection["dailyTCVStats"];
_dailyTCV = dailyTCVSection.Select(j => BuildDailyTCVData(j as JObject)).ToList();
_dailyTCVRefresh = DateTime.UtcNow.AddSeconds(_systemConfiguration.GeneralSettings.Monitor.RefreshSeconds - 1);
}
}
}
}
}
}
return _dailyTCV;
}
}
public int GetTotalTCVDays()
{
return DailyTCV?.Count ?? 0;
}
private DailyTCVData BuildDailyTCVData(dynamic dailyTCVDataJson)
{
return new DailyTCVData()
{
Date = dailyTCVDataJson["date"],
TCV = dailyTCVDataJson["TCV"],
Order = dailyTCVDataJson["order"],
};
}
public List<MonthlyStatsData> MonthlyStats
{
get
@ -375,6 +458,7 @@ namespace Core.Main.DataObjects
TotalSales = monthlyStatsDataJson["totalSales"],
TotalProfitCurrency = monthlyStatsDataJson["totalProfitCurrency"],
AvgGrowth = monthlyStatsDataJson["avgGrowth"],
Order = monthlyStatsDataJson["order"],
};
}
public List<SellLogData> SellLog

View File

@ -19,14 +19,11 @@
<thead>
<tr>
@{
string totalCurrentValueString = Model.totalCurrentValue.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"));
if (Model.totalCurrentValue > 100)
{
totalCurrentValueString = Math.Round(Model.totalCurrentValue, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"));
}
double totalCurrentValue = double.Parse(Model.PTData.Misc.TotalCurrentValue);
string totalCurrentValueString = Model.PTData.Misc.TotalCurrentValue;
}
<th class="m-t-0 header-title text-left">Total Current Value: &nbsp; <text class="text-autocolor"> @totalCurrentValueString @Model.Summary.MainMarket </text> <small> <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="This is based on the TCV reported by Profit Trailer."></i></small></th>
<th class="text-right">Starting Value: &nbsp; <text class="text-autocolor"> @Model.MiscData.StartBalance &nbsp; @Model.Summary.MainMarket </text> <small> <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="This is the starting value found in your settings file"></i></small></th>
<th class="m-t-0 header-title text-left">Total Current Value: &nbsp; <text class="text-autocolor"> @totalCurrentValueString @Model.Summary.MainMarket </text> <small> <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="This is based on the Total Current Value reported by Profit Trailer."></i></small></th>
<th class="text-right">Starting Value: &nbsp; <text class="text-autocolor"> @Model.MiscData.StartBalance &nbsp; @Model.Summary.MainMarket </text> <small> <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="This is the starting value set in your PT account settings."></i></small></th>
</tr>
</thead>
</table>
@ -34,16 +31,33 @@
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card-box">
<h4 class="m-t-0 header-title text-center">Cumulative PNL <small> <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="This value is based on your sales history"></i></small></h4>
<div class="balance-chart">
<svg style="height:350px;width:100%"></svg>
<div class="row">
<div class="col-md-6">
<div class="card-box px-2" style="height:320px;">
<h4 class="m-t-0 header-title"><b>Cumulative Profits</b>
@if (!Model.CumulativeProfitChartDataJSON.Equals("")) {
<div class="cumulative-profit-chart">
<svg style="height:300px;width:100%"></svg>
</div>
} else {
<p>Unable to load graph, no sales data found.</p>
}
</div>
</div>
<div class="col-md-6">
<div class="card-box px-2" style="height:320px;">
<h4 class="m-t-0 header-title"><b>Daily TCV</b>
@if (!Model.TCVChartDataJSON.Equals("")) {
<div class="TCV-chart">
<svg style="height:300px;width:100%"></svg>
</div>
} else {
<p>Unable to load graph, no sales data found.</p>
}
</div>
</div>
</div>
</div>
@if (Model.PTData.SellLog.Count == 0) {
<div class="row">
@ -60,10 +74,11 @@
<div class="card-box">
@{
int totalDays = Model.PTData.GetTotalDays();
double startBalance = Model.MiscData.StartBalance;
double totalSales = Model.PTData.Stats.TotalSales;
double totalProfit = Model.PTData.Stats.TotalProfit;
double totalFundingFees = Model.PTData.Stats.FundingTotal;
double totalPercentGain = Model.PTData.Stats.TotalProfitPerc;
double totalPercentGain = ((totalProfit + totalFundingFees) / startBalance) * 100;
double totalProfitFiat = @Math.Round((totalProfit + totalFundingFees) * Model.PTData.Misc.FiatConversionRate, 0);
double avgDailySales = @Math.Round(totalSales/totalDays, 1);
double avgDailyGain = totalPercentGain / totalDays;
@ -76,9 +91,8 @@
double avgMonthlyProfit = totalProfit / totalMonths;
double avgMonthlyGain = totalPercentGain / totalMonths;
double avgMonthlyFunding = totalFundingFees / totalMonths;
string percentGainText = totalPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US")) + "%";
}
<h4 class="m-t-0 header-title" style="display: inline;">Sales Analysis </h4><span style="font-size: x-small"> (@startDate - @endDate)</span>
<h4 class="m-t-0 header-title" style="display: inline;">Sales Analysis</h4>&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-size: x-small"> (@startDate - @endDate)</span>
<table class="table table-striped table-sm">
<thead>
<tr>
@ -101,12 +115,6 @@
<td class="text-right text-autocolor">@totalProfit.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@Math.Round(totalProfit / totalDays, 8).ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@avgMonthlyProfit.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
</tr>
<tr>
<th>% Gain</th>
<td class="text-right text-autocolor">@Html.Raw(percentGainText)</td>
<td class="text-right text-autocolor">@avgDailyGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
<td class="text-right text-autocolor">@avgMonthlyGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
@if(Model.PropertiesData.IsLeverageExchange)
{
@ -123,6 +131,12 @@
<td class="text-right text-autocolor">@Html.Raw(Math.Round(totalProfitFiat / totalDays, 0).ToString("#,#0", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@Html.Raw(Math.Round(totalProfitFiat / totalMonths, 0).ToString("#,#0", new System.Globalization.CultureInfo("en-US")))</td>
</tr>
<tr>
<th>% Gain</th>
<td class="text-right text-autocolor">@totalPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
<td class="text-right text-autocolor">@avgDailyGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
<td class="text-right text-autocolor">@avgMonthlyGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
</tbody>
</table>
</div>
@ -131,46 +145,52 @@
<div class="col-md-6">
<div class="card-box">
@{
double currentTotalBalance = Model.totalCurrentValue;
double estimatedBalance1Month = Math.Round(currentTotalBalance * Math.Pow((1 + (avgDailyGain / 100)), 30.0), 8);
double estimatedBalance3Months = Math.Round(currentTotalBalance * Math.Pow((1 + (avgDailyGain / 100)), 90.0), 8);
double estimatedBalance6Months = Math.Round(currentTotalBalance * Math.Pow((1 + (avgDailyGain / 100)), 180.0), 8);
double estimatedBalance1Year = Math.Round(currentTotalBalance * Math.Pow((1 + (avgDailyGain / 100)), 365.0), 8);
double estimatedBalance1Week = Math.Round(totalCurrentValue * Math.Pow((1 + (avgDailyGain / 100)), 7.0), 8);
double estimatedBalance1Month = Math.Round(totalCurrentValue * Math.Pow((1 + (avgDailyGain / 100)), 30.0), 8);
double estimatedBalance3Months = Math.Round(totalCurrentValue * Math.Pow((1 + (avgDailyGain / 100)), 90.0), 8);
double estimatedBalance6Months = Math.Round(totalCurrentValue * Math.Pow((1 + (avgDailyGain / 100)), 180.0), 8);
double estimatedBalance1Year = Math.Round(totalCurrentValue * Math.Pow((1 + (avgDailyGain / 100)), 365.0), 8);
}
<h4 class="m-t-0 header-title">Balance Prediction <small><i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The balance prediction is based on your daily average gain of @avgDailyGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))% and your current approximate balance of @currentTotalBalance.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))"></i></small></h4>
<h4 class="m-t-0 header-title">TCV Prediction <small><i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The balance prediction is based on your daily average gain of @avgDailyGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))% and your current TCV of @totalCurrentValue.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))"></i></small></h4>
<table class="table table-striped table-sm">
<thead>
<tr>
<th class="text-right"></th>
<th class="text-right">Est. Balance</th>
<th class="text-right">Est. TCV</th>
<th class="text-right">Est. @Model.PTData.Properties.Currency Value</th>
<th class="text-right">Est. Gain</th>
</tr>
</thead>
<tbody>
<tr>
<th>1 month</th>
<th>1 Week</th>
<td class="text-right text-autocolor">@estimatedBalance1Week.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@Html.Raw(Math.Round(estimatedBalance1Week * Model.MiscData.FiatConversionRate, 0).ToString("#,#0", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance1Week - totalCurrentValue) / totalCurrentValue * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>1 Month</th>
<td class="text-right text-autocolor">@estimatedBalance1Month.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@Html.Raw(Math.Round(estimatedBalance1Month * Model.MiscData.FiatConversionRate, 0).ToString("#,#0", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance1Month - currentTotalBalance) / currentTotalBalance * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance1Month - totalCurrentValue) / totalCurrentValue * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>3 months</th>
<th>3 Months</th>
<td class="text-right text-autocolor">@estimatedBalance3Months.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@Html.Raw(Math.Round(estimatedBalance3Months * Model.MiscData.FiatConversionRate, 0).ToString("#,#0", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance3Months - currentTotalBalance) / currentTotalBalance * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance3Months - totalCurrentValue) / totalCurrentValue * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>6 months</th>
<th>6 Months</th>
<td class="text-right text-autocolor">@estimatedBalance6Months.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@Html.Raw(Math.Round(estimatedBalance6Months * Model.MiscData.FiatConversionRate, 0).ToString("#,#0", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance6Months - currentTotalBalance) / currentTotalBalance * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance6Months - totalCurrentValue) / totalCurrentValue * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>1 year</th>
<th>1 Year</th>
<td class="text-right text-autocolor">@estimatedBalance1Year.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@Html.Raw(Math.Round(estimatedBalance1Year * Model.MiscData.FiatConversionRate, 0).ToString("#,#0", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance1Year - currentTotalBalance) / currentTotalBalance * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
<td class="text-right text-autocolor">@Math.Round((estimatedBalance1Year - totalCurrentValue) / totalCurrentValue * 100, 2).ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
</tbody>
</table>
@ -180,20 +200,27 @@
<div class="row">
<div class="col-md-6">
<div class="card-box">
<div class="card-box px-3" style="height:340px;">
<h4 class="m-t-0 m-b-20 header-title"><b>Daily Sales </b>
<div class="trades-chart">
<svg style="height:220px;width:100%"></svg>
<svg style="height:300px;width:100%"></svg>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card-box">
<div class="profit-chart">
<svg style="height:220px;width:100%"></svg>
</div>
<div class="card-box px-3" style="height:340px;">
<h4 class="m-t-0 m-b-20 header-title"><b>Daily Profit </b>
@if (!Model.ProfitChartDataJSON.Equals("")) {
<div class="profit-chart">
<svg style="height:300px;width:100%"></svg>
</div>
} else {
<p>Unable to load graph, no sales data found.</p>
}
</div>
</div>
</div>
</div>
<div class="row">
@ -375,7 +402,7 @@
nv.utils.windowResize(lineChart.update);
return lineChart;
});
@*
nv.addGraph(function () {
var lineChart = nv.models.lineChart();
var height = 300;
@ -402,7 +429,7 @@
d3.select('.balance-chart svg').attr('perserveAspectRatio', 'xMinYMid').datum(chartData).transition().duration(500).call(lineChart);
nv.utils.windowResize(lineChart.update);
return lineChart;
});
}); *@
$("#salesList").on("show.bs.modal", function (e) {
$(this).find(".modal-content").html('<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>');
@ -412,7 +439,146 @@
});
});
})(jQuery);
</script>
<script type="text/javascript">
(function ($) {
'use strict';
$('[role="tooltip"]').remove();
$('[data-toggle="tooltip"]').tooltip();
$('.text-autocolor').autocolor(false);
var cumulativeProfitChart; // Keep a reference to the chart
var cumulativeProfitData; // Keep a reference to the data
@if (!Model.CumulativeProfitChartDataJSON.Equals("")) {
<text>
nv.addGraph(function () {
cumulativeProfitChart = nv.models.lineChart();
var height = 300;
cumulativeProfitChart.useInteractiveGuideline(true);
cumulativeProfitChart.xAxis.tickFormat(function (d) { return d3.time.format('%m/%d')(new Date(d)); });
cumulativeProfitChart.yAxis.axisLabel('').tickFormat(d3.format(',.2f'));
cumulativeProfitData = @Html.Raw(Model.CumulativeProfitChartDataJSON);
d3.select('.cumulative-profit-chart svg')
.datum(cumulativeProfitData)
.transition().duration(0)
.call(cumulativeProfitChart);
// Add mouseleave, and mousemove event listeners to hide tooltip
d3.select('.cumulative-profit-chart').on('mouseleave', function() {
d3.select('.nvtooltip').style('opacity', 0);
});
d3.select('body').on('mousemove', function() {
var chartBounds = d3.select('.cumulative-profit-chart')[0][0].getBoundingClientRect();
var mouseX = d3.event.clientX;
var mouseY = d3.event.clientY;
if (mouseX < chartBounds.left || mouseX > chartBounds.right || mouseY < chartBounds.top || mouseY > chartBounds.bottom) {
d3.select('.nvtooltip').style('opacity', 0);
}
});
return cumulativeProfitChart;
});
</text>
}
})(jQuery);
</script>
<script type="text/javascript">
(function ($) {
'use strict';
$('[role="tooltip"]').remove();
$('[data-toggle="tooltip"]').tooltip();
$('.text-autocolor').autocolor(false);
var TCVChart; // Keep a reference to the chart
var TCVData; // Keep a reference to the data
@if (!Model.TCVChartDataJSON.Equals("")) {
<text>
nv.addGraph(function () {
TCVChart = nv.models.lineChart();
var height = 300;
TCVChart.useInteractiveGuideline(true);
TCVChart.xAxis.tickFormat(function (d) { return d3.time.format('%m/%d')(new Date(d)); });
TCVChart.yAxis.axisLabel('').tickFormat(d3.format(',.2f'));
TCVData = @Html.Raw(Model.TCVChartDataJSON);
d3.select('.TCV-chart svg')
.datum(TCVData)
.transition().duration(0)
.call(TCVChart);
// Add mouseleave, and mousemove event listeners to hide tooltip
d3.select('.TCV-chart').on('mouseleave', function() {
d3.select('.nvtooltip').style('opacity', 0);
});
d3.select('body').on('mousemove', function() {
var chartBounds = d3.select('.TCV-chart')[0][0].getBoundingClientRect();
var mouseX = d3.event.clientX;
var mouseY = d3.event.clientY;
if (mouseX < chartBounds.left || mouseX > chartBounds.right || mouseY < chartBounds.top || mouseY > chartBounds.bottom) {
d3.select('.nvtooltip').style('opacity', 0);
}
});
return TCVChart;
});
</text>
}
})(jQuery);
</script>
<script type="text/javascript">
(function ($) {
'use strict';
$('[role="tooltip"]').remove();
$('[data-toggle="tooltip"]').tooltip();
$('.text-autocolor').autocolor(false);
var profitChart; // Keep a reference to the chart
var profitData; // Keep a reference to the data
@if (!Model.ProfitChartDataJSON.Equals("")) {
<text>
nv.addGraph(function () {
profitChart = nv.models.lineChart();
var height = 300;
profitChart.useInteractiveGuideline(true);
profitChart.xAxis.tickFormat(function (d) { return d3.time.format('%m/%d')(new Date(d)); });
profitChart.yAxis.axisLabel('').tickFormat(d3.format(',.2f'));
profitData = @Html.Raw(Model.ProfitChartDataJSON);
d3.select('.profit-chart svg')
.datum(profitData)
.transition().duration(0)
.call(profitChart);
// Add mouseleave, and mousemove event listeners to hide tooltip
d3.select('.profit-chart').on('mouseleave', function() {
d3.select('.nvtooltip').style('opacity', 0);
});
d3.select('body').on('mousemove', function() {
var chartBounds = d3.select('.profit-chart')[0][0].getBoundingClientRect();
var mouseX = d3.event.clientX;
var mouseY = d3.event.clientY;
if (mouseX < chartBounds.left || mouseX > chartBounds.right || mouseY < chartBounds.top || mouseY > chartBounds.bottom) {
d3.select('.nvtooltip').style('opacity', 0);
}
});
return profitChart;
});
</text>
}
})(jQuery);
</script>
}

View File

@ -15,9 +15,14 @@ namespace Monitor.Pages
public PropertiesData PropertiesData { get; set; }
public StatsData StatsData { get; set; }
public List<DailyPNLData> DailyPNL { get; set; }
public List<DailyTCVData> DailyTCV { get; set; }
public int ProfitDays { get; set; }
public int TCVDays { get; set; }
public List<MonthlyStatsData> MonthlyStats { get; set; }
public string TradesChartDataJSON = "";
public string CumulativeProfitChartDataJSON = "";
public string TCVChartDataJSON = "";
public string ProfitChartDataJSON = "";
public string BalanceChartDataJSON = "";
public IEnumerable<KeyValuePair<string, double>> TopMarkets = null;
@ -42,6 +47,7 @@ namespace Monitor.Pages
StatsData = this.PTData.Stats;
MonthlyStats = this.PTData.MonthlyStats;
DailyPNL = this.PTData.DailyPNL;
DailyTCV = this.PTData.DailyTCV;
//List<MonthlyStatsData> monthlyStatsData = this.PTData.MonthlyStats;
//List<DailyPNLData> dailyPNLData = this.PTData.DailyPNL;
@ -53,9 +59,198 @@ namespace Monitor.Pages
BuildTopMarkets();
BuildSalesChartData();
BuildTCV();
BuildProfitChartData();
BuildCumulativeProfitChartData();
BuildTCVChartData();
//MonthlyAverages(monthlyStatsData, PTData.Stats.FundingTotal);
}
private void BuildTCVChartData()
{
List<object> TCVPerDayList = new List<object>();
if (PTData.DailyTCV.Count > 0)
{
// Get timezone offset
TimeSpan offset;
bool isNegative = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.StartsWith("-");
string offsetWithoutSign = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.TrimStart('+', '-');
if (!TimeSpan.TryParse(offsetWithoutSign, out offset))
{
offset = TimeSpan.Zero; // If offset is invalid, set it to zero
}
DateTime endDate = DateTime.UtcNow.Add(isNegative ? -offset : offset).Date;
// Parse dates once and adjust them to the local timezone
Dictionary<DateTime, DailyTCVData> dailyTCVByDate = PTData.DailyTCV
.Select(data => {
DateTime dateUtc = DateTime.ParseExact(data.Date, "d-M-yyyy", CultureInfo.InvariantCulture);
DateTime dateLocal = dateUtc.Add(isNegative ? -offset : offset);
return new { Date = dateLocal.Date, Data = data };
})
.ToDictionary(
item => item.Date,
item => item.Data
);
DateTime earliestDataDate = dailyTCVByDate.Keys.Min();
DateTime startDate = earliestDataDate;
// Calculate the total days of data available
TCVDays = (endDate - startDate).Days;
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
// Use the dictionary to find the Data for the date
if (dailyTCVByDate.TryGetValue(date, out DailyTCVData dailyTCV))
{
double TCV = dailyTCV.TCV;
// Add the data point to the list
TCVPerDayList.Add(new { x = new DateTimeOffset(date).ToUnixTimeMilliseconds(), y = TCV });
}
}
// Convert the list to a JSON string using Newtonsoft.Json
TCVChartDataJSON = Newtonsoft.Json.JsonConvert.SerializeObject(new[] {
new {
key = "TCV in " + PTData.Misc.Market,
color = Constants.ChartLineColors[1],
values = TCVPerDayList
}
});
}
}
private void BuildCumulativeProfitChartData()
{
List<object> profitPerDayList = new List<object>();
if (PTData.DailyPNL.Count > 0)
{
// Get timezone offset
TimeSpan offset;
bool isNegative = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.StartsWith("-");
string offsetWithoutSign = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.TrimStart('+', '-');
if (!TimeSpan.TryParse(offsetWithoutSign, out offset))
{
offset = TimeSpan.Zero; // If offset is invalid, set it to zero
}
DateTime endDate = DateTime.UtcNow.Add(isNegative ? -offset : offset).Date;
// Parse dates once and adjust them to the local timezone
Dictionary<DateTime, DailyPNLData> dailyPNLByDate = PTData.DailyPNL
.Select(data => {
DateTime dateUtc = DateTime.ParseExact(data.Date, "d-M-yyyy", CultureInfo.InvariantCulture);
DateTime dateLocal = dateUtc.Add(isNegative ? -offset : offset);
return new { Date = dateLocal.Date, Data = data };
})
.ToDictionary(
item => item.Date,
item => item.Data
);
DateTime earliestDataDate = dailyPNLByDate.Keys.Min();
DateTime startDate = earliestDataDate;
// Calculate the total days of data available
ProfitDays = (endDate - startDate).Days;
double previousDayCumulativeProfit = 0;
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
// Use the dictionary to find the DailyPNLData for the date
if (dailyPNLByDate.TryGetValue(date, out DailyPNLData dailyPNL))
{
// Use the CumulativeProfitCurrency directly
double profitFiat = dailyPNL.CumulativeProfitCurrency;
// Add the data point to the list
profitPerDayList.Add(new { x = new DateTimeOffset(date).ToUnixTimeMilliseconds(), y = profitFiat });
previousDayCumulativeProfit = dailyPNL.CumulativeProfitCurrency;
}
}
// Convert the list to a JSON string using Newtonsoft.Json
CumulativeProfitChartDataJSON = Newtonsoft.Json.JsonConvert.SerializeObject(new[] {
new {
key = "Profit in " + PTData.Misc.Market,
color = Constants.ChartLineColors[1],
values = profitPerDayList
}
});
}
}
private void BuildProfitChartData()
{
List<object> profitPerDayList = new List<object>();
if (PTData.DailyPNL.Count > 0)
{
// Get timezone offset
TimeSpan offset;
bool isNegative = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.StartsWith("-");
string offsetWithoutSign = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.TrimStart('+', '-');
if (!TimeSpan.TryParse(offsetWithoutSign, out offset))
{
offset = TimeSpan.Zero; // If offset is invalid, set it to zero
}
DateTime endDate = DateTime.UtcNow.Add(isNegative ? -offset : offset).Date;
// Parse dates once and adjust them to the local timezone
Dictionary<DateTime, DailyPNLData> dailyPNLByDate = PTData.DailyPNL
.Select(data => {
DateTime dateUtc = DateTime.ParseExact(data.Date, "d-M-yyyy", CultureInfo.InvariantCulture);
DateTime dateLocal = dateUtc.Add(isNegative ? -offset : offset);
return new { Date = dateLocal.Date, Data = data };
})
.ToDictionary(
item => item.Date,
item => item.Data
);
DateTime earliestDataDate = dailyPNLByDate.Keys.Min();
DateTime startDate = earliestDataDate;
// Calculate the total days of data available
ProfitDays = (endDate - startDate).Days;
double previousDayCumulativeProfit = 0;
bool isFirstDay = true;
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
// Use the dictionary to find the DailyPNLData for the date
if (dailyPNLByDate.TryGetValue(date, out DailyPNLData dailyPNL))
{
if (isFirstDay)
{
isFirstDay = false;
}
else
{
// Calculate the profit for the current day
double profitFiat = Math.Round(dailyPNL.CumulativeProfitCurrency - previousDayCumulativeProfit, 2);
// Add the data point to the list
profitPerDayList.Add(new { x = new DateTimeOffset(date).ToUnixTimeMilliseconds(), y = profitFiat });
}
previousDayCumulativeProfit = dailyPNL.CumulativeProfitCurrency;
}
}
// Convert the list to a JSON string using Newtonsoft.Json
ProfitChartDataJSON = Newtonsoft.Json.JsonConvert.SerializeObject(new[] {
new {
key = "Profit in " + PTData.Misc.Market,
color = Constants.ChartLineColors[1],
values = profitPerDayList
}
});
}
}
public (double totalMonths, DateTime startDate, DateTime endDate) MonthlyAverages(List<MonthlyStatsData> monthlyStats, List<DailyPNLData> dailyPNL)
{
@ -186,19 +381,5 @@ namespace Monitor.Pages
}
}
}
private void BuildTCV()
{
double AvailableBalance = PTData.GetCurrentBalance();
foreach (Core.Main.DataObjects.PTMagicData.DCALogData dcaLogEntry in PTData.DCALog)
{
double leverage = dcaLogEntry.Leverage;
if (leverage == 0)
{
leverage = 1;
}
totalCurrentValue = totalCurrentValue + ((dcaLogEntry.Amount * dcaLogEntry.CurrentPrice) / leverage);
}
totalCurrentValue = totalCurrentValue + AvailableBalance;
}
}
}

View File

@ -11,7 +11,7 @@
<div class="row">
<div class="col-md-5 px-1">
<div class="card-box px-2" style="height:320px;">
<div class="card-box px-2" style="height:340px;">
<h4 class="m-t-0 m-b-20 header-title" style="display: inline;"><b>Market Trend History </b><i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="@Math.Round(Model.DataHours, 1) hours of data available. Currently set to show @Model.PTMagicConfiguration.GeneralSettings.Monitor.GraphMaxTimeframeHours hours in general settings."></i></h4>
@if (!Model.TrendChartDataJSON.Equals("")) {
<div class="trend-chart">
@ -24,7 +24,7 @@
</div>
<div class="col-md-3 px-1">
<div class="card-box px-3" style="height:320px;">
<div class="card-box px-3" style="height:340px;">
<div class="cdev" data-percent="100" data-duration="@Html.Raw(@Model.PTMagicConfiguration.GeneralSettings.Monitor.RefreshSeconds * 1000)" data-color="#aaa,#414d59"></div>
@{
string totalCurrentValueString = Model.totalCurrentValue.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"));
@ -127,44 +127,42 @@
<h4 class="m-t-0 m-b-20 header-title"><b>Sales Overview</b><small class="pull-right"><a href="@Html.Raw(Model.PTMagicConfiguration.GeneralSettings.Monitor.RootUrl)SalesAnalyzer">more</a></small></h4>
@{
double avgGrowthThisMonth = Model.PTData.MonthlyStats.FirstOrDefault(data => data.Order == 1)?.AvgGrowth ?? 0.0;
double avgGrowthLastMonth = Model.PTData.MonthlyStats.FirstOrDefault(data => data.Order == 2)?.AvgGrowth ?? 0.0;
var overviewStats = Model.StatsData; // todaysStats is a new variable
//var startingBalance = Model.MiscData.StartBalance;
var totalCurrentValue = Model.totalCurrentValue;
var overviewStats = Model.StatsData;
var todaysSales = overviewStats.SalesToday;
var todaysProfit = overviewStats.ProfitToday;
var todaysFunding = overviewStats.FundingToday;
var todaysPercentGain = overviewStats.ProfitPercToday;
//var todaysFundingGain = todaysPercentGain * ((todaysProfit - todaysFunding) / todaysProfit);
var todaysPercentGain = overviewStats.ProfitPercToday + Model.PTData.Stats.TotalFundingPercToday;
var yesterdaysSales = overviewStats.SalesYesterday;
var yesterdaysProfit = overviewStats.ProfitYesterday;
var yesterdaysFunding = overviewStats.FundingYesterday;
var yesterdaysPercentGain = overviewStats.ProfitPercYesterday;
//var yesterdaysFundingGain = yesterdaysPercentGain * ((yesterdaysProfit + yesterdaysFunding) / yesterdaysProfit);
var yesterdaysPercentGain = overviewStats.ProfitPercYesterday + Model.PTData.Stats.TotalFundingPercYesterday;
var last7DaysSales = overviewStats.SalesWeek;
var last7DaysProfit = overviewStats.ProfitWeek;
var last7DaysFunding = overviewStats.FundingWeek;
var last7DaysPercentGain = overviewStats.ProfitPercWeek;
//var last7DaysFundingGain = last7DaysPercentGain * ((last7DaysProfit + last7DaysFunding) / last7DaysProfit);
var last7DaysPercentGain = overviewStats.ProfitPercWeek + Model.PTData.Stats.TotalFundingPercWeek;
var thisMonthSales = overviewStats.SalesThisMonth;
var thisMonthProfit = overviewStats.ProfitThisMonth;
var thisMonthFunding = overviewStats.FundingThisMonth;
var thisMonthPercentGain = overviewStats.ProfitPercThisMonth;
//var thisMonthFundingGain = thisMonthPercentGain * ((thisMonthProfit + thisMonthFunding) / thisMonthProfit);
var thisMonthPercentGain = avgGrowthThisMonth;
var lastMonthSales = overviewStats.SalesLastMonth;
var lastMonthProfit = overviewStats.ProfitLastMonth;
var lastMonthFunding = overviewStats.FundingLastMonth;
var lastMonthPercentGain = overviewStats.ProfitPercLastMonth;
//var lastMonthFundingGain = lastMonthPercentGain * ((lastMonthProfit + lastMonthFunding) / lastMonthProfit);
var lastMonthPercentGain = avgGrowthLastMonth;
var totalSales = overviewStats.TotalSales;
var totalProfit = overviewStats.TotalProfit;
var totalFunding = overviewStats.FundingTotal;
var totalProfitPercent = overviewStats.TotalProfitPerc;
//var totalFundingGain = totalProfitPercent * ((totalProfit + totalFunding) / totalProfit);
var totalPercentGain = overviewStats.TotalProfitPerc + Model.PTData.Stats.TotalFundingPerc;
double todaysProfitFiat = Math.Round((todaysProfit + todaysFunding) * Model.PTData.Misc.FiatConversionRate, 2);
double yesterdaysProfitFiat = Math.Round((yesterdaysProfit + yesterdaysFunding) * Model.PTData.Misc.FiatConversionRate, 2);
@ -182,12 +180,12 @@
<th></th>
<th class="text-right">Sales</th>
<th class="text-right">Profit @Model.PTData.Misc.Market</th>
<th class="text-right">Gain</th>
@if (futuresFunding)
{
<th class="text-right">Funding</th>
<th class="text-right">Funding @Model.PTData.Misc.Market</th>
}
<th class="text-right">@Model.PTData.Properties.Currency</th>
<th class="text-right">Gain</th>
</tr>
</thead>
<tbody>
@ -195,67 +193,67 @@
<th>Today</th>
<td class="text-right">@overviewStats.SalesToday</td>
<td class="text-right text-autocolor">@todaysProfit.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@todaysPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
@if (futuresFunding)
{
<td class="text-right text-autocolor">@todaysFunding.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
}
<td class="text-right text-autocolor">@Html.Raw(todaysProfitFiat.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@todaysPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>Yesterday</th>
<td class="text-right">@yesterdaysSales</td>
<td class="text-right text-autocolor">@yesterdaysProfit.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@yesterdaysPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
@if (futuresFunding)
{
<td class="text-right text-autocolor">@yesterdaysFunding.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
}
}
<td class="text-right text-autocolor">@Html.Raw(yesterdaysProfitFiat.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@yesterdaysPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>Last 7 Days</th>
<td class="text-right">@last7DaysSales</td>
<td class="text-right text-autocolor">@last7DaysProfit.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@last7DaysPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
@if (futuresFunding)
{
<td class="text-right text-autocolor">@last7DaysFunding.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
}
<td class="text-right text-autocolor">@Html.Raw(last7DaysProfitFiat.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@last7DaysPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>This Month</th>
<td class="text-right">@thisMonthSales</td>
<td class="text-right text-autocolor">@thisMonthProfit.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@thisMonthPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
@if (futuresFunding)
{
<td class="text-right text-autocolor">@thisMonthFunding.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
}
<td class="text-right text-autocolor">@Html.Raw(thisMonthProfitFiat.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@thisMonthPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>Last Month</th>
<td class="text-right">@lastMonthSales</td>
<td class="text-right text-autocolor">@lastMonthProfit.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@lastMonthPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
@if (futuresFunding)
{
<td class="text-right text-autocolor">@lastMonthFunding.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
}
<td class="text-right text-autocolor">@Html.Raw(lastMonthProfitFiat.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@lastMonthPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
<tr>
<th>Total</th>
<td class="text-right">@totalSales</td>
<td class="text-right text-autocolor">@totalProfit.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
<td class="text-right text-autocolor">@totalProfitPercent.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
@if (futuresFunding)
{
<td class="text-right text-autocolor">@totalFunding.ToString("#,#0.00000000", new System.Globalization.CultureInfo("en-US"))</td>
}
<td class="text-right text-autocolor">@Html.Raw(totalProfitFiat.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US")))</td>
<td class="text-right text-autocolor">@totalPercentGain.ToString("#,#0.00", new System.Globalization.CultureInfo("en-US"))%</td>
</tr>
</tbody>
</table>

View File

@ -42,7 +42,9 @@ namespace Monitor.Pages
StatsData = this.PTData.Stats;
PropertiesData = this.PTData.Properties;
MiscData = this.PTData.Misc;
List<MonthlyStatsData> monthlyStatsData = this.PTData.MonthlyStats;
List<DailyPNLData> dailyPNLData = this.PTData.DailyPNL;
// Cleanup temp files
FileHelper.CleanupFilesMinutes(PTMagicMonitorBasePath + "wwwroot" + System.IO.Path.DirectorySeparatorChar + "assets" + System.IO.Path.DirectorySeparatorChar + "tmp" + System.IO.Path.DirectorySeparatorChar, 5);
@ -65,161 +67,162 @@ namespace Monitor.Pages
BuildAssetDistributionData();
BuildProfitChartData();
}
private void BuildMarketTrendChartData()
{
List<string> trendChartData = new List<string>();
if (MarketTrends.Count > 0)
{
int mtIndex = 0;
foreach (MarketTrend mt in MarketTrends)
List<string> trendChartData = new List<string>();
if (MarketTrends.Count > 0)
{
if (mt.DisplayGraph)
int mtIndex = 0;
foreach (MarketTrend mt in MarketTrends)
{
string lineColor = mtIndex < Constants.ChartLineColors.Length
? Constants.ChartLineColors[mtIndex]
: Constants.ChartLineColors[mtIndex - 20];
if (Summary.MarketTrendChanges.ContainsKey(mt.Name))
if (mt.DisplayGraph)
{
List<MarketTrendChange> marketTrendChangeSummaries = Summary.MarketTrendChanges[mt.Name];
string lineColor = mtIndex < Constants.ChartLineColors.Length
? Constants.ChartLineColors[mtIndex]
: Constants.ChartLineColors[mtIndex - 20];
if (marketTrendChangeSummaries.Count > 0)
if (Summary.MarketTrendChanges.ContainsKey(mt.Name))
{
List<string> trendValues = new List<string>();
List<MarketTrendChange> marketTrendChangeSummaries = Summary.MarketTrendChanges[mt.Name];
// Sort marketTrendChangeSummaries by TrendDateTime
marketTrendChangeSummaries = marketTrendChangeSummaries.OrderBy(m => m.TrendDateTime).ToList();
// Get trend ticks for chart
TimeSpan offset;
bool isNegative = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.StartsWith("-");
string offsetWithoutSign = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.TrimStart('+', '-');
if (!TimeSpan.TryParse(offsetWithoutSign, out offset))
if (marketTrendChangeSummaries.Count > 0)
{
offset = TimeSpan.Zero; // If offset is invalid, set it to zero
}
List<string> trendValues = new List<string>();
DateTime currentDateTime = DateTime.UtcNow;
DateTime startDateTime = currentDateTime.AddHours(-PTMagicConfiguration.GeneralSettings.Monitor.GraphMaxTimeframeHours);
DateTime endDateTime = currentDateTime;
// Sort marketTrendChangeSummaries by TrendDateTime
marketTrendChangeSummaries = marketTrendChangeSummaries.OrderBy(m => m.TrendDateTime).ToList();
// Ensure startDateTime doesn't exceed the available data
DateTime earliestTrendDateTime = marketTrendChangeSummaries.Min(mtc => mtc.TrendDateTime);
startDateTime = startDateTime > earliestTrendDateTime ? startDateTime : earliestTrendDateTime;
DataHours = (currentDateTime - earliestTrendDateTime).TotalHours;
// Get trend ticks for chart
TimeSpan offset;
bool isNegative = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.StartsWith("-");
string offsetWithoutSign = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.TrimStart('+', '-');
// Cache the result of SplitCamelCase(mt.Name)
string splitCamelCaseName = SystemHelper.SplitCamelCase(mt.Name);
for (DateTime tickTime = startDateTime; tickTime <= endDateTime; tickTime = tickTime.AddMinutes(PTMagicConfiguration.GeneralSettings.Monitor.GraphIntervalMinutes))
{
// Use binary search to find the range of items that match the condition
int index = marketTrendChangeSummaries.BinarySearch(new MarketTrendChange { TrendDateTime = tickTime }, Comparer<MarketTrendChange>.Create((x, y) => x.TrendDateTime.CompareTo(y.TrendDateTime)));
if (index < 0) index = ~index;
if (index < marketTrendChangeSummaries.Count)
if (!TimeSpan.TryParse(offsetWithoutSign, out offset))
{
MarketTrendChange mtc = marketTrendChangeSummaries[index];
if (Double.IsInfinity(mtc.TrendChange)) mtc.TrendChange = 0;
// Adjust tickTime to the desired timezone before converting to string
DateTime adjustedTickTime = tickTime.Add(isNegative ? -offset : offset);
trendValues.Add("{ x: new Date('" + adjustedTickTime.ToString("yyyy-MM-ddTHH:mm:ss").Replace(".", ":") + "'), y: " + mtc.TrendChange.ToString("0.00", CultureInfo.InvariantCulture) + "}");
offset = TimeSpan.Zero; // If offset is invalid, set it to zero
}
DateTime currentDateTime = DateTime.UtcNow;
DateTime startDateTime = currentDateTime.AddHours(-PTMagicConfiguration.GeneralSettings.Monitor.GraphMaxTimeframeHours);
DateTime endDateTime = currentDateTime;
// Ensure startDateTime doesn't exceed the available data
DateTime earliestTrendDateTime = marketTrendChangeSummaries.Min(mtc => mtc.TrendDateTime);
startDateTime = startDateTime > earliestTrendDateTime ? startDateTime : earliestTrendDateTime;
DataHours = (currentDateTime - earliestTrendDateTime).TotalHours;
// Cache the result of SplitCamelCase(mt.Name)
string splitCamelCaseName = SystemHelper.SplitCamelCase(mt.Name);
for (DateTime tickTime = startDateTime; tickTime <= endDateTime; tickTime = tickTime.AddMinutes(PTMagicConfiguration.GeneralSettings.Monitor.GraphIntervalMinutes))
{
// Use binary search to find the range of items that match the condition
int index = marketTrendChangeSummaries.BinarySearch(new MarketTrendChange { TrendDateTime = tickTime }, Comparer<MarketTrendChange>.Create((x, y) => x.TrendDateTime.CompareTo(y.TrendDateTime)));
if (index < 0) index = ~index;
if (index < marketTrendChangeSummaries.Count)
{
MarketTrendChange mtc = marketTrendChangeSummaries[index];
if (Double.IsInfinity(mtc.TrendChange)) mtc.TrendChange = 0;
// Adjust tickTime to the desired timezone before converting to string
DateTime adjustedTickTime = tickTime.Add(isNegative ? -offset : offset);
trendValues.Add("{ x: new Date('" + adjustedTickTime.ToString("yyyy-MM-ddTHH:mm:ss").Replace(".", ":") + "'), y: " + mtc.TrendChange.ToString("0.00", CultureInfo.InvariantCulture) + "}");
}
}
// Add most recent tick
MarketTrendChange latestMtc = marketTrendChangeSummaries.Last();
if (Double.IsInfinity(latestMtc.TrendChange)) latestMtc.TrendChange = 0;
// Adjust latestMtc.TrendDateTime to the desired timezone before converting to string
DateTime adjustedLatestTrendDateTime = latestMtc.TrendDateTime.Add(isNegative ? -offset : offset);
trendValues.Add("{ x: new Date('" + adjustedLatestTrendDateTime.ToString("yyyy-MM-ddTHH:mm:ss").Replace(".", ":") + "'), y: " + latestMtc.TrendChange.ToString("0.00", CultureInfo.InvariantCulture) + "}");
// Use cached splitCamelCaseName
trendChartData.Add("{ key: '" + splitCamelCaseName + "', color: '" + lineColor + "', values: [" + string.Join(",\n", trendValues) + "] }");
mtIndex++;
}
// Add most recent tick
MarketTrendChange latestMtc = marketTrendChangeSummaries.Last();
if (Double.IsInfinity(latestMtc.TrendChange)) latestMtc.TrendChange = 0;
// Adjust latestMtc.TrendDateTime to the desired timezone before converting to string
DateTime adjustedLatestTrendDateTime = latestMtc.TrendDateTime.Add(isNegative ? -offset : offset);
trendValues.Add("{ x: new Date('" + adjustedLatestTrendDateTime.ToString("yyyy-MM-ddTHH:mm:ss").Replace(".", ":") + "'), y: " + latestMtc.TrendChange.ToString("0.00", CultureInfo.InvariantCulture) + "}");
// Use cached splitCamelCaseName
trendChartData.Add("{ key: '" + splitCamelCaseName + "', color: '" + lineColor + "', values: [" + string.Join(",\n", trendValues) + "] }");
mtIndex++;
}
}
}
}
TrendChartDataJSON = "[" + string.Join(",", trendChartData) + "]";
}
TrendChartDataJSON = "[" + string.Join(",", trendChartData) + "]";
}
private void BuildProfitChartData()
{
List<object> profitPerDayList = new List<object>();
if (PTData.DailyPNL.Count > 0)
{
// Get timezone offset
TimeSpan offset;
bool isNegative = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.StartsWith("-");
string offsetWithoutSign = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.TrimStart('+', '-');
List<object> profitPerDayList = new List<object>();
if (!TimeSpan.TryParse(offsetWithoutSign, out offset))
if (PTData.DailyPNL.Count > 0)
{
offset = TimeSpan.Zero; // If offset is invalid, set it to zero
}
// Get timezone offset
TimeSpan offset;
bool isNegative = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.StartsWith("-");
string offsetWithoutSign = PTMagicConfiguration.GeneralSettings.Application.TimezoneOffset.TrimStart('+', '-');
DateTime endDate = DateTime.UtcNow.Add(isNegative ? -offset : offset).Date;
// Parse dates once and adjust them to the local timezone
Dictionary<DateTime, DailyPNLData> dailyPNLByDate = PTData.DailyPNL
.Select(data => {
DateTime dateUtc = DateTime.ParseExact(data.Date, "d-M-yyyy", CultureInfo.InvariantCulture);
DateTime dateLocal = dateUtc.Add(isNegative ? -offset : offset);
return new { Date = dateLocal.Date, Data = data };
})
.ToDictionary(
item => item.Date,
item => item.Data
);
DateTime earliestDataDate = dailyPNLByDate.Keys.Min();
DateTime startDate = endDate.AddDays(-PTMagicConfiguration.GeneralSettings.Monitor.ProfitsMaxTimeframeDays - 1); // Fetch data for timeframe + 1 days
if (startDate < earliestDataDate)
{
startDate = earliestDataDate;
}
// Calculate the total days of data available
ProfitDays = (endDate - startDate).Days;
double previousDayCumulativeProfit = 0;
bool isFirstDay = true;
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
// Use the dictionary to find the DailyPNLData for the date
if (dailyPNLByDate.TryGetValue(date, out DailyPNLData dailyPNL))
if (!TimeSpan.TryParse(offsetWithoutSign, out offset))
{
if (isFirstDay)
{
isFirstDay = false;
}
else
{
// Calculate the profit for the current day
double profitFiat = Math.Round(dailyPNL.CumulativeProfitCurrency - previousDayCumulativeProfit, 2);
offset = TimeSpan.Zero; // If offset is invalid, set it to zero
}
// Add the data point to the list
profitPerDayList.Add(new { x = new DateTimeOffset(date).ToUnixTimeMilliseconds(), y = profitFiat });
DateTime endDate = DateTime.UtcNow.Add(isNegative ? -offset : offset).Date;
// Parse dates once and adjust them to the local timezone
Dictionary<DateTime, DailyPNLData> dailyPNLByDate = PTData.DailyPNL
.Select(data => {
DateTime dateUtc = DateTime.ParseExact(data.Date, "d-M-yyyy", CultureInfo.InvariantCulture);
DateTime dateLocal = dateUtc.Add(isNegative ? -offset : offset);
return new { Date = dateLocal.Date, Data = data };
})
.ToDictionary(
item => item.Date,
item => item.Data
);
DateTime earliestDataDate = dailyPNLByDate.Keys.Min();
DateTime startDate = endDate.AddDays(-PTMagicConfiguration.GeneralSettings.Monitor.ProfitsMaxTimeframeDays - 1); // Fetch data for timeframe + 1 days
if (startDate < earliestDataDate)
{
startDate = earliestDataDate;
}
// Calculate the total days of data available
ProfitDays = (endDate - startDate).Days;
double previousDayCumulativeProfit = 0;
bool isFirstDay = true;
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
// Use the dictionary to find the DailyPNLData for the date
if (dailyPNLByDate.TryGetValue(date, out DailyPNLData dailyPNL))
{
if (isFirstDay)
{
isFirstDay = false;
}
else
{
// Calculate the profit for the current day
double profitFiat = Math.Round(dailyPNL.CumulativeProfitCurrency - previousDayCumulativeProfit, 2);
// Add the data point to the list
profitPerDayList.Add(new { x = new DateTimeOffset(date).ToUnixTimeMilliseconds(), y = profitFiat });
}
previousDayCumulativeProfit = dailyPNL.CumulativeProfitCurrency;
}
previousDayCumulativeProfit = dailyPNL.CumulativeProfitCurrency;
}
// Convert the list to a JSON string using Newtonsoft.Json
ProfitChartDataJSON = Newtonsoft.Json.JsonConvert.SerializeObject(new[] {
new {
key = "Profit in " + PTData.Misc.Market,
color = Constants.ChartLineColors[1],
values = profitPerDayList
}
});
}
// Convert the list to a JSON string using Newtonsoft.Json
ProfitChartDataJSON = Newtonsoft.Json.JsonConvert.SerializeObject(new[] {
new {
key = "Profit in " + PTData.Misc.Market,
color = Constants.ChartLineColors[1],
values = profitPerDayList
}
});
}
}
private void BuildAssetDistributionData()
{