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
//! # Interactive Brokers API Endpoints
//!
//! URL constants, endpoint enum, and helper functions for IB Client Portal Web API.
use crate::core::types::Symbol;
/// Base URLs for IB Client Portal Web API
pub struct IBEndpoints {
/// REST API base URL
pub rest_base: String,
/// WebSocket base URL (optional)
pub _ws_base: Option<String>,
}
impl IBEndpoints {
/// Create endpoints for Gateway (local)
pub fn gateway() -> Self {
Self {
rest_base: "https://localhost:5000/v1/api".to_string(),
_ws_base: Some("wss://localhost:5000/v1/api/ws".to_string()),
}
}
/// Create endpoints for production OAuth
#[allow(dead_code)]
pub fn production() -> Self {
Self {
rest_base: "https://api.ibkr.com/v1/api".to_string(),
_ws_base: Some("wss://api.ibkr.com/v1/api/ws".to_string()),
}
}
/// Create custom endpoints
pub fn custom(rest_base: impl Into<String>, ws_base: Option<impl Into<String>>) -> Self {
Self {
rest_base: rest_base.into(),
_ws_base: ws_base.map(|s| s.into()),
}
}
}
impl Default for IBEndpoints {
fn default() -> Self {
Self::gateway()
}
}
/// API endpoint paths
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum IBEndpoint {
// ═══════════════════════════════════════════════════════════════════════
// Authentication & Session Management
// ═══════════════════════════════════════════════════════════════════════
/// Check authentication status
AuthStatus,
/// Initialize brokerage session
AuthInit,
/// Validate SSO session
SsoValidate,
/// Keep session alive (tickle)
Tickle,
/// Logout
Logout,
// ═══════════════════════════════════════════════════════════════════════
// Portfolio & Account
// ═══════════════════════════════════════════════════════════════════════
/// Get portfolio accounts
PortfolioAccounts,
/// Get sub-accounts
PortfolioSubAccounts,
/// Get portfolio positions for account
PortfolioPositions { account_id: String, page: u32 },
/// Get position details
PortfolioPosition { account_id: String, conid: i64 },
/// Get account summary
PortfolioSummary { account_id: String },
/// Get account ledger
PortfolioLedger { account_id: String },
/// Get allocation data
PortfolioAllocation { account_id: String },
/// Get partitioned P&L
PnlPartitioned,
// ═══════════════════════════════════════════════════════════════════════
// Contract & Symbol Search
// ═══════════════════════════════════════════════════════════════════════
/// Search contracts by symbol
ContractSearch,
/// Get contract details
ContractInfo { conid: i64 },
/// Get contract info with trading rules
ContractInfoAndRules { conid: i64 },
/// Get trading rules for contract
ContractRules { conid: i64 },
/// Get algorithm parameters
ContractAlgos { conid: i64 },
/// Security definition info
SecdefInfo,
// ═══════════════════════════════════════════════════════════════════════
// Market Data
// ═══════════════════════════════════════════════════════════════════════
/// Get market data snapshot
MarketDataSnapshot,
/// Get historical market data
MarketDataHistory,
/// Unsubscribe market data for single contract
MarketDataUnsubscribe { conid: i64 },
/// Unsubscribe all market data
MarketDataUnsubscribeAll,
// ═══════════════════════════════════════════════════════════════════════
// Trading & Orders
// ═══════════════════════════════════════════════════════════════════════
/// Place order
PlaceOrder { account_id: String },
/// Confirm order
ConfirmOrder { reply_id: String },
/// Get live orders
LiveOrders,
/// Get trades (executions)
Trades,
/// Modify order
ModifyOrder { account_id: String, order_id: String },
/// Cancel order
CancelOrder { account_id: String, order_id: String },
/// What-if order (preview)
WhatIfOrder { account_id: String },
// ═══════════════════════════════════════════════════════════════════════
// Market Scanner
// ═══════════════════════════════════════════════════════════════════════
/// Get scanner parameters
ScannerParams,
/// Run market scanner
ScannerRun,
// ═══════════════════════════════════════════════════════════════════════
// Alerts & Notifications
// ═══════════════════════════════════════════════════════════════════════
/// Create alert
CreateAlert { account_id: String },
/// Get alerts
GetAlerts { account_id: String },
/// Delete alert
DeleteAlert { order_id: String },
/// Get unread notifications count
NotificationsUnreadCount,
/// Get notifications
GetNotifications,
/// Mark notification as read
MarkNotificationRead { notification_id: String },
// ═══════════════════════════════════════════════════════════════════════
// Watchlists
// ═══════════════════════════════════════════════════════════════════════
/// Create watchlist
CreateWatchlist,
/// Get all watchlists
GetWatchlists,
/// Get watchlist details
GetWatchlist { watchlist_id: String },
/// Delete watchlist
DeleteWatchlist { watchlist_id: String },
// ═══════════════════════════════════════════════════════════════════════
// Portfolio Analytics
// ═══════════════════════════════════════════════════════════════════════
/// Get performance metrics
PerformanceMetrics,
/// Get performance summary
PerformanceSummary,
/// Get transaction history
TransactionHistory,
// ═══════════════════════════════════════════════════════════════════════
// Flex Web Service
// ═══════════════════════════════════════════════════════════════════════
/// Generate flex report
FlexGenerate,
/// Check flex report status
FlexStatus { request_id: String },
}
impl IBEndpoint {
/// Get endpoint path
pub fn path(&self) -> String {
match self {
// Authentication & Session
Self::AuthStatus => "/iserver/auth/status".to_string(),
Self::AuthInit => "/iserver/auth/ssodh/init".to_string(),
Self::SsoValidate => "/sso/validate".to_string(),
Self::Tickle => "/tickle".to_string(),
Self::Logout => "/logout".to_string(),
// Portfolio & Account
Self::PortfolioAccounts => "/portfolio/accounts".to_string(),
Self::PortfolioSubAccounts => "/portfolio/subaccounts".to_string(),
Self::PortfolioPositions { account_id, page } => {
format!("/portfolio/{}/positions/{}", account_id, page)
}
Self::PortfolioPosition { account_id, conid } => {
format!("/portfolio/{}/position/{}", account_id, conid)
}
Self::PortfolioSummary { account_id } => {
format!("/portfolio/{}/summary", account_id)
}
Self::PortfolioLedger { account_id } => {
format!("/portfolio/{}/ledger", account_id)
}
Self::PortfolioAllocation { account_id } => {
format!("/portfolio/{}/allocation", account_id)
}
Self::PnlPartitioned => "/iserver/account/pnl/partitioned".to_string(),
// Contract & Symbol Search
Self::ContractSearch => "/iserver/secdef/search".to_string(),
Self::ContractInfo { conid } => format!("/iserver/contract/{}/info", conid),
Self::ContractInfoAndRules { conid } => {
format!("/iserver/contract/{}/info-and-rules", conid)
}
Self::ContractRules { conid } => format!("/iserver/contract/{}/rules", conid),
Self::ContractAlgos { conid } => format!("/iserver/contract/{}/algos", conid),
Self::SecdefInfo => "/iserver/secdef/info".to_string(),
// Market Data
Self::MarketDataSnapshot => "/iserver/marketdata/snapshot".to_string(),
Self::MarketDataHistory => "/iserver/marketdata/history".to_string(),
Self::MarketDataUnsubscribe { conid } => {
format!("/iserver/marketdata/{}/unsubscribe", conid)
}
Self::MarketDataUnsubscribeAll => "/iserver/marketdata/unsubscribe".to_string(),
// Trading & Orders
Self::PlaceOrder { account_id } => {
format!("/iserver/account/{}/orders", account_id)
}
Self::ConfirmOrder { reply_id } => format!("/iserver/reply/{}", reply_id),
Self::LiveOrders => "/iserver/account/orders".to_string(),
Self::Trades => "/iserver/account/trades".to_string(),
Self::ModifyOrder { account_id, order_id } => {
format!("/iserver/account/{}/order/{}", account_id, order_id)
}
Self::CancelOrder { account_id, order_id } => {
format!("/iserver/account/{}/order/{}", account_id, order_id)
}
Self::WhatIfOrder { account_id } => {
format!("/iserver/account/{}/whatiforder", account_id)
}
// Market Scanner
Self::ScannerParams => "/iserver/scanner/params".to_string(),
Self::ScannerRun => "/iserver/scanner/run".to_string(),
// Alerts & Notifications
Self::CreateAlert { account_id } => {
format!("/iserver/account/{}/alert", account_id)
}
Self::GetAlerts { account_id } => {
format!("/iserver/account/{}/alerts", account_id)
}
Self::DeleteAlert { order_id } => format!("/iserver/account/alert/{}", order_id),
Self::NotificationsUnreadCount => "/fyi/unreadnumber".to_string(),
Self::GetNotifications => "/fyi/notifications".to_string(),
Self::MarkNotificationRead { notification_id } => {
format!("/fyi/notification/{}", notification_id)
}
// Watchlists
Self::CreateWatchlist => "/iserver/watchlists".to_string(),
Self::GetWatchlists => "/iserver/watchlists".to_string(),
Self::GetWatchlist { watchlist_id } => {
format!("/iserver/watchlists/{}", watchlist_id)
}
Self::DeleteWatchlist { watchlist_id } => {
format!("/iserver/watchlists/{}", watchlist_id)
}
// Portfolio Analytics
Self::PerformanceMetrics => "/pa/performance".to_string(),
Self::PerformanceSummary => "/pa/summary".to_string(),
Self::TransactionHistory => "/pa/transactions".to_string(),
// Flex Web Service
Self::FlexGenerate => "/pa/flex/generate".to_string(),
Self::FlexStatus { request_id } => format!("/pa/flex/status/{}", request_id),
}
}
}
/// Format symbol for IB API
///
/// IB doesn't use symbols directly - it uses Contract IDs (conid).
/// This function is for display/logging purposes only.
/// Actual trading requires resolving symbol to conid via contract search.
pub fn _format_symbol(symbol: &Symbol) -> String {
// IB doesn't trade by symbol — it uses Contract IDs. This formatter is for
// display/logging only. Output conventions:
// stock → "AAPL" (4+ letter ticker; quote dropped)
// forex → "EUR.USD" (3-letter base + ISO quote; dot separator)
// crypto → "BTC/USDT" (BASE/QUOTE, slash separator)
//
// The previous heuristic was reversed: it returned the ticker for any
// base of len <= 5, which dropped the quote on 3-letter forex pairs like
// EUR/USD → "EUR".
let fiat = matches!(symbol.quote.as_str(), "USD" | "EUR" | "GBP" | "JPY" | "CHF" | "CAD" | "AUD" | "NZD");
if symbol.base.len() == 3 && fiat {
// Forex pair (3-letter ISO base × ISO fiat quote) → dot form.
format!("{}.{}", symbol.base, symbol.quote)
} else if fiat {
// Stock ticker quoted in fiat → drop the quote.
symbol.base.to_uppercase()
} else {
// Crypto / other → slash form.
format!("{}/{}", symbol.base, symbol.quote)
}
}
/// Parse symbol from IB API format
///
/// Note: IB primarily uses conid, not symbols.
/// This is for parsing symbol strings when available.
pub fn _parse_symbol(api_symbol: &str) -> Option<Symbol> {
// Try different separators
if let Some((base, quote)) = api_symbol.split_once('/') {
return Some(Symbol::new(base, quote));
}
if let Some((base, quote)) = api_symbol.split_once('.') {
return Some(Symbol::new(base, quote));
}
// If no separator, assume stock with USD quote
if !api_symbol.is_empty() {
return Some(Symbol::new(api_symbol, "USD"));
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gateway_endpoints() {
let endpoints = IBEndpoints::gateway();
assert_eq!(endpoints.rest_base, "https://localhost:5000/v1/api");
assert_eq!(
endpoints._ws_base.unwrap(),
"wss://localhost:5000/v1/api/ws"
);
}
#[test]
fn test_production_endpoints() {
let endpoints = IBEndpoints::production();
assert_eq!(endpoints.rest_base, "https://api.ibkr.com/v1/api");
assert_eq!(endpoints._ws_base.unwrap(), "wss://api.ibkr.com/v1/api/ws");
}
#[test]
fn test_endpoint_paths() {
assert_eq!(IBEndpoint::AuthStatus.path(), "/iserver/auth/status");
assert_eq!(IBEndpoint::Tickle.path(), "/tickle");
assert_eq!(
IBEndpoint::PortfolioPositions {
account_id: "DU12345".to_string(),
page: 0
}
.path(),
"/portfolio/DU12345/positions/0"
);
assert_eq!(
IBEndpoint::MarketDataUnsubscribe { conid: 265598 }.path(),
"/iserver/marketdata/265598/unsubscribe"
);
}
#[test]
fn test_format_symbol() {
let symbol = Symbol::new("AAPL", "USD");
assert_eq!(_format_symbol(&symbol), "AAPL");
let symbol = Symbol::new("EUR", "USD");
assert_eq!(_format_symbol(&symbol), "EUR.USD");
let symbol = Symbol::new("BTC", "USDT");
assert_eq!(_format_symbol(&symbol), "BTC/USDT");
}
#[test]
fn test_parse_symbol() {
assert_eq!(
_parse_symbol("AAPL"),
Some(Symbol::new("AAPL", "USD"))
);
assert_eq!(
_parse_symbol("EUR.USD"),
Some(Symbol::new("EUR", "USD"))
);
assert_eq!(
_parse_symbol("BTC/USDT"),
Some(Symbol::new("BTC", "USDT"))
);
}
}