sdk

package module
v0.6.2-0...-ab5b2a4 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2022 License: Apache-2.0 Imports: 13 Imported by: 0

README

OpenAPI Go SDK

GoDoc

Данный проект представляет собой инструментарий на языке Go для работы с OpenAPI Тинькофф Инвестиции, который можно использовать для создания торговых роботов.

Начало работы

Где взять токен аутентификации?

В разделе инвестиций вашего личного кабинета tinkoff . Далее:

  • Перейдите в настройки
  • Проверьте, что функция “Подтверждение сделок кодом” отключена
  • Выпустите токен для торговли на бирже и режима “песочницы” (sandbox)
  • Скопируйте токен и сохраните, токен отображается только один раз, просмотреть его позже не получится, тем не менее вы можете выпускать неограниченное количество токенов

Документация

Документацию непосредственно по OpenAPI можно найти по ссылке.

Быстрый старт

Для непосредственного взаимодействия с OpenAPI нужно создать клиента. Клиенты разделены на streaming и rest.

Примеры использования SDK находятся в директории examples

У меня есть вопрос

Основной репозиторий с документацией — в нем вы можете задать вопрос в Issues и получать информацию о релизах в Releases. Если возникают вопросы по данному SDK, нашёлся баг или есть предложения по улучшению, то можно задать его в Issues

Documentation

Overview

Package sdk provides REST and Stream clients for Tinkoff Invest OpenAPI. More documentation https://api-invest.tinkoff.ru/openapi/docs/.

Index

Constants

View Source
const (
	// RestAPIURL contains main api url for tinkoff invest api.
	RestAPIURL = "https://api-invest.tinkoff.ru/openapi"
	// MaxTimeout for provider request.
	MaxTimeout = time.Second * 30
)
View Source
const DefaultAccount = "" // Номер счета (по умолчанию - Тинькофф)
View Source
const DefaultPingPeriod = 54 * time.Second
View Source
const DefaultPongWait = 60 * time.Second
View Source
const MaxOrderbookDepth = 20
View Source
const StreamingApiURL = "wss://api-invest.tinkoff.ru/openapi/md/v1/md-openapi/ws"

Variables

View Source
var (
	ErrDepth    = fmt.Errorf("invalid depth. Should be in interval 0 < x <= %d", MaxOrderbookDepth)
	ErrNotFound = errors.New("not found")
)

Errors.

View Source
var ErrForbidden = errors.New("invalid token")
View Source
var ErrUnauthorized = errors.New("token not provided")

Functions

This section is empty.

Types

type Account

type Account struct {
	Type AccountType `json:"brokerAccountType"`
	ID   string      `json:"brokerAccountId"`
}

type AccountType

type AccountType string
const (
	AccountTinkoff    AccountType = "Tinkoff"
	AccountTinkoffIIS AccountType = "TinkoffIis"
)

type BuildOption

type BuildOption func(*RestClient)

BuildOption build options for rest client.

func WithProvider

func WithProvider(p Provider) BuildOption

WithProvider build rest client by custom provider client.

func WithURL

func WithURL(url string) BuildOption

WithURL build rest client by custom api url.

type Candle

type Candle struct {
	FIGI       string         `json:"figi"`
	Interval   CandleInterval `json:"interval"`
	OpenPrice  float64        `json:"o"`
	ClosePrice float64        `json:"c"`
	HighPrice  float64        `json:"h"`
	LowPrice   float64        `json:"l"`
	Volume     float64        `json:"v"`
	TS         time.Time      `json:"time"`
}

type CandleEvent

type CandleEvent struct {
	FullEvent
	Candle Candle `json:"payload"`
}

type CandleInterval

type CandleInterval string
const (
	CandleInterval1Min   CandleInterval = "1min"
	CandleInterval2Min   CandleInterval = "2min"
	CandleInterval3Min   CandleInterval = "3min"
	CandleInterval5Min   CandleInterval = "5min"
	CandleInterval10Min  CandleInterval = "10min"
	CandleInterval15Min  CandleInterval = "15min"
	CandleInterval30Min  CandleInterval = "30min"
	CandleInterval1Hour  CandleInterval = "hour"
	CandleInterval2Hour  CandleInterval = "2hour"
	CandleInterval4Hour  CandleInterval = "4hour"
	CandleInterval1Day   CandleInterval = "day"
	CandleInterval1Week  CandleInterval = "week"
	CandleInterval1Month CandleInterval = "month"
)

type Currency

type Currency string
const (
	RUB Currency = "RUB"
	USD Currency = "USD"
	EUR Currency = "EUR"
	TRY Currency = "TRY"
	JPY Currency = "JPY"
	CNY Currency = "CNY"
	CHF Currency = "CHF"
	GBP Currency = "GBP"
	HKD Currency = "HKD"
)

type CurrencyBalance

type CurrencyBalance struct {
	Currency Currency `json:"currency"`
	Balance  float64  `json:"balance"`
	Blocked  float64  `json:"blocked"`
}

type Error

type Error struct {
	RequestID string `json:"request_id,omitempty"`
	Error     string `json:"error"`
}

type ErrorEvent

type ErrorEvent struct {
	FullEvent
	Error Error `json:"payload"`
}

type Event

type Event struct {
	Name string `json:"event"`
}

type FullEvent

type FullEvent struct {
	Name string    `json:"event"`
	Time time.Time `json:"time"`
}

type Instrument

type Instrument struct {
	FIGI              string         `json:"figi"`
	Ticker            string         `json:"ticker"`
	ISIN              string         `json:"isin"`
	Name              string         `json:"name"`
	MinPriceIncrement float64        `json:"minPriceIncrement"`
	Lot               int            `json:"lot"`
	Currency          Currency       `json:"currency"`
	Type              InstrumentType `json:"type"`
}

type InstrumentInfo

type InstrumentInfo struct {
	FIGI              string        `json:"figi"`
	TradeStatus       TradingStatus `json:"trade_status"`
	MinPriceIncrement float64       `json:"min_price_increment"`
	Lot               float64       `json:"lot"`
	AccruedInterest   float64       `json:"accrued_interest,omitempty"`
	LimitUp           float64       `json:"limit_up,omitempty"`
	LimitDown         float64       `json:"limit_down,omitempty"`
}

type InstrumentInfoEvent

type InstrumentInfoEvent struct {
	FullEvent
	Info InstrumentInfo `json:"payload"`
}

type InstrumentType

type InstrumentType string
const (
	InstrumentTypeStock    InstrumentType = "Stock"
	InstrumentTypeCurrency InstrumentType = "Currency"
	InstrumentTypeBond     InstrumentType = "Bond"
	InstrumentTypeEtf      InstrumentType = "Etf"
)

type Logger

type Logger interface {
	Printf(format string, args ...interface{})
}

type MoneyAmount

type MoneyAmount struct {
	Currency Currency `json:"currency"`
	Value    float64  `json:"value"`
}

type Operation

type Operation struct {
	ID               string          `json:"id"`
	Status           OperationStatus `json:"status"`
	Trades           []Trade         `json:"trades"`
	Commission       MoneyAmount     `json:"commission"`
	Currency         Currency        `json:"currency"`
	Payment          float64         `json:"payment"`
	Price            float64         `json:"price"`
	Quantity         int             `json:"quantity"`
	QuantityExecuted int             `json:"quantityExecuted"`
	FIGI             string          `json:"figi"`
	InstrumentType   InstrumentType  `json:"instrumentType"`
	IsMarginCall     bool            `json:"isMarginCall"`
	DateTime         time.Time       `json:"date"`
	OperationType    OperationType   `json:"operationType"`
}

type OperationStatus

type OperationStatus string
const (
	OperationStatusDone     OperationStatus = "Done"
	OperationStatusDecline  OperationStatus = "Decline"
	OperationStatusProgress OperationStatus = "Progress"
)

type OperationType

type OperationType string
const (
	BUY                             OperationType = "Buy"
	SELL                            OperationType = "Sell"
	OperationTypeBrokerCommission   OperationType = "BrokerCommission"
	OperationTypeExchangeCommission OperationType = "ExchangeCommission"
	OperationTypeServiceCommission  OperationType = "ServiceCommission"
	OperationTypeMarginCommission   OperationType = "MarginCommission"
	OperationTypeOtherCommission    OperationType = "OtherCommission"
	OperationTypePayIn              OperationType = "PayIn"
	OperationTypePayOut             OperationType = "PayOut"
	OperationTypeTax                OperationType = "Tax"
	OperationTypeTaxLucre           OperationType = "TaxLucre"
	OperationTypeTaxDividend        OperationType = "TaxDividend"
	OperationTypeTaxCoupon          OperationType = "TaxCoupon"
	OperationTypeTaxBack            OperationType = "TaxBack"
	OperationTypeRepayment          OperationType = "Repayment"
	OperationTypePartRepayment      OperationType = "PartRepayment"
	OperationTypeCoupon             OperationType = "Coupon"
	OperationTypeDividend           OperationType = "Dividend"
	OperationTypeSecurityIn         OperationType = "SecurityIn"
	OperationTypeSecurityOut        OperationType = "SecurityOut"
	OperationTypeBuyCard            OperationType = "BuyCard"
)

type Order

type Order struct {
	ID            string        `json:"orderId"`
	FIGI          string        `json:"figi"`
	Operation     OperationType `json:"operation"`
	Status        OrderStatus   `json:"status"`
	RequestedLots int           `json:"requestedLots"`
	ExecutedLots  int           `json:"executedLots"`
	Type          OrderType     `json:"type"`
	Price         float64       `json:"price"`
}

type OrderBook

type OrderBook struct {
	FIGI  string          `json:"figi"`
	Depth int             `json:"depth"`
	Bids  []PriceQuantity `json:"bids"`
	Asks  []PriceQuantity `json:"asks"`
}

type OrderBookEvent

type OrderBookEvent struct {
	FullEvent
	OrderBook OrderBook `json:"payload"`
}

type OrderStatus

type OrderStatus string
const (
	OrderStatusNew            OrderStatus = "New"
	OrderStatusPartiallyFill  OrderStatus = "PartiallyFill"
	OrderStatusFill           OrderStatus = "Fill"
	OrderStatusCancelled      OrderStatus = "Cancelled"
	OrderStatusReplaced       OrderStatus = "Replaced"
	OrderStatusPendingCancel  OrderStatus = "PendingCancel"
	OrderStatusRejected       OrderStatus = "Rejected"
	OrderStatusPendingReplace OrderStatus = "PendingReplace"
	OrderStatusPendingNew     OrderStatus = "PendingNew"
)

type OrderType

type OrderType string
const (
	OrderTypeLimit  OrderType = "Limit"
	OrderTypeMarket OrderType = "Market"
)

type PingPongConfig

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

type PlacedOrder

type PlacedOrder struct {
	ID            string        `json:"orderId"`
	Operation     OperationType `json:"operation"`
	Status        OrderStatus   `json:"status"`
	RejectReason  string        `json:"rejectReason"`
	RequestedLots int           `json:"requestedLots"`
	ExecutedLots  int           `json:"executedLots"`
	Commission    MoneyAmount   `json:"commission"`
	Message       string        `json:"message,omitempty"`
}

type Portfolio

type Portfolio struct {
	Positions  []PositionBalance
	Currencies []CurrencyBalance
}

type PositionBalance

type PositionBalance struct {
	FIGI                      string         `json:"figi"`
	Ticker                    string         `json:"ticker"`
	ISIN                      string         `json:"isin"`
	InstrumentType            InstrumentType `json:"instrumentType"`
	Balance                   float64        `json:"balance"`
	Blocked                   float64        `json:"blocked"`
	Lots                      int            `json:"lots"`
	ExpectedYield             MoneyAmount    `json:"expectedYield"`
	AveragePositionPrice      MoneyAmount    `json:"averagePositionPrice"`
	AveragePositionPriceNoNkd MoneyAmount    `json:"averagePositionPriceNoNkd"`
	Name                      string         `json:"name"`
}

type PriceQuantity

type PriceQuantity [2]float64 // 0 - price, 1 - quantity

type Provider

type Provider interface {
	Get(ctx context.Context, url string, token string, unmarshal interface{}) error
	Post(ctx context.Context, url string, token string, payload, unmarshal interface{}) error
}

Provider interface for change provider client.

type RestClient

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

RestClient provide to rest methods from tinkoff invest api.

func NewRestClient

func NewRestClient(token string, options ...BuildOption) *RestClient

NewRestClient build rest client by option.

func NewRestClientCustom

func NewRestClientCustom(token, apiURL string) *RestClient

NewRestClientCustom for backward compatibility only. Deprecated: have to use NewRestClient by options.

func (*RestClient) LimitOrder

func (c *RestClient) LimitOrder(
	ctx context.Context,
	accountID, figi string,
	lots int,
	operation OperationType,
	price float64,
) (PlacedOrder, error)

LimitOrder see docs https://tinkoffcreditsystems.github.io/invest-openapi/swagger-ui/#/orders/post_orders_limit_order.

func (*RestClient) MarketOrder

func (c *RestClient) MarketOrder(ctx context.Context, accountID, figi string, lots int, operation OperationType) (PlacedOrder, error)

MarketOrder see docs https://tinkoffcreditsystems.github.io/invest-openapi/swagger-ui/#/orders/post_orders_market_order.

func (*RestClient) Operations

func (c *RestClient) Operations(ctx context.Context, accountID string, from, to time.Time, figi string) ([]Operation, error)

Operations see docs https://tinkoffcreditsystems.github.io/invest-openapi/swagger-ui/#/operations/get_operations.

func (*RestClient) Portfolio

func (c *RestClient) Portfolio(ctx context.Context, accountID string) (Portfolio, error)

Portfolio contains calls two method for get portfolio info.

func (*RestClient) PositionsPortfolio

func (c *RestClient) PositionsPortfolio(ctx context.Context, accountID string) ([]PositionBalance, error)

PositionsPortfolio see docs https://tinkoffcreditsystems.github.io/invest-openapi/swagger-ui/#/portfolio/get_portfolio.

type RestOrderBook

type RestOrderBook struct {
	FIGI              string              `json:"figi"`
	Depth             int                 `json:"depth"`
	Bids              []RestPriceQuantity `json:"bids"`
	Asks              []RestPriceQuantity `json:"asks"`
	TradeStatus       TradingStatus       `json:"tradeStatus"`
	MinPriceIncrement float64             `json:"minPriceIncrement"`
	LastPrice         float64             `json:"lastPrice,omitempty"`
	ClosePrice        float64             `json:"closePrice,omitempty"`
	LimitUp           float64             `json:"limitUp,omitempty"`
	LimitDown         float64             `json:"limitDown,omitempty"`
	FaceValue         float64             `json:"faceValue,omitempty"`
}

type RestPriceQuantity

type RestPriceQuantity struct {
	Price    float64 `json:"price"`
	Quantity float64 `json:"quantity"`
}

type SandboxRestClient

type SandboxRestClient struct {
	*RestClient
}

SandboxRestClient rest client for sandbox tinkoff invest.

func NewSandboxRestClient

func NewSandboxRestClient(token string) *SandboxRestClient

NewSandboxRestClient returns new SandboxRestClient by token.

func NewSandboxRestClientCustom

func NewSandboxRestClientCustom(token, apiURL string) *SandboxRestClient

NewSandboxRestClientCustom returns new custom SandboxRestClient by token and api url.

func (*SandboxRestClient) SetCurrencyBalance

func (c *SandboxRestClient) SetCurrencyBalance(ctx context.Context, accountID string, currency Currency, balance float64) error

SetCurrencyBalance see docs https://tinkoffcreditsystems.github.io/invest-openapi/swagger-ui/#/sandbox/post_sandbox_currencies_balance.

func (*SandboxRestClient) SetPositionsBalance

func (c *SandboxRestClient) SetPositionsBalance(ctx context.Context, accountID, figi string, balance float64) error

SetPositionsBalance see docs https://tinkoffcreditsystems.github.io/invest-openapi/swagger-ui/#/sandbox/post_sandbox_positions_balance.

type StreamingClient

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

func NewStreamingClient

func NewStreamingClient(logger Logger, token string) (*StreamingClient, error)

func NewStreamingClientCustom

func NewStreamingClientCustom(logger Logger, token, apiURL string) (*StreamingClient, error)

func NewStreamingClientCustomPingPong

func NewStreamingClientCustomPingPong(logger Logger, token, apiURL string, pingPongCfg *PingPongConfig) (*StreamingClient, error)

func (*StreamingClient) Close

func (c *StreamingClient) Close() error

func (*StreamingClient) RunReadLoop

func (c *StreamingClient) RunReadLoop(fn func(event interface{}) error) error

func (*StreamingClient) SubscribeCandle

func (c *StreamingClient) SubscribeCandle(figi string, interval CandleInterval, requestID string) error

func (*StreamingClient) SubscribeInstrumentInfo

func (c *StreamingClient) SubscribeInstrumentInfo(figi, requestID string) error

func (*StreamingClient) SubscribeOrderbook

func (c *StreamingClient) SubscribeOrderbook(figi string, depth int, requestID string) error

func (*StreamingClient) UnsubscribeCandle

func (c *StreamingClient) UnsubscribeCandle(figi string, interval CandleInterval, requestID string) error

func (*StreamingClient) UnsubscribeInstrumentInfo

func (c *StreamingClient) UnsubscribeInstrumentInfo(figi, requestID string) error

func (*StreamingClient) UnsubscribeOrderbook

func (c *StreamingClient) UnsubscribeOrderbook(figi string, depth int, requestID string) error

type Trade

type Trade struct {
	ID       string    `json:"tradeId"`
	DateTime time.Time `json:"date"`
	Price    float64   `json:"price"`
	Quantity int       `json:"quantity"`
}

type TradingError

type TradingError struct {
	TrackingID string `json:"trackingId"`
	Status     string `json:"status"`
	Hint       string
	Payload    struct {
		Message string `json:"message"`
		Code    string `json:"code"`
	} `json:"payload"`
}

TradingError contains error info from tinkoff invest.

func (TradingError) Error

func (t TradingError) Error() string

Error for implements error.

func (TradingError) InvalidTokenSpace

func (t TradingError) InvalidTokenSpace() bool

InvalidTokenSpace for check error.

func (TradingError) NotEnoughBalance

func (t TradingError) NotEnoughBalance() bool

NotEnoughBalance for check error.

type TradingStatus

type TradingStatus string
const (
	BreakInTrading               TradingStatus = "BreakInTrading"
	NormalTrading                TradingStatus = "NormalTrading"
	NotAvailableForTrading       TradingStatus = "NotAvailableForTrading"
	ClosingAuction               TradingStatus = "ClosingAuction"
	ClosingPeriod                TradingStatus = "ClosingPeriod"
	DarkPoolAuction              TradingStatus = "DarkPoolAuction"
	DiscreteAuction              TradingStatus = "DiscreteAuction"
	OpeningPeriod                TradingStatus = "OpeningPeriod"
	OpeningAuctionPeriod         TradingStatus = "OpeningAuctionPeriod"
	TradingAtClosingAuctionPrice TradingStatus = "TradingAtClosingAuctionPrice"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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