Skip to main content

ig_client/
lib.rs

1//! # IG Markets API Client for Rust
2//!
3//! A comprehensive Rust client for the IG Markets trading API. This library
4//! provides a type-safe, async-first way to access IG Markets' REST and
5//! real-time streaming APIs for trading and market-data retrieval.
6//!
7//! ## Overview
8//!
9//! The IG Markets API Client for Rust offers a reliable interface to the IG
10//! Markets trading platform. It handles authentication and session management,
11//! automatic token refresh, rate limiting, finite retry with backoff, and
12//! real-time streaming over the Lightstreamer protocol, exposing a clean,
13//! idiomatic Rust API.
14//!
15//! ## Features
16//!
17//! - **Authentication**: IG session v2 (`CST` / `X-SECURITY-TOKEN` headers) and
18//!   v3 (OAuth bearer) with automatic, transparent token refresh and account
19//!   switching.
20//! - **Account Management**: Accounts, balances, positions, working orders,
21//!   preferences, activity, and transaction history.
22//! - **Market Data**: Market search, instrument details, market navigation, and
23//!   historical prices at several resolutions.
24//! - **Order Management**: Create, update, and close positions and working
25//!   orders with typed request builders.
26//! - **Watchlists**: Full CRUD over watchlists and their instruments.
27//! - **Client Sentiment**: Sentiment for single, multiple, and related markets.
28//! - **Indicative Costs**: Costs and charges for opening, closing, or editing
29//!   positions, plus cost history.
30//! - **Real-time Streaming**: Market, price, trade, and account updates over
31//!   Lightstreamer, with thread-safe dynamic subscription management.
32//! - **Rate Limiting**: `governor`-backed pacing configured per IG's trading vs
33//!   non-trading budgets.
34//! - **Finite Retry**: Exponential backoff with jitter via `RetryConfig`
35//!   (bounded — no unbounded retry loops).
36//! - **Type Safety**: Strongly typed request / response DTOs and domain enums.
37//! - **Async**: Built on `tokio` with a shared, pooled `reqwest` client.
38//! - **Persistence (optional)**: PostgreSQL storage via `sqlx`.
39//!
40//! ## Installation
41//!
42//! Add this to your `Cargo.toml`:
43//!
44//! ```toml
45//! [dependencies]
46//! ig-client = "0.12.2"
47//! tokio = { version = "1", features = ["full"] }  # Async runtime
48//! tracing = "0.1"                                  # Logging facade
49//! # Optional, only if you use the PostgreSQL persistence layer:
50//! sqlx = { version = "0.9", features = ["runtime-tokio", "tls-native-tls", "postgres"] }
51//! ```
52//!
53//! You do not need to add `dotenv` yourself — `Config::new()` loads a local
54//! `.env` file internally. If your application supplies its own configuration
55//! and must not read a `.env` file or the `IG_*` namespace, use
56//! `Config::from_credentials()` with `Client::with_config()` instead (see
57//! [Programmatic configuration](#programmatic-configuration-embedders)).
58//!
59//! ### Requirements
60//!
61//! - Rust 2024 edition on the stable toolchain.
62//! - An IG Markets account (demo or live) and API credentials.
63//! - A PostgreSQL database (optional, only for the persistence layer).
64//!
65//! ## Configuration
66//!
67//! `Config::new()` reads configuration from the environment (and a local `.env`
68//! file, if present). Create a `.env` file in your project root with the
69//! following variables:
70//!
71//! ```text
72//! IG_USERNAME=your_username
73//! IG_PASSWORD=your_password
74//! IG_API_KEY=your_api_key
75//! IG_ACCOUNT_ID=your_account_id
76//! IG_API_VERSION=3                                   # 2 (CST/XST) or 3 (OAuth); defaults to 3
77//! IG_REST_BASE_URL=https://demo-api.ig.com/gateway/deal   # Use demo or live as needed
78//! IG_REST_TIMEOUT=30                                 # REST request timeout in seconds
79//! IG_WS_URL=wss://demo-apd.marketdatasystems.com     # Lightstreamer endpoint
80//! IG_WS_RECONNECT_INTERVAL=5                         # Reconnect interval in seconds
81//! IG_RATE_LIMIT_MAX_REQUESTS=4                       # Rate-limiter budget
82//! IG_RATE_LIMIT_PERIOD_SECONDS=12                    # Rate-limiter period (seconds)
83//! IG_RATE_LIMIT_BURST_SIZE=3                         # Rate-limiter burst size
84//! DATABASE_URL=postgres://user:password@localhost/ig_db   # Optional persistence
85//! DATABASE_MAX_CONNECTIONS=5                         # Optional connection-pool size
86//! TX_LOOP_INTERVAL_HOURS=1                           # Transaction loop interval (hours)
87//! TX_PAGE_SIZE=20                                    # Transaction page size
88//! TX_DAYS_LOOKBACK=7                                 # Days to look back for transactions
89//! ```
90//!
91//! Live examples and integration tests default to the IG **demo** environment;
92//! pointing anything at production requires an explicit opt-in via
93//! `IG_REST_BASE_URL` / `IG_WS_URL`.
94//!
95//! ### Programmatic configuration (embedders)
96//!
97//! There are two configuration paths and they do not mix:
98//!
99//! - `Config::new()` / `Client::try_new()` — the **convenience path**. Loads a
100//!   local `.env` file and reads the global `IG_*` namespace, as above.
101//! - `Config::from_credentials()` / `Client::with_config()` — the **injection
102//!   path**. Reads no environment variable and loads no `.env` file, for an
103//!   embedding application that owns its configuration source (its own
104//!   namespaced variables, a config file, a secrets manager). Useful under
105//!   `#![forbid(unsafe_code)]`, where pre-populating `IG_*` is not an option
106//!   because `std::env::set_var` is `unsafe` on edition 2024.
107//!
108//! ```rust,no_run
109//! use ig_client::prelude::*;
110//!
111//! // Fail fast on a missing variable: an empty credential would only surface
112//! // later as a confusing authentication failure. Never log the value.
113//! fn required_var(name: &str) -> Result<String, AppError> {
114//!     std::env::var(name).map_err(|_| AppError::InvalidInput(format!("{name} is not set")))
115//! }
116//!
117//! # fn main() -> Result<(), AppError> {
118//! let credentials = Credentials::new(
119//!     required_var("MYAPP_IG_USERNAME")?,
120//!     required_var("MYAPP_IG_PASSWORD")?,
121//!     required_var("MYAPP_IG_ACCOUNT_ID")?,
122//!     required_var("MYAPP_IG_API_KEY")?,
123//! );
124//!
125//! // Struct update overrides individual sections and stays env-free,
126//! // because the base value is the env-free constructor.
127//! let config = Config {
128//!     rest_api: RestApiConfig {
129//!         base_url: "https://demo-api.ig.com/gateway/deal".to_string(),
130//!         timeout: 30,
131//!     },
132//!     ..Config::from_credentials(credentials)
133//! };
134//!
135//! let client = Client::with_config(config)?;
136//! println!("REST base URL: {}", client.config().rest_api.base_url);
137//! # Ok(())
138//! # }
139//! ```
140//!
141//! Non-credential fields default to the IG **demo** endpoints; see
142//! `examples/simples/src/bin/client_with_config.rs` for a runnable version.
143//!
144//! For streaming, build the streamer from the injected client with
145//! `StreamerClient::with_client(&client)` — `StreamerClient::new()` goes
146//! through `Client::try_new()` and therefore back to `.env` / `IG_*`.
147//!
148//! Two knobs are still resolved from the process environment on the injected
149//! path, because they are not part of `Config`:
150//!
151//! - Retry policy — `MAX_RETRY_COUNT` and `RETRY_DELAY_SECS` are read per
152//!   request via `RetryConfig::default()`; unset means the crate defaults.
153//! - `IG_PRICING_ADAPTER` — the Lightstreamer price adapter name, defaulting
154//!   to `Pricing` when unset.
155//!
156//! Neither carries a credential, and both have safe defaults, so an embedder
157//! that sets neither variable is unaffected. Moving them into `Config` is a
158//! breaking change scheduled for a future minor release.
159//!
160//! ## Usage
161//!
162//! The main entry points are `Config` and `Client`. A single `Client`
163//! implements every REST service trait (`AccountService`, `MarketService`,
164//! `OrderService`, `WatchlistService`, `SentimentService`, `CostsService`,
165//! `OperationsService`). Session login and token refresh are performed
166//! transparently on first use. The prelude re-exports the full public surface,
167//! including the streaming API and the service traits, so a single glob import
168//! is usually enough:
169//!
170//! ```rust
171//! use ig_client::prelude::*;
172//! ```
173//!
174//! ### Client setup and account information
175//!
176//! ```rust,no_run
177//! use ig_client::prelude::*;
178//!
179//! #[tokio::main]
180//! async fn main() -> Result<(), AppError> {
181//!     // Configuration is read from the environment / a local `.env` file.
182//!     let config = Config::new();
183//!     println!("configured API version: {:?}", config.api_version);
184//!
185//!     // `try_new` is the fallible constructor for the REST client.
186//!     // (`new()` / `default()` no longer exist.) Session login and automatic
187//!     // token refresh happen transparently on the first API call.
188//!     let client = Client::try_new()?;
189//!
190//!     // `Client` implements `AccountService`.
191//!     let accounts = client.get_accounts().await?;
192//!     println!("{} account(s) available", accounts.accounts.len());
193//!     Ok(())
194//! }
195//! ```
196//!
197//! ### Market data
198//!
199//! ```rust,no_run
200//! use ig_client::prelude::*;
201//!
202//! #[tokio::main]
203//! async fn main() -> Result<(), AppError> {
204//!     let client = Client::try_new()?;
205//!
206//!     // `Client` implements `MarketService`.
207//!     let results = client.search_markets("EUR/USD").await?;
208//!     if let Some(market) = results.markets.first() {
209//!         let details = client.get_market_details(&market.epic).await?;
210//!         println!("{}: {}", market.epic, details.instrument.name);
211//!     }
212//!     Ok(())
213//! }
214//! ```
215//!
216//! ### Placing an order
217//!
218//! ```rust,no_run
219//! use ig_client::prelude::*;
220//!
221//! #[tokio::main]
222//! async fn main() -> Result<(), AppError> {
223//!     let client = Client::try_new()?;
224//!
225//!     // Build a market order with the typed constructor. `size` is rounded to
226//!     // two decimals; a `None` currency code defaults to "EUR".
227//!     let order = CreateOrderRequest::market(
228//!         "CS.D.EURUSD.CFD.IP".to_string(), // epic
229//!         Direction::Buy,                   // direction
230//!         1.0,                              // size
231//!         Some("USD".to_string()),          // currency_code
232//!         None,                             // deal_reference
233//!     );
234//!
235//!     // `Client` implements `OrderService`.
236//!     let confirmation = client.create_order(&order).await?;
237//!     println!("deal reference: {}", confirmation.deal_reference);
238//!     Ok(())
239//! }
240//! ```
241//!
242//! ### Real-time streaming
243//!
244//! `DynamicMarketStreamer` wraps the lower-level `StreamerClient` and manages
245//! subscriptions in a thread-safe way. Its constructor is **synchronous** — it
246//! only wires up in-memory channels; the network connection is established later
247//! by `start`. Updates arrive as `PriceData`, resolved through the prelude.
248//!
249//! ```rust,no_run
250//! use ig_client::prelude::*;
251//! use std::collections::HashSet;
252//!
253//! #[tokio::main]
254//! async fn main() -> Result<(), AppError> {
255//!     // Fields to receive on each market tick.
256//!     let fields = HashSet::from([StreamingMarketField::Bid, StreamingMarketField::Offer]);
257//!
258//!     // Synchronous construction — no `await`, no fallibility.
259//!     let mut streamer = DynamicMarketStreamer::new(fields);
260//!
261//!     // Take the receiver before connecting.
262//!     let mut receiver = streamer.get_receiver().await?;
263//!
264//!     // Subscribe to an instrument and open the Lightstreamer connection.
265//!     streamer.add("IX.D.DAX.DAILY.IP".to_string()).await?;
266//!     streamer.start().await?;
267//!
268//!     // Consume `PriceData` updates.
269//!     while let Some(price) = receiver.recv().await {
270//!         let price: PriceData = price;
271//!         println!("price update: {price}");
272//!     }
273//!     Ok(())
274//! }
275//! ```
276//!
277//! ## Available Services
278//!
279//! Every service trait below is implemented by `Client`; bring the traits into
280//! scope via `use ig_client::prelude::*;`.
281//!
282//! ### `AccountService`
283//! - `get_accounts()` — all accounts for the authenticated user
284//! - `get_positions()` / `get_positions_w_filter(filter)` — open positions
285//! - `get_working_orders()` — working orders
286//! - `get_activity(from, to)` / `get_activity_with_details(from, to)` — activity
287//! - `get_activity_by_period(period_ms)` — activity for a period in milliseconds
288//! - `get_transactions(from, to)` — transaction history (paginated internally)
289//! - `get_preferences()` / `update_preferences(trailing_stops_enabled)`
290//!
291//! ### `MarketService`
292//! - `search_markets(term)` — search markets by keyword
293//! - `get_market_details(epic)` / `get_multiple_market_details(epics)`
294//! - `get_historical_prices(epic, resolution, from, to)` and
295//!   `get_historical_prices_by_date_range(epic, resolution, start, end)`
296//! - `get_historical_prices_by_count_v1` / `_v2(epic, resolution, num_points)`
297//! - `get_recent_prices(params)`
298//! - `get_market_navigation()` / `get_market_navigation_node(node_id)`
299//! - `get_all_markets()` / `get_vec_db_entries()`
300//! - `get_categories()` / `get_category_instruments(category_id, page, size)`
301//!
302//! ### `OrderService`
303//! - `create_order(request)` — open a position
304//! - `get_order_confirmation(deal_reference)` and
305//!   `get_order_confirmation_w_retry(deal_reference, retries, delay_ms)`
306//! - `update_position(deal_id, update)` / `update_level_in_position(deal_id, level)`
307//! - `close_position(request)` / `get_position(deal_id)`
308//! - `create_working_order(request)` / `update_working_order(deal_id, update)` /
309//!   `delete_working_order(deal_id)`
310//!
311//! ### `WatchlistService`
312//! - `get_watchlists()` / `create_watchlist(name, epics)`
313//! - `get_watchlist(id)` / `delete_watchlist(id)`
314//! - `add_to_watchlist(id, epic)` / `remove_from_watchlist(id, epic)`
315//!
316//! ### `SentimentService`
317//! - `get_client_sentiment(market_ids)`
318//! - `get_client_sentiment_by_market(market_id)`
319//! - `get_related_sentiment(market_id)`
320//!
321//! ### `CostsService`
322//! - `get_indicative_costs_open(request)` / `_close(request)` / `_edit(request)`
323//! - `get_costs_history(from, to)` / `get_durable_medium(quote_reference)`
324//!
325//! ### `OperationsService`
326//! - `get_client_apps()` — API application details
327//! - `disable_client_app()` — disable the current API key
328//!
329//! ## Rate Limiting
330//!
331//! All requests are paced by a `governor`-backed `RateLimiter` so the client
332//! stays within IG's published limits (trading and non-trading endpoints have
333//! different budgets). The budget is configured from the environment via
334//! `IG_RATE_LIMIT_MAX_REQUESTS`, `IG_RATE_LIMIT_PERIOD_SECONDS`, and
335//! `IG_RATE_LIMIT_BURST_SIZE` (see `RateLimiterConfig`). On top of pacing,
336//! transient failures (429 / 5xx / connection errors) are retried with
337//! **finite** exponential backoff and jitter via `RetryConfig`; non-idempotent
338//! trading calls are never retried blindly.
339//!
340//! ## Architecture
341//!
342//! The crate is organized as a module-oriented library under `src/`:
343//!
344//! - **`application`** — all I/O. The REST `Client` and its service-trait
345//!   implementations, `Auth` / `Session` (login, refresh, logout, account
346//!   switching), `Config`, the `RateLimiter`, and the streaming layer
347//!   (`StreamerClient`, `DynamicMarketStreamer`). Service traits live under
348//!   `application::interfaces`.
349//! - **`model`** — pure request / response DTOs, streaming message DTOs, session
350//!   DTOs, and the retry policy. Serde only; no I/O.
351//! - **`presentation`** — domain entities per area: account, chart, instrument,
352//!   market, order, price, trade, transaction. Serde only; no I/O.
353//! - **`storage`** — optional PostgreSQL persistence via `sqlx` (sits on top of
354//!   `model` / `presentation`).
355//! - **`utils`** — leaf helpers: env-var config, logging, finance (P&L), parsing,
356//!   deal-reference id generation.
357//! - **`error`** — canonical typed error enums: `AppError`, `AuthError`, and
358//!   `FetchError`.
359//! - **`constants`** — crate-wide endpoint paths, header names, and defaults.
360//! - **`prelude`** — curated public re-exports (the recommended import surface).
361//!
362//! ### API Documentation
363//!
364//! Browse the API documentation on [docs.rs](https://docs.rs/ig-client) or
365//! generate it locally with:
366//!
367//! ```bash
368//! make doc-open
369//! ```
370//!
371//! ## Project Structure
372//!
373//! ```text
374//! src/
375//! ├── application/       # I/O: client, auth, config, rate limiter, streaming
376//! │   ├── interfaces/    # Service traits (account, market, order, costs, …)
377//! │   ├── auth.rs        # Auth / Session: login, refresh, logout, switch
378//! │   ├── client.rs      # Client (REST services) + StreamerClient
379//! │   ├── config.rs      # Config, Credentials, REST / WS / rate-limiter config
380//! │   ├── rate_limiter.rs      # governor-backed request pacing
381//! │   └── dynamic_streamer.rs  # DynamicMarketStreamer (subscriptions)
382//! ├── model/             # Pure DTOs: requests, responses, streaming, retry
383//! ├── presentation/      # Domain entities (account, market, order, price, …)
384//! ├── storage/           # Optional PostgreSQL persistence via sqlx
385//! ├── utils/             # config, logger, finance, parsing, id helpers
386//! ├── constants.rs       # Endpoint paths, header names, defaults
387//! ├── error.rs           # AppError / AuthError / FetchError
388//! ├── prelude.rs         # Curated public re-exports
389//! └── lib.rs             # Public API and crate docs (README source)
390//! examples/              # Runnable demos (workspace members)
391//! tests/                 # unit/ and env-gated integration/ tests
392//! benches/               # Criterion benchmarks
393//! ```
394//!
395//! ## Development
396//!
397//! This project includes a Makefile with common development tasks:
398//!
399//! ```bash
400//! make build        # Debug build
401//! make release      # Release build
402//! make test         # Run all tests
403//! make fmt          # Format code with rustfmt
404//! make lint         # Run clippy
405//! make readme       # Regenerate README.md from these crate docs
406//! make pre-push     # Run all checks before pushing
407//! ```
408//!
409//! ## Contributing
410//!
411//! Contributions are welcome:
412//!
413//! 1. Fork the repository.
414//! 2. Create a feature branch: `git checkout -b feature/my-feature`.
415//! 3. Make your changes and commit them.
416//! 4. Run the checks: `make pre-push`.
417//! 5. Push the branch and open a pull request.
418//!
419//! Please make sure your code passes all tests and linting checks before
420//! submitting a pull request.
421
422/// Core application logic and services
423pub mod application;
424
425/// User interface and presentation layer
426pub mod presentation;
427
428/// Module containing global constants used throughout the library
429pub mod constants;
430
431/// Error types and handling
432pub mod error;
433
434/// Data persistence and storage
435pub mod storage;
436
437/// Data models for IG Markets API entities
438pub mod model;
439/// Prelude module for convenient imports
440pub mod prelude;
441/// Utility functions and helpers
442pub mod utils;
443
444/// Library version
445pub const VERSION: &str = env!("CARGO_PKG_VERSION");
446
447/// Returns the library version
448pub fn version() -> &'static str {
449    VERSION
450}