aiden-shared-calculations-unified 1.0.35 → 1.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.MD +77 -77
  2. package/calculations/activity/historical/activity_by_pnl_status.js +85 -85
  3. package/calculations/activity/historical/daily_asset_activity.js +85 -85
  4. package/calculations/activity/historical/daily_user_activity_tracker.js +144 -144
  5. package/calculations/activity/historical/speculator_adjustment_activity.js +76 -76
  6. package/calculations/asset_metrics/asset_position_size.js +57 -57
  7. package/calculations/backtests/strategy-performance.js +229 -245
  8. package/calculations/behavioural/historical/asset_crowd_flow.js +165 -165
  9. package/calculations/behavioural/historical/drawdown_response.js +58 -58
  10. package/calculations/behavioural/historical/dumb-cohort-flow.js +217 -249
  11. package/calculations/behavioural/historical/gain_response.js +57 -57
  12. package/calculations/behavioural/historical/in_loss_asset_crowd_flow.js +98 -98
  13. package/calculations/behavioural/historical/in_profit_asset_crowd_flow.js +99 -99
  14. package/calculations/behavioural/historical/paper_vs_diamond_hands.js +39 -39
  15. package/calculations/behavioural/historical/position_count_pnl.js +67 -67
  16. package/calculations/behavioural/historical/smart-cohort-flow.js +217 -250
  17. package/calculations/behavioural/historical/smart_money_flow.js +165 -165
  18. package/calculations/behavioural/historical/user-investment-profile.js +358 -412
  19. package/calculations/capital_flow/historical/crowd-cash-flow-proxy.js +121 -121
  20. package/calculations/capital_flow/historical/deposit_withdrawal_percentage.js +117 -117
  21. package/calculations/capital_flow/historical/new_allocation_percentage.js +49 -49
  22. package/calculations/insights/daily_bought_vs_sold_count.js +55 -55
  23. package/calculations/insights/daily_buy_sell_sentiment_count.js +49 -49
  24. package/calculations/insights/daily_ownership_delta.js +55 -55
  25. package/calculations/insights/daily_total_positions_held.js +39 -39
  26. package/calculations/meta/capital_deployment_strategy.js +129 -137
  27. package/calculations/meta/capital_liquidation_performance.js +121 -163
  28. package/calculations/meta/capital_vintage_performance.js +121 -158
  29. package/calculations/meta/cash-flow-deployment.js +110 -124
  30. package/calculations/meta/cash-flow-liquidation.js +126 -142
  31. package/calculations/meta/crowd_sharpe_ratio_proxy.js +83 -91
  32. package/calculations/meta/profit_cohort_divergence.js +77 -91
  33. package/calculations/meta/smart-dumb-divergence-index.js +116 -138
  34. package/calculations/meta/social_flow_correlation.js +99 -125
  35. package/calculations/pnl/asset_pnl_status.js +46 -46
  36. package/calculations/pnl/historical/profitability_migration.js +57 -57
  37. package/calculations/pnl/historical/user_profitability_tracker.js +117 -117
  38. package/calculations/pnl/profitable_and_unprofitable_status.js +64 -64
  39. package/calculations/sectors/historical/diversification_pnl.js +76 -76
  40. package/calculations/sectors/historical/sector_rotation.js +67 -67
  41. package/calculations/sentiment/historical/crowd_conviction_score.js +80 -80
  42. package/calculations/socialPosts/social-asset-posts-trend.js +52 -52
  43. package/calculations/socialPosts/social-top-mentioned-words.js +102 -102
  44. package/calculations/socialPosts/social-topic-interest-evolution.js +53 -53
  45. package/calculations/socialPosts/social-word-mentions-trend.js +62 -62
  46. package/calculations/socialPosts/social_activity_aggregation.js +103 -103
  47. package/calculations/socialPosts/social_event_correlation.js +121 -121
  48. package/calculations/socialPosts/social_sentiment_aggregation.js +114 -114
  49. package/calculations/speculators/historical/risk_appetite_change.js +54 -54
  50. package/calculations/speculators/historical/tsl_effectiveness.js +74 -74
  51. package/index.js +33 -33
  52. package/package.json +32 -32
  53. package/utils/firestore_utils.js +76 -76
  54. package/utils/price_data_provider.js +142 -142
  55. package/utils/sector_mapping_provider.js +74 -74
  56. package/calculations/capital_flow/historical/reallocation_increase_percentage.js +0 -63
  57. package/calculations/speculators/stop_loss_distance_by_sector_short_long_breakdown.js +0 -91
  58. package/calculations/speculators/stop_loss_distance_by_ticker_short_long_breakdown.js +0 -73
@@ -1,122 +1,122 @@
1
- /**
2
- * @fileoverview Correlates social post volume spikes with topics from Gemini analysis.
3
- * This calculation ONLY uses the social post insights context.
4
- */
5
-
6
- class SocialEventCorrelation {
7
- constructor() {
8
- this.todayTickerVolume = {};
9
- this.yesterdayTickerVolume = {};
10
- this.todayTopicCounts = {}; // { "TICKER": { "topic": count } }
11
- this.processed = false;
12
- }
13
-
14
- /**
15
- * Helper to process a set of posts and populate volume/topic counts.
16
- * @param {object} socialPostInsights - Map of { [postId]: postData }
17
- * @param {object} volumeTarget - The object to store volume counts.
18
- * @param {object} [topicTarget] - Optional. The object to store topic counts.
19
- */
20
- _processPosts(socialPostInsights, volumeTarget, topicTarget = null) {
21
- if (!socialPostInsights) return;
22
- const posts = Object.values(socialPostInsights);
23
-
24
- for (const post of posts) {
25
- if (!post.tickers || !Array.isArray(post.tickers)) continue;
26
-
27
- for (const ticker of post.tickers) {
28
- // 1. Aggregate Volume
29
- volumeTarget[ticker] = (volumeTarget[ticker] || 0) + 1;
30
-
31
- // 2. Aggregate Topics (if target provided)
32
- if (topicTarget) {
33
- if (!topicTarget[ticker]) {
34
- topicTarget[ticker] = {};
35
- }
36
- // New structure: post.sentiment is { overallSentiment: "...", topics: [...] }
37
- const topics = post.sentiment?.topics;
38
- if (topics && Array.isArray(topics)) {
39
- for (const topic of topics) {
40
- // Normalize topic to lowercase for consistent counting
41
- const normalizedTopic = topic.toLowerCase();
42
- topicTarget[ticker][normalizedTopic] = (topicTarget[ticker][normalizedTopic] || 0) + 1;
43
- }
44
- }
45
- }
46
- }
47
- }
48
- }
49
-
50
- /**
51
- * @param {null} todayPortfolio - Not used.
52
- * @param {null} yesterdayPortfolio - Not used.
53
- * @param {null} userId - Not used.
54
- * @param {object} context - Shared context (e.g., mappings).
55
- * @param {object} todayInsights - Daily instrument insights.
56
- * @param {object} yesterdayInsights - Yesterday's instrument insights.
57
- * @param {object} todaySocialPostInsights - Map of { [postId]: postData } for today.
58
- * @param {object} yesterdaySocialPostInsights - Map of { [postId]: postData } for yesterday.
59
- */
60
- async process(todayPortfolio, yesterdayPortfolio, userId, context, todayInsights, yesterdayInsights, todaySocialPostInsights, yesterdaySocialPostInsights) {
61
-
62
- if (this.processed) {
63
- return; // Run only once
64
- }
65
- this.processed = true;
66
-
67
- // 1. Process yesterday's posts for baseline volume
68
- this._processPosts(yesterdaySocialPostInsights, this.yesterdayTickerVolume);
69
-
70
- // 2. Process today's posts for volume AND topic correlation
71
- this._processPosts(todaySocialPostInsights, this.todayTickerVolume, this.todayTopicCounts);
72
- }
73
-
74
- async getResult() {
75
- if (!this.processed) return {};
76
-
77
- const results = {};
78
- const allTickers = new Set([
79
- ...Object.keys(this.todayTickerVolume),
80
- ...Object.keys(this.yesterdayTickerVolume)
81
- ]);
82
-
83
- for (const ticker of allTickers) {
84
- const todayVolume = this.todayTickerVolume[ticker] || 0;
85
- // Use 1 as baseline if yesterday was 0 to avoid -100% change, but 0 for spike calc
86
- const yesterdayVolumeForCalc = this.yesterdayTickerVolume[ticker] || 0;
87
-
88
- let volumeSpikePercent = 0;
89
- if (yesterdayVolumeForCalc > 0) {
90
- volumeSpikePercent = ((todayVolume - yesterdayVolumeForCalc) / yesterdayVolumeForCalc) * 100;
91
- } else if (todayVolume > 0) {
92
- volumeSpikePercent = todayVolume * 100.0; // e.g., 0 to 5 posts is a 500% increase
93
- }
94
-
95
- // Only report tickers with activity today
96
- if (todayVolume === 0) continue;
97
-
98
- // Correlate topics
99
- const topics = this.todayTopicCounts[ticker] || {};
100
- const correlatedEvents = Object.entries(topics)
101
- .map(([topic, postCount]) => ({ topic, postCount }))
102
- .sort((a, b) => b.postCount - a.postCount); // Sort by count descending
103
-
104
- results[ticker] = {
105
- volume: todayVolume,
106
- volumeSpikePercent: volumeSpikePercent,
107
- correlatedEvents: correlatedEvents
108
- };
109
- }
110
-
111
- return results;
112
- }
113
-
114
- reset() {
115
- this.todayTickerVolume = {};
116
- this.yesterdayTickerVolume = {};
117
- this.todayTopicCounts = {};
118
- this.processed = false;
119
- }
120
- }
121
-
1
+ /**
2
+ * @fileoverview Correlates social post volume spikes with topics from Gemini analysis.
3
+ * This calculation ONLY uses the social post insights context.
4
+ */
5
+
6
+ class SocialEventCorrelation {
7
+ constructor() {
8
+ this.todayTickerVolume = {};
9
+ this.yesterdayTickerVolume = {};
10
+ this.todayTopicCounts = {}; // { "TICKER": { "topic": count } }
11
+ this.processed = false;
12
+ }
13
+
14
+ /**
15
+ * Helper to process a set of posts and populate volume/topic counts.
16
+ * @param {object} socialPostInsights - Map of { [postId]: postData }
17
+ * @param {object} volumeTarget - The object to store volume counts.
18
+ * @param {object} [topicTarget] - Optional. The object to store topic counts.
19
+ */
20
+ _processPosts(socialPostInsights, volumeTarget, topicTarget = null) {
21
+ if (!socialPostInsights) return;
22
+ const posts = Object.values(socialPostInsights);
23
+
24
+ for (const post of posts) {
25
+ if (!post.tickers || !Array.isArray(post.tickers)) continue;
26
+
27
+ for (const ticker of post.tickers) {
28
+ // 1. Aggregate Volume
29
+ volumeTarget[ticker] = (volumeTarget[ticker] || 0) + 1;
30
+
31
+ // 2. Aggregate Topics (if target provided)
32
+ if (topicTarget) {
33
+ if (!topicTarget[ticker]) {
34
+ topicTarget[ticker] = {};
35
+ }
36
+ // New structure: post.sentiment is { overallSentiment: "...", topics: [...] }
37
+ const topics = post.sentiment?.topics;
38
+ if (topics && Array.isArray(topics)) {
39
+ for (const topic of topics) {
40
+ // Normalize topic to lowercase for consistent counting
41
+ const normalizedTopic = topic.toLowerCase();
42
+ topicTarget[ticker][normalizedTopic] = (topicTarget[ticker][normalizedTopic] || 0) + 1;
43
+ }
44
+ }
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ /**
51
+ * @param {null} todayPortfolio - Not used.
52
+ * @param {null} yesterdayPortfolio - Not used.
53
+ * @param {null} userId - Not used.
54
+ * @param {object} context - Shared context (e.g., mappings).
55
+ * @param {object} todayInsights - Daily instrument insights.
56
+ * @param {object} yesterdayInsights - Yesterday's instrument insights.
57
+ * @param {object} todaySocialPostInsights - Map of { [postId]: postData } for today.
58
+ * @param {object} yesterdaySocialPostInsights - Map of { [postId]: postData } for yesterday.
59
+ */
60
+ async process(todayPortfolio, yesterdayPortfolio, userId, context, todayInsights, yesterdayInsights, todaySocialPostInsights, yesterdaySocialPostInsights) {
61
+
62
+ if (this.processed) {
63
+ return; // Run only once
64
+ }
65
+ this.processed = true;
66
+
67
+ // 1. Process yesterday's posts for baseline volume
68
+ this._processPosts(yesterdaySocialPostInsights, this.yesterdayTickerVolume);
69
+
70
+ // 2. Process today's posts for volume AND topic correlation
71
+ this._processPosts(todaySocialPostInsights, this.todayTickerVolume, this.todayTopicCounts);
72
+ }
73
+
74
+ async getResult() {
75
+ if (!this.processed) return {};
76
+
77
+ const results = {};
78
+ const allTickers = new Set([
79
+ ...Object.keys(this.todayTickerVolume),
80
+ ...Object.keys(this.yesterdayTickerVolume)
81
+ ]);
82
+
83
+ for (const ticker of allTickers) {
84
+ const todayVolume = this.todayTickerVolume[ticker] || 0;
85
+ // Use 1 as baseline if yesterday was 0 to avoid -100% change, but 0 for spike calc
86
+ const yesterdayVolumeForCalc = this.yesterdayTickerVolume[ticker] || 0;
87
+
88
+ let volumeSpikePercent = 0;
89
+ if (yesterdayVolumeForCalc > 0) {
90
+ volumeSpikePercent = ((todayVolume - yesterdayVolumeForCalc) / yesterdayVolumeForCalc) * 100;
91
+ } else if (todayVolume > 0) {
92
+ volumeSpikePercent = todayVolume * 100.0; // e.g., 0 to 5 posts is a 500% increase
93
+ }
94
+
95
+ // Only report tickers with activity today
96
+ if (todayVolume === 0) continue;
97
+
98
+ // Correlate topics
99
+ const topics = this.todayTopicCounts[ticker] || {};
100
+ const correlatedEvents = Object.entries(topics)
101
+ .map(([topic, postCount]) => ({ topic, postCount }))
102
+ .sort((a, b) => b.postCount - a.postCount); // Sort by count descending
103
+
104
+ results[ticker] = {
105
+ volume: todayVolume,
106
+ volumeSpikePercent: volumeSpikePercent,
107
+ correlatedEvents: correlatedEvents
108
+ };
109
+ }
110
+
111
+ return results;
112
+ }
113
+
114
+ reset() {
115
+ this.todayTickerVolume = {};
116
+ this.yesterdayTickerVolume = {};
117
+ this.todayTopicCounts = {};
118
+ this.processed = false;
119
+ }
120
+ }
121
+
122
122
  module.exports = SocialEventCorrelation;
@@ -1,115 +1,115 @@
1
- /**
2
- * @fileoverview Aggregates sentiment data from social posts.
3
- * This calculation ONLY uses the social post insights context, not portfolio data.
4
- * UPDATED: To read sentiment from the `sentiment.overallSentiment` property.
5
- */
6
-
7
- class SocialSentimentAggregation {
8
- constructor() {
9
- this.tickerSentiments = {};
10
- this.totalPosts = 0;
11
- this.sentimentCounts = {
12
- Bullish: 0,
13
- Bearish: 0,
14
- Neutral: 0
15
- };
16
- this.processed = false; // Flag to ensure this runs only once
17
- }
18
-
19
- /**
20
- * @param {null} todayPortfolio - Not used.
21
- * @param {null} yesterdayPortfolio - Not used.
22
- * @param {null} userId - Not used.
23
- * @param {object} context - Shared context (e.g., mappings).
24
- * @param {object} todayInsights - Daily instrument insights.
25
- * @param {object} yesterdayInsights - Yesterday's instrument insights.
26
- * @param {object} todaySocialPostInsights - Map of { [postId]: postData } for today.
27
- * @param {object} yesterdaySocialPostInsights - Map of { [postId]: postData } for yesterday.
28
- */
29
- async process(todayPortfolio, yesterdayPortfolio, userId, context, todayInsights, yesterdayInsights, todaySocialPostInsights, yesterdaySocialPostInsights) {
30
- // This process should only run once per day, triggered by the first "user" (which is just a trigger).
31
- if (this.processed || !todaySocialPostInsights) {
32
- return;
33
- }
34
- this.processed = true;
35
-
36
- const posts = Object.values(todaySocialPostInsights);
37
- this.totalPosts = posts.length;
38
-
39
- for (const post of posts) {
40
- // --- FIX: Read from the nested overallSentiment property ---
41
- const sentiment = post.sentiment?.overallSentiment || 'Neutral';
42
- // --- END FIX ---
43
-
44
- // 1. Aggregate global sentiment counts
45
- if (this.sentimentCounts.hasOwnProperty(sentiment)) {
46
- this.sentimentCounts[sentiment]++;
47
- }
48
-
49
- // 2. Aggregate sentiment per ticker
50
- if (post.tickers && Array.isArray(post.tickers)) {
51
- for (const ticker of post.tickers) {
52
- if (!this.tickerSentiments[ticker]) {
53
- this.tickerSentiments[ticker] = {
54
- Bullish: 0,
55
- Bearish: 0,
56
- Neutral: 0,
57
- totalPosts: 0
58
- };
59
- }
60
- if (this.tickerSentiments[ticker].hasOwnProperty(sentiment)) {
61
- this.tickerSentiments[ticker][sentiment]++;
62
- }
63
- this.tickerSentiments[ticker].totalPosts++;
64
- }
65
- }
66
- }
67
- }
68
-
69
- async getResult() {
70
- if (!this.processed) return {};
71
-
72
- // Calculate global sentiment ratio
73
- let globalSentimentRatio = 0;
74
- const totalSentiments = this.sentimentCounts.Bullish + this.sentimentCounts.Bearish;
75
- if (totalSentiments > 0) {
76
- globalSentimentRatio = (this.sentimentCounts.Bullish / totalSentiments) * 100;
77
- }
78
-
79
- // Calculate per-ticker sentiment ratios
80
- const tickerSentimentRatios = {};
81
- for (const ticker in this.tickerSentiments) {
82
- const data = this.tickerSentiments[ticker];
83
- const totalTickerSentiments = data.Bullish + data.Bearish;
84
- if (totalTickerSentiments > 0) {
85
- tickerSentimentRatios[ticker] = {
86
- sentimentRatio: (data.Bullish / totalTickerSentiments) * 100,
87
- ...data // Include counts
88
- };
89
- } else {
90
- tickerSentimentRatios[ticker] = {
91
- sentimentRatio: 50, // Default to neutral if no clear sentiment
92
- ...data // Include counts
93
- };
94
- }
95
- }
96
-
97
- return {
98
- globalSentiment: {
99
- ...this.sentimentCounts,
100
- totalPosts: this.totalPosts,
101
- sentimentRatio: globalSentimentRatio
102
- },
103
- tickerSentiment: tickerSentimentRatios
104
- };
105
- }
106
-
107
- reset() {
108
- this.tickerSentiments = {};
109
- this.totalPosts = 0;
110
- this.sentimentCounts = { Bullish: 0, Bearish: 0, Neutral: 0 };
111
- this.processed = false;
112
- }
113
- }
114
-
1
+ /**
2
+ * @fileoverview Aggregates sentiment data from social posts.
3
+ * This calculation ONLY uses the social post insights context, not portfolio data.
4
+ * UPDATED: To read sentiment from the `sentiment.overallSentiment` property.
5
+ */
6
+
7
+ class SocialSentimentAggregation {
8
+ constructor() {
9
+ this.tickerSentiments = {};
10
+ this.totalPosts = 0;
11
+ this.sentimentCounts = {
12
+ Bullish: 0,
13
+ Bearish: 0,
14
+ Neutral: 0
15
+ };
16
+ this.processed = false; // Flag to ensure this runs only once
17
+ }
18
+
19
+ /**
20
+ * @param {null} todayPortfolio - Not used.
21
+ * @param {null} yesterdayPortfolio - Not used.
22
+ * @param {null} userId - Not used.
23
+ * @param {object} context - Shared context (e.g., mappings).
24
+ * @param {object} todayInsights - Daily instrument insights.
25
+ * @param {object} yesterdayInsights - Yesterday's instrument insights.
26
+ * @param {object} todaySocialPostInsights - Map of { [postId]: postData } for today.
27
+ * @param {object} yesterdaySocialPostInsights - Map of { [postId]: postData } for yesterday.
28
+ */
29
+ async process(todayPortfolio, yesterdayPortfolio, userId, context, todayInsights, yesterdayInsights, todaySocialPostInsights, yesterdaySocialPostInsights) {
30
+ // This process should only run once per day, triggered by the first "user" (which is just a trigger).
31
+ if (this.processed || !todaySocialPostInsights) {
32
+ return;
33
+ }
34
+ this.processed = true;
35
+
36
+ const posts = Object.values(todaySocialPostInsights);
37
+ this.totalPosts = posts.length;
38
+
39
+ for (const post of posts) {
40
+ // --- FIX: Read from the nested overallSentiment property ---
41
+ const sentiment = post.sentiment?.overallSentiment || 'Neutral';
42
+ // --- END FIX ---
43
+
44
+ // 1. Aggregate global sentiment counts
45
+ if (this.sentimentCounts.hasOwnProperty(sentiment)) {
46
+ this.sentimentCounts[sentiment]++;
47
+ }
48
+
49
+ // 2. Aggregate sentiment per ticker
50
+ if (post.tickers && Array.isArray(post.tickers)) {
51
+ for (const ticker of post.tickers) {
52
+ if (!this.tickerSentiments[ticker]) {
53
+ this.tickerSentiments[ticker] = {
54
+ Bullish: 0,
55
+ Bearish: 0,
56
+ Neutral: 0,
57
+ totalPosts: 0
58
+ };
59
+ }
60
+ if (this.tickerSentiments[ticker].hasOwnProperty(sentiment)) {
61
+ this.tickerSentiments[ticker][sentiment]++;
62
+ }
63
+ this.tickerSentiments[ticker].totalPosts++;
64
+ }
65
+ }
66
+ }
67
+ }
68
+
69
+ async getResult() {
70
+ if (!this.processed) return {};
71
+
72
+ // Calculate global sentiment ratio
73
+ let globalSentimentRatio = 0;
74
+ const totalSentiments = this.sentimentCounts.Bullish + this.sentimentCounts.Bearish;
75
+ if (totalSentiments > 0) {
76
+ globalSentimentRatio = (this.sentimentCounts.Bullish / totalSentiments) * 100;
77
+ }
78
+
79
+ // Calculate per-ticker sentiment ratios
80
+ const tickerSentimentRatios = {};
81
+ for (const ticker in this.tickerSentiments) {
82
+ const data = this.tickerSentiments[ticker];
83
+ const totalTickerSentiments = data.Bullish + data.Bearish;
84
+ if (totalTickerSentiments > 0) {
85
+ tickerSentimentRatios[ticker] = {
86
+ sentimentRatio: (data.Bullish / totalTickerSentiments) * 100,
87
+ ...data // Include counts
88
+ };
89
+ } else {
90
+ tickerSentimentRatios[ticker] = {
91
+ sentimentRatio: 50, // Default to neutral if no clear sentiment
92
+ ...data // Include counts
93
+ };
94
+ }
95
+ }
96
+
97
+ return {
98
+ globalSentiment: {
99
+ ...this.sentimentCounts,
100
+ totalPosts: this.totalPosts,
101
+ sentimentRatio: globalSentimentRatio
102
+ },
103
+ tickerSentiment: tickerSentimentRatios
104
+ };
105
+ }
106
+
107
+ reset() {
108
+ this.tickerSentiments = {};
109
+ this.totalPosts = 0;
110
+ this.sentimentCounts = { Bullish: 0, Bearish: 0, Neutral: 0 };
111
+ this.processed = false;
112
+ }
113
+ }
114
+
115
115
  module.exports = SocialSentimentAggregation;
@@ -1,55 +1,55 @@
1
- /**
2
- * @fileoverview Calculates the change in risk appetite for speculators based on stop-loss distance.
3
- */
4
-
5
- class RiskAppetiteChange {
6
- constructor() {
7
- this.totalYesterdaySLDistance = 0;
8
- this.totalTodaySLDistance = 0;
9
- this.userCount = 0;
10
- }
11
-
12
- process(todayPortfolio, yesterdayPortfolio, userId) {
13
- if (!todayPortfolio || !yesterdayPortfolio || !todayPortfolio.PublicPositions || !yesterdayPortfolio.PublicPositions) {
14
- return;
15
- }
16
-
17
- const yesterdayAvgDistance = this.calculateAverageSLDistance(yesterdayPortfolio.PublicPositions);
18
- const todayAvgDistance = this.calculateAverageSLDistance(todayPortfolio.PublicPositions);
19
-
20
- if (yesterdayAvgDistance !== null && todayAvgDistance !== null) {
21
- this.totalYesterdaySLDistance += yesterdayAvgDistance;
22
- this.totalTodaySLDistance += todayAvgDistance;
23
- this.userCount++;
24
- }
25
- }
26
-
27
- calculateAverageSLDistance(positions) {
28
- let totalDistance = 0;
29
- let count = 0;
30
- for (const pos of positions) {
31
- if (pos.StopLossRate > 0.0001 && pos.OpenRate > 0) {
32
- const distance = pos.IsBuy ? pos.OpenRate - pos.StopLossRate : pos.StopLossRate - pos.OpenRate;
33
- if (distance > 0) {
34
- totalDistance += (distance / pos.OpenRate) * 100;
35
- count++;
36
- }
37
- }
38
- }
39
- return count > 0 ? totalDistance / count : null;
40
- }
41
-
42
- getResult() {
43
- if (this.userCount === 0) return {};
44
- const avgYesterday = this.totalYesterdaySLDistance / this.userCount;
45
- const avgToday = this.totalTodaySLDistance / this.userCount;
46
-
47
- return {
48
- average_stop_loss_distance_yesterday: avgYesterday,
49
- average_stop_loss_distance_today: avgToday,
50
- change_in_risk_appetite: avgToday - avgYesterday,
51
- };
52
- }
53
- }
54
-
1
+ /**
2
+ * @fileoverview Calculates the change in risk appetite for speculators based on stop-loss distance.
3
+ */
4
+
5
+ class RiskAppetiteChange {
6
+ constructor() {
7
+ this.totalYesterdaySLDistance = 0;
8
+ this.totalTodaySLDistance = 0;
9
+ this.userCount = 0;
10
+ }
11
+
12
+ process(todayPortfolio, yesterdayPortfolio, userId) {
13
+ if (!todayPortfolio || !yesterdayPortfolio || !todayPortfolio.PublicPositions || !yesterdayPortfolio.PublicPositions) {
14
+ return;
15
+ }
16
+
17
+ const yesterdayAvgDistance = this.calculateAverageSLDistance(yesterdayPortfolio.PublicPositions);
18
+ const todayAvgDistance = this.calculateAverageSLDistance(todayPortfolio.PublicPositions);
19
+
20
+ if (yesterdayAvgDistance !== null && todayAvgDistance !== null) {
21
+ this.totalYesterdaySLDistance += yesterdayAvgDistance;
22
+ this.totalTodaySLDistance += todayAvgDistance;
23
+ this.userCount++;
24
+ }
25
+ }
26
+
27
+ calculateAverageSLDistance(positions) {
28
+ let totalDistance = 0;
29
+ let count = 0;
30
+ for (const pos of positions) {
31
+ if (pos.StopLossRate > 0.0001 && pos.OpenRate > 0) {
32
+ const distance = pos.IsBuy ? pos.OpenRate - pos.StopLossRate : pos.StopLossRate - pos.OpenRate;
33
+ if (distance > 0) {
34
+ totalDistance += (distance / pos.OpenRate) * 100;
35
+ count++;
36
+ }
37
+ }
38
+ }
39
+ return count > 0 ? totalDistance / count : null;
40
+ }
41
+
42
+ getResult() {
43
+ if (this.userCount === 0) return {};
44
+ const avgYesterday = this.totalYesterdaySLDistance / this.userCount;
45
+ const avgToday = this.totalTodaySLDistance / this.userCount;
46
+
47
+ return {
48
+ average_stop_loss_distance_yesterday: avgYesterday,
49
+ average_stop_loss_distance_today: avgToday,
50
+ change_in_risk_appetite: avgToday - avgYesterday,
51
+ };
52
+ }
53
+ }
54
+
55
55
  module.exports = RiskAppetiteChange;