ipoalerts Logoipoalerts
Quick Start Examples

C# Examples

Quick start examples for integrating with the API using C#

This page provides practical quick start examples for integrating with the API using C#.

Basic Client

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class IPOAlertsClient
{
    private readonly string _apiKey;
    private readonly string _baseUrl;
    private readonly HttpClient _httpClient;

    public IPOAlertsClient(string apiKey)
    {
        _apiKey = apiKey;
        _baseUrl = "https://api.ipoalerts.in";
        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.Add("x-api-key", apiKey);
        _httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
    }

    public async Task<IPOResponse> GetIPOsAsync(string status = null, string type = null, int page = 1, int limit = 10)
    {
        var queryParams = new List<string>();
        if (!string.IsNullOrEmpty(status)) queryParams.Add($"status={status}");
        if (!string.IsNullOrEmpty(type)) queryParams.Add($"type={type}");
        queryParams.Add($"page={page}");
        queryParams.Add($"limit={limit}");

        var endpoint = $"/ipos?{string.Join("&", queryParams)}";
        var response = await _httpClient.GetAsync(_baseUrl + endpoint);

        if (!response.IsSuccessStatusCode)
        {
            throw new HttpRequestException($"HTTP error: {response.StatusCode}");
        }

        var json = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<IPOResponse>(json);
    }

    public async Task<IPO> GetIPOAsync(string identifier)
    {
        var response = await _httpClient.GetAsync(_baseUrl + $"/ipos/{identifier}");

        if (!response.IsSuccessStatusCode)
        {
            throw new HttpRequestException($"HTTP error: {response.StatusCode}");
        }

        var json = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<dynamic>(json);
        return JsonConvert.DeserializeObject<IPO>(result.ipo.ToString());
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}

public class IPOResponse
{
    public Meta Meta { get; set; }
    public List<IPO> IPOs { get; set; }
}

public class Meta
{
    public int Count { get; set; }
    public int CountOnPage { get; set; }
    public int TotalPages { get; set; }
    public int Page { get; set; }
    public int Limit { get; set; }
}

public class IPO
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Symbol { get; set; }
    public string Slug { get; set; }
    public string Type { get; set; }
    public string StartDate { get; set; }
    public string EndDate { get; set; }
    public string ListingDate { get; set; }
    public string PriceRange { get; set; }
    public string ListingGain { get; set; }
    public string Status { get; set; }
    public string IssueSize { get; set; }
    public int MinQty { get; set; }
    public int MinAmount { get; set; }
    public string Logo { get; set; }
    public string About { get; set; }
    public List<string> Strengths { get; set; }
    public List<string> Risks { get; set; }
    public List<ScheduleItem> Schedule { get; set; }
}

public class ScheduleItem
{
    public string Event { get; set; }
    public string Date { get; set; }
}

// Usage
class Program
{
    static async Task Main(string[] args)
    {
        var client = new IPOAlertsClient("YOUR_API_KEY");

        try
        {
            // Get upcoming IPOs
            var ipos = await client.GetIPOsAsync("upcoming", "EQ", 1, 10);
            Console.WriteLine($"Found {ipos.Meta.Count} upcoming equity IPOs");

            foreach (var ipo in ipos.IPOs)
            {
                Console.WriteLine($"{ipo.Name} ({ipo.Symbol}) - {ipo.PriceRange}");
            }

            // Get specific IPO
            var ipoDetails = await client.GetIPOAsync("example-company-limited");
            Console.WriteLine($"IPO Details: {ipoDetails.Name}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            client.Dispose();
        }
    }
}

Advanced Client with Rate Limiting and Caching

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

public class RateLimitedIPOAlertsClient : IPOAlertsClient
{
    private readonly SemaphoreSlim _rateLimiter;
    private readonly ConcurrentDictionary<string, CacheEntry> _cache;
    private readonly TimeSpan _cacheTTL;

    public RateLimitedIPOAlertsClient(string apiKey, int requestsPerMinute = 6) : base(apiKey)
    {
        _rateLimiter = new SemaphoreSlim(requestsPerMinute, requestsPerMinute);
        _cache = new ConcurrentDictionary<string, CacheEntry>();
        _cacheTTL = TimeSpan.FromMinutes(5);

        // Start rate limiter refill task
        _ = Task.Run(RefillRateLimiter);
    }

    private async Task RefillRateLimiter()
    {
        while (true)
        {
            await Task.Delay(TimeSpan.FromMinutes(1) / 6); // 6 requests per minute
            _rateLimiter.Release();
        }
    }

    private async Task WaitForRateLimit()
    {
        await _rateLimiter.WaitAsync();
    }

    private string GetCacheKey(string endpoint, Dictionary<string, object> parameters)
    {
        var key = endpoint;
        foreach (var param in parameters)
        {
            key += $"_{param.Key}_{param.Value}";
        }
        return key;
    }

    private T GetFromCache<T>(string key) where T : class
    {
        if (_cache.TryGetValue(key, out var entry) && entry.ExpiresAt > DateTime.UtcNow)
        {
            return entry.Data as T;
        }
        return null;
    }

    private void SetCache<T>(string key, T data) where T : class
    {
        _cache[key] = new CacheEntry
        {
            Data = data,
            ExpiresAt = DateTime.UtcNow.Add(_cacheTTL)
        };
    }

    public async Task<IPOResponse> GetIPOsWithCacheAsync(string status = null, string type = null, int page = 1, int limit = 10)
    {
        var parameters = new Dictionary<string, object>
        {
            ["status"] = status ?? "",
            ["type"] = type ?? "",
            ["page"] = page,
            ["limit"] = limit
        };

        var cacheKey = GetCacheKey("/ipos", parameters);

        var cached = GetFromCache<IPOResponse>(cacheKey);
        if (cached != null)
        {
            Console.WriteLine("Returning cached data");
            return cached;
        }

        await WaitForRateLimit();

        var result = await GetIPOsAsync(status, type, page, limit);
        SetCache(cacheKey, result);

        return result;
    }

    public async Task<IPO> GetIPOWithCacheAsync(string identifier)
    {
        var parameters = new Dictionary<string, object>
        {
            ["identifier"] = identifier
        };

        var cacheKey = GetCacheKey($"/ipos/{identifier}", parameters);

        var cached = GetFromCache<IPO>(cacheKey);
        if (cached != null)
        {
            Console.WriteLine("Returning cached IPO data");
            return cached;
        }

        await WaitForRateLimit();

        var result = await GetIPOAsync(identifier);
        SetCache(cacheKey, result);

        return result;
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _rateLimiter?.Dispose();
        }
        base.Dispose(disposing);
    }
}

public class CacheEntry
{
    public object Data { get; set; }
    public DateTime ExpiresAt { get; set; }
}

// Usage
class Program
{
    static async Task Main(string[] args)
    {
        var client = new RateLimitedIPOAlertsClient("YOUR_API_KEY");

        try
        {
            // First request - will be cached
            var ipos1 = await client.GetIPOsWithCacheAsync("upcoming", "EQ", 1, 10);

            // Second request - will return cached data
            var ipos2 = await client.GetIPOsWithCacheAsync("upcoming", "EQ", 1, 10);

            Console.WriteLine($"Found {ipos1.Meta.Count} upcoming equity IPOs");
            Console.WriteLine($"Cached result: {ipos2.Meta.Count} upcoming equity IPOs");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            client.Dispose();
        }
    }
}

ASP.NET Core Integration

// Startup.cs or Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Caching.Memory;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
        services.AddHttpClient<IPOAlertsService>();
        services.AddScoped<IPOAlertsService>();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

// IPOAlertsService.cs
public class IPOAlertsService
{
    private readonly HttpClient _httpClient;
    private readonly IMemoryCache _cache;
    private readonly string _apiKey;
    private readonly string _baseUrl = "https://api.ipoalerts.in";

    public IPOAlertsService(HttpClient httpClient, IMemoryCache cache, IConfiguration configuration)
    {
        _httpClient = httpClient;
        _cache = cache;
        _apiKey = configuration["IPOAlerts:ApiKey"];
        
        _httpClient.DefaultRequestHeaders.Add("x-api-key", _apiKey);
        _httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
    }

    public async Task<IPOResponse> GetIPOsAsync(string status = null, string type = null, int page = 1, int limit = 10)
    {
        var cacheKey = $"ipos_{status}_{type}_{page}_{limit}";
        
        if (_cache.TryGetValue(cacheKey, out IPOResponse cachedResponse))
        {
            return cachedResponse;
        }

        var queryParams = new List<string>();
        if (!string.IsNullOrEmpty(status)) queryParams.Add($"status={status}");
        if (!string.IsNullOrEmpty(type)) queryParams.Add($"type={type}");
        queryParams.Add($"page={page}");
        queryParams.Add($"limit={limit}");

        var endpoint = $"/ipos?{string.Join("&", queryParams)}";
        var response = await _httpClient.GetAsync(_baseUrl + endpoint);

        if (!response.IsSuccessStatusCode)
        {
            throw new HttpRequestException($"HTTP error: {response.StatusCode}");
        }

        var json = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<IPOResponse>(json);

        _cache.Set(cacheKey, result, TimeSpan.FromMinutes(5));

        return result;
    }

    public async Task<IPO> GetIPOAsync(string identifier)
    {
        var cacheKey = $"ipo_{identifier}";
        
        if (_cache.TryGetValue(cacheKey, out IPO cachedIPO))
        {
            return cachedIPO;
        }

        var response = await _httpClient.GetAsync(_baseUrl + $"/ipos/{identifier}");

        if (!response.IsSuccessStatusCode)
        {
            throw new HttpRequestException($"HTTP error: {response.StatusCode}");
        }

        var json = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<dynamic>(json);
        var ipo = JsonConvert.DeserializeObject<IPO>(result.ipo.ToString());

        _cache.Set(cacheKey, ipo, TimeSpan.FromMinutes(5));

        return ipo;
    }
}

// IPOController.cs
[ApiController]
[Route("api/[controller]")]
public class IPOController : ControllerBase
{
    private readonly IPOAlertsService _ipoAlertsService;

    public IPOController(IPOAlertsService ipoAlertsService)
    {
        _ipoAlertsService = ipoAlertsService;
    }

    [HttpGet]
    public async Task<ActionResult<IPOResponse>> GetIPOs(
        [FromQuery] string status = null,
        [FromQuery] string type = null,
        [FromQuery] int page = 1,
        [FromQuery] int limit = 10)
    {
        try
        {
            var result = await _ipoAlertsService.GetIPOsAsync(status, type, page, limit);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { error = ex.Message });
        }
    }

    [HttpGet("{identifier}")]
    public async Task<ActionResult<IPO>> GetIPO(string identifier)
    {
        try
        {
            var result = await _ipoAlertsService.GetIPOAsync(identifier);
            return Ok(new { ipo = result });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { error = ex.Message });
        }
    }
}

// appsettings.json
{
  "IPOAlerts": {
    "ApiKey": "your_api_key_here"
  }
}