# Trade Payout Storage Implementation

## Overview
This system stores trade payout information in a JSON database file during active trades, eliminating the need for DOM-based payout retrieval and fallback mechanisms.

## Architecture

### 1. Database File
**Location:** `js/database/ongoing-trade-information.json`

**Structure:**
```json
{
  "trade_12345": {
    "tradeId": "trade_12345",
    "assetName": "EUR/USD",
    "payoutPercentage": 85,
    "timestamp": 1234567890,
    "expiryTime": 1234567950
  }
}
```

### 2. PHP Backend
**File:** `php/trade_payout_manager.php`

**Actions:**
- `save` - Save trade payout info when trade is placed
- `get` - Retrieve payout info by trade ID
- `delete` - Remove trade info (called 5 seconds after trade ends)
- `cleanup` - Auto-cleanup expired trades

### 3. JavaScript Module
**File:** `js/trade-payout-storage.js`

**Class:** `TradePayoutStorage`

**Methods:**
- `saveTradeInfo(tradeId, assetName, payoutPercentage, expiryTime)` - Save trade data
- `getTradeInfo(tradeId)` - Retrieve trade data
- `deleteTradeInfo(tradeId)` - Delete trade data
- `scheduleCleanup(tradeId, tradeEndTime)` - Auto-delete 5 seconds after trade ends
- `calculatePayout(tradeId, investmentAmount)` - Calculate payout using stored percentage

## Integration Points

### When Trade is Placed
```javascript
// Get current payout percentage from DOM
const payoutPercentage = getDynamicPayoutPercentage();

// Calculate trade expiry time
const expiryTime = Date.now() + (tradeDuration * 1000);

// Save to database
await window.tradePayoutStorage.saveTradeInfo(
    tradeId,
    assetName,
    payoutPercentage,
    expiryTime
);
```

### When Trade Ends
```javascript
// Retrieve payout info from database
const tradeInfo = await window.tradePayoutStorage.getTradeInfo(tradeId);

// Calculate payout
const profit = investmentAmount * (tradeInfo.payoutPercentage / 100);
const totalPayout = investmentAmount + profit;

// Schedule cleanup (5 seconds after trade ends)
window.tradePayoutStorage.scheduleCleanup(tradeId, Date.now());
```

## Benefits

1. **No DOM Dependency** - Payout percentage captured at trade placement, not retrieval
2. **Accurate Historical Data** - Each trade remembers its exact payout percentage
3. **No Fallbacks Needed** - Payout always available for active trades
4. **Auto-Cleanup** - Data automatically removed 5 seconds after trade ends
5. **Persistent Storage** - Survives page refreshes and browser restarts

## Implementation Status

✅ Database file created: `ongoing-trade-information.json`
✅ PHP endpoint created: `trade_payout_manager.php`
✅ JavaScript module created: `trade-payout-storage.js`
✅ Script loaded in index.php

## Next Steps

1. Integrate `saveTradeInfo()` call when trade is placed in app.js
2. Integrate `getTradeInfo()` call when calculating trade results
3. Test trade placement and payout calculation
4. Verify auto-cleanup after 5 seconds

## Example Usage

```javascript
// When placing trade
const tradeId = Date.now();
const assetName = document.querySelector('.asset-name')?.textContent;
const payoutPercentage = getDynamicPayoutPercentage();
const tradeDuration = 60; // seconds
const expiryTime = Date.now() + (tradeDuration * 1000);

await window.tradePayoutStorage.saveTradeInfo(
    tradeId,
    assetName,
    payoutPercentage,
    expiryTime
);

// When trade ends
const totalPayout = await window.tradePayoutStorage.calculatePayout(
    tradeId,
    investmentAmount
);

// Cleanup after 5 seconds
window.tradePayoutStorage.scheduleCleanup(tradeId, Date.now());
```

## File Structure
```
Integrated-Trading-Platform/
├── js/
│   ├── database/
│   │   └── ongoing-trade-information.json  (NEW)
│   └── trade-payout-storage.js             (NEW)
├── php/
│   └── trade_payout_manager.php            (NEW)
└── index.php                                (MODIFIED)
```
