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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
/**
 * Comprehensive Testing Suite for Trading System
 * Tests all components with mock data and real scenarios
 */

import { IntegratedTradingSystem } from './integrated-trading-system.js';
import { analyzeMarketStructure, detectMomentumDivergences } from './advanced-strategies-v2.js';
import { AdaptiveRegimeDetector, MARKET_REGIMES } from './adaptive-regime-detector.js';
import { NotificationManager } from './enhanced-notification-system.js';

/**
 * Test runner
 */
export class TradingSystemTests {
    constructor() {
        this.results = {
            passed: 0,
            failed: 0,
            total: 0,
            tests: []
        };
    }

    /**
     * Run all tests
     * @returns {Promise<Object>} Test results
     */
    async runAll() {
        console.log('๐Ÿงช Running Trading System Tests...\n');

        await this.testMarketStructureAnalysis();
        await this.testMomentumDivergence();
        await this.testRegimeDetection();
        await this.testNotificationSystem();
        await this.testIntegratedSystem();
        await this.testErrorHandling();
        await this.testDataValidation();
        await this.testStrategySelection();

        return this.getSummary();
    }

    /**
     * Test market structure analysis
     */
    async testMarketStructureAnalysis() {
        console.log('๐Ÿ“Š Testing Market Structure Analysis...');

        try {
            // Generate bullish trend data
            const bullishData = this.generateTrendData('bullish', 100);
            const bullishResult = analyzeMarketStructure(bullishData);

            this.assert(
                'Bullish market structure detected',
                bullishResult.structure === 'bullish' || bullishResult.structure === 'bullish-weakening',
                `Expected bullish structure, got: ${bullishResult.structure}`
            );

            this.assert(
                'Order blocks identified',
                bullishResult.orderBlocks.length > 0,
                `Expected order blocks, got: ${bullishResult.orderBlocks.length}`
            );

            // Generate bearish trend data
            const bearishData = this.generateTrendData('bearish', 100);
            const bearishResult = analyzeMarketStructure(bearishData);

            this.assert(
                'Bearish market structure detected',
                bearishResult.structure === 'bearish' || bearishResult.structure === 'bearish-weakening',
                `Expected bearish structure, got: ${bearishResult.structure}`
            );

            // Generate ranging data
            const rangingData = this.generateRangingData(100);
            const rangingResult = analyzeMarketStructure(rangingData);

            this.assert(
                'Ranging market detected',
                rangingResult.structure === 'ranging' || rangingResult.structure === 'neutral',
                `Expected ranging/neutral, got: ${rangingResult.structure}`
            );
        } catch (error) {
            this.fail('Market structure analysis', error);
        }
    }

    /**
     * Test momentum divergence detection
     */
    async testMomentumDivergence() {
        console.log('๐Ÿ“ˆ Testing Momentum Divergence Detection...');

        try {
            // Generate divergence scenario
            const data = this.generateDivergenceData();
            const result = detectMomentumDivergences(data);

            this.assert(
                'Divergences detected',
                result.divergences !== undefined,
                'Divergence detection returned result'
            );

            this.assert(
                'Signal generated',
                ['buy', 'sell', 'hold'].includes(result.signal),
                `Valid signal: ${result.signal}`
            );

            this.assert(
                'Confidence calculated',
                result.confidence >= 0 && result.confidence <= 100,
                `Confidence in range: ${result.confidence}`
            );
        } catch (error) {
            this.fail('Momentum divergence detection', error);
        }
    }

    /**
     * Test regime detection
     */
    async testRegimeDetection() {
        console.log('๐ŸŽฏ Testing Regime Detection...');

        try {
            const detector = new AdaptiveRegimeDetector();

            // Test trending bullish
            const trendData = this.generateTrendData('bullish', 100);
            const trendResult = detector.detectRegime(trendData);

            this.assert(
                'Trend regime detected',
                Object.values(MARKET_REGIMES).includes(trendResult.regime),
                `Valid regime: ${trendResult.regime}`
            );

            this.assert(
                'Confidence calculated',
                trendResult.confidence >= 0 && trendResult.confidence <= 100,
                `Confidence: ${trendResult.confidence}`
            );

            // Test ranging
            const rangeData = this.generateRangingData(100);
            const rangeResult = detector.detectRegime(rangeData);

            this.assert(
                'Ranging regime detected',
                rangeResult.regime === MARKET_REGIMES.RANGING || rangeResult.regime === MARKET_REGIMES.CALM,
                `Expected ranging/calm, got: ${rangeResult.regime}`
            );

            // Test volatile
            const volatileData = this.generateVolatileData(100);
            const volatileResult = detector.detectRegime(volatileData);

            this.assert(
                'Volatile regime detected',
                volatileResult.regime.includes('volatile') || volatileResult.metrics.volatility > 5,
                `Volatility: ${volatileResult.metrics.volatility}%`
            );

            // Test recommended strategies
            const strategies = detector.getRecommendedStrategies();
            
            this.assert(
                'Strategies recommended',
                Array.isArray(strategies) && strategies.length > 0,
                `Strategies: ${strategies.length}`
            );
        } catch (error) {
            this.fail('Regime detection', error);
        }
    }

    /**
     * Test notification system
     */
    async testNotificationSystem() {
        console.log('๐Ÿ”” Testing Notification System...');

        try {
            const notifManager = new NotificationManager({
                enabled: true,
                channels: ['browser']
            });

            // Test signal notification
            const signal = {
                strategy: 'Test Strategy',
                signal: 'buy',
                confidence: 85,
                entry: 50000,
                stopLoss: 48000,
                targets: [
                    { level: 52000, type: 'TP1', percentage: 50 },
                    { level: 54000, type: 'TP2', percentage: 50 }
                ],
                riskRewardRatio: '1:3'
            };

            const result = await notifManager.sendSignal(signal);

            this.assert(
                'Signal notification sent',
                result.success || result.results?.browser?.success === false, // May fail if browser notifications disabled
                `Result: ${JSON.stringify(result)}`
            );

            // Test validation
            const invalidNotif = { title: null };
            const validationResult = notifManager.validateNotification(invalidNotif);

            this.assert(
                'Invalid notification rejected',
                !validationResult.valid,
                'Validation catches invalid notifications'
            );

            // Test history
            const history = notifManager.getHistory();
            
            this.assert(
                'History available',
                Array.isArray(history),
                'History is an array'
            );
        } catch (error) {
            this.fail('Notification system', error);
        }
    }

    /**
     * Test integrated system
     */
    async testIntegratedSystem() {
        console.log('๐ŸŽฎ Testing Integrated System...');

        try {
            const system = new IntegratedTradingSystem({
                symbol: 'BTC',
                strategy: 'ict-market-structure',
                enableNotifications: false,
                useAdaptiveStrategy: true
            });

            // Test initialization
            this.assert(
                'System initialized',
                system !== null,
                'System object created'
            );

            // Test status
            const status = system.getStatus();
            
            this.assert(
                'Status retrieved',
                status.isRunning !== undefined,
                'Status contains running state'
            );

            // Test configuration update
            system.updateConfig({ symbol: 'ETH' });
            
            this.assert(
                'Config updated',
                system.config.symbol === 'ETH',
                'Symbol updated to ETH'
            );

            // Test analysis
            const sampleData = system.generateSampleData();
            const analysis = await system.performAnalysis(sampleData);

            this.assert(
                'Analysis performed',
                analysis.signal !== undefined,
                `Signal: ${analysis.signal}`
            );

            this.assert(
                'Confidence calculated',
                analysis.confidence >= 0 && analysis.confidence <= 100,
                `Confidence: ${analysis.confidence}`
            );

            // Test performance stats
            const stats = system.getPerformanceStats();
            
            this.assert(
                'Performance stats available',
                stats.totalSignals !== undefined,
                'Stats structure valid'
            );
        } catch (error) {
            this.fail('Integrated system', error);
        }
    }

    /**
     * Test error handling
     */
    async testErrorHandling() {
        console.log('๐Ÿ›ก๏ธ Testing Error Handling...');

        try {
            // Test with insufficient data
            const shortData = this.generateTrendData('bullish', 10);
            
            try {
                const result = analyzeMarketStructure(shortData);
                this.assert(
                    'Handles insufficient data',
                    result.error !== undefined || result.structure === 'unknown',
                    'Returns error or default for short data'
                );
            } catch (e) {
                this.pass('Handles insufficient data (threw expected error)');
            }

            // Test with null data
            try {
                const result = analyzeMarketStructure(null);
                this.assert(
                    'Handles null data',
                    result.error !== undefined,
                    'Returns error for null data'
                );
            } catch (e) {
                this.pass('Handles null data (threw expected error)');
            }

            // Test with invalid OHLCV data
            const invalidData = [
                { timestamp: 123, open: 'invalid', high: 100, low: 90, close: 95, volume: 1000 }
            ];
            
            try {
                const result = analyzeMarketStructure(invalidData);
                this.pass('Handles invalid data types');
            } catch (e) {
                this.pass('Handles invalid data types (threw expected error)');
            }
        } catch (error) {
            this.fail('Error handling', error);
        }
    }

    /**
     * Test data validation
     */
    async testDataValidation() {
        console.log('โœ… Testing Data Validation...');

        try {
            // Test valid OHLCV data
            const validData = {
                timestamp: Date.now(),
                open: 50000,
                high: 51000,
                low: 49000,
                close: 50500,
                volume: 1000000
            };

            this.assert(
                'Valid OHLCV data',
                this.isValidOHLCV(validData),
                'Valid data passes validation'
            );

            // Test invalid OHLCV data
            const invalidData = {
                timestamp: Date.now(),
                open: -1,
                high: 51000,
                low: 49000,
                close: 50500,
                volume: 1000000
            };

            this.assert(
                'Invalid OHLCV data rejected',
                !this.isValidOHLCV(invalidData),
                'Invalid data fails validation'
            );

            // Test data with missing fields
            const incompleteData = {
                timestamp: Date.now(),
                open: 50000,
                high: 51000
            };

            this.assert(
                'Incomplete data rejected',
                !this.isValidOHLCV(incompleteData),
                'Incomplete data fails validation'
            );
        } catch (error) {
            this.fail('Data validation', error);
        }
    }

    /**
     * Test strategy selection
     */
    async testStrategySelection() {
        console.log('๐ŸŽฒ Testing Strategy Selection...');

        try {
            const strategies = IntegratedTradingSystem.getAvailableStrategies();

            this.assert(
                'Strategies available',
                strategies.advanced !== undefined && strategies.hybrid !== undefined,
                'Both strategy types available'
            );

            this.assert(
                'Advanced strategies present',
                Object.keys(strategies.advanced).length > 0,
                `${Object.keys(strategies.advanced).length} advanced strategies`
            );

            this.assert(
                'Hybrid strategies present',
                Object.keys(strategies.hybrid).length > 0,
                `${Object.keys(strategies.hybrid).length} hybrid strategies`
            );

            // Test regime-based strategy recommendation
            const detector = new AdaptiveRegimeDetector();
            const data = this.generateTrendData('bullish', 100);
            const regimeResult = detector.detectRegime(data);
            const recommended = detector.getRecommendedStrategies();

            this.assert(
                'Strategies recommended for regime',
                Array.isArray(recommended) && recommended.length > 0,
                `${recommended.length} strategies recommended for ${regimeResult.regime}`
            );
        } catch (error) {
            this.fail('Strategy selection', error);
        }
    }

    /**
     * Assert helper
     */
    assert(name, condition, message) {
        this.results.total++;
        
        if (condition) {
            this.pass(name);
        } else {
            this.fail(name, new Error(message));
        }
    }

    /**
     * Pass helper
     */
    pass(name) {
        this.results.passed++;
        this.results.tests.push({
            name,
            status: 'passed',
            message: 'โœ… Passed'
        });
        console.log(`  โœ… ${name}`);
    }

    /**
     * Fail helper
     */
    fail(name, error) {
        this.results.failed++;
        this.results.tests.push({
            name,
            status: 'failed',
            message: `โŒ ${error.message}`,
            error: error.stack
        });
        console.error(`  โŒ ${name}: ${error.message}`);
    }

    /**
     * Get test summary
     */
    getSummary() {
        console.log('\n' + '='.repeat(50));
        console.log('๐Ÿ“Š Test Summary');
        console.log('='.repeat(50));
        console.log(`Total: ${this.results.total}`);
        console.log(`Passed: ${this.results.passed} โœ…`);
        console.log(`Failed: ${this.results.failed} โŒ`);
        console.log(`Success Rate: ${((this.results.passed / this.results.total) * 100).toFixed(1)}%`);
        console.log('='.repeat(50) + '\n');

        return this.results;
    }

    /**
     * Generate trending data
     */
    generateTrendData(direction, length) {
        const data = [];
        let price = 50000;
        const trendFactor = direction === 'bullish' ? 1.002 : 0.998;

        for (let i = 0; i < length; i++) {
            const volatility = price * 0.01;
            const open = price;
            price = price * trendFactor;
            const close = price + (Math.random() - 0.5) * volatility;
            const high = Math.max(open, close) + Math.random() * volatility * 0.3;
            const low = Math.min(open, close) - Math.random() * volatility * 0.3;
            const volume = 500000 + Math.random() * 500000;

            data.push({
                timestamp: Date.now() - (length - i) * 3600000,
                open, high, low, close, volume
            });

            price = close;
        }

        return data;
    }

    /**
     * Generate ranging data
     */
    generateRangingData(length) {
        const data = [];
        const basePrice = 50000;
        const rangeSize = basePrice * 0.02;

        for (let i = 0; i < length; i++) {
            const price = basePrice + (Math.random() - 0.5) * rangeSize;
            const volatility = price * 0.005;
            
            const open = price;
            const close = price + (Math.random() - 0.5) * volatility;
            const high = Math.max(open, close) + Math.random() * volatility;
            const low = Math.min(open, close) - Math.random() * volatility;
            const volume = 500000 + Math.random() * 500000;

            data.push({
                timestamp: Date.now() - (length - i) * 3600000,
                open, high, low, close, volume
            });
        }

        return data;
    }

    /**
     * Generate volatile data
     */
    generateVolatileData(length) {
        const data = [];
        let price = 50000;

        for (let i = 0; i < length; i++) {
            const volatility = price * 0.05; // High volatility
            const open = price;
            const close = price + (Math.random() - 0.5) * volatility * 2;
            const high = Math.max(open, close) + Math.random() * volatility;
            const low = Math.min(open, close) - Math.random() * volatility;
            const volume = 800000 + Math.random() * 1000000;

            data.push({
                timestamp: Date.now() - (length - i) * 3600000,
                open, high, low, close, volume
            });

            price = close;
        }

        return data;
    }

    /**
     * Generate divergence data
     */
    generateDivergenceData() {
        const data = [];
        let price = 50000;

        for (let i = 0; i < 100; i++) {
            let close;
            
            // Create divergence: price makes lower low, but momentum increases
            if (i < 50) {
                close = price - (i * 50); // Declining price
            } else {
                close = price - (50 * 50) + ((i - 50) * 30); // Price slightly recovering
            }

            const volatility = Math.abs(close) * 0.01;
            const open = price;
            const high = Math.max(open, close) + volatility;
            const low = Math.min(open, close) - volatility;
            const volume = 500000 + Math.random() * 500000;

            data.push({
                timestamp: Date.now() - (100 - i) * 3600000,
                open, high, low, close, volume
            });

            price = close;
        }

        return data;
    }

    /**
     * Validate OHLCV data
     */
    isValidOHLCV(data) {
        if (!data) return false;

        const requiredFields = ['timestamp', 'open', 'high', 'low', 'close', 'volume'];
        
        for (const field of requiredFields) {
            if (!(field in data)) return false;
            if (typeof data[field] !== 'number') return false;
            if (field !== 'timestamp' && data[field] < 0) return false;
        }

        // High should be highest, low should be lowest
        if (data.high < data.low) return false;
        if (data.high < data.open || data.high < data.close) return false;
        if (data.low > data.open || data.low > data.close) return false;

        return true;
    }
}

/**
 * Run tests when module is loaded
 */
export async function runTests() {
    const tester = new TradingSystemTests();
    return await tester.runAll();
}

export default TradingSystemTests;