OptionEdge.API.AliceBlue
2.0.2
dotnet add package OptionEdge.API.AliceBlue --version 2.0.2
NuGet\Install-Package OptionEdge.API.AliceBlue -Version 2.0.2
<PackageReference Include="OptionEdge.API.AliceBlue" Version="2.0.2" />
paket add OptionEdge.API.AliceBlue --version 2.0.2
#r "nuget: OptionEdge.API.AliceBlue, 2.0.2"
// Install OptionEdge.API.AliceBlue as a Cake Addin #addin nuget:?package=OptionEdge.API.AliceBlue&version=2.0.2 // Install OptionEdge.API.AliceBlue as a Cake Tool #tool nuget:?package=OptionEdge.API.AliceBlue&version=2.0.2
.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 Optionedge - Your Guide to Options
Refer to this video for free course on Algo Trading using broker APIs
Requirements
This library targets netstandard2.1
and can be used with .Net Core 3.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.
BREAKING CHANGES V2.0.X
This version has breaking changes from previous version
- Various fields from the Tick class removed to improve the performance
Install library
Install-Package OptionEdge.API.AliceBlue -Version 2.0.2
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);
}
Links
- AliceBlue V2 API Documentation
- AliceBlue V2 API Postman Collection
- AliceBlue Ant Web
- OptionEdge X (Twitter) @OptionEdgeIn
- OptionEdge Youtube Channel
Credits
- Websocket code reference is based on Zerodha Kite Connect .Net Client Library
Product | Versions 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 | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.1 is compatible. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- Cryptisk.Utf8Json (>= 1.4.0)
- LumenWorksCsvReader (>= 4.0.0)
- Microsoft.CSharp (>= 4.7.0)
- Newtonsoft.Json (>= 13.0.3)
- RestSharp (>= 111.4.0)
- RestSharp.Serializers.NewtonsoftJson (>= 111.4.0)
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 |
---|---|---|
2.0.2 | 70 | 12/24/2024 |
2.0.1 | 83 | 12/23/2024 |
2.0.0 | 155 | 7/17/2024 |
1.0.7 | 172 | 5/5/2024 |
1.0.6 | 188 | 4/23/2024 |
1.0.5 | 109 | 4/23/2024 |
1.0.4 | 171 | 4/23/2024 |
1.0.3 | 844 | 3/27/2023 |
1.0.2 | 1,129 | 10/13/2022 |
1.0.1 | 1,514 | 9/23/2022 |
1.0.0.15-beta | 665 | 9/16/2022 |
1.0.0.14-beta | 670 | 9/16/2022 |
1.0.0.13-beta | 703 | 9/15/2022 |
1.0.0.12-beta | 655 | 9/15/2022 |
1.0.0.11-beta | 651 | 9/15/2022 |
1.0.0.10-beta | 681 | 9/14/2022 |
1.0.0.9-beta | 651 | 9/14/2022 |
1.0.0.8-beta | 658 | 9/14/2022 |
1.0.0.6-beta | 671 | 9/14/2022 |
1.0.0.5-beta | 625 | 9/11/2022 |
1.0.0.4-beta | 621 | 9/11/2022 |
1.0.0.3-beta | 597 | 9/10/2022 |
1.0.0.2-beta | 627 | 9/9/2022 |
1.0.0.1-beta | 596 | 9/9/2022 |