tinvest

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: AGPL-3.0 Imports: 14 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 FormatMoney added in v0.3.0

func FormatMoney(moneyValue *pb.MoneyValue) (string, error)

FormatMoney formats a MoneyValue as "250.50 RUB". Shows 2 decimal places (nano is truncated to centesimal precision). Returns an error if moneyValue is nil or units and nano have mixed signs.

func FormatQuotation added in v0.3.0

func FormatQuotation(quotation *pb.Quotation) (string, error)

FormatQuotation formats a Quotation as a decimal string. Shows 2 decimal places only when Nano is non-zero (truncated to centesimal precision). Returns an error if quotation is nil or units and nano have mixed signs.

func FuturesPointValue added in v0.4.0

func FuturesPointValue(
	margin *pb.GetFuturesMarginResponse,
) (*pb.Quotation, error)

FuturesPointValue returns the value of a single price point for a futures contract, derived as min_price_increment_amount / min_price_increment from the given GetFuturesMargin response. The result is a unitless multiplier (price-point value), not a currency amount. Returns an error if margin is nil, either increment field is missing, or the step is zero.

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 MoneyValueToQuotation added in v0.4.0

func MoneyValueToQuotation(moneyValue *pb.MoneyValue) (*pb.Quotation, error)

MoneyValueToQuotation converts a proto MoneyValue to a Quotation, dropping the currency. Returns an error if moneyValue is nil or has mixed signs.

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 NewInstrumentRequest added in v0.4.0

func NewInstrumentRequest(id string) *pb.InstrumentRequest

NewInstrumentRequest builds an InstrumentRequest with IdType inferred from the shape of id:

  • valid UUID → INSTRUMENT_ID_TYPE_UID
  • "<TICKER>_<CLASS_CODE>" (at least one char on each side of the last underscore) → INSTRUMENT_ID_TYPE_TICKER with class_code split off
  • otherwise → INSTRUMENT_ID_TYPE_FIGI

func OrderDirectionFromStop added in v0.4.0

func OrderDirectionFromStop(d pb.StopOrderDirection) pb.OrderDirection

OrderDirectionFromStop maps a StopOrderDirection to the equivalent OrderDirection. Unknown values map to ORDER_DIRECTION_UNSPECIFIED.

Used when feeding a stop order's direction into endpoints that take the regular OrderDirection enum (e.g. GetOrderPrice).

func PerLotMoney added in v0.4.0

func PerLotMoney(
	price *pb.Quotation,
	instrument *pb.Instrument,
) (*pb.MoneyValue, error)

PerLotMoney returns price * instrument.Lot as a MoneyValue in the instrument's currency. Returns an error if instrument or price is nil, if lot is non-positive, or if the arithmetic overflows MoneyValue precision.

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