otc-rfq 0.1.1

High-performance OTC Request-for-Quote engine supporting DeFi protocols and TradFi venues via FIX 4.4
Documentation
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
# OTC RFQ Engine

[![MIT License](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
[![Crates.io](https://img.shields.io/crates/v/otc-rfq.svg)](https://crates.io/crates/otc-rfq)
[![Downloads](https://img.shields.io/crates/d/otc-rfq.svg)](https://crates.io/crates/otc-rfq)
[![Stars](https://img.shields.io/github/stars/joaquinbejar/otc-rfq.svg)](https://github.com/joaquinbejar/otc-rfq/stargazers)
[![Issues](https://img.shields.io/github/issues/joaquinbejar/otc-rfq.svg)](https://github.com/joaquinbejar/otc-rfq/issues)
[![PRs](https://img.shields.io/github/issues-pr/joaquinbejar/otc-rfq.svg)](https://github.com/joaquinbejar/otc-rfq/pulls)

[![Build Status](https://img.shields.io/github/actions/workflow/status/joaquinbejar/otc-rfq/ci.yml?branch=main)](https://github.com/joaquinbejar/otc-rfq/actions)
[![Coverage](https://img.shields.io/codecov/c/github/joaquinbejar/otc-rfq)](https://codecov.io/gh/joaquinbejar/otc-rfq)
[![Dependencies](https://img.shields.io/librariesio/github/joaquinbejar/otc-rfq)](https://libraries.io/github/joaquinbejar/otc-rfq)
[![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://docs.rs/otc-rfq)

**High-performance OTC Request-for-Quote engine supporting DeFi protocols (0x, 1inch, Uniswap, Hashflow) and TradFi venues via FIX 4.4. Built in Rust with sub-millisecond latency.**

---

## Table of Contents

- [Overview]#overview
- [Key Features]#key-features
- [Architecture]#architecture
- [Domain Model]#domain-model
- [Project Structure]#project-structure
- [Technology Stack]#technology-stack
- [Prerequisites]#prerequisites
- [Installation]#installation
- [Configuration]#configuration
- [Usage]#usage
- [API Reference]#api-reference
- [Testing]#testing
- [Performance]#performance
- [Documentation]#documentation
- [Roadmap]#roadmap
- [Contribution and Contact]#contribution-and-contact

---

## Overview

OTC RFQ Engine is an enterprise-grade liquidity aggregation system that enables institutional-quality Over-The-Counter (OTC) trading across multiple venues. The system implements a **reverse auction pattern** where quote requests are broadcast to multiple liquidity providers simultaneously, and the best quotes are presented to clients for execution.

### Problem Statement

Institutional traders face several challenges when executing large OTC trades:

- **Fragmented Liquidity**: Liquidity is spread across multiple venues (banks, market makers, DEXs)
- **Manual Processes**: Traditional RFQ workflows involve phone calls and chat messages
- **Limited Transparency**: Difficult to compare prices across venues in real-time
- **Operational Risk**: Manual execution increases error rates
- **DeFi Integration Gap**: Traditional systems don't connect to on-chain liquidity

### Solution

The OTC RFQ System addresses these challenges by:

- **Aggregating liquidity** from TradFi and DeFi sources
- **Automating the RFQ workflow** from request to settlement
- **Providing real-time price discovery** across all venues
- **Ensuring compliance** with regulatory requirements
- **Supporting multiple asset classes** (crypto, stocks, forex, commodities)

---

## Key Features

### Core Capabilities

| Feature | Description |
|---------|-------------|
| **Multi-Venue Aggregation** | Simultaneously query DeFi protocols and TradFi market makers |
| **Sub-Millisecond Latency** | Optimized for high-frequency trading workflows |
| **FIX 4.4 Protocol** | Native support for traditional finance connectivity via [IronFix]https://github.com/joaquinbejar/IronFix |
| **DeFi Integration** | 0x, 1inch, Paraswap, Hashflow, Bebop, Uniswap V3, Curve |
| **Event Sourcing** | Complete audit trail with domain event persistence |
| **Multi-Protocol API** | gRPC (trading), REST (management), WebSocket (streaming) |
| **Binary Encoding** | High-performance SBE encoding via [IronSBE]https://github.com/joaquinbejar/IronSBE |

### Supported Venue Types

| Category | Venues |
|----------|--------|
| **TradFi Market Makers** | FIX 4.4, Internal Market Makers |
| **DEX Aggregators** | 0x, 1inch, Paraswap |
| **RFQ Protocols** | Hashflow, Bebop, Airswap |
| **On-Chain Protocols** | Uniswap V3, Curve, Balancer |
| **Settlement Options** | On-chain, Off-chain, Hybrid |

### Supported Asset Classes

- **Crypto Spot**: BTC, ETH, and major tokens
- **Crypto Derivatives**: Perpetuals, options (future)
- **Forex**: Major currency pairs
- **Equities**: Stocks and ETFs
- **Commodities**: Precious metals, energy

---

## Architecture

The system follows a **layered architecture** based on Domain-Driven Design (DDD) principles with clear separation between business logic and infrastructure concerns.

### High-Level Architecture

```mermaid
flowchart TB
    subgraph CLIENTS["CLIENTS"]
        direction LR
        C1["Trading Desks"]
        C2["Algo Traders"]
        C3["DeFi Apps"]
    end

    subgraph API["API LAYER"]
        direction TB
        GRPC["gRPC<br/>(Trading)"]
        REST["REST<br/>(Management)"]
        WS["WebSocket<br/>(Streaming)"]
    end

    subgraph APPLICATION["APPLICATION LAYER"]
        direction TB
        RFQ_SVC["RFQ Service"]
        QUOTE_AGG["Quote Aggregation<br/>Engine"]
        EXEC_SVC["Execution Service"]
        COMPLIANCE["Compliance<br/>Service"]
    end

    subgraph DOMAIN["DOMAIN LAYER"]
        direction TB
        RFQ["RFQ Aggregate"]
        QUOTE["Quote Entity"]
        TRADE["Trade Aggregate"]
    end

    subgraph INFRASTRUCTURE["INFRASTRUCTURE LAYER"]
        direction TB
        
        subgraph VENUES["Venue Adapters"]
            FIX["FIX MM<br/>(IronFix)"]
            DEX["DEX Aggregators<br/>(0x, 1inch)"]
            RFQ_PROTO["RFQ Protocols<br/>(Hashflow)"]
        end
        
        subgraph PERSISTENCE["Persistence"]
            PG["PostgreSQL"]
            REDIS["Redis Cache"]
            KAFKA["Kafka Events"]
        end
    end

    CLIENTS --> API
    API --> APPLICATION
    APPLICATION --> DOMAIN
    APPLICATION --> INFRASTRUCTURE
    DOMAIN --> INFRASTRUCTURE
```

### Architecture Principles

| Principle | Description |
|-----------|-------------|
| **Layered Architecture** | Clear separation between domain, application, and infrastructure |
| **Domain-Driven Design** | Business logic encapsulated in domain layer |
| **Hexagonal Architecture** | Ports and adapters for external integrations |
| **Event Sourcing** | Immutable event log for audit and replay |
| **CQRS** | Separate read and write models where beneficial |
| **Microservices Ready** | Monolith that can be split into services |

### Layer Responsibilities

```mermaid
block-beta
    columns 1
    block:API["🌐 API LAYER"]
        A1["Handles external communication (gRPC, REST, WebSocket)"]
        A2["Request/response serialization, authentication, rate limiting"]
    end
    block:APP["⚙️ APPLICATION LAYER"]
        B1["Use cases, orchestration, transaction management"]
        B2["No business logic, only coordination"]
    end
    block:DOM["🎯 DOMAIN LAYER"]
        C1["Core business logic, entities, value objects, domain events"]
        C2["Pure Rust, no I/O, no external dependencies"]
    end
    block:INF["🔧 INFRASTRUCTURE LAYER"]
        D1["Adapters for external systems (venues, databases, messaging)"]
        D2["Implements domain interfaces"]
    end
    
    API --> APP --> DOM --> INF
```

---

## Domain Model

### RFQ Workflow (Reverse Auction)

```mermaid
sequenceDiagram
    participant Client as 👤 Client (Taker)
    participant Engine as 🔄 RFQ Engine
    participant V1 as 🏦 Venue 1
    participant V2 as 🏦 Venue 2
    participant V3 as 🏦 Venue 3
    participant Settlement as 💰 Settlement

    Note over Client,V3: 1. CLIENT REQUESTS QUOTES
    Client->>Engine: Create RFQ
    Engine->>V1: Request Quote
    Engine->>V2: Request Quote
    Engine->>V3: Request Quote

    Note over Client,V3: 2. VENUES RESPOND WITH PRICES
    V1-->>Engine: Quote $100.05
    V2-->>Engine: Quote $100.02
    V3-->>Engine: Quote $100.08

    Note over Client,V3: 3. CLIENT SELECTS BEST QUOTE
    Engine-->>Client: Ranked Quotes
    Client->>Engine: Select Best (Venue 2)

    Note over Client,Settlement: 4. EXECUTION & 5. SETTLEMENT
    Engine->>V2: Execute Trade
    V2-->>Engine: Trade Confirmed
    Engine->>Settlement: Initiate Settlement
    Settlement-->>Client: Assets Exchanged ✅
```

### RFQ State Machine

```mermaid
stateDiagram-v2
    [*] --> Created
    
    Created --> QuoteRequesting: start_quote_collection()
    
    QuoteRequesting --> QuotesReceived: receive_quote()
    QuoteRequesting --> Expired: timeout/no quotes
    QuoteRequesting --> Cancelled: cancel()
    
    QuotesReceived --> Executing: select_quote()
    QuotesReceived --> Expired: timeout
    QuotesReceived --> Cancelled: cancel()
    
    Executing --> Executed: mark_executed()
    Executing --> Failed: mark_failed()
    Executing --> Cancelled: cancel()
    
    Expired --> [*]
    Executed --> [*]
    Failed --> [*]
    Cancelled --> [*]
```

### Core Aggregates

| Aggregate | Description |
|-----------|-------------|
| **RFQ** | Central aggregate managing the complete trading workflow |
| **Quote** | Price quote from a venue with validity period |
| **Trade** | Executed trade with settlement tracking |
| **Venue** | Liquidity source configuration and health |
| **Counterparty** | Client or market maker with compliance status |

### Domain Events

```mermaid
graph LR
    subgraph RFQ_EVENTS["📋 RFQ Lifecycle Events"]
        E1[RFQCreated]
        E2[QuoteCollectionStarted]
        E3[QuoteReceived]
        E4[QuoteSelected]
        E5[TradeExecuted]
        E6[RFQCancelled]
        E7[RFQExpired]
    end
    
    subgraph SETTLEMENT_EVENTS["💰 Settlement Events"]
        S1[SettlementInitiated]
        S2[SettlementConfirmed]
        S3[SettlementFailed]
    end
    
    subgraph COMPLIANCE_EVENTS["✅ Compliance Events"]
        C1[ComplianceCheckPassed]
        C2[ComplianceCheckFailed]
    end
```

---

## Project Structure

```
otc-rfq/
├── src/
│   ├── domain/                  # Core business logic (DDD)
│   │   ├── entities/            # Aggregates: RFQ, Quote, Trade, Venue
│   │   │   ├── rfq.rs           # RFQ aggregate with state machine
│   │   │   ├── quote.rs         # Quote entity
│   │   │   ├── trade.rs         # Trade aggregate
│   │   │   └── venue.rs         # Venue aggregate
│   │   ├── value_objects/       # Immutable value types
│   │   │   ├── ids.rs           # RFQId, QuoteId, TradeId, VenueId
│   │   │   ├── price.rs         # Price with precision
│   │   │   ├── quantity.rs      # Quantity with validation
│   │   │   ├── timestamp.rs     # Timestamp wrapper
│   │   │   └── enums.rs         # OrderSide, AssetClass, etc.
│   │   ├── events/              # Domain events for event sourcing
│   │   │   ├── rfq_events.rs    # RFQ lifecycle events
│   │   │   └── trade_events.rs  # Trade execution events
│   │   └── errors/              # Domain-specific errors
│   │       └── domain_error.rs
│   │
│   ├── application/             # Use cases and services
│   │   ├── use_cases/           # Business workflows
│   │   │   ├── create_rfq.rs    # CreateRFQUseCase
│   │   │   ├── collect_quotes.rs # CollectQuotesUseCase
│   │   │   └── execute_trade.rs # ExecuteTradeUseCase
│   │   ├── services/            # Application services
│   │   │   ├── quote_aggregation.rs  # Quote ranking and selection
│   │   │   └── circuit_breaker.rs    # Fault tolerance
│   │   ├── dto/                 # Data transfer objects
│   │   └── error.rs             # Application errors
│   │
│   ├── infrastructure/          # External adapters
│   │   ├── venues/              # Venue adapters (ports & adapters)
│   │   │   ├── traits.rs        # VenueAdapter trait
│   │   │   ├── internal_mm.rs   # Internal market maker
│   │   │   ├── fix_adapter.rs   # FIX protocol adapter
│   │   │   ├── dex_aggregator.rs # DEX aggregator adapter
│   │   │   └── registry.rs      # Venue registry
│   │   ├── persistence/         # Data persistence
│   │   │   ├── postgres/        # PostgreSQL repositories
│   │   │   ├── redis/           # Redis cache
│   │   │   └── event_store.rs   # Event sourcing store
│   │   ├── blockchain/          # Blockchain clients
│   │   │   └── ethereum.rs      # Ethereum/L2 client
│   │   └── sbe/                 # SBE binary encoding
│   │
│   ├── api/                     # External interfaces
│   │   ├── grpc/                # gRPC services (tonic)
│   │   │   ├── service.rs       # RFQ service implementation
│   │   │   └── proto/           # Protocol buffer definitions
│   │   ├── rest/                # REST endpoints (axum)
│   │   │   ├── handlers.rs      # Request handlers
│   │   │   └── routes.rs        # Route configuration
│   │   ├── websocket/           # Real-time streaming
│   │   │   └── handlers.rs      # WebSocket handlers
│   │   └── middleware/          # Cross-cutting concerns
│   │       ├── auth.rs          # JWT authentication
│   │       └── rate_limit.rs    # Rate limiting
│   │
│   ├── config.rs                # Configuration management
│   ├── lib.rs                   # Library entry point
│   └── main.rs                  # Application entry point
│
├── proto/                       # Protocol Buffer definitions
│   └── rfq.proto                # gRPC service definitions
├── schemas/sbe/                 # SBE message schemas
├── migrations/                  # Database migrations
├── benches/                     # Performance benchmarks
└── tests/                       # Integration tests
```

---

## Technology Stack

| Layer | Technology | Rationale |
|-------|------------|-----------|
| **Language** | Rust | Performance, safety, async |
| **Async Runtime** | Tokio | Industry standard for Rust async |
| **Web Framework** | Axum | Modern, tower-based |
| **gRPC** | Tonic | High-performance Rust gRPC |
| **Database** | PostgreSQL | Reliability, JSON support |
| **Cache** | Redis | Speed, pub/sub |
| **Message Queue** | Kafka | Throughput, durability |
| **Blockchain** | ethers-rs | Ethereum interaction |
| **Serialization** | serde, prost | Rust standard |
| **Binary Encoding** | IronSBE | High-performance SBE |
| **FIX Protocol** | IronFix | FIX 4.4 support |
| **Observability** | tracing | Structured logging |

### Dependencies Highlights

```toml
[dependencies]
tokio = { version = "1.49", features = ["full"] }
axum = { version = "0.8", features = ["ws", "macros"] }
tonic = { version = "0.14", features = ["transport", "tls"] }
sqlx = { version = "0.8", features = ["postgres", "uuid", "chrono"] }
redis = { version = "1.0", features = ["tokio-comp"] }
ethers = { version = "2.0", features = ["rustls"] }
serde = { version = "1.0", features = ["derive"] }
uuid = { version = "1.20", features = ["v4", "serde"] }
rust_decimal = { version = "1.40", features = ["serde"] }
```

---

## Prerequisites

- **Rust**: 1.75+ (stable)
- **PostgreSQL**: 14+
- **Redis**: 7+
- **Kafka**: 3+ (optional, for event streaming)
- **Docker**: 20+ (optional, for containerized development)

---

## Installation

### From Source

```bash
# Clone repository
git clone https://github.com/joaquinbejar/otc-rfq.git
cd otc-rfq

# Build release
cargo build --release

# Run tests
cargo test --all-features

# Run lints
cargo clippy --all-targets --all-features -- -D warnings
```

### From Crates.io

```bash
cargo add otc-rfq
```

### Docker

```bash
# Build image
docker build -t otc-rfq:latest .

# Run container
docker run -p 50051:50051 -p 8080:8080 otc-rfq:latest
```

---

## Configuration

### Environment Variables

Create a `.env` file or set environment variables:

```bash
# =============================================================================
# Database Configuration
# =============================================================================
DATABASE_URL=postgres://user:pass@localhost:5432/otc_rfq
DATABASE_MAX_CONNECTIONS=20
DATABASE_MIN_CONNECTIONS=5

# =============================================================================
# Redis Configuration
# =============================================================================
REDIS_URL=redis://localhost:6379
REDIS_MAX_CONNECTIONS=10

# =============================================================================
# API Configuration
# =============================================================================
GRPC_PORT=50051
REST_PORT=8080
WEBSOCKET_PORT=8081

# =============================================================================
# Authentication
# =============================================================================
JWT_SECRET=your-secret-key-here
JWT_EXPIRATION_HOURS=24
API_KEY_HEADER=X-API-Key

# =============================================================================
# FIX Protocol (TradFi)
# =============================================================================
FIX_ENABLED=true
FIX_SENDER_COMP_ID=OTC_RFQ
FIX_TARGET_COMP_ID=MARKET_MAKER
FIX_HOST=fix.marketmaker.com
FIX_PORT=9878

# =============================================================================
# DeFi Venues
# =============================================================================
ZERO_X_API_KEY=your_api_key
ZERO_X_BASE_URL=https://api.0x.org
ONE_INCH_API_KEY=your_api_key
ONE_INCH_BASE_URL=https://api.1inch.io
HASHFLOW_API_KEY=your_api_key

# =============================================================================
# Blockchain
# =============================================================================
ETHEREUM_RPC_URL=https://mainnet.infura.io/v3/your-key
POLYGON_RPC_URL=https://polygon-rpc.com
ARBITRUM_RPC_URL=https://arb1.arbitrum.io/rpc

# =============================================================================
# Observability
# =============================================================================
LOG_LEVEL=info
TRACING_ENABLED=true
METRICS_PORT=9090
```

### Configuration File (TOML)

```toml
[server]
grpc_port = 50051
rest_port = 8080
websocket_port = 8081

[database]
url = "postgres://user:pass@localhost:5432/otc_rfq"
max_connections = 20
min_connections = 5

[redis]
url = "redis://localhost:6379"
max_connections = 10

[venues]
quote_timeout_ms = 500
min_quotes_required = 1
max_concurrent_requests = 100

[compliance]
kyc_required = true
aml_check_enabled = true
max_notional_usd = 10000000
```

---

## Usage

### Starting the Server

```bash
# Development
cargo run

# Production
cargo run --release

# With custom config
CONFIG_PATH=./config.toml cargo run --release
```

### gRPC Client Example

```rust
use otc_rfq::api::grpc::RfqServiceClient;
use otc_rfq::api::grpc::{CreateRfqRequest, Instrument, OrderSide, AssetClass};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to gRPC server
    let mut client = RfqServiceClient::connect("http://localhost:50051").await?;
    
    // Create RFQ
    let response = client.create_rfq(CreateRfqRequest {
        client_id: "DESK_001".to_string(),
        instrument: Some(Instrument {
            symbol: "BTC/USD".to_string(),
            asset_class: AssetClass::CryptoSpot as i32,
            ..Default::default()
        }),
        side: OrderSide::Buy as i32,
        quantity: Some(Decimal { value: "10.0".to_string() }),
        timeout_seconds: 30,
    }).await?;
    
    let rfq = response.into_inner().rfq.unwrap();
    println!("RFQ created: {}", rfq.id);
    
    // Stream quotes
    let mut stream = client.stream_quotes(StreamQuotesRequest {
        rfq_id: rfq.id.clone(),
    }).await?.into_inner();
    
    while let Some(quote) = stream.message().await? {
        println!("Quote received: {} @ {}", quote.venue_id, quote.price);
    }
    
    Ok(())
}
```

### REST API Examples

```bash
# Create RFQ
curl -X POST http://localhost:8080/api/v1/rfqs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "client_id": "DESK_001",
    "symbol": "BTC/USD",
    "side": "BUY",
    "quantity": "10.0",
    "timeout_seconds": 30
  }'

# Get RFQ by ID
curl http://localhost:8080/api/v1/rfqs/{rfq_id} \
  -H "Authorization: Bearer $TOKEN"

# List RFQs with pagination
curl "http://localhost:8080/api/v1/rfqs?page=1&page_size=20&status=QUOTES_RECEIVED" \
  -H "Authorization: Bearer $TOKEN"

# Execute trade
curl -X POST http://localhost:8080/api/v1/rfqs/{rfq_id}/execute \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "quote_id": "quote-uuid-here"
  }'

# List venues
curl http://localhost:8080/api/v1/venues \
  -H "Authorization: Bearer $TOKEN"

# Get venue health
curl http://localhost:8080/api/v1/venues/{venue_id}/health \
  -H "Authorization: Bearer $TOKEN"
```

### WebSocket Streaming

```javascript
// Connect to WebSocket
const ws = new WebSocket('ws://localhost:8081/ws');

// Subscribe to quote updates
ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'quotes',
  rfq_id: 'rfq-uuid-here'
}));

// Handle messages
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Quote update:', data);
};
```

---

## API Reference

### gRPC Services

| Service | Method | Description |
|---------|--------|-------------|
| `RfqService` | `CreateRfq` | Create a new RFQ |
| `RfqService` | `GetRfq` | Get RFQ by ID |
| `RfqService` | `ListRfqs` | List RFQs with filters |
| `RfqService` | `CancelRfq` | Cancel an active RFQ |
| `RfqService` | `StreamQuotes` | Stream quotes for an RFQ |
| `RfqService` | `ExecuteTrade` | Execute trade on selected quote |
| `VenueService` | `ListVenues` | List available venues |
| `VenueService` | `GetVenueHealth` | Get venue health status |

### REST Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/v1/rfqs` | Create RFQ |
| `GET` | `/api/v1/rfqs/{id}` | Get RFQ |
| `GET` | `/api/v1/rfqs` | List RFQs |
| `DELETE` | `/api/v1/rfqs/{id}` | Cancel RFQ |
| `POST` | `/api/v1/rfqs/{id}/execute` | Execute trade |
| `GET` | `/api/v1/venues` | List venues |
| `GET` | `/api/v1/venues/{id}/health` | Venue health |
| `GET` | `/api/v1/trades` | List trades |
| `GET` | `/api/v1/trades/{id}` | Get trade |

### WebSocket Channels

| Channel | Description |
|---------|-------------|
| `quotes` | Real-time quote updates |
| `rfq_status` | RFQ state changes |
| `trades` | Trade execution updates |
| `venue_health` | Venue health changes |

---

## Testing

### Running Tests

```bash
# Run all tests
cargo test --all-features

# Run specific test module
cargo test domain::entities::rfq

# Run with output
cargo test -- --nocapture

# Run integration tests (requires database)
TEST_DATABASE_URL=postgres://... cargo test --test integration

# Run benchmarks
cargo bench
```

### Test Categories

| Category | Description | Count |
|----------|-------------|-------|
| **Unit Tests** | Domain logic, value objects | 800+ |
| **Integration Tests** | Repository, API handlers | 200+ |
| **E2E Tests** | Complete RFQ workflow | 12 |
| **Property Tests** | Proptest-based invariants | 50+ |
| **Benchmarks** | Performance measurements | 10+ |

### Makefile Commands

The project includes a comprehensive Makefile with all development commands. Run `make help` for the full list.

#### 🔧 Build & Run

```bash
make build         # Compile the project
make release       # Build in release mode
make run           # Run the main binary
make run-release   # Run in release mode
make clean         # Clean build artifacts
```

#### 🧪 Test & Quality

```bash
make test          # Run all tests
make test-lib      # Run library tests only
make test-integration # Run integration tests
make fmt           # Format code
make fmt-check     # Check formatting without applying
make lint          # Run clippy with warnings as errors
make lint-fix      # Auto-fix lint issues
make fix           # Auto-fix Rust compiler suggestions
make check         # Run fmt-check + lint + test
make pre-push      # Run all pre-push checks
```

#### 📦 Packaging & Docs

```bash
make doc           # Generate documentation
make doc-open      # Build and open Rust documentation
make doc-check     # Check for missing docs via clippy
make create-doc    # Generate internal docs
make readme        # Regenerate README using cargo-readme
make publish       # Prepare and publish crate to crates.io
```

#### 📈 Coverage & Benchmarks

```bash
make coverage            # Generate code coverage report (XML)
make coverage-html       # Generate HTML coverage report
make open-coverage       # Open HTML report
make bench               # Run benchmarks using Criterion
make bench-show          # Open benchmark report
make bench-save          # Save benchmark history snapshot
make bench-compare       # Compare benchmark runs
make bench-json          # Output benchmarks in JSON
make bench-clean         # Remove benchmark data
```

#### 🗄️ Database

```bash
make migrate         # Run database migrations
make migrate-new     # Create a new migration
make migrate-revert  # Revert last migration
make db-reset        # Reset database (drop, create, migrate)
```

#### 🐳 Docker

```bash
make docker-up       # Start Docker services
make docker-down     # Stop Docker services
make docker-logs     # Show Docker logs
make docker-build    # Build Docker image
make docker-run      # Run Docker container
```

#### 🧹 Git & Workflow Helpers

```bash
make git-log             # Show commits on current branch vs main
make check-spanish       # Check for Spanish words in code
make zip                 # Create zip without target/ and temp files
make tree                # Visualize project tree
make loc                 # Count lines of code
make deps                # Show dependency tree
make outdated            # Check for outdated dependencies
make audit               # Run security audit
```

#### 🤖 GitHub Actions (via act)

```bash
make workflow-build      # Simulate build workflow
make workflow-lint       # Simulate lint workflow
make workflow-test       # Simulate test workflow
make workflow-coverage   # Simulate coverage workflow
make workflow            # Run all workflows
```

#### 🚀 Release

```bash
make version         # Show current version
make tag             # Create git tag from Cargo.toml version
```

---

## Performance

### Targets

| Metric | Target | Achieved |
|--------|--------|----------|
| Quote collection latency | < 100ms (p99) ||
| Trade execution latency | < 50ms (p99) ||
| Concurrent RFQs | 10,000+ ||
| Quotes per second | 100,000+ ||
| API response time | < 10ms (p99) ||

### Benchmarks

```bash
# Run benchmarks
make bench

# View benchmark report
make bench-show

# Save baseline and compare
make bench-save
make bench-compare
```

### Optimization Features

- **Zero-copy deserialization** with SBE encoding
- **Connection pooling** for database and Redis
- **Concurrent venue requests** with tokio
- **Circuit breakers** for fault tolerance
- **Response caching** with Redis

---

## Documentation

### Internal Documentation

| Document | Description |
|----------|-------------|
| [System Overview].internalDoc/architecture/01-SYSTEM-OVERVIEW.md | Business context and goals |
| [Architecture].internalDoc/architecture/02-ARCHITECTURE.md | Layered architecture design |
| [Domain Model].internalDoc/architecture/03-DOMAIN-MODEL.md | Entities, aggregates, events |
| [Data Model].internalDoc/architecture/04-DATA-MODEL.md | Database schema and caching |
| [API Overview].internalDoc/api/01-API-OVERVIEW.md | Multi-protocol API design |
| [FIX Protocol].internalDoc/protocols/02-FIX-PROTOCOL.md | FIX 4.4 integration |
| [DeFi Protocols].internalDoc/protocols/03-DEFI-PROTOCOLS.md | DEX and RFQ protocol adapters |
| [SBE Encoding].internalDoc/protocols/04-SBE-ENCODING.md | Binary message encoding |
| [Rust Guidelines].internalDoc/09-rust-guidelines.md | Coding standards |

### API Documentation

```bash
# Generate and open docs
cargo doc --open --no-deps
```

---

## Roadmap

### Completed Milestones

- [x] **M0**: Project Setup - Repository, CI/CD, documentation structure
- [x] **M1**: Domain Layer - Entities, value objects, domain events
- [x] **M2**: Infrastructure Layer - Venues, persistence, blockchain
- [x] **M3**: Application Layer - Use cases, services, DTOs
- [x] **M4**: API Layer - gRPC, REST, WebSocket
- [x] **M5**: Testing & Integration - Unit, integration, E2E tests

### Future Milestones

- [ ] **M6**: Production Hardening - Monitoring, alerting, deployment
- [ ] **M7**: Advanced Features - Algorithmic execution, portfolio management
- [ ] **M8**: Multi-Region - Geographic distribution, failover

See [GitHub Issues](https://github.com/joaquinbejar/otc-rfq/issues) for detailed progress.

---

## Contribution and Contact

We welcome contributions to this project! If you would like to contribute, please follow these steps:

1. Fork the repository.
2. Create a new branch for your feature or bug fix.
3. Make your changes and ensure that the project still builds and all tests pass.
4. Commit your changes and push your branch to your forked repository.
5. Submit a pull request to the main repository.

### Development Workflow

```bash
# Create feature branch
git checkout -b M[N]/issue-[NUM]-description

# Make changes and test
cargo test --all-features
make pre-push

# Commit and push
git commit -m "feat: description"
git push origin your-branch

# Create PR
gh pr create
```

If you have any questions, issues, or would like to provide feedback, please feel free to contact the project maintainer:

### **Contact Information**

- **Author**: Joaquín Béjar García
- **Email**: jb@taunais.com
- **Telegram**: [@joaquin_bejar]https://t.me/joaquin_bejar
- **Repository**: <https://github.com/joaquinbejar/otc-rfq>
- **Documentation**: <https://docs.rs/otc-rfq>

We appreciate your interest and look forward to your contributions!

---

**License**: MIT