aiden-shared-calculations-unified 1.0.90 → 1.0.92

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.
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * @fileoverview Core Metric (Pass 2)
3
- * REFACTORED: Buckets users by P&L status (Win/Loss).
3
+ * REFACTORED: Buckets P&L status by User Profile.
4
+ * - Pivots data to be User-Centric (User -> Winners/Losers).
5
+ * - Removes sharding complexity (fits within 1MB via structure optimization).
4
6
  */
5
7
  class AssetPnlStatus {
6
8
  constructor() {
7
- this.tickerBuckets = new Map();
8
- this.sectorBuckets = new Map();
9
+ // Map<UserId, { winners: Set<String>, losers: Set<String> }>
10
+ this.userStats = new Map();
9
11
  }
10
12
 
11
13
  static getMetadata() {
@@ -21,80 +23,92 @@ class AssetPnlStatus {
21
23
  static getDependencies() { return []; }
22
24
 
23
25
  static getSchema() {
24
- const cohortSchema = {
25
- "type": "object",
26
- "properties": {
27
- "winners": { "type": "array", "items": { "type": "string" } },
28
- "losers": { "type": "array", "items": { "type": "string" } }
29
- },
30
- "required": ["winners", "losers"]
31
- };
32
26
  return {
33
27
  "type": "object",
34
28
  "properties": {
35
- "by_ticker": { "type": "object", "patternProperties": { "^.*$": cohortSchema } },
36
- "by_sector": { "type": "object", "patternProperties": { "^.*$": cohortSchema } }
29
+ "by_user": {
30
+ "type": "object",
31
+ "description": "Map of User IDs to their winning/losing assets and sectors.",
32
+ "patternProperties": {
33
+ "^[0-9]+$": { // Matches User IDs (CIDs)
34
+ "type": "object",
35
+ "properties": {
36
+ "winners": { "type": "array", "items": { "type": "string" } },
37
+ "losers": { "type": "array", "items": { "type": "string" } }
38
+ },
39
+ "required": ["winners", "losers"]
40
+ }
41
+ }
42
+ }
37
43
  }
38
44
  };
39
45
  }
40
46
 
41
- _init(map, key) {
42
- if (!map.has(key)) map.set(key, { winners: new Set(), losers: new Set() });
47
+ _initUser(userId) {
48
+ if (!this.userStats.has(userId)) {
49
+ this.userStats.set(userId, { winners: new Set(), losers: new Set() });
50
+ }
51
+ return this.userStats.get(userId);
43
52
  }
44
53
 
45
54
  process(context) {
46
55
  const { extract } = context.math;
47
56
  const { mappings, user } = context;
57
+ const userId = user.id;
48
58
 
59
+ // 1. Get Positions using the standard extractor
49
60
  const positions = extract.getPositions(user.portfolio.today, user.type);
61
+ if (!positions || positions.length === 0) return;
62
+
63
+ // 2. Lazy init stats only if needed
64
+ let stats = null;
50
65
 
51
66
  for (const pos of positions) {
52
67
  const instId = extract.getInstrumentId(pos);
53
68
  if (!instId) continue;
54
69
 
55
70
  const pnl = extract.getNetProfit(pos);
56
- if (pnl === 0) continue;
71
+ if (pnl === 0) continue; // Ignore flat positions
57
72
 
58
73
  const ticker = mappings.instrumentToTicker[instId];
59
74
  const sector = mappings.instrumentToSector[instId];
60
75
  const isWinner = pnl > 0;
61
76
 
62
- if (ticker) {
63
- this._init(this.tickerBuckets, ticker);
64
- const asset = this.tickerBuckets.get(ticker);
65
- if (isWinner) asset.winners.add(user.id);
66
- else asset.losers.add(user.id);
67
- }
68
-
69
- if (sector) {
70
- this._init(this.sectorBuckets, sector);
71
- const sec = this.sectorBuckets.get(sector);
72
- if (isWinner) sec.winners.add(user.id);
73
- else sec.losers.add(user.id);
77
+ if (ticker || sector) {
78
+ if (!stats) stats = this._initUser(userId);
79
+
80
+ if (ticker) {
81
+ if (isWinner) stats.winners.add(ticker);
82
+ else stats.losers.add(ticker);
83
+ }
84
+
85
+ if (sector) {
86
+ if (isWinner) stats.winners.add(sector);
87
+ else stats.losers.add(sector);
88
+ }
74
89
  }
75
90
  }
76
91
  }
77
92
 
78
93
  async getResult() {
79
- const result = { by_ticker: {}, by_sector: {} };
80
-
81
- const buildResult = (map, out) => {
82
- for (const [key, data] of map.entries()) {
83
- out[key] = {
84
- winners: Array.from(data.winners),
85
- losers: Array.from(data.losers)
94
+ const byUser = {};
95
+
96
+ for (const [userId, stats] of this.userStats) {
97
+ // Only include users who actually have relevant P&L data
98
+ if (stats.winners.size > 0 || stats.losers.size > 0) {
99
+ byUser[userId] = {
100
+ winners: Array.from(stats.winners),
101
+ losers: Array.from(stats.losers)
86
102
  };
87
103
  }
88
- };
104
+ }
89
105
 
90
- buildResult(this.tickerBuckets, result.by_ticker);
91
- buildResult(this.sectorBuckets, result.by_sector);
92
- return result;
106
+ return { by_user: byUser };
93
107
  }
94
108
 
95
109
  reset() {
96
- this.tickerBuckets.clear();
97
- this.sectorBuckets.clear();
110
+ this.userStats.clear();
98
111
  }
99
112
  }
113
+
100
114
  module.exports = AssetPnlStatus;
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @fileoverview Calculation (Pass 1 - Meta) for 1-day price change.
3
- * REFACTORED: Uses process(context) solely.
3
+ * FIXED: Uses priceExtractor properly
4
4
  */
5
5
  class InstrumentPriceChange1D {
6
6
  constructor() {
@@ -29,41 +29,37 @@ class InstrumentPriceChange1D {
29
29
  };
30
30
  return { "type": "object", "patternProperties": { "^.*$": tickerSchema } };
31
31
  }
32
-
33
- _getPrices(priceData) {
34
- if (!priceData || !priceData.prices) return [];
35
- return Object.entries(priceData.prices)
36
- .map(([date, price]) => ({ date, price }))
37
- .sort((a, b) => new Date(a.date) - new Date(b.date));
38
- }
39
32
 
40
33
  process(context) {
41
- const { mappings, prices } = context;
34
+ const { mappings, prices, date, math } = context;
42
35
  const { instrumentToTicker } = mappings;
36
+ const { priceExtractor } = math;
43
37
 
44
- // Expecting context.prices to be populated by the controller for 'meta' + 'price' dependency
45
- const todayPrices = prices?.today || [];
46
- const yesterdayPrices = prices?.yesterday || [];
47
-
48
- const results = {};
38
+ if (!prices || !prices.history) {
39
+ this.result = {};
40
+ return;
41
+ }
49
42
 
50
- const todayPriceMap = new Map(todayPrices.map(p => {
51
- const pList = this._getPrices(p);
52
- const lastPrice = pList.length > 0 ? pList[pList.length - 1].price : 0;
53
- return [p.instrumentId, lastPrice];
54
- }));
43
+ const todayStr = date.today;
44
+ const todayDate = new Date(todayStr + 'T00:00:00Z');
45
+ const yesterdayDate = new Date(todayDate);
46
+ yesterdayDate.setUTCDate(yesterdayDate.getUTCDate() - 1);
47
+ const yesterdayStr = yesterdayDate.toISOString().slice(0, 10);
55
48
 
56
- const yesterdayPriceMap = new Map(yesterdayPrices.map(p => {
57
- const pList = this._getPrices(p);
58
- const lastPrice = pList.length > 0 ? pList[pList.length - 1].price : 0;
59
- return [p.instrumentId, lastPrice];
60
- }));
49
+ const results = {};
61
50
 
62
- for (const [instrumentId, todayPrice] of todayPriceMap) {
63
- const yesterdayPrice = yesterdayPriceMap.get(instrumentId);
51
+ // Iterate over all instruments in price history
52
+ for (const [instrumentId, priceData] of Object.entries(prices.history)) {
64
53
  const ticker = instrumentToTicker[instrumentId];
65
54
  if (!ticker) continue;
66
55
 
56
+ const history = priceExtractor.getHistory(prices, instrumentId);
57
+ if (history.length === 0) continue;
58
+
59
+ // Find today's and yesterday's prices
60
+ const todayPrice = priceData.prices?.[todayStr];
61
+ const yesterdayPrice = priceData.prices?.[yesterdayStr];
62
+
67
63
  if (todayPrice && yesterdayPrice && yesterdayPrice > 0) {
68
64
  const changePct = ((todayPrice - yesterdayPrice) / yesterdayPrice) * 100;
69
65
  results[ticker] = {
@@ -73,6 +69,7 @@ class InstrumentPriceChange1D {
73
69
  results[ticker] = { change_1d_pct: 0 };
74
70
  }
75
71
  }
72
+
76
73
  this.result = results;
77
74
  }
78
75
 
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @fileoverview Calculation (Pass 1 - Meta) for 20-day momentum.
3
- * REFACTORED: Uses process(context) solely.
3
+ * FIXED: Uses priceExtractor properly
4
4
  */
5
5
  class InstrumentPriceMomentum20D {
6
6
  constructor() {
@@ -30,13 +30,14 @@ class InstrumentPriceMomentum20D {
30
30
  return { "type": "object", "patternProperties": { "^.*$": tickerSchema } };
31
31
  }
32
32
 
33
- _findPriceOnOrBefore(priceHistoryObj, targetDateStr) {
34
- if (!priceHistoryObj || !priceHistoryObj.prices) return null;
33
+ _findPriceOnOrBefore(prices, instrumentId, targetDateStr) {
34
+ const priceData = prices.history[instrumentId];
35
+ if (!priceData || !priceData.prices) return null;
35
36
 
36
37
  let checkDate = new Date(targetDateStr + 'T00:00:00Z');
37
38
  for (let i = 0; i < 5; i++) {
38
39
  const str = checkDate.toISOString().slice(0, 10);
39
- const price = priceHistoryObj.prices[str];
40
+ const price = priceData.prices[str];
40
41
  if (price !== undefined && price !== null && price > 0) return price;
41
42
  checkDate.setUTCDate(checkDate.getUTCDate() - 1);
42
43
  }
@@ -47,8 +48,10 @@ class InstrumentPriceMomentum20D {
47
48
  const { mappings, prices, date } = context;
48
49
  const { instrumentToTicker } = mappings;
49
50
 
50
- // Use historical price data available in context
51
- const priceData = prices?.history || [];
51
+ if (!prices || !prices.history) {
52
+ this.result = {};
53
+ return;
54
+ }
52
55
 
53
56
  const todayStr = date.today;
54
57
  const todayDate = new Date(todayStr + 'T00:00:00Z');
@@ -58,13 +61,13 @@ class InstrumentPriceMomentum20D {
58
61
 
59
62
  const results = {};
60
63
 
61
- for (const p of priceData) {
62
- const instrumentId = p.instrumentId;
64
+ // Iterate over all instruments in price history
65
+ for (const [instrumentId, priceData] of Object.entries(prices.history)) {
63
66
  const ticker = instrumentToTicker[instrumentId];
64
67
  if (!ticker) continue;
65
68
 
66
- const currentPrice = this._findPriceOnOrBefore(p, todayStr);
67
- const oldPrice = this._findPriceOnOrBefore(p, oldStr);
69
+ const currentPrice = this._findPriceOnOrBefore(prices, instrumentId, todayStr);
70
+ const oldPrice = this._findPriceOnOrBefore(prices, instrumentId, oldStr);
68
71
 
69
72
  if (currentPrice && oldPrice && oldPrice > 0) {
70
73
  const momPct = ((currentPrice - oldPrice) / oldPrice) * 100;
@@ -75,6 +78,7 @@ class InstrumentPriceMomentum20D {
75
78
  results[ticker] = { momentum_20d_pct: 0 };
76
79
  }
77
80
  }
81
+
78
82
  this.result = results;
79
83
  }
80
84
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiden-shared-calculations-unified",
3
- "version": "1.0.90",
3
+ "version": "1.0.92",
4
4
  "description": "Shared calculation modules for the BullTrackers Computation System.",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -41,7 +41,6 @@ async function withRetry(asyncOperation, operationName = 'Firestore operation')
41
41
  const code = error.code || error.details;
42
42
 
43
43
  if (RETRYABLE_ERROR_CODES.has(code)) {
44
- // Assuming logger is available globally or passed in somehow in the package context
45
44
  if (typeof logger !== 'undefined' && logger.log) {
46
45
  logger.log('WARN', `[Retry ${attempt}/${MAX_RETRIES}] Retrying ${operationName} due to ${code}. Waiting ${backoff}ms...`);
47
46
  } else {