# Exchange Asset Naming Conventions

## Overview

Different exchanges use different naming conventions for the same assets. Our application needs to manage these differences internally while presenting a unified interface.

---

## Exchange-Specific Naming

### **Delta Exchange**

**Market Type**: Derivatives (Perpetuals, Futures, Options)  
**Base Currency**: USD  
**Naming Convention**: `{ASSET}USD`

| Internal Asset | Delta Symbol | Market Name | Type |
|----------------|--------------|-------------|------|
| BTC | BTCUSD | BTCUSD | Perpetual |
| ETH | ETHUSD | ETHUSD | Perpetual |
| SOL | SOLUSD | SOLUSD | Perpetual |

**Options Naming**: `{ASSET}-{EXPIRY}-{STRIKE}-{TYPE}`
- Example: `BTC-29DEC23-40000-C` (BTC Call option)
- Example: `ETH-29DEC23-2000-P` (ETH Put option)

**API Response Fields**:
```json
{
  "symbol": "BTCUSD",
  "product_id": 27,
  "mark_price": "89900.50",
  "size": 1
}
```

---

### **CoinDCX**

**Market Type**: Spot Trading  
**Base Currency**: INR (Indian Rupee)  
**Naming Convention**: `{ASSET}INR`

| Internal Asset | CoinDCX Symbol | Market Name | Type |
|----------------|----------------|-------------|------|
| BTC | BTCINR | BTCINR | Spot |
| ETH | ETHINR | ETHINR | Spot |
| SHIB | SHIBINR | SHIBINR | Spot |
| AVAX | AVAXINR | AVAXINR | Spot |
| SAND | SANDINR | SANDINR | Spot |
| SOL | SOLINR | SOLINR | Spot |

**Important Notes**:
- CoinDCX ALSO has `BTCUSDT` pairs (Tether-based), but these are DIFFERENT markets
- We trade INR pairs for direct fiat exposure
- `BTCINR` ≠ `BTCUSD` (these are completely separate trading pairs)

**API Response Fields**:
```json
{
  "market": "BTCINR",
  "balance": "0.00001079",
  "locked_balance": "0.0",
  "last_price": "7500000.5"
}
```

---

## Internal Asset Representation

### Canonical Asset Model

Our application uses a **canonical asset model** internally:

```
Internal Asset Code: BTC
├─ Delta Exchange:  BTCUSD (Perpetual)
├─ CoinDCX:        BTCINR (Spot)
└─ Binance:        BTCUSDT (Future - not yet implemented)
```

### Asset Properties

**Core Properties** (Exchange-agnostic):
- `asset_code`: BTC, ETH, SHIB (canonical identifier)
- `name`: Bitcoin, Ethereum, Shiba Inu
- `type`: CRYPTO
- `decimals`: 8 (for BTC)

**Exchange-Specific Properties**:
- `exchange_symbol`: BTCUSD, BTCINR, etc.
- `exchange_market`: Same as symbol or specific market ID
- `base_currency`: USD, INR, USDT
- `quote_currency`: Asset being traded
- `min_quantity`: Exchange-specific minimum order size
- `min_notional`: Minimum order value in base currency

---

## Asset Mapping Service Architecture

### Database Schema

**`assets` table** (Canonical assets):
```sql
CREATE TABLE assets (
    id INT PRIMARY KEY,
    code VARCHAR(10) UNIQUE,     -- BTC, ETH, SHIB
    name VARCHAR(100),            -- Bitcoin, Ethereum
    type ENUM('CRYPTO', 'FIAT'),
    decimals INT DEFAULT 8,
    is_active BOOLEAN DEFAULT TRUE
);
```

**`exchange_assets` table** (Exchange-specific mappings):
```sql
CREATE TABLE exchange_assets (
    id INT PRIMARY KEY,
    asset_id INT,                 -- FK to assets.id
    exchange_code VARCHAR(20),    -- DELTA, COINDCX
    symbol VARCHAR(50),           -- BTCUSD, BTCINR
    market_name VARCHAR(50),      -- Exchange-specific market identifier
    base_currency VARCHAR(10),    -- USD, INR, USDT
    trading_type ENUM('SPOT', 'PERPETUAL', 'FUTURES', 'OPTIONS'),
    min_quantity DECIMAL(20,8),
    min_notional DECIMAL(20,2),
    price_precision INT,
    quantity_precision INT,
    is_active BOOLEAN DEFAULT TRUE,
    
    UNIQUE KEY (exchange_code, symbol)
);
```

### Mapping Examples

**BTC Mappings**:
```sql
-- Canonical Asset
INSERT INTO assets (code, name, type, decimals) 
VALUES ('BTC', 'Bitcoin', 'CRYPTO', 8);

-- Delta Exchange Mapping
INSERT INTO exchange_assets 
(asset_id, exchange_code, symbol, market_name, base_currency, trading_type, min_quantity)
VALUES 
(1, 'DELTA', 'BTCUSD', 'BTCUSD', 'USD', 'PERPETUAL', 0.001);

-- CoinDCX Mapping  
INSERT INTO exchange_assets
(asset_id, exchange_code, symbol, market_name, base_currency, trading_type, min_quantity)
VALUES
(1, 'COINDCX', 'BTCINR', 'BTCINR', 'INR', 'SPOT', 0.0001);
```

---

## AssetMappingService

### PHP Implementation

```php
class AssetMappingService
{
    /**
     * Get exchange-specific symbol from canonical asset code
     */
    public static function getExchangeSymbol(string $assetCode, string $exchangeCode): string
    {
        $stmt = $pdo->prepare("
            SELECT ea.symbol
            FROM exchange_assets ea
            JOIN assets a ON ea.asset_id = a.id
            WHERE a.code = ? AND ea.exchange_code = ?
            AND ea.is_active = 1
        ");
        
        $stmt->execute([$assetCode, $exchangeCode]);
        return $stmt->fetchColumn() ?: null;
    }
    
    /**
     * Get canonical asset code from exchange symbol
     */
    public static function getAssetCode(string $exchangeSymbol, string $exchangeCode): string
    {
        $stmt = $pdo->prepare("
            SELECT a.code
            FROM assets a
            JOIN exchange_assets ea ON a.id = ea.asset_id
            WHERE ea.symbol = ? AND ea.exchange_code = ?
        ");
        
        $stmt->execute([$exchangeSymbol, $exchangeCode]);
        return $stmt->fetchColumn() ?: null;
    }
    
    /**
     * Get all exchange symbols for an asset
     */
    public static function getAllSymbols(string $assetCode): array
    {
        // Returns: ['DELTA' => 'BTCUSD', 'COINDCX' => 'BTCINR']
    }
}
```

---

## Usage Examples

### Example 1: Order Placement

```php
// User wants to trade BTC
$assetCode = 'BTC';
$broker = 'COINDCX';

// Get correct exchange symbol
$symbol = AssetMappingService::getExchangeSymbol($assetCode, $broker);
// Result: 'BTCINR'

// Place order with exchange-specific symbol
$broker->placeOrder($symbol, 'BUY', 0.001);
```

### Example 2: Multi-Exchange Trading

```php
// Trade BTC on both exchanges
$assetCode = 'BTC';

$symbols = AssetMappingService::getAllSymbols($assetCode);
// Result: ['DELTA' => 'BTCUSD', 'COINDCX' => 'BTCINR']

foreach ($symbols as $exchange => $symbol) {
    $broker = BrokerFactory::create($exchange);
    $broker->placeOrder($symbol, 'BUY', 0.001);
}
```

### Example 3: WebSocket Subscription

```php
// Subscribe to BTC price feeds on all exchanges
$assetCode = 'BTC';
$symbols = AssetMappingService::getAllSymbols($assetCode);

$deltaWs->subscribe($symbols['DELTA']);    // Subscribes to BTCUSD
$coindcxWs->subscribe($symbols['COINDCX']); // Subscribes to BTCINR
```

---

## Benefits

### 1. **Exchange Agnostic**
- Add new exchanges without changing business logic
- Centralized mapping management

### 2. **Type Safety**
- Clear separation between internal and external representations
- Prevents mixing Delta USD symbols with CoinDCX INR symbols

### 3. **Flexibility**
- Easy to add new exchanges
- Support multiple symbol formats per asset

### 4. **Maintainability**
- Single source of truth for asset mappings
- Database-driven configuration

---

## Current Implementation Status

### ✅ Implemented
- Basic asset table
- Tradeable assets with broker-specific symbols
- Symbol-to-market conversion in brokers

### 🔄 In Progress
- Canonical asset model
- AssetMappingService
- Exchange-specific asset table

### 📋 To Do
- Migrate existing code to use AssetMappingService
- Add more exchanges (Binance, Bybit, etc.)
- Add fiat currency support
- Add stablecoin mappings

---

## Migration Plan

### Phase 1: Create New Schema ✅
- Create `exchange_assets` table
- Populate with current mappings
- Update `assets` table with canonical codes

### Phase 2: Update Services
- Create `AssetMappingService`
- Update `BrokerFactory` to use mappings
- Update `AssetDetectionService`

### Phase 3: Migrate Code
- Update brokers to use `AssetMappingService`
- Remove hardcoded symbol conversions
- Update WebSocket subscriptions

### Phase 4: Testing
- Test all asset mappings
- Verify order placement
- Test multi-exchange scenarios

---

*Last Updated: January 21, 2026*
*Version: 1.0*
