# Architecture & Folder Structure
## π Project Structure
```
node-ig-api/
βββ src/ # Source code
β βββ core/ # Core modules
β β βββ api-client.js # HTTP client with retry & throttling
β β βββ config.js # Configuration management
β β βββ encryption.cjs # pidCrypt RSA encryption (IG-specific)
β β
β βββ services/ # Business logic services
β β βββ ig-service.js # Main IG Trading API service
β β βββ streaming-service.js # Lightstreamer real-time data
β β βββ mcp-service.js # MCP server for AI integration
β β
β βββ indicators/ # Trading indicators
β β βββ supertrend.js # Supertrend indicator calculation
β β
β βββ security/ # Security modules
β β βββ index.js # Security exports
β β βββ audit-logger.js # Audit trail logging
β β βββ credential-manager.js # Secure credential storage
β β βββ rate-limiter.js # API rate limiting
β β βββ session-manager.js # JWT session management
β β βββ validator.js # Input validation & sanitization
β β
β βββ index.js # Main entry point
β
βββ examples/ # Example scripts
β βββ basic-trading.js # Basic trading operations
β βββ streaming-example.js # Real-time streaming example
β
βββ scripts/ # Utility scripts
β βββ setup.js # Interactive setup wizard
β βββ test-account.js # Account connection test
β
βββ tests/ # Test files
β βββ unit/ # Unit tests (TBD)
β βββ integration/ # Integration tests (TBD)
β
βββ config/ # Configuration files
βββ .env # Environment variables (git-ignored)
βββ .env.example # Example environment file
βββ package.json # Dependencies & scripts
βββ README.md # Main documentation
βββ LICENSE # License file
```
## ποΈ Architecture Overview
### Core Layer (`src/core/`)
- **api-client.js**: Low-level HTTP client with:
- Automatic retry logic (3 attempts)
- Rate limiting (60 requests/minute)
- Request/response interceptors
- Error handling with custom `IGApiError`
- **config.js**: Centralized configuration:
- Credential management
- Environment detection (demo/live)
- Session token storage
- Winston logger setup
- **encryption.cjs**: IG-specific RSA encryption:
- Uses pidCrypt library (required by IG)
- CommonJS module for compatibility
- Handles password encryption for login
### Service Layer (`src/services/`)
- **ig-service.js**: Main trading service:
- Account management (login, logout, switch)
- Position operations (create, update, close)
- Order management (working orders)
- Market data queries
- Watchlist management
- **streaming-service.js**: Real-time data:
- Lightstreamer client wrapper
- Price streaming subscriptions
- Order/position updates
- **mcp-service.js**: AI Integration:
- Model Context Protocol server
- 25+ tools for AI assistants
- Async tool execution
### Security Layer (`src/security/`)
- Multi-layered security approach:
- Credential encryption (AES-256-GCM)
- Rate limiting (per user/IP)
- Input validation (Joi schemas)
- Audit logging (tamper-proof)
- Session management (JWT tokens)
## π Data Flow
```
User Request
β
[Input Validation]
β
[Rate Limiting]
β
[IG Service Layer]
β
[API Client]
β
[Encryption if needed]
β
[HTTP Request to IG]
β
[Response Processing]
β
[Audit Logging]
β
User Response
```
## π Usage Patterns
### Basic Usage
```javascript
import { IGService } from './src/services/ig-service.js';
import { config } from './src/core/config.js';
// Initialize
config.credentials = { /* ... */ };
const ig = new IGService();
// Use
await ig.login();
const positions = await ig.getPositions();
await ig.logout();
```
### Streaming Usage
```javascript
import { StreamingClient } from './src/services/streaming-service.js';
const streaming = new StreamingClient(session);
await streaming.connect();
await streaming.subscribeToPrice('CS.D.EURUSD.CFD.IP');
```
### MCP Server
```bash
npm run mcp # Starts MCP server for AI tools
```
## π Security Best Practices
1. **Never commit credentials** - Use .env files
2. **Always use encryption** - Passwords are RSA encrypted
3. **Rate limiting enforced** - 60 requests/minute
4. **Input validation** - All inputs sanitized
5. **Audit trail** - All operations logged
6. **Session expiry** - Tokens expire after 12 hours
## π¦ Module System
- **ES Modules** (`.js`): Main codebase uses modern imports
- **CommonJS** (`.cjs`): Only for pidCrypt compatibility
- **No mixed patterns**: Clear separation of module types
## π§ͺ Testing Strategy
```bash
npm test # Run all tests
npm run test:account # Test account connection
```
## π― Design Principles
1. **Separation of Concerns**: Clear layer boundaries
2. **Single Responsibility**: Each module has one purpose
3. **DRY**: Shared code in core modules
4. **Security First**: Multiple security layers
5. **Modern JavaScript**: ES6+, async/await
6. **Error Handling**: Consistent error patterns
7. **Logging**: Comprehensive audit trail