Documentation
¶
Overview ¶
Package tinvest is a read-only Go client for the T-Bank Invest gRPC API, wrapping the same broker and transport layers the tinvest CLI uses over one shared connection with the full interceptor stack: Bearer auth, per-call deadlines, call-phase and x-tracking-id capture, the idempotency-aware retry policy, and client-side rate limiting.
The *Client surface is deliberately read-only. Order placement, stop orders, sandbox mutations, streaming, and the intent ledger are intentionally absent and remain CLI-only by design; no *Client method mutates account state.
This guarantee is about *Client only. The generated package github.com/Dronnn/tinvest/pb/investapi is the full T-Invest gRPC contract and necessarily exports the raw service clients, including mutating RPCs (PostOrder, CancelOrder, and the sandbox and stop-order services). Calling those directly bypasses this package's guardrails and is entirely at your own risk; the read-only guarantee does not extend to them.
Getting started ¶
ctx := context.Background()
client, err := tinvest.New(ctx, tinvest.Config{Token: token})
if err != nil {
// handle error
}
defer client.Close()
inst, err := client.Resolve(ctx, "BBG004730N88") // uid, FIGI, or TICKER@CLASSCODE
if err != nil {
// handle error
}
prices, err := client.LastPrices(ctx, inst.GetUid())
Identifiers ¶
Every method that takes an instrument identifier accepts the same three shapes the CLI does — an instrument_uid, a FIGI, or a TICKER@CLASSCODE pair — and resolves it through the same resolver and local cache. A malformed identifier is reported as an error before any network call is made.
Types ¶
Methods return the generated protobuf types from github.com/Dronnn/tinvest/pb/investapi, or small result structs mirroring what the CLI prints. Money and Quotation values carry an exact units+nano pair; use QuotationString and MoneyString to render them as decimal strings without floating-point error.
Example ¶
Example shows the read-only workflow: construct a client, resolve an instrument identifier, and read its last price. It is compiled to keep the documentation honest but is not run, since it needs a real token and network.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/Dronnn/tinvest"
)
func main() {
ctx := context.Background()
client, err := tinvest.New(ctx, tinvest.Config{
Token: "t.your_token_here",
Timeout: 10 * time.Second,
})
if err != nil {
log.Fatal(err)
}
defer func() { _ = client.Close() }()
// Identifiers may be an instrument_uid, a FIGI, or a TICKER@CLASSCODE pair.
inst, err := client.Resolve(ctx, "SBER@TQBR")
if err != nil {
log.Fatal(err)
}
prices, err := client.LastPrices(ctx, inst.GetUid())
if err != nil {
log.Fatal(err)
}
for _, p := range prices {
fmt.Printf("%s: %s\n", inst.GetTicker(), tinvest.QuotationString(p.GetPrice()))
}
}
Output:
Index ¶
- Constants
- func MoneyString(m *investapi.MoneyValue) string
- func ParseCandleInterval(raw string) (investapi.CandleInterval, error)
- func QuotationString(q *investapi.Quotation) string
- type APIError
- type Client
- func (c *Client) AccruedInterests(ctx context.Context, id string, from, to time.Time) ([]*investapi.AccruedInterest, error)
- func (c *Client) Candles(ctx context.Context, id string, interval investapi.CandleInterval, ...) ([]*investapi.HistoricCandle, error)
- func (c *Client) Close() error
- func (c *Client) ClosePrices(ctx context.Context, ids ...string) ([]*investapi.InstrumentClosePriceResponse, error)
- func (c *Client) Consensus(ctx context.Context, params ConsensusParams) (ConsensusResult, error)
- func (c *Client) Coupons(ctx context.Context, id string, from, to time.Time) ([]*investapi.Coupon, error)
- func (c *Client) Dividends(ctx context.Context, id string, from, to time.Time) ([]*investapi.Dividend, error)
- func (c *Client) Forecast(ctx context.Context, id string) (ForecastResult, error)
- func (c *Client) Fundamentals(ctx context.Context, assetUIDs ...string) ([]*investapi.GetAssetFundamentalsResponse_StatisticResponse, error)
- func (c *Client) InsiderDeals(ctx context.Context, params InsiderDealsParams) (InsiderDealsResult, error)
- func (c *Client) Instruments(ctx context.Context, instrumentType string) ([]ListedInstrument, error)
- func (c *Client) LastPrices(ctx context.Context, ids ...string) ([]*investapi.LastPrice, error)
- func (c *Client) News(ctx context.Context, params NewsParams) (NewsResult, error)
- func (c *Client) OrderBook(ctx context.Context, id string, depth int32) (*investapi.GetOrderBookResponse, error)
- func (c *Client) Resolve(ctx context.Context, id string) (*investapi.Instrument, error)
- func (c *Client) Search(ctx context.Context, query string) ([]*investapi.InstrumentShort, error)
- func (c *Client) TradingSchedules(ctx context.Context, exchange string, from, to time.Time) ([]*investapi.TradingSchedule, error)
- func (c *Client) TradingStatus(ctx context.Context, id string) (*investapi.GetTradingStatusResponse, error)
- type Config
- type ConsensusParams
- type ConsensusResult
- type ForecastResult
- type InsiderDealsParams
- type InsiderDealsResult
- type ListedInstrument
- type NewsParams
- type NewsResult
Examples ¶
Constants ¶
const ( // ProdEndpoint is the production host:port. ProdEndpoint = clientconn.ProdEndpoint // SandboxEndpoint is the sandbox host:port. SandboxEndpoint = clientconn.SandboxEndpoint )
Canonical API endpoints, re-exported so callers can pin an endpoint without depending on an internal package.
Variables ¶
This section is empty.
Functions ¶
func MoneyString ¶
func MoneyString(m *investapi.MoneyValue) string
MoneyString renders a MoneyValue's exact units+nano pair as a decimal string, the same way QuotationString does; the currency is available separately via MoneyValue.GetCurrency. A nil MoneyValue renders as "0".
func ParseCandleInterval ¶
func ParseCandleInterval(raw string) (investapi.CandleInterval, error)
ParseCandleInterval maps a CLI-style interval spelling ("1m", "5m", "1h", "1d", "1w", "1M", …) to the protobuf enum. Callers may also use the investapi.CandleInterval constants directly.
func QuotationString ¶
QuotationString renders a Quotation's exact units+nano pair as a decimal string ("1.5", "-0.001"), trimming trailing fractional zeros. It never uses floating point. A nil Quotation renders as "0".
Types ¶
type APIError ¶
type APIError struct {
// GRPCCode is the gRPC status code of the failure (codes.Unknown for an
// error detected before the request reached the broker).
GRPCCode codes.Code
// TrackingID is the broker's x-tracking-id for the failing call, or "" when
// the broker returned none (including local, pre-flight failures).
TrackingID string
// contains filtered or unexported fields
}
APIError wraps every error a broker-facing Client method returns. It exposes the gRPC status code and, when the broker returned one, the x-tracking-id of the failing call — the identifier T-Bank support needs to investigate a request. (Close is not broker-facing: it returns the underlying gRPC connection-close error unwrapped.)
GRPCCode is the gRPC status code of a broker failure; for an error detected locally before any call was made (a malformed identifier, an invalid order-book depth, an unknown instrument type or candle interval) it is codes.Unknown and TrackingID is empty. Unwrap returns the underlying error, so errors.Is / errors.As against gRPC status errors and the internal typed errors keep working through the wrapper.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a read-only T-Invest API client over one shared gRPC connection. It is safe for concurrent use. Call Close to release the connection.
func New ¶
New dials the broker and returns a ready Client. The connection is lazy: no network traffic happens until the first method call, so New only fails for a missing token, an unreadable CA bundle, or a malformed endpoint. Call Close when done.
func (*Client) AccruedInterests ¶
func (c *Client) AccruedInterests(ctx context.Context, id string, from, to time.Time) ([]*investapi.AccruedInterest, error)
AccruedInterests lists accrued-interest values for one bond in [from, to) — the equivalent of `tinvest instruments accrued-interest`. The identifier is resolved to its instrument_uid first.
func (*Client) Candles ¶
func (c *Client) Candles(ctx context.Context, id string, interval investapi.CandleInterval, from, to time.Time) ([]*investapi.HistoricCandle, error)
Candles returns historic candles for one instrument in [from, to] — the equivalent of `tinvest candles get`. Long ranges are split automatically into broker-safe windows per the interval, with each window's response concatenated in request order. The identifier is resolved to its instrument_uid first.
func (*Client) ClosePrices ¶
func (c *Client) ClosePrices(ctx context.Context, ids ...string) ([]*investapi.InstrumentClosePriceResponse, error)
ClosePrices returns the trading-session close price for each instrument — the equivalent of `tinvest quotes close`. Each identifier is resolved to its instrument_uid first, in order.
func (*Client) Consensus ¶
func (c *Client) Consensus(ctx context.Context, params ConsensusParams) (ConsensusResult, error)
Consensus fetches exactly one page of consensus forecasts — the equivalent of `tinvest research consensus`.
func (*Client) Coupons ¶
func (c *Client) Coupons(ctx context.Context, id string, from, to time.Time) ([]*investapi.Coupon, error)
Coupons lists bond coupon events for one instrument in [from, to) — the equivalent of `tinvest instruments coupons`. The identifier is resolved to its instrument_uid first.
func (*Client) Dividends ¶
func (c *Client) Dividends(ctx context.Context, id string, from, to time.Time) ([]*investapi.Dividend, error)
Dividends lists dividend events for one instrument in [from, to) — the equivalent of `tinvest instruments dividends`. The identifier is resolved to its instrument_uid first.
func (*Client) Forecast ¶
Forecast returns investment-house forecasts for one instrument — the equivalent of `tinvest research forecast`. The identifier is resolved to its instrument_uid first.
func (*Client) Fundamentals ¶
func (c *Client) Fundamentals(ctx context.Context, assetUIDs ...string) ([]*investapi.GetAssetFundamentalsResponse_StatisticResponse, error)
Fundamentals returns fundamental statistics for one through 100 asset UIDs — the equivalent of `tinvest research fundamentals --asset`. An asset UID for an instrument can be obtained from Resolve(...).GetAssetUid().
func (*Client) InsiderDeals ¶
func (c *Client) InsiderDeals(ctx context.Context, params InsiderDealsParams) (InsiderDealsResult, error)
InsiderDeals fetches exactly one page of insider deals for one instrument — the equivalent of `tinvest research insider-deals`. params.InstrumentID accepts a uid, FIGI, or TICKER@CLASSCODE and is resolved to its instrument_uid first.
func (*Client) Instruments ¶
func (c *Client) Instruments(ctx context.Context, instrumentType string) ([]ListedInstrument, error)
Instruments lists base instruments of one type — the equivalent of `tinvest instruments list --type`. instrumentType is one of "share", "bond", "etf", "currency", "future", or "option". An unknown type returns a plain error without a network call.
func (*Client) LastPrices ¶
LastPrices returns the last trade price for each instrument — the equivalent of `tinvest quotes last`. Each identifier is resolved to its instrument_uid first, in order.
func (*Client) News ¶
func (c *Client) News(ctx context.Context, params NewsParams) (NewsResult, error)
News fetches exactly one page of current news — the equivalent of `tinvest research news`.
func (*Client) OrderBook ¶
func (c *Client) OrderBook(ctx context.Context, id string, depth int32) (*investapi.GetOrderBookResponse, error)
OrderBook returns the order book for one instrument at the given depth — the equivalent of `tinvest orderbook get`. Valid depths are 1, 10, 20, 30, 40, and 50; depth is validated before any network call. The identifier is resolved to its instrument_uid first.
func (*Client) Resolve ¶
Resolve resolves an instrument identifier (an instrument_uid, a FIGI, or a TICKER@CLASSCODE pair) to its full reference record via GetInstrumentBy — the library equivalent of `tinvest instruments get`. Successful resolutions are cached locally unless the client was created with DisableCache. A malformed identifier is caught locally before any network call; a broker failure carries the tracking id — both as an *APIError.
func (*Client) Search ¶
Search runs a free-text instrument search via FindInstrument — the equivalent of `tinvest instruments search`.
func (*Client) TradingSchedules ¶
func (c *Client) TradingSchedules(ctx context.Context, exchange string, from, to time.Time) ([]*investapi.TradingSchedule, error)
TradingSchedules returns exchange trading calendars in [from, to) — the equivalent of `tinvest instruments schedules`. An empty exchange returns all exchanges.
func (*Client) TradingStatus ¶
func (c *Client) TradingStatus(ctx context.Context, id string) (*investapi.GetTradingStatusResponse, error)
TradingStatus returns the current trading and order availability for one instrument — the equivalent of `tinvest instruments trading-status`. The identifier is resolved to its instrument_uid first.
type Config ¶
type Config struct {
// Token is the T-Invest API token. It is required and is only ever placed
// in the authorization metadata of outgoing calls — never logged.
Token string
// Sandbox selects the sandbox endpoint. Ignored when Endpoint is set.
Sandbox bool
// Endpoint overrides the host:port to dial. Empty means the production or
// sandbox endpoint per Sandbox.
Endpoint string
// CAFile, when non-empty, is a path to a PEM bundle used in place of the
// system trust store to verify the server certificate — the same trust
// behavior as the CLI's TINVEST_CA_FILE, including a leading "~/" that
// expands to the user's home directory. Hostname verification is
// unaffected; only the root pool changes.
CAFile string
// Timeout is the per-call deadline applied to calls whose context carries
// none. Zero means the default (10s).
Timeout time.Duration
// DisableRateLimit turns off the process-local client-side rate limiter.
// The limiter is on by default.
DisableRateLimit bool
// DisableCache turns off the local instrument-resolution cache (a JSON file
// under the user cache directory; see instruments.DefaultCachePath for the
// exact location and why platform-native dirs are not used). The cache is
// on by default. Known limitation: concurrent processes sharing the cache
// file can race on write (last writer wins) through the shared .tmp path,
// which can also cause a rename failure or transient malformed cache
// content. The cache is best-effort: any such failure degrades to a cache
// miss (a re-resolution), and results stay correct.
DisableCache bool
}
Config configures a Client. Token is required; every other field has a safe default (production endpoint, 10s per-call timeout, rate limiter and instrument cache both on).
type ConsensusParams ¶
ConsensusParams carries the zero-based page settings for Consensus.
type ConsensusResult ¶
type ConsensusResult struct {
Items []*investapi.GetConsensusForecastsResponse_ConsensusForecastsItem
Page *investapi.PageResponse
}
ConsensusResult is one Consensus page.
type ForecastResult ¶
type ForecastResult struct {
Targets []*investapi.GetForecastResponse_TargetItem
Consensus *investapi.GetForecastResponse_ConsensusItem
}
ForecastResult holds investment-house targets and the broker consensus.
type InsiderDealsParams ¶
InsiderDealsParams carries the instrument and page settings for InsiderDeals.
type InsiderDealsResult ¶
type InsiderDealsResult struct {
Deals []*investapi.GetInsiderDealsResponse_InsiderDeal
NextCursor *string
}
InsiderDealsResult is one InsiderDeals page.
type ListedInstrument ¶
type ListedInstrument struct {
UID string
FIGI string
Ticker string
ClassCode string
Name string
Type string
Lot int32
Currency string
TradingStatus investapi.SecurityTradingStatus
}
ListedInstrument is the reference-data projection returned by Instruments, shared by every per-type list.
type NewsParams ¶
NewsParams carries the optional pagination fields for News.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
tinvest
command
Command tinvest is the T-Invest CLI: a deterministic, machine-first broker adapter for the T-Bank Invest gRPC API.
|
Command tinvest is the T-Invest CLI: a deterministic, machine-first broker adapter for the T-Bank Invest gRPC API. |
|
internal
|
|
|
broker
Package broker is the CLI-independent domain layer over the T-Invest API: typed params in, typed results out, one sub-package per service domain.
|
Package broker is the CLI-independent domain layer over the T-Invest API: typed params in, typed results out, one sub-package per service domain. |
|
broker/accounts
Package accounts wraps the accounts surface of UsersService.
|
Package accounts wraps the accounts surface of UsersService. |
|
broker/history
Package history downloads the REST bulk candle-history zip archives.
|
Package history downloads the REST bulk candle-history zip archives. |
|
broker/instruments
Package instruments resolves instrument identifiers (<instrument_uid | FIGI | TICKER@CLASSCODE>) to the full instrument record via InstrumentsService, with a local TTL cache, plus free-text search (plan §5/§8).
|
Package instruments resolves instrument identifiers (<instrument_uid | FIGI | TICKER@CLASSCODE>) to the full instrument record via InstrumentsService, with a local TTL cache, plus free-text search (plan §5/§8). |
|
broker/marketdata
Package marketdata wraps the quote/orderbook/status surface of MarketDataService (plan §5/§8): last prices, close prices, order book, and trading status.
|
Package marketdata wraps the quote/orderbook/status surface of MarketDataService (plan §5/§8): last prices, close prices, order book, and trading status. |
|
broker/operations
Package operations wraps cursor-paginated operation history reads.
|
Package operations wraps cursor-paginated operation history reads. |
|
broker/orders
Package orders wraps OrdersService (plan §5/§8/§9): typed placement, cancellation, replacement, state lookups, and the two pre-trade checks (GetOrderPrice, GetMaxLots).
|
Package orders wraps OrdersService (plan §5/§8/§9): typed placement, cancellation, replacement, state lookups, and the two pre-trade checks (GetOrderPrice, GetMaxLots). |
|
broker/portfolio
Package portfolio wraps the account portfolio, positions, and withdraw-limit reads of OperationsService.
|
Package portfolio wraps the account portfolio, positions, and withdraw-limit reads of OperationsService. |
|
broker/research
Package research wraps the read-only research RPCs on InstrumentsService.
|
Package research wraps the read-only research RPCs on InstrumentsService. |
|
broker/sandbox
Package sandbox wraps the account-management surface of SandboxService (plan §1.1/§8): opening/closing sandbox accounts, listing them, and paying virtual money in.
|
Package sandbox wraps the account-management surface of SandboxService (plan §1.1/§8): opening/closing sandbox accounts, listing them, and paying virtual money in. |
|
broker/signals
Package signals wraps analyst and technical signal reads.
|
Package signals wraps analyst and technical signal reads. |
|
broker/stoporders
Package stoporders wraps StopOrdersService (plan §1.1/§8/§9): typed placement, cancellation, and listing of stop-loss/take-profit/stop-limit orders, including trailing take-profit.
|
Package stoporders wraps StopOrdersService (plan §1.1/§8/§9): typed placement, cancellation, and listing of stop-loss/take-profit/stop-limit orders, including trailing take-profit. |
|
broker/streaming
Package streaming adapts the T-Invest stream services to the generic resilient runner and builds de-duplicated market-data subscription requests.
|
Package streaming adapts the T-Invest stream services to the generic resilient runner and builds de-duplicated market-data subscription requests. |
|
broker/users
Package users wraps the user-info surface of UsersService.
|
Package users wraps the user-info surface of UsersService. |
|
clientconn
Package clientconn assembles the shared gRPC connection used by both the CLI and the public library facade.
|
Package clientconn assembles the shared gRPC connection used by both the CLI and the public library facade. |
|
config
Package config resolves profiles, environment, and token sources into the effective settings for a command invocation.
|
Package config resolves profiles, environment, and token sources into the effective settings for a command invocation. |
|
ledger
Package ledger implements the write-ahead intent ledger described in plan-tinvest-cli.md §9 (reliability model) and §10 (intent ledger spec).
|
Package ledger implements the write-ahead intent ledger described in plan-tinvest-cli.md §9 (reliability model) and §10 (intent ledger spec). |
|
policy
Package policy implements the pre-trade guardrails described in plan-tinvest-cli.md §6: an instrument allowlist, per-order lot and notional caps, an open-order cap, market/short opt-in flags, and a kill-switch file whose presence blocks every mutation.
|
Package policy implements the pre-trade guardrails described in plan-tinvest-cli.md §6: an instrument allowlist, per-order lot and notional caps, an open-order cap, market/short opt-in flags, and a kill-switch file whose presence blocks every mutation. |
|
ratelimit
Package ratelimit provides the process-local unary RPC token buckets used to stay below the broker's per-method-group limits.
|
Package ratelimit provides the process-local unary RPC token buckets used to stay below the broker's per-method-group limits. |
|
render
Package render turns broker results into the CLI's output formats (JSON envelope and tables) and maps errors to stable exit codes.
|
Package render turns broker results into the CLI's output formats (JSON envelope and tables) and maps errors to stable exit codes. |
|
stream
Package stream owns resilient stream connection lifecycle: reconnect, authoritative subscription replay, ping/data watchdog, reconciliation, and explicit consumer-visible gap events.
|
Package stream owns resilient stream connection lifecycle: reconnect, authoritative subscription replay, ping/data watchdog, reconciliation, and explicit consumer-visible gap events. |
|
transport
Package transport owns the gRPC connection and interceptors: Bearer auth, per-call deadlines, call-phase tracking, and x-tracking-id capture.
|
Package transport owns the gRPC connection and interceptors: Bearer auth, per-call deadlines, call-phase tracking, and x-tracking-id capture. |
|
pb
|
|