# Release Notes - v0.18.0a15

**Date:** 2025-10-30  
**Type:** CRITICAL Bug Fix

## OTB-267: Fix Missing Transactions for Tastytrade Orders

### 🔴 Critical Issue Fixed

**Problem:** Tastytrade orders were created and filled successfully, but **NO transactions were saved to the database**. This caused:
- ❌ Incorrect `realizedPNL` calculations  
- ❌ Missing audit trail for compliance  
- ❌ Empty transactions table for all Tastytrade orders

### ✅ Root Cause

The Tastytrade connector only emitted `orderStatusEvent` (FILLED, CANCELLED, etc.) but **never emitted `orderExecutionDetailsEvent`**. Without execution details events, `TradeManager._onOrderExecutionDetailsEvent()` was never called, so no transactions were created in the database.

In contrast, IBKR connector emits both events correctly.

### ✅ Solution

1. **Added execution details emission** in `_update_accounts()` when orders reach FILLED status
2. **Implemented `_emit_execution_details_for_order()`** to extract fill data from Tastytrade API
3. **Used actual fill prices** from `PlacedOrder.legs[].fills[]` array (not approximations!)
4. **Prevented duplicates** with `_processed_fills` set (Tastytrade sends 10+ FILLED events per order)

### 🎯 Tastytrade API Discovery

Initially thought Tastytrade only provided total spread price, but discovered `PlacedOrder.legs[i].fills[]` contains **individual fill information per leg**:

```python
PlacedOrder.legs[i].fills[] = [
    FillInfo(
        fill_id="abc123",
        quantity=Decimal("2"),
        fill_price=Decimal("0.65"),  # Actual leg price from exchange!
        filled_at=datetime(...),      # Exact execution timestamp!
        destination_venue="CBOE"
    )
]
```

This provides:
- ✅ **Accurate leg prices** from actual exchange fills
- ✅ **Exact execution timestamps** for audit compliance  
- ✅ **Handles partial fills** (multiple fills per leg)
- ✅ **No approximations** - real market data

### 📋 Changes

**Modified Files:**
- `optrabot/broker/tastytradeconnector.py`
  - Added `_processed_fills: set` to track processed orders
  - Modified `_update_accounts()` to emit execution details for FILLED orders
  - Implemented `_emit_execution_details_for_order()` using `leg.fills` data

**New Documentation:**
- `OTB-267-tastytrade-transactions.md` - Technical details and API analysis
- `TEST-PLAN-tastytrade-transactions.md` - Test cases and verification queries

### ⚠️ Important Notes

**Duplicate Prevention:**  
Tastytrade sends **10+ FILLED status updates** for the same order (one per contract filled). The `_processed_fills` set ensures we only create transactions once per order ID.

**Backward Compatibility:**  
- Existing IBKR orders: ✅ No impact, continue working correctly
- Historical Tastytrade trades: ⚠️ Transactions still missing (created before fix)
- Future Tastytrade trades: ✅ Transactions created correctly

**Migration:**  
No database migration required. Historical trades with missing transactions will remain incomplete, but trade status and P&L are still correct (calculated at trade level).

### 🧪 Testing

**Required Tests:**
1. ✅ Single leg order creates 1 transaction
2. ✅ Multi-leg spread (Iron Condor) creates 4 transactions  
3. ✅ Multiple FILLED events don't create duplicate transactions
4. ✅ Exit orders add additional transactions
5. ✅ realizedPNL calculated correctly with complete transaction history

**Verification Queries:**
```sql
-- Check transaction count for a trade
SELECT COUNT(*) FROM transactions WHERE tradeid = [TRADE_ID];

-- Verify no duplicates
SELECT symbol, strike, sectype, COUNT(*) as count
FROM transactions 
WHERE tradeid = [TRADE_ID]
GROUP BY symbol, strike, sectype
HAVING COUNT(*) > 1;

-- Check realizedPNL accuracy
SELECT id, entry_net_value, exit_net_value, realized_pnl
FROM trades WHERE id = [TRADE_ID];
```

### 🔗 Related Issues

- **OTB-253:** Per-broker trade recovery (v0.18.0a14)
- **OTB-236:** Shutdown RecursionError fix (v0.18.0a14)

### 📚 API Documentation

Tastytrade Python SDK: https://tastyworks-api.readthedocs.io/en/latest/  
Order API Reference: https://tastyworks-api.readthedocs.io/en/latest/api/order.html

---

**Upgrade Impact:** HIGH - Critical data integrity fix for Tastytrade users  
**Breaking Changes:** None  
**Database Migration:** Not required
