tinvest

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2026 License: AGPL-3.0 Imports: 12 Imported by: 0

README

tinvest

Go client library for the T-Invest (Tinkoff Investments) gRPC API.

Installation

go get github.com/acidsailor/tinvest

Quick Start

package main

import (
    "context"
    "log"

    "github.com/acidsailor/tinvest"
)

func main() {
    ctx := context.Background()

    connConfig := tinvest.NewConnConfig(tinvest.EndpointProduction, "your-api-token")
    conn, err := tinvest.NewConn(ctx, connConfig)
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    client, err := tinvest.NewClient(conn, tinvest.NewClientConfig())
    if err != nil {
        log.Fatal(err)
    }

    // Use client.Instruments, client.MarketData, client.Orders, etc.
    _ = client
}

Configuration

ConnConfig

ConnConfig holds gRPC connection settings and is created with a required endpoint and API token:

// Production environment
config := tinvest.NewConnConfig(tinvest.EndpointProduction, token)

// Sandbox environment (for testing without real money)
config := tinvest.NewConnConfig(tinvest.EndpointSandbox, token)

// Optionally set a custom app name (sent as x-app-name header)
config = config.WithAppName("my-trading-bot")
Constant Value
EndpointProduction invest-public-api.tinkoff.ru:443
EndpointSandbox sandbox-invest-public-api.tinkoff.ru:443
ClientConfig

ClientConfig holds client-level settings:

config := tinvest.NewClientConfig()

API Services

Client exposes all T-Invest gRPC services as typed sub-clients:

Field Service
Instruments Instrument and security lookups
MarketData Candles, prices, order books, trading status
MarketDataStream Streaming market data
Operations Portfolio, positions, broker reports
OperationsStream Streaming portfolio, positions, and operations
Orders Place, cancel, and manage orders
OrdersStream Streaming order state and trades
StopOrders Stop orders management
Sandbox Sandbox account management
Users User account information and settings
Signals Trading signals and strategies

The underlying proto-generated interfaces live in the pb sub-package.

Financial Value Helpers

T-Invest encodes monetary values as protobuf Quotation and MoneyValue messages. The library provides helpers to convert these to and from udecimal.Decimal:

import "github.com/acidsailor/tinvest"

// Quotation ↔ Decimal
d, err := tinvest.QuotationToDecimal(q)
q, err := tinvest.DecimalToQuotation(d)

// MoneyValue ↔ Decimal (currency field is preserved separately)
d, err := tinvest.MoneyValueToDecimal(m)
m, err := tinvest.DecimalToMoneyValue(d, "RUB")

Financial values support up to 9 fractional digits.

Error Handling

Errors originating inside the tinvest package (validation, conversion) wrap ErrClient and can be detected with errors.Is:

if errors.Is(err, tinvest.ErrClient) {
    // configuration or conversion error
}

Errors returned by gRPC RPC calls are passed through unwrapped as standard gRPC status errors.

OpenTelemetry

The gRPC connection is automatically instrumented with OpenTelemetry via otelgrpc. Traces and metrics are exported through any configured global OTEL provider.

Connection Lifecycle

NewConn returns a lazily-dialed *grpc.ClientConn — no TCP connection is established until the first RPC call. The caller owns the connection and is responsible for closing it:

conn, err := tinvest.NewConn(ctx, connConfig)
if err != nil { ... }
defer conn.Close()

Development

Regenerate protobuf bindings:

task proto

Run tests:

task test

Run linter:

task lint

Proto sources are fetched from https://opensource.tbank.ru/invest/invest-contracts.git into tmp/invest-contracts/ at build time.

License

See LICENSE.

Documentation

Overview

Package tinvest provides a Go client for the T-Invest (Tinkoff Investments) gRPC API.

Use NewConn to create a configured gRPC connection and NewClient to wrap it with typed service sub-clients. Financial values are converted between proto representations (pb.Quotation, pb.MoneyValue) and udecimal.Decimal via helper functions.

Index

Constants

View Source
const (
	// EndpointProduction is the T-Invest live trading API endpoint.
	EndpointProduction = "invest-public-api.tinkoff.ru:443"
	// EndpointSandbox is the T-Invest sandbox API endpoint for testing without real money.
	EndpointSandbox = "sandbox-invest-public-api.tinkoff.ru:443"
	// AppName is the default x-app-name header value identifying this client library.
	AppName = "github.com/acidsailor/tinvest"
)

Variables

View Source
var (
	// ErrNil indicates a required argument was nil.
	ErrNil = errors.New("nil")
	// ErrInvalidConfig indicates a configuration value is missing or invalid.
	ErrInvalidConfig = errors.New("invalid config")
	// ErrOverflow indicates a value does not fit the target representation
	// (int64 units, int32 nano, or 9-digit fractional precision).
	ErrOverflow = errors.New("overflow")
	// ErrConversion indicates a failure in decimal ↔ units/nano conversion.
	ErrConversion = errors.New("conversion")
)

Sub-sentinel errors for finer-grained errors.Is matching. All wrap ErrClient, so errors.Is(err, ErrClient) still works.

View Source
var ErrClient = errors.New("tinvest client")

ErrClient is the sentinel error for the tinvest package. Errors returned by this package's own validation and conversion functions wrap it, enabling callers to detect them with errors.Is(err, ErrClient). Errors from gRPC RPC calls are passed through unwrapped.

Functions

func DecimalToMoneyValue

func DecimalToMoneyValue(
	d udecimal.Decimal,
	currency string,
) (*pb.MoneyValue, error)

DecimalToMoneyValue converts a udecimal.Decimal and currency to a proto MoneyValue.

func DecimalToQuotation

func DecimalToQuotation(d udecimal.Decimal) (*pb.Quotation, error)

DecimalToQuotation converts a udecimal.Decimal to a proto Quotation.

func MoneyValueToDecimal

func MoneyValueToDecimal(moneyValue *pb.MoneyValue) (udecimal.Decimal, error)

MoneyValueToDecimal converts a proto MoneyValue to udecimal.Decimal. The currency field is dropped. Returns an error if moneyValue is nil.

func NewConn

func NewConn(
	ctx context.Context,
	connConfig *ConnConfig,
) (*grpc.ClientConn, error)

NewConn creates a *grpc.ClientConn configured for the T-Invest API. The connection is lazy (grpc.NewClient default) — no actual TCP dial until the first RPC. The caller owns the connection lifecycle and is responsible for calling conn.Close(). ctx is used for structured logging and trace propagation.

func QuotationToDecimal

func QuotationToDecimal(quotation *pb.Quotation) (udecimal.Decimal, error)

QuotationToDecimal converts a proto Quotation to udecimal.Decimal. Returns an error if quotation is nil.

Types

type Client

type Client struct {
	// Instruments provides reference data for bonds, shares, ETFs, futures, etc.
	Instruments pb.InstrumentsServiceClient
	// MarketData provides current prices, order books, and candles.
	MarketData pb.MarketDataServiceClient
	// MarketDataStream provides real-time market data via server-side streaming.
	MarketDataStream pb.MarketDataStreamServiceClient
	// Operations provides trade and portfolio operation history.
	Operations pb.OperationsServiceClient
	// OperationsStream provides real-time portfolio updates via server-side streaming.
	OperationsStream pb.OperationsStreamServiceClient
	// Orders provides order placement and management.
	Orders pb.OrdersServiceClient
	// OrdersStream provides real-time order state updates via server-side streaming.
	OrdersStream pb.OrdersStreamServiceClient
	// StopOrders provides stop-order placement and management.
	StopOrders pb.StopOrdersServiceClient
	// Sandbox provides a paper-trading environment that mirrors the production API.
	Sandbox pb.SandboxServiceClient
	// Users provides account and tariff information.
	Users pb.UsersServiceClient
	// Signals provides trading signals and strategies.
	Signals pb.SignalServiceClient
}

Client provides access to all T-Invest API services. It wraps an existing *grpc.ClientConn — use NewConn to create one with standard T-Invest configuration, or pass your own. Does not own the connection — caller is responsible for conn.Close().

func NewClient

func NewClient(conn *grpc.ClientConn, config *ClientConfig) (*Client, error)

NewClient wraps an existing gRPC connection with T-Invest service sub-clients. Does not own the connection — caller is responsible for conn.Close(). Returns an error if conn is nil or if config fails validation.

type ClientConfig

type ClientConfig struct{}

ClientConfig holds configuration for the Client created by NewClient. Build with NewClientConfig.

func NewClientConfig

func NewClientConfig() *ClientConfig

NewClientConfig creates a ClientConfig with default values.

func (*ClientConfig) Validate

func (c *ClientConfig) Validate() error

Validate checks that the ClientConfig is valid before use.

type ConnConfig

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

ConnConfig holds configuration for the gRPC connection created by NewConn. Build with NewConnConfig and use WithAppName to override the default app name.

func NewConnConfig

func NewConnConfig(endpoint, token string) *ConnConfig

NewConnConfig creates a ConnConfig with the required endpoint and API token. Use EndpointProduction or EndpointSandbox as the endpoint value.

func (*ConnConfig) Validate

func (c *ConnConfig) Validate() error

Validate checks that the ConnConfig is valid before use.

func (*ConnConfig) WithAppName

func (c *ConnConfig) WithAppName(name string) *ConnConfig

WithAppName sets the x-app-name header sent with every request. T-Invest uses this to identify the client application in their logs.

Directories

Path Synopsis
pb

Jump to

Keyboard shortcuts

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