Skip to content
This repository was archived by the owner on Aug 21, 2025. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 2 additions & 168 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,169 +1,3 @@
# The Smart API Go client
# Migrated to New Github Repo https://github.com/angel-one/smartapigo
For latest updates and bug fixes please refer to the new git repo.

The official Go client for communicating with the Angel Broking Smart APIs.

SmartAPI is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (WebSockets), and more, with the simple HTTP API collection.


## Installation
```
go get github.com/angel-one/smartapigo
```
## API usage
```golang
package main

import (
"fmt"
SmartApi "github.com/angel-one/smartapigo"
)

func main() {

// Create New Angel Broking Client
ABClient := SmartApi.New("ClientCode", "Password","API Key")

fmt.Println("Client :- ",ABClient)

// User Login and Generate User Session
session, err := ABClient.GenerateSession("totp here")

if err != nil {
fmt.Println(err.Error())
return
}

//Renew User Tokens using refresh token
session.UserSessionTokens, err = ABClient.RenewAccessToken(session.RefreshToken)

if err != nil {
fmt.Println(err.Error())
return
}

fmt.Println("User Session Tokens :- ", session.UserSessionTokens)

//Get User Profile
session.UserProfile, err = ABClient.GetUserProfile()

if err != nil {
fmt.Println(err.Error())
return
}

fmt.Println("User Profile :- ", session.UserProfile)
fmt.Println("User Session Object :- ", session)

//Place Order
order, err := ABClient.PlaceOrder(SmartApi.OrderParams{Variety: "NORMAL", TradingSymbol: "SBIN-EQ", SymbolToken: "3045", TransactionType: "BUY", Exchange: "NSE", OrderType: "LIMIT", ProductType: "INTRADAY", Duration: "DAY", Price: "19500", SquareOff: "0", StopLoss: "0", Quantity: "1"})

if err != nil {
fmt.Println(err.Error())
return
}

fmt.Println("Placed Order ID and Script :- ", order)
}
```
## Websocket Data Streaming
```golang
package main

import (
"fmt"
SmartApi "github.com/angel-one/smartapigo"
"github.com/angel-one/smartapigo/websocket"
"time"
)

var socketClient *websocket.SocketClient

// Triggered when any error is raised
func onError(err error) {
fmt.Println("Error: ", err)
}

// Triggered when websocket connection is closed
func onClose(code int, reason string) {
fmt.Println("Close: ", code, reason)
}

// Triggered when connection is established and ready to send and accept data
func onConnect() {
fmt.Println("Connected")
err := socketClient.Subscribe()
if err != nil {
fmt.Println("err: ", err)
}
}

// Triggered when a message is received
func onMessage(message []map[string]interface{}) {
fmt.Printf("Message Received :- %v\n",message)
}

// Triggered when reconnection is attempted which is enabled by default
func onReconnect(attempt int, delay time.Duration) {
fmt.Printf("Reconnect attempt %d in %fs\n", attempt, delay.Seconds())
}

// Triggered when maximum number of reconnect attempt is made and the program is terminated
func onNoReconnect(attempt int) {
fmt.Printf("Maximum no of reconnect attempt reached: %d\n", attempt)
}

func main() {

// Create New Angel Broking Client
ABClient := SmartApi.New("ClientCode", "Password","API Key")

// User Login and Generate User Session
session, err := ABClient.GenerateSession()

if err != nil {
fmt.Println(err.Error())
return
}

//Get User Profile
session.UserProfile, err = ABClient.GetUserProfile()

if err != nil {
fmt.Println(err.Error())
return
}

// New Websocket Client
socketClient = websocket.New(session.ClientCode,session.FeedToken,"nse_cm|17963&nse_cm|3499&nse_cm|11536&nse_cm|21808&nse_cm|317")

// Assign callbacks
socketClient.OnError(onError)
socketClient.OnClose(onClose)
socketClient.OnMessage(onMessage)
socketClient.OnConnect(onConnect)
socketClient.OnReconnect(onReconnect)
socketClient.OnNoReconnect(onNoReconnect)

// Start Consuming Data
socketClient.Serve()

}
```

## Examples
Check example folder for more examples.

You can run the following after updating the Credentials in the examples:
```
go run example/example.go
```
For websocket example
```
go run example/websocket/example.go
```

## Run unit tests

```
go test -v
```
2 changes: 1 addition & 1 deletion example/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func main() {
fmt.Println("Client :- ", ABClient)

// User Login and Generate User Session
session, err := ABClient.GenerateSession("your totp here")
session, err := ABClient.GenerateSession()

if err != nil {
fmt.Println(err.Error())
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module github.com/angel-one/smartapigo

go 1.14
go 1.17

require (
github.com/gorilla/websocket v1.4.2
github.com/jarcoal/httpmock v1.0.6
github.com/gorilla/websocket v1.5.0
github.com/jarcoal/httpmock v1.2.0
)
12 changes: 8 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jarcoal/httpmock v1.0.6 h1:e81vOSexXU3mJuJ4l//geOmKIt+Vkxerk1feQBC8D0g=
github.com/jarcoal/httpmock v1.0.6/go.mod h1:ATjnClrvW/3tijVmpL/va5Z3aAyGvqU3gCT8nX0Txik=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jarcoal/httpmock v1.2.0 h1:gSvTxxFR/MEMfsGrvRbdfpRUMBStovlSRLw0Ep1bwwc=
github.com/jarcoal/httpmock v1.2.0/go.mod h1:oCoTsnAz4+UoOUIf5lJOWV2QQIW5UoeUI6aM2YnWAZk=
github.com/maxatome/go-testdeep v1.11.0 h1:Tgh5efyCYyJFGUYiT0qxBSIDeXw0F5zSoatlou685kk=
github.com/maxatome/go-testdeep v1.11.0/go.mod h1:011SgQ6efzZYAen6fDn4BqQ+lUR72ysdyKe7Dyogw70=
4 changes: 3 additions & 1 deletion market.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package smartapigo

import "net/http"
import (
"net/http"
)

// LTPResponse represents LTP API Response.
type LTPResponse struct {
Expand Down
104 changes: 104 additions & 0 deletions model/smartstream.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package model

type ExchangeType int
type SmartStreamAction int8
type SmartStreamSubsMode int8

const BYTES int = 20

const (
NSECM ExchangeType = 1
NSEFO ExchangeType = 2
BSECM ExchangeType = 3
BSEFO ExchangeType = 4
MCXFO ExchangeType = 5
NCXFO ExchangeType = 7
CDEFO ExchangeType = 13
)

const (
SUBS SmartStreamAction = 1
UNSUBS SmartStreamAction = 0
)

const (
LTP SmartStreamSubsMode = 1
QUOTE SmartStreamSubsMode = 2
SNAPQUOTE SmartStreamSubsMode = 3
)

type TokenInfo struct {
ExchangeType ExchangeType
Token string
}

type SmartApiBBSInfo struct {
Flag uint16
Quantity uint64
Price uint64
NumberOfOrders uint16
}

type LTPInfo struct {
TokenInfo TokenInfo
SequenceNumber uint64
ExchangeFeedTimeEpochMillis uint64
LastTradedPrice uint64
}

type Quote struct {
TokenInfo TokenInfo
SequenceNumber uint64
ExchangeFeedTimeEpochMillis uint64
LastTradedPrice uint64
LastTradedQty uint64
AvgTradedPrice uint64
VolumeTradedToday uint64
TotalBuyQty float64
TotalSellQty float64
OpenPrice uint64
HighPrice uint64
LowPrice uint64
ClosePrice uint64
}

type SnapQuote struct {
TokenInfo TokenInfo
SequenceNumber uint64
ExchangeFeedTimeEpochMillis uint64
LastTradedPrice uint64
LastTradedQty uint64
AvgTradedPrice uint64
VolumeTradedToday uint64
TotalBuyQty float64
TotalSellQty float64
OpenPrice uint64
HighPrice uint64
LowPrice uint64
ClosePrice uint64
LastTradedTimestamp uint64
OpenInterest uint64
OpenInterestChangePerc float64
BestFiveBuy []SmartApiBBSInfo
BestFiveSell []SmartApiBBSInfo
UpperCircuit uint64
LowerCircuit uint64
YearlyHighPrice uint64
YearlyLowPrice uint64
}

type SubscriptionRequest struct {
CorrelationID string `json:"correlationID"`
Action int8 `json:"action"`
Params SubscriptionParam `json:"params"`
}

type SubscriptionParam struct {
Mode SmartStreamSubsMode `json:"mode"`
TokenList []SubscriptionTokens `json:"tokenList"`
}

type SubscriptionTokens struct {
ExchangeType ExchangeType `json:"exchangeType"`
Tokens []string `json:"tokens"`
}
Loading