How to retrieve historical prices from IG Markets using C#
Introduction
This C# recipe shows how you can retrieve historical prices from IG Markets using their Rest API.
Note
historical prices for equities are not available from IG Market's REST API. However, you can retrieve indices, commodities, FX, crypto historical prices. See IG Labs FAQ - 'Can I subscribe to equity instrument prices?'
Ingredients
The recipe uses the ServiceStack.Text Nuget package. You can install it using Nuget Package manager:
Install-Package ServiceStack.Text
From v4.0.62+ ServiceStack.Text is free!
C# Code Snippet
Step 1.
Login to IG Markets and retrieve a session and CST token.
// reference documentatin: https://api.ig.com/gateway/deal/session
string securityToken = "";
string cst = "";
var response ="https://api.ig.com/gateway/deal/session"
.PostJsonToUrl(@"{""identifier"":""YOURUSERNAME"",
""password"":""YOURPASSWORD**"",
""encryptedPassword"":null}",
requestFilter: webReq =>
{
webReq.Headers["X-IG-API-KEY"] = "YOURAPIKEY";
webReq.Headers["Version"] = "2";
}, responseFilter: webResp =>
{
securityToken = webResp.Headers.Get("X-SECURITY-TOKEN"); //
cst = webResp.Headers.Get("CST");
});
// print out security token and CST to console
Console.WriteLine($"Great! Here is your security token: {securityToken}");
Console.WriteLine($"and CST: {securityToken}");
Step 2.
Retrieve historical prices for a specific instrument (or epic)
string epic = "CC.D.CL.UNC.IP"; // wti oil price
string resolution = "DAY"; // MINUTE, MINUTE_2, MINUTE_3, MINUTE_5, MINUTE_10, MINUTE_15, MINUTE_30, HOUR, HOUR_2, HOUR_3, HOUR_4, DAY, WEEK, MONTH
int pageSize = 10;
int pageNr = 1;
var response2 = $"https://api.ig.com/gateway/deal/prices/{epic}?resolution={resolution}&pageSize={pageSize}&pageNr={pageNr}".GetJsonFromUrl(requestFilter: webReq =>
{
webReq.Headers["X-IG-API-KEY"] = "62769736af54315f19a96f5aaa0f07794f71f4e0";
webReq.Headers["Version"] = "3";
webReq.Headers["X-SECURITY-TOKEN"] = securityToken;
webReq.Headers["CST"] = cst;
}, responseFilter: webResp =>
{
securityToken = webResp.Headers.Get("X-SECURITY-TOKEN");
cst = webResp.Headers.Get("CST");
});
// convert json to pricelist
var priceList = response2.FromJson<PriceList>();
Step 3
Save Results to an Excel file.
string Path = @"C:\Temp\ExcelRecipes\";
var fileName = "igmarkets_oil.xlsx";
var fileInfo = new FileInfo(Path + fileName);
using (var excelFile = new ExcelPackage(fileInfo))
{
// add worksheet named Prices if not exists
if (!excelFile.Workbook.Worksheets.Any(ar => ar.Name == "Prices"))
excelFile.Workbook.Worksheets.Add("Prices");
var ws = excelFile.Workbook.Worksheets["Prices"];
// add headers
ws.Cells[1, 1].Value = "Date";
ws.Cells[1, 2].Value = "Price (Bid)";
// add rows
int row = 2;
foreach (var price in priceList.prices)
{
ws.Cells[row, 1].Value = price.snapshotTime;
ws.Cells[row, 2].Value = price.closePrice.bid.GetValueOrDefault();
row++;
}
// save file
excelFile.Save();
}
PriceList.cs
these are the C# objects you will need
public class PriceList {
///<Summary>
///Price list
///</Summary>
public List<PriceSnapshot> prices { get; set; }
///<Summary>
///the instrument type of this instrument
///</Summary>
public string instrumentType { get; set; }
///<Summary>
///Historical price data allowance
///</Summary>
public Allowance allowance { get; set; }
}
public class PriceSnapshot{
///<Summary>
///Snapshot time, format is yyyy/MM/dd hh:mm:ss
///</Summary>
public string snapshotTime { get; set; }
///<Summary>
///Open price
///</Summary>
public Price openPrice { get; set; }
///<Summary>
///Close price
///</Summary>
public Price closePrice { get; set; }
///<Summary>
///High price
///</Summary>
public Price highPrice { get; set; }
///<Summary>
///Low price
///</Summary>
public Price lowPrice { get; set; }
///<Summary>
///Last traded volume. This will generally be null for non exchange-traded instruments
///</Summary>
public decimal? lastTradedVolume { get; set; }
}
public class Price{
///<Summary>
///Bid price
///</Summary>
public decimal? bid { get; set; }
///<Summary>
///Ask price
///</Summary>
public decimal? ask { get; set; }
///<Summary>
///Last traded price. This will generally be null for non exchange-traded instruments
///</Summary>
public decimal? lastTraded { get; set; }
}