To retrieve specific market data such as PointDelta, DLow(0), DHigh(0), PipSize, TransparencyLines, and ClassicDelta for the Nasdaq index from the IG API using Rust, you'll need to interact with the IG REST API. Since there isn't an official Rust SDK for the IG API, we'll use the reqwest crate to make HTTP requests and serde for JSON serialization/deserialization.
Here's a step-by-step guide along with example code.
Prerequisites
- IG Account: You need an IG account with API access. You can sign up for a demo account for testing purposes.
- API Key: Obtain your API key from the IG dashboard.
- Epic Code: The unique identifier for the Nasdaq market on IG. For this example, we'll use the epic code for the NASDAQ 100 index:
IX.D.NASDAQ.IFD.IP. You can confirm or find other epic codes via the API or IG platform.
Setup
-
Create a new Rust project:
cargo new ig_api_example
cd ig_api_example
-
Add dependencies in Cargo.toml:
[dependencies]
reqwest = { version = "0.11", features = ["json", "gzip"] }
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
Example Code
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE, USER_AGENT};
use serde::{Deserialize, Serialize};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Replace with your actual IG API credentials
let ig_api_key = "YOUR_IG_API_KEY";
let ig_username = "YOUR_IG_USERNAME";
let ig_password = "YOUR_IG_PASSWORD";
// Step 1: Authenticate with the IG API
let (client, cst_token, x_sec_token) = authenticate(ig_api_key, ig_username, ig_password).await?;
// Step 2: Get market details for Nasdaq
let epic = "IX.D.NASDAQ.IFD.IP"; // Epic code for NASDAQ 100 (example)
let market_details = get_market_details(&client, ig_api_key, &cst_token, &x_sec_token, epic).await?;
// Step 3: Extract and display the required values
display_market_data(&market_details);
Ok(())
}
async fn authenticate(
ig_api_key: &str,
ig_username: &str,
ig_password: &str,
) -> Result<(reqwest::Client, String, String), Box<dyn Error>> {
let auth_url = "https://demo-api.ig.com/gateway/deal/session"; // Use demo environment for testing
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json; charset=UTF-8"));
headers.insert(ACCEPT, HeaderValue::from_static("application/json; charset=UTF-8"));
headers.insert("X-IG-API-KEY", HeaderValue::from_str(ig_api_key)?);
headers.insert("Version", HeaderValue::from_static("2"));
headers.insert(USER_AGENT, HeaderValue::from_static("RustReqwestClient/1.0"));
let credentials = serde_json::json!({
"identifier": ig_username,
"password": ig_password,
});
let client = reqwest::Client::builder()
.default_headers(headers.clone())
.build()?;
let resp = client.post(auth_url).json(&credentials).send().await?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await?;
println!("Authentication failed: {} {}", status, text);
return Err("Authentication failed".into());
}
let cst_token = resp
.headers()
.get("CST")
.ok_or("Missing CST token")?
.to_str()?
.to_string();
let x_sec_token = resp
.headers()
.get("X-SECURITY-TOKEN")
.ok_or("Missing X-SECURITY-TOKEN")?
.to_str()?
.to_string();
Ok((client, cst_token, x_sec_token))
}
#[derive(Debug, Deserialize)]
struct MarketDetailsResponse {
#[serde(rename = "instrument")]
instrument: InstrumentDetails,
#[serde(rename = "snapshot")]
snapshot: MarketSnapshot,
}
#[derive(Debug, Deserialize)]
struct InstrumentDetails {
epic: String,
name: String,
#[serde(rename = "lotSize")]
lot_size: f64,
#[serde(rename = "minimumPriceMovement")]
minimum_price_movement: f64,
#[serde(rename = "pipValue")]
pip_value: f64,
#[serde(rename = "expiry")]
expiry: String,
// Add other fields as needed
}
#[derive(Debug, Deserialize)]
struct MarketSnapshot {
#[serde(rename = "low")]
low: Option<f64>,
#[serde(rename = "high")]
high: Option<f64>,
// Add other fields as needed
}
async fn get_market_details(
client: &reqwest::Client,
ig_api_key: &str,
cst_token: &str,
x_sec_token: &str,
epic: &str,
) -> Result<MarketDetailsResponse, Box<dyn Error>> {
let url = format!("https://demo-api.ig.com/gateway/deal/markets/{}", epic);
let mut headers = HeaderMap::new();
headers.insert("X-IG-API-KEY", HeaderValue::from_str(ig_api_key)?);
headers.insert("CST", HeaderValue::from_str(cst_token)?);
headers.insert("X-SECURITY-TOKEN", HeaderValue::from_str(x_sec_token)?);
headers.insert("Version", HeaderValue::from_static("3"));
headers.insert(ACCEPT, HeaderValue::from_static("application/json; charset=UTF-8"));
let resp = client
.get(&url)
.headers(headers)
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().await?;
println!("Failed to get market details: {} {}", status, text);
return Err("Failed to get market details".into());
}
let market_details = resp.json::<MarketDetailsResponse>().await?;
Ok(market_details)
}
fn display_market_data(market_details: &MarketDetailsResponse) {
println!("Market Details for {} ({})", market_details.instrument.name, market_details.instrument.epic);
// Extracting and displaying the required values
// PointDelta: Assuming it refers to the minimum price movement
println!("PointDelta (Minimum Price Movement): {}", market_details.instrument.minimum_price_movement);
// DLow(0): Daily Low from snapshot
if let Some(low) = market_details.snapshot.low {
println!("DLow(0) (Daily Low): {}", low);
}
// DHigh(0): Daily High from snapshot
if let Some(high) = market_details.snapshot.high {
println!("DHigh(0) (Daily High): {}", high);
}
// PipSize: The value of one pip
println!("PipSize: {}", market_details.instrument.pip_value);
// TransparencyLines and ClassicDelta are not standard fields in the IG API.
// You may need to compute or fetch them separately if applicable.
// TODO: If TransparencyLines and ClassicDelta relate to other data,
// include logic here to compute or retrieve them.
}
Explanation
1. Authentication
-
Endpoint: POST /gateway/deal/session
-
Headers:
Content-Type: application/json; charset=UTF-8
Accept: application/json; charset=UTF-8
X-IG-API-KEY: Your API key
Version: 2
-
Body:
{
"identifier": "YOUR_IG_USERNAME",
"password": "YOUR_IG_PASSWORD"
}
-
Tokens: Upon successful authentication, IG returns CST and X-SECURITY-TOKEN headers. These must be included in subsequent requests.
2. Fetching Market Details
- Endpoint:
GET /gateway/deal/markets/{epic}
- Headers:
X-IG-API-KEY: Your API key
CST: Token from authentication response
X-SECURITY-TOKEN: Token from authentication response
Version: 3
Accept: application/json; charset=UTF-8
- Response: Contains detailed information about the market, including instrument details and snapshot data.
3. Parsing and Displaying Data
- InstrumentDetails: Contains details about the instrument, such as
lotSize, pipValue, minimumPriceMovement, etc.
- MarketSnapshot: Contains the latest market data, including
low and high prices for the day.
- Fields Explanation:
PointDelta: Interpreted as the minimumPriceMovement.
DLow(0): The day's low price from the snapshot.
DHigh(0): The day's high price from the snapshot.
PipSize: The value of one pip (pipValue).
TransparencyLines and ClassicDelta: Not standard in IG's API. You may need to calculate or retrieve them from different data sources or clarify their meaning.
Understanding the Data Fields
- PointDelta (Minimum Price Movement): The smallest increment by which the market price can move.
- DLow(0) (Daily Low): The lowest price reached by the market during the current trading day.
- DHigh(0) (Daily High): The highest price reached by the market during the current trading day.
- PipSize (Pip Value): The value of one pip move in the base currency.
- TransparencyLines: Unclear in IG's context; may need further clarification or may refer to order book depth not directly available via the API.
- ClassicDelta: Also unclear; could refer to options delta or another calculated metric.
Important Notes
- Error Handling: The code includes basic error handling. Ensure to handle potential errors appropriately in a production environment.
- API Limits: Be aware of IG's API rate limits to avoid being blocked.
- Security:
- Do not share your API credentials.
- Securely store and handle your credentials, especially if committing code to version control.
- Demo Environment: Use the demo API endpoint (
https://demo-api.ig.com/) for testing to prevent unintended trades on your live account.
- Further Development:
- Expand the
InstrumentDetails and MarketSnapshot structs to include any additional fields you require.
- Implement additional functionality as needed, such as streaming prices via IG's streaming API (which would require WebSocket support).
Dependencies Explanation
- reqwest: A high-level HTTP client library in Rust, used to make HTTP requests.
- serde: A framework for serializing and deserializing Rust data structures efficiently and generically.
- tokio: An asynchronous runtime for Rust, enabling concurrency and async/await syntax.
References
Conclusion
By following the steps above and using the provided code, you should be able to authenticate with the IG API and retrieve the specified market data for the Nasdaq index using Rust. Ensure to handle any exceptions and edge cases according to your application's needs.
Disclaimer: The code provided is for educational purposes and may require adjustments to fit your specific use case. Always refer to the latest IG API documentation for any updates or changes.