finam

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 17, 2025 License: MIT Imports: 25 Imported by: 0

README

go-finam-grpc

gRPC-клиент на Go для работы с API Финама
tradeapi.finam

Установка

go get github.com/Ruvad39/go-finam-grpc

Примеры

Пример создание клиента. Получение данных по токену
ctx := context.Background()
token, _ := "FINAM_TOKEN"
client, err := finam.NewClient(ctx, token)
if err != nil {
    slog.Error("NewClient", "err", err.Error())
return
}
defer client.Close()

// Получение информации о токене сессии
res, err := client.GetTokenDetails(ctx)
if err != nil {
    slog.Error("main", "AuthService.TokenDetails", err.Error())
}
slog.Info("main", "res", res)

Получить информацию по торговому счету
// добавим заголовок с авторизацией (accessToken)
ctx, err = client.WithAuthToken(ctx)
if err != nil {
	slog.Error("main", "WithAuthToken", err.Error())
	// если прошла ошибка, дальше работа бесполезна, не будет авторизации
	return
}

// Получение информации по конкретному аккаунту
accountId := "FINAM_ACCOUNT_ID"
res, err := client.AccountsService.GetAccount(ctx, &accounts_service.GetAccountRequest{AccountId: accountId})
if err != nil {
	slog.Error("accountService", "GetAccount", err.Error())
}
slog.Info("main", "Account", res)

// список позиций
//slog.Info("main", "Positions", res.Positions)
for row, pos := range res.Positions {
	slog.Info("positions",
		"row", row,
		"Symbol", pos.Symbol,
		"Quantity", finam.DecimalToFloat64(pos.Quantity),
		"AveragePrice", finam.DecimalToFloat64(pos.AveragePrice),
		"CurrentPrice", finam.DecimalToFloat64(pos.CurrentPrice),
	)
}	
Другие примеры смотрите тут

TODO

  • MarketDataService.SubscribeLatestTrades

Documentation

Index

Constants

View Source
const (
	QuoteChannel     = Channel("quote")      // Подписка на информацию о котировках
	BookChannel      = Channel("book")       // Подписка на биржевой стакан
	AllTradesChannel = Channel("all_trades") // подписка на все сделки
)

Variables

View Source
var TzMoscow = initMoscow()

Functions

func DecimalToFloat64

func DecimalToFloat64(d *decimal.Decimal) float64

DecimalToFloat64 конвертируем google.Decimal в float64 БЕЗ обработки ошибки

func DecimalToFloat64E

func DecimalToFloat64E(d *decimal.Decimal) (float64, error)

DecimalToFloat64E конвертируем google.Decimal в float64 с обработкой ошибки

func DecimalToInt

func DecimalToInt(d *decimal.Decimal) int

func DecimalToIntE

func DecimalToIntE(d *decimal.Decimal) (int, error)

func Float64ToDecimal

func Float64ToDecimal(f float64) *decimal.Decimal

Float64ToDecimal конвертируем float64 в google.Decimal

func Float64ToMoney

func Float64ToMoney(value float64, currency string) *money.Money

func IntToDecimal

func IntToDecimal(i int) *decimal.Decimal

IntToDecimal конвертируем int в google.Decimal

func IsWithinInterval

func IsWithinInterval(t time.Time, iv *interval.Interval) bool

Проверка: входит ли t в интервал [start, end] TODO в параметры добавить зону

func MoneyToFloat64

func MoneyToFloat64(m *money.Money) float64

MoneyToFloat64 конвертируем google.money в float64

func NewAssetsRequest

func NewAssetsRequest() *assets_service.AssetsRequest

func NewBarsRequest

NewBarsRequest

func NewCancelOrderRequest

func NewCancelOrderRequest(accountId, orderId string) *orders_service.CancelOrderRequest

NewCancelOrderReques

func NewExchangesRequest

func NewExchangesRequest() *assets_service.ExchangesRequest

func NewGetAccountRequest

func NewGetAccountRequest(accountId string) *accounts_service.GetAccountRequest

NewGetAccountRequest

func NewGetOrderRequest

func NewGetOrderRequest(accountId, orderId string) *orders_service.GetOrderRequest

NewGetOrderRequest

func NewInterval

func NewInterval(start, end time.Time) *interval.Interval

NewInterval создадим google.interval start time.Time = StartTime end time.Time = EndTime

func NewLatestTradesRequest

func NewLatestTradesRequest(symbol string) *marketdata_service.LatestTradesRequest

NewLatestTradesRequest

func NewOptionsChainRequest

func NewOptionsChainRequest(symbol string) *assets_service.OptionsChainRequest

func NewOrderBookRequest

func NewOrderBookRequest(symbol string) *marketdata_service.OrderBookRequest

NewOrderBookRequest

func NewOrderBuy

func NewOrderBuy(accountId, symbol string, quantity int) *orders_service.Order

NewOrderBuy сформируем ордер на покупку по рынку accountId string Идентификатор аккаунта symbol string Символ инструмента quantity Количество в шт.

func NewOrderBuyLimit

func NewOrderBuyLimit(accountId, symbol string, quantity int, price float64) *orders_service.Order

NewOrderBuyLimut сформируем ордер на покупку по лимитной цене accountId string Идентификатор аккаунта symbol string Символ инструмента quantity Количество в шт. price float64 по какой цене заявка

func NewOrderBuyStopLimit

func NewOrderBuyStopLimit(accountId, symbol string, quantity int, price, stopPrice float64) *orders_service.Order

NewOrderBuyStopLimit сформируем ордер на покупку по stop лимитной цене accountId string Идентификатор аккаунта symbol string Символ инструмента quantity Количество в шт. price float64 по какой цене заявка stopPrice float64 по какой цене stop

func NewOrderSell

func NewOrderSell(accountId, symbol string, quantity int) *orders_service.Order

NewOrderSell сформируем ордер на продажу по рынку accountId string Идентификатор аккаунта symbol string Символ инструмента quantity Количество в шт.

func NewOrderSellLimit

func NewOrderSellLimit(accountId, symbol string, quantity int, price float64) *orders_service.Order

NewOrderSellLimit сформируем ордер на продажу по лимитной цене accountId string Идентификатор аккаунта symbol string Символ инструмента quantity Количество в шт. price float64 по какой цене заявка

func NewOrderSellStopLimit

func NewOrderSellStopLimit(accountId, symbol string, quantity int, price, stopPrice float64) *orders_service.Order

NewOrderSellStopLimit сформируем ордер на покупку по stop лимитной цене accountId string Идентификатор аккаунта symbol string Символ инструмента quantity Количество в шт. price float64 по какой цене заявка stopPrice float64 по какой цене stop

func NewOrdersRequest

func NewOrdersRequest(accountId string) *orders_service.OrdersRequest

NewOrdersRequest

func NewQuoteRequest

func NewQuoteRequest(symbol string) *marketdata_service.QuoteRequest

NewQuoteRequest

func NewScheduleRequest

func NewScheduleRequest(symbol string) *assets_service.ScheduleRequest

func NewSubscribeLatestTradesRequest

func NewSubscribeLatestTradesRequest(symbol string) *marketdata_service.SubscribeLatestTradesRequest

NewSubscribeLatestTradesRequest

func NewSubscribeOrderBookRequest

func NewSubscribeOrderBookRequest(symbol string) *marketdata_service.SubscribeOrderBookRequest

NewSubscribeOrderBookRequest

func NewSubscribeQuoteRequest

func NewSubscribeQuoteRequest(symbols []string) *marketdata_service.SubscribeQuoteRequest

NewSubscribeQuoteRequest

func NewTradesRequest

func NewTradesRequest(accountId string, limit int32, start, end time.Time) *accounts_service.TradesRequest

NewTradesRequest

func NewTransactionsRequest

func NewTransactionsRequest(accountId string, limit int32, start, end time.Time) *accounts_service.TransactionsRequest

NewTransactionsRequest

func SecurityToMap

func SecurityToMap(sec []Security) map[string]Security

SecurityToMap

func SetLogDebug

func SetLogDebug(debug bool)

SetLogDebug установим уровень логгирования Debug

func SetLogger

func SetLogger(logger *slog.Logger)

func ToSecurityMap

func ToSecurityMap(assets []*assets_service.Asset) map[string]Security

ToSecurityMap

Types

type Channel

type Channel string

Channel канал для подписки потока данных

type Client

type Client struct {
	AuthService       auth_service.AuthServiceClient
	AccountsService   accounts_service.AccountsServiceClient
	AssetsService     assets_service.AssetsServiceClient
	MarketDataService marketdata_service.MarketDataServiceClient
	OrdersService     orders_service.OrdersServiceClient
	Securities        map[string]Security //  Список инструментов с которыми работаем (или весь список? )
	// contains filtered or unexported fields
}

Client

func NewClient

func NewClient(ctx context.Context, token string) (*Client, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) GetJWT

func (c *Client) GetJWT(ctx context.Context) (string, error)

GetJWT Получение JWT токена из API токена

идет вызов AuthService.Auth

func (*Client) GetSecurity

func (c *Client) GetSecurity(symbol string) (Security, bool)

GetSecurity Вернем параметры инструмента (из локальных данных Client)

func (*Client) GetTokenDetails

func (c *Client) GetTokenDetails(ctx context.Context) (*auth_service.TokenDetailsResponse, error)

GetTokenDetails Получение информации о токене сессии

идет вызов AuthService.TokenDetails

func (*Client) LoadSecurities

func (c *Client) LoadSecurities(ctx context.Context) error

загрузим список торговых инструментов TODO (1) с сервера assets, err := client.AssetsService.Assets(ctx, finam.NewAssetsRequest()) TODO (2) с локального файла json (какой путь? какой формат? откуда файл взялся?)

func (*Client) NewStream

func (c *Client) NewStream() *Stream

func (*Client) UpdateJWT

func (c *Client) UpdateJWT(ctx context.Context) error

UpdateJWT если jwt токен пустой или вышло его время получим JWT и запишем его в параметры клиента. Проставим время получения

func (*Client) WithAuthToken

func (c *Client) WithAuthToken(ctx context.Context) (context.Context, error)

WithAuthToken Создаем новый контекст с заголовком Authorization пишем в него jwt токен

type Quote

type Quote struct {
	Symbol    string // Символ инструмента
	Timestamp int64  // Метка времени
	Ask       float64
	Bid       float64
	Last      float64 // Цена последней сделки
}

Информация о котировке

func (*Quote) Reset

func (q *Quote) Reset()

func (*Quote) Time

func (q *Quote) Time() time.Time

type QuoteFunc

type QuoteFunc func(quote Quote)

type QuoteStore

type QuoteStore struct {
	// contains filtered or unexported fields
}

type RawQuoteFunc

type RawQuoteFunc func(quote *marketdata_service.Quote)

type Security

type Security struct {
	Ticker string `json:"ticker,omitempty"` // Тикер инструмента
	Symbol string `json:"symbol,omitempty"` // Символ инструмента ticker@mic
	Name   string `json:"name,omitempty"`   // Наименование инструмента
	Mic    string `json:"mic,omitempty"`    // Идентификатор биржи
	Type   string `json:"type,omitempty"`   // Тип инструмента
	Id     string `json:"id,omitempty"`     // Идентификатор инструмента
}

Security Информация об инструменте

func ToSecurity

func ToSecurity(assets []*assets_service.Asset) []Security

type SecurityStory

type SecurityStory struct {
	Securities map[string]Security
}

TODO

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

func (*Stream) Close

func (s *Stream) Close()

Close закроем сигнальный канал, что бы закончить работу

func (*Stream) Connect

func (s *Stream) Connect(ctx context.Context) error

Connect запускаем воркеры (startHandleWorkers(ctx)) активируем и запускаем потоки (startStreams(ctx)) запускаем реконектор (reconnector(ctx))

func (*Stream) GetErrorChan

func (s *Stream) GetErrorChan() chan error

func (*Stream) Reconnect

func (s *Stream) Reconnect(ch Channel)

Reconnect в канал рекконета пошлем сообщение channel какой канал нужно переконнектить

func (*Stream) SetAllTradesHandler

func (s *Stream) SetAllTradesHandler(handler TradesFunc)

SetAllTradesHandler установим функцию для обработки поступления всех сделок

func (*Stream) SetQuoteHandler

func (s *Stream) SetQuoteHandler(handler QuoteFunc)

SetQuoteHandler установим функцию для обработки поступления котировок должен устанавливать раньше Start

func (*Stream) SetRawOrderBookHandler

func (s *Stream) SetRawOrderBookHandler(handler StreamOrderBookFunc)

SetRawOrderBookHandler установим функцию для обработки поступления "сырых" данных по стакану

func (*Stream) SetRawQuoteHandler

func (s *Stream) SetRawQuoteHandler(handler RawQuoteFunc)

SetRawQuoteHandler установим функцию для обработки поступления "сырых" котировок должен устанавливать раньше Start

func (*Stream) Subscribe

func (s *Stream) Subscribe(channel Channel, symbol string)

Subscribe подписка на поток информации

type StreamOrderBookFunc

type StreamOrderBookFunc func(book *marketdata_service.StreamOrderBook)

type RawOrderBookFunc func(quote *marketdata_service.OrderBook_Row)

type Subscription

type Subscription struct {
	Symbol  string  `json:"symbol"`
	Channel Channel `json:"channel"`
}

Subscription

Directories

Path Synopsis
_examples
trade_api
v1

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL