File size: 10,306 Bytes
f568a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/**

 * πŸ” COINAPI ANOMALY DETECTOR

 * 

 * Detects wash trading, pump & dump schemes, and other

 * market manipulation patterns for signal filtering.

 */

import { unifiedBus, type SystemState } from './unifiedBus';
import { temporalLadder } from './temporalLadder';

export enum AnomalyType {
  WASH_TRADING = 'WASH_TRADING',
  PUMP_AND_DUMP = 'PUMP_AND_DUMP',
  SPOOFING = 'SPOOFING',
  LAYERING = 'LAYERING',
  VOLUME_SPIKE = 'VOLUME_SPIKE',
  PRICE_MANIPULATION = 'PRICE_MANIPULATION',
  WHALE_ACTIVITY = 'WHALE_ACTIVITY',
  NONE = 'NONE'
}

export interface Anomaly {
  type: AnomalyType;
  symbol: string;
  severity: number; // 0-1
  timestamp: number;
  description: string;
  recommendation: 'BLACKLIST' | 'REDUCE_SIZE' | 'MONITOR' | 'IGNORE';
  duration?: number; // How long to apply recommendation
}

export interface AnomalyDetectorState {
  anomalies: Anomaly[];
  blacklistedSymbols: Set<string>;
  reducedSymbols: Map<string, number>; // symbol -> reduction factor
  overallMarketHealth: number;
  lastScan: number;
}

export class CoinAPIAnomalyDetector {
  private anomalies: Anomaly[] = [];
  private blacklist: Map<string, number> = new Map(); // symbol -> expiry timestamp
  private reducedSymbols: Map<string, { factor: number; expiry: number }> = new Map();
  private priceHistory: Map<string, number[]> = new Map();
  private volumeHistory: Map<string, number[]> = new Map();
  private registered = false;
  
  // Configuration
  private readonly blacklistDuration = 3600 * 1000; // 1 hour in ms
  private readonly minSeverity = 0.4;
  private readonly volumeSpikeThreshold = 5.0; // 5x normal volume
  private readonly priceManipulationThreshold = 0.1; // 10% sudden move
  
  constructor() {}
  
  register(): void {
    if (this.registered) return;
    
    temporalLadder.registerSystem('anomaly-detector');
    
    // Start heartbeat
    setInterval(() => {
      temporalLadder.heartbeat('anomaly-detector', this.getMarketHealth());
    }, 5000);
    
    this.registered = true;
    console.log('πŸ” CoinAPI Anomaly Detector registered');
  }
  
  addDataPoint(symbol: string, price: number, volume: number): void {
    // Update price history
    if (!this.priceHistory.has(symbol)) {
      this.priceHistory.set(symbol, []);
    }
    const prices = this.priceHistory.get(symbol)!;
    prices.push(price);
    if (prices.length > 100) prices.shift();
    
    // Update volume history
    if (!this.volumeHistory.has(symbol)) {
      this.volumeHistory.set(symbol, []);
    }
    const volumes = this.volumeHistory.get(symbol)!;
    volumes.push(volume);
    if (volumes.length > 100) volumes.shift();
  }
  
  scan(): Anomaly[] {
    const now = Date.now();
    this.anomalies = [];
    
    // Clean expired blacklist entries
    for (const [symbol, expiry] of this.blacklist) {
      if (now > expiry) {
        this.blacklist.delete(symbol);
      }
    }
    
    // Scan each symbol
    for (const [symbol, prices] of this.priceHistory) {
      const volumes = this.volumeHistory.get(symbol) || [];
      
      // Check for volume spike
      const volumeAnomaly = this.detectVolumeSpike(symbol, volumes);
      if (volumeAnomaly) this.anomalies.push(volumeAnomaly);
      
      // Check for price manipulation
      const priceAnomaly = this.detectPriceManipulation(symbol, prices);
      if (priceAnomaly) this.anomalies.push(priceAnomaly);
      
      // Check for wash trading patterns
      const washAnomaly = this.detectWashTrading(symbol, prices, volumes);
      if (washAnomaly) this.anomalies.push(washAnomaly);
      
      // Check for pump and dump
      const pumpAnomaly = this.detectPumpAndDump(symbol, prices, volumes);
      if (pumpAnomaly) this.anomalies.push(pumpAnomaly);
    }
    
    // Apply recommendations
    for (const anomaly of this.anomalies) {
      if (anomaly.severity >= this.minSeverity) {
        if (anomaly.recommendation === 'BLACKLIST') {
          this.blacklist.set(anomaly.symbol, now + this.blacklistDuration);
        } else if (anomaly.recommendation === 'REDUCE_SIZE') {
          this.reducedSymbols.set(anomaly.symbol, {
            factor: 1 - anomaly.severity,
            expiry: now + (anomaly.duration || 300000)
          });
        }
      }
    }
    
    // Publish to UnifiedBus
    unifiedBus.publish({
      systemName: 'AnomalyDetector',
      timestamp: now,
      ready: true,
      coherence: this.getMarketHealth(),
      confidence: 1 - (this.anomalies.length / 10),
      signal: this.getMarketHealth() > 0.7 ? 'NEUTRAL' : 'SELL',
      data: {
        anomalies: this.anomalies.length,
        blacklisted: this.blacklist.size,
        marketHealth: this.getMarketHealth()
      }
    });
    
    return this.anomalies;
  }
  
  private detectVolumeSpike(symbol: string, volumes: number[]): Anomaly | null {
    if (volumes.length < 10) return null;
    
    const recent = volumes.slice(-5);
    const historical = volumes.slice(0, -5);
    
    const avgRecent = recent.reduce((a, b) => a + b, 0) / recent.length;
    const avgHistorical = historical.reduce((a, b) => a + b, 0) / historical.length;
    
    if (avgHistorical === 0) return null;
    
    const ratio = avgRecent / avgHistorical;
    
    if (ratio > this.volumeSpikeThreshold) {
      return {
        type: AnomalyType.VOLUME_SPIKE,
        symbol,
        severity: Math.min(1, (ratio - this.volumeSpikeThreshold) / 10),
        timestamp: Date.now(),
        description: `Volume spike: ${ratio.toFixed(1)}x normal`,
        recommendation: ratio > 10 ? 'REDUCE_SIZE' : 'MONITOR',
        duration: 300000
      };
    }
    
    return null;
  }
  
  private detectPriceManipulation(symbol: string, prices: number[]): Anomaly | null {
    if (prices.length < 5) return null;
    
    const recent = prices[prices.length - 1];
    const previous = prices[prices.length - 2];
    
    if (previous === 0) return null;
    
    const change = Math.abs((recent - previous) / previous);
    
    if (change > this.priceManipulationThreshold) {
      return {
        type: AnomalyType.PRICE_MANIPULATION,
        symbol,
        severity: Math.min(1, change / 0.5),
        timestamp: Date.now(),
        description: `Sudden price move: ${(change * 100).toFixed(1)}%`,
        recommendation: change > 0.3 ? 'BLACKLIST' : 'REDUCE_SIZE',
        duration: change > 0.3 ? this.blacklistDuration : 600000
      };
    }
    
    return null;
  }
  
  private detectWashTrading(symbol: string, prices: number[], volumes: number[]): Anomaly | null {
    if (prices.length < 20 || volumes.length < 20) return null;
    
    // Wash trading indicator: high volume but minimal price movement
    const priceRange = Math.max(...prices.slice(-20)) - Math.min(...prices.slice(-20));
    const avgPrice = prices.slice(-20).reduce((a, b) => a + b, 0) / 20;
    const priceRangePct = priceRange / avgPrice;
    
    const avgVolume = volumes.slice(-20).reduce((a, b) => a + b, 0) / 20;
    const volumeStd = Math.sqrt(
      volumes.slice(-20).reduce((sum, v) => sum + (v - avgVolume) ** 2, 0) / 20
    );
    
    // High volume variance but low price movement
    if (volumeStd / avgVolume > 0.5 && priceRangePct < 0.01) {
      return {
        type: AnomalyType.WASH_TRADING,
        symbol,
        severity: 0.7,
        timestamp: Date.now(),
        description: 'Potential wash trading detected',
        recommendation: 'BLACKLIST',
        duration: this.blacklistDuration
      };
    }
    
    return null;
  }
  
  private detectPumpAndDump(symbol: string, prices: number[], volumes: number[]): Anomaly | null {
    if (prices.length < 30) return null;
    
    // Look for rapid rise followed by decline
    const mid = Math.floor(prices.length / 2);
    const firstHalf = prices.slice(0, mid);
    const secondHalf = prices.slice(mid);
    
    const firstAvg = firstHalf.reduce((a, b) => a + b, 0) / firstHalf.length;
    const peak = Math.max(...prices);
    const current = prices[prices.length - 1];
    
    const riseFromFirst = (peak - firstAvg) / firstAvg;
    const dropFromPeak = (peak - current) / peak;
    
    // Significant rise followed by significant drop
    if (riseFromFirst > 0.3 && dropFromPeak > 0.2) {
      return {
        type: AnomalyType.PUMP_AND_DUMP,
        symbol,
        severity: Math.min(1, (riseFromFirst + dropFromPeak) / 2),
        timestamp: Date.now(),
        description: `Pump and dump pattern: +${(riseFromFirst * 100).toFixed(0)}% then -${(dropFromPeak * 100).toFixed(0)}%`,
        recommendation: 'BLACKLIST',
        duration: this.blacklistDuration * 2
      };
    }
    
    return null;
  }
  
  isBlacklisted(symbol: string): boolean {
    const expiry = this.blacklist.get(symbol);
    if (!expiry) return false;
    if (Date.now() > expiry) {
      this.blacklist.delete(symbol);
      return false;
    }
    return true;
  }
  
  getPositionSizeMultiplier(symbol: string): number {
    if (this.isBlacklisted(symbol)) return 0;
    
    const reduced = this.reducedSymbols.get(symbol);
    if (reduced) {
      if (Date.now() > reduced.expiry) {
        this.reducedSymbols.delete(symbol);
        return 1;
      }
      return reduced.factor;
    }
    
    return 1;
  }
  
  getMarketHealth(): number {
    const totalSymbols = this.priceHistory.size;
    if (totalSymbols === 0) return 1;
    
    const anomalyRatio = this.anomalies.length / totalSymbols;
    const blacklistRatio = this.blacklist.size / totalSymbols;
    
    return Math.max(0, 1 - anomalyRatio * 0.5 - blacklistRatio * 0.3);
  }
  
  getState(): AnomalyDetectorState {
    return {
      anomalies: this.anomalies,
      blacklistedSymbols: new Set(this.blacklist.keys()),
      reducedSymbols: new Map(
        Array.from(this.reducedSymbols.entries())
          .map(([k, v]) => [k, v.factor])
      ),
      overallMarketHealth: this.getMarketHealth(),
      lastScan: Date.now()
    };
  }
}

export const coinAPIAnomalyDetector = new CoinAPIAnomalyDetector();