OptionEdge.API.AliceBlue 1.0.7

dotnet add package OptionEdge.API.AliceBlue --version 1.0.7
NuGet\Install-Package OptionEdge.API.AliceBlue -Version 1.0.7
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OptionEdge.API.AliceBlue" Version="1.0.7" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add OptionEdge.API.AliceBlue --version 1.0.7
#r "nuget: OptionEdge.API.AliceBlue, 1.0.7"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install OptionEdge.API.AliceBlue as a Cake Addin
#addin nuget:?package=OptionEdge.API.AliceBlue&version=1.0.7

// Install OptionEdge.API.AliceBlue as a Cake Tool
#tool nuget:?package=OptionEdge.API.AliceBlue&version=1.0.7

.Net library for AliceBlue REST API

Client library to communicate with AliceBlue v2 REST API.

OptionEdge client library provides simpler interface to connect to AliceBlue REST Api and live streaming services.

Disclaimer

This software is an unofficial client libray for AliceBlue Api V2 and 
is not affiliated with / endorsed or approved by AliceBlue in any way.

This is purely an enthusiast program intended for educational purposes only and 
is not financial advice.

By downloading this software you acknowledge that you are using this 
at your own risk and that I am is not responsible for any damages that 
may occur to you due to the usage or installation of this program

Refer to this Youtube video for API usage & integration guide ProfTheta - Your Guide to Options

Watch the video

Refer to this video for free course on Algo Trading using broker APIs

Algo Trading Course

Requirements

This library targets netstandard2.0 and can be used with .Net Core 2.0 and above & .Net Framework 4.6 and above.

Getting Started

You have to first generate the Api Key from ANT Web application. Please login to ANT web app and then click on the Generate API Key button.

Log into ANT Web » Apps » API Key » Generate/Regenerate API Key

Please note down the Api key & your Alice Blue User Id. You will be using the Api key & user id to initialize the client library.

NOTE: User should Login through Web (a3.aliceblueonline.com) or Single Sign On (SSO) or Mobile at least once in a day, before connecting the API

Troubleshooting

While creating the instance of Alice Blue Api Client set enable logging parameter as true. Client library will log all the error/info messages to the console. This will help to troubleshoot any issues while integrating library with your project. You can disable this flag in production.

Install library

Install-Package OptionEdge.API.AliceBlue -Version 1.0.7

Sample project

Please refer the sample FeaturesDemo.cs class in `OptionEdge.API.AliceBlue.Samples' project which demonstrate the capabilities of this library.

Getting Started guide on Youtube

Please refer this Youtube video to get started using the library by creating a new project and calling the provided methods from the library for placing orders, getting order & trade history, historical data & live quotes.

Import namespaces

using OptionEdge.API.AliceBlue;
using OptionEdge.API.AliceBlue.Records;

Declare variables

AliceBlue _aliceBlue;
Ticker _ticker;

string _cachedTokenFile = $"cached_token_{DateTime.Now.ToString("dd_mmm_yyyy")}.txt";

Initialize

       
// Create new instance of AliceBlue client library
var_aliceBlue = new AliceBlue(_settings.UserId, _settings.ApiKey, enableLogging: _settings.EnableLogging,
    onAccessTokenGenerated: (accessToken) =>
{
    // Store the generated access token to database or file store
    // Token needs to be generated only once for the day

    File.WriteAllText(_cachedTokenFile, accessToken);
}, cachedAccessTokenProvider: () =>
{
    // Provide the saved token that will be used to making the REST calls.
    // This method will be used when re-initializing the api client during the the day (eg after app restart etc)

    // If token is invalid or not available, just return empty or null value
    return File.Exists(_cachedTokenFile) ? File.ReadAllText(_cachedTokenFile) : null;
});

Live Feeds Data Streaming

// Create Ticker instance
// No need to provide the userId, apiKey, it will be automatically set
var _ticker = _aliceBlue.CreateTicker();

// Setup event handlers
_ticker.OnTick += _ticker_OnTick;
_ticker.OnConnect += _ticker_OnConnect;
_ticker.OnClose += _ticker_OnClose;
_ticker.OnError += _ticker_OnError;
_ticker.OnNoReconnect += _ticker_OnNoReconnect;
_ticker.OnReconnect += _ticker_OnReconnect;
_ticker.OnReady += _ticker_OnReady;

// Connect the ticker to start receiving the live feeds
// DO NOT FORGOT TO CONNECT else you will not receive any feed
_ticker.Connect();

Subscribe for live feeds

// Once connected, subscribe to tokens to start receiving the feeds

// Subscribe live feeds
// Set feed mode to Quote (no depth data will be received)
// Set feed mode to Full to get depth data as well
// Token for multiple exchnages in one call
_ticker.Subscribe(Constants.TICK_MODE_QUOTE,
    new SubscriptionToken[]
        {
            new SubscriptionToken
            {
                Token = 26000,
                Exchange = Constants.EXCHANGE_NSE
            },
            new SubscriptionToken
            {
                Token = 26009,
                Exchange = Constants.EXCHANGE_NSE
            },
            new SubscriptionToken
            {
                Token = 35042,
                Exchange = Constants.EXCHANGE_NFO
            }
        });
// or subscribe to tokens for specific exchange
_ticker.Subscribe(Constants.EXCHANGE_NSE, Constants.TICK_MODE_FULL, new int[] { 26000, 26009 });

Unsubscribe from live feeds

// To unscubscribe
// tokens for multiple exchanges in one call
_ticker.UnSubscribe(new SubscriptionToken[]
{
    new SubscriptionToken
    {
        Token = 35042,
        Exchange = Constants.EXCHANGE_NFO
    },
    new SubscriptionToken
    {
        Token = 26000,
        Exchange  = Constants.EXCHANGE_NSE
    } 
});
// or unsubscribe tokens from specific exchange
_ticker.UnSubscribe(Constants.EXCHANGE_NFO, new int[] { 26000, 26000 });

Auto Reconnect

// Ticker has built in re-connection mechanism
// Once disconnectd it will try to reconnect, once connected, it will automatically subscribe to
// previously subscribed tokens

// Reconnection settings
_ticker.EnableReconnect(interval: 5, retries: 20);
// interval: interval between re-connection retries.
// For every reconnect attempt OnReconnect event will be called

// retries: number of retries before it give up reconnecting.
// OnNoReconnect will be called if not able to reconnect

Download Master Contracts

_aliceBlue.SaveMasterContracts(Constants.EXCHANGE_NFO, $"c:\\data\\master_contracts_{Constants.EXCHANGE_NFO}.csv");

// or load Master Contracts into list
var masterContracts = _aliceBlue.GetMasterContracts(Constants.EXCHANGE_NFO);

Account Details

var accountDetails = _aliceBlue.GetAccountDetails();

Funds

var funds = _aliceBlue.GetFunds();

Historical Data

var historicalCandles = _aliceBlue.GetHistoricalData(
    Constants.EXCHANGE_NFO,
    36257,
    DateTime.Parse("6-Sep-2022 9:30 AM"),
    DateTime.Parse("8-Sep-2022 3:30 PM"),
    Constants.HISTORICAL_DATA_RESOLUTION_1_MINUTE);

Holdings

var holdings = _aliceBlue.GetHoldings();

Open Interest

var openInterest = _aliceBlue.GetOpenInterest(new OpenInterestParams
{
    OpenInterestTokens = new[]
    {
        new OpenInterestToken
        {
            Exchange = Constants.EXCHANGE_NFO,
            InstrumentToken = 36257
        }
    },
    UserId = _settings.UserId
});
// or pass tokens for specific exchange
var openInterestNFO = _aliceBlue.GetOpenInterest(Constants.EXCHANGE_NFO, new[] { 12345, 43343, 5432 });

Scrip Quote

var scripQuote = _aliceBlue.GetScripQuote(Constants.EXCHANGE_NFO, 36257);

Order Book

var orderBook = _aliceBlue.GetOrderBook();

Trade Book

var tradeBook = _aliceBlue.GetTradeBook();

Order History

var orderHistory = _aliceBlue.GetOrderHistory(orderNumber: "123456789");

Day/net wise Position Book

var positionBookDayWise = _aliceBlue.GetPositionBookDayWise();
var positionBookNetWise = _aliceBlue.GetPositionBookNetWise();

Place Order - Regular

var placeRegularOrderResult = _aliceBlue.PlaceOrder(new PlaceRegularOrderParams
{
    Exchange = Constants.EXCHANGE_NFO,
    OrderTag = "Test",
    PriceType = Constants.PRICE_TYPE_MARKET,
    ProductCode = Constants.PRODUCT_CODE_MIS,
    Quantity = 25,
    TransactionType = Constants.TRANSACTION_TYPE_BUY,
    InstrumentToken = 46335,
    TradingSymbol = "BANKNIFTY2290838000PE"
});

Place Order - Cover

var placeCoverOrderResult = _aliceBlue.PlaceCoverOrder(new PlaceCoverOrderParams
{
    Exchange = Constants.EXCHANGE_NSE,
    OrderTag = "Test",
    PriceType = Constants.PRICE_TYPE_LIMIT,
    ProductCode = Constants.PRODUCT_CODE_MIS,
    TransactionType = Constants.TRANSACTION_TYPE_BUY,
    InstrumentToken = 2885,
    TradingSymbol = "RELIANCE-EQ",
    Quantity = 1,
    Price = 2560m,
    TriggerPrice = 2559m,
    StopLoss = 2545m
});

Place Order - Bracket

var placeBracketOrderResult = _aliceBlue.PlaceBracketOrder(new PlaceBracketOrderParams
{
    Exchange = Constants.EXCHANGE_NSE,
    OrderTag = "Test",
    PriceType = Constants.PRICE_TYPE_LIMIT,
    ProductCode = Constants.PRODUCT_CODE_MIS,
    TransactionType = Constants.TRANSACTION_TYPE_BUY,
    InstrumentToken = 2885,
    TradingSymbol = "RELIANCE-EQ",
    Quantity = 1,
    Price = 2560m,
    TriggerPrice = 2559m,
    StopLoss = 2545m,
    Target = 2590m,
});

Modify Order

if (placeRegularOrderResult != null && placeRegularOrderResult.Status == Constants.STATUS_OK)
{
    Console.WriteLine($"Order executed. Order Number: {placeRegularOrderResult.OrderNumber}");

    // Get the status of the order
    var orderStatus = _aliceBlue.ModifyOrder(new ModifyOrderParams
    {
        Exchange = Constants.EXCHANGE_NFO,
        OrderNumber = placeRegularOrderResult.OrderNumber,
        Price = .5m,
        PriceType = Constants.PRICE_TYPE_LIMIT,
        ProductCode = Constants.PRODUCT_CODE_MIS,
        Qty = 25,
        TradingSymbol = "BANKNIFTY2290838000PE",
        TransactionType = Constants.TRANSACTION_TYPE_SELL,
    });
}

Cancel Order

if (placeRegularOrderResult != null && placeRegularOrderResult.Status == Constants.STATUS_OK)
{
    Console.WriteLine($"Order executed. Order Number: {placeRegularOrderResult.OrderNumber}");

    var orderStatus = _aliceBlue.CancelOrder(placeRegularOrderResult.OrderNumber);
}

Web Socket event handlers

private void _ticker_OnReady()
{
    Console.WriteLine("Socket connection authenticated. Ready to live stream feeds.");
}

private static void _ticker_OnTick(Tick TickData)
{
    Console.WriteLine(JsonConvert.SerializeObject(TickData));
}

private static void _ticker_OnReconnect()
{
    Console.WriteLine("Ticker reconnecting.");
}

private static void _ticker_OnNoReconnect()
{
    Console.WriteLine("Ticker not reconnected.");
}

private static void _ticker_OnError(string Message)
{
    Console.WriteLine("Ticker error." + Message);
}

private static void _ticker_OnClose()
{
    Console.WriteLine("Ticker closed.");
}

private static void _ticker_OnConnect()
{
    Console.WriteLine("Ticker connected.");

    _ticker.Subscribe(new SubscriptionToken[]
    {
        new SubscriptionToken
        {
            Exchange = Constants.EXCHANGE_NSE,
            Token = 26000
        },
        new SubscriptionToken
        {
            Exchange = Constants.EXCHANGE_NSE,
            Token = 26009
        },
        new SubscriptionToken
        {
            Exchange = Constants.EXCHANGE_NFO,
            Token = 35042
        },
    }, Constants.TICK_MODE_FULL);
}

Credits

  • Websocket code reference is based on Zerodha Kite Connect .Net Client Library

License: MIT

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on OptionEdge.API.AliceBlue:

Package Downloads
OptionEdge.API.AliceBlue.Smart

Smart Extensions for AliceBlue .Net Client Library

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.7 139 5/5/2024
1.0.6 140 4/23/2024
1.0.5 83 4/23/2024
1.0.4 118 4/23/2024
1.0.3 812 3/27/2023
1.0.2 1,088 10/13/2022
1.0.1 1,430 9/23/2022
1.0.0.15-beta 631 9/16/2022
1.0.0.14-beta 637 9/16/2022
1.0.0.13-beta 668 9/15/2022
1.0.0.12-beta 618 9/15/2022
1.0.0.11-beta 630 9/15/2022
1.0.0.10-beta 658 9/14/2022
1.0.0.9-beta 626 9/14/2022
1.0.0.8-beta 635 9/14/2022
1.0.0.6-beta 648 9/14/2022
1.0.0.5-beta 587 9/11/2022
1.0.0.4-beta 594 9/11/2022
1.0.0.3-beta 575 9/10/2022
1.0.0.2-beta 599 9/9/2022
1.0.0.1-beta 574 9/9/2022