tinkoff

package
v0.0.0-...-f7f5d23 Latest Latest
Warning

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

Go to latest
Published: May 23, 2022 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccountStringTableHead

func AccountStringTableHead() string

func CalcLotsInOrders

func CalcLotsInOrders(orders []alex.Order) map[string]int64

func IsLimitError

func IsLimitError(e error) bool

TODO надо вводить свой класс ошибок

func NewPositions

func NewPositions(responce *proto.PositionsResponse) *alex.Positions

func NewRealAccount

func NewRealAccount(ctx context.Context, client *Client, ad *proto.Account) alex.Account

func NewSandboxAccount

func NewSandboxAccount(c *Client, ad *proto.Account) alex.Account

func SetLogger

func SetLogger(logger *zap.Logger)

Types

type Account

type Account interface {
	alex.Account
}

type AccountAbstract

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

func NewAccountAbstract

func NewAccountAbstract(client *Client, ad *proto.Account) *AccountAbstract

func (*AccountAbstract) CancelOrder

func (a *AccountAbstract) CancelOrder(ctx context.Context, orderId string) (time.Time, error)

func (*AccountAbstract) DoPosition

func (a *AccountAbstract) DoPosition(ctx context.Context, bot alex.Bot, instrument alex.Instrument, targetPositionLots int64) alex.TargetPosition

Функция запускает процесс приведения позиции по инструменту к указанной ОГРАНИЧЕНИЯ - только один робот на инструмент, иначе они будут конфликтовать между собой по позициям

func (*AccountAbstract) DoPositionExtended

func (a *AccountAbstract) DoPositionExtended(ctx context.Context, bot alex.Bot, instrument alex.Instrument, targetPositionLots int64, priceIncrement big.Decimal) alex.TargetPosition

func (*AccountAbstract) GetAccessLevel

func (a *AccountAbstract) GetAccessLevel() proto.AccessLevel

func (*AccountAbstract) GetBalance

func (a *AccountAbstract) GetBalance(ctx context.Context, i alex.Instrument) int64

func (*AccountAbstract) GetBlocked

func (a *AccountAbstract) GetBlocked(ctx context.Context, i alex.Instrument) int64

func (*AccountAbstract) GetClient

func (a *AccountAbstract) GetClient() alex.Client

func (*AccountAbstract) GetClosedDate

func (a *AccountAbstract) GetClosedDate() time.Time

func (*AccountAbstract) GetId

func (a *AccountAbstract) GetId() string

func (*AccountAbstract) GetName

func (a *AccountAbstract) GetName() string

func (*AccountAbstract) GetOpenedDate

func (a *AccountAbstract) GetOpenedDate() time.Time

func (*AccountAbstract) GetOrders

func (a *AccountAbstract) GetOrders(ctx context.Context) ([]alex.Order, error)

func (*AccountAbstract) GetPositions

func (a *AccountAbstract) GetPositions(ctx context.Context) (*alex.Positions, error)

func (*AccountAbstract) GetStatus

func (a *AccountAbstract) GetStatus() proto.AccountStatus

func (*AccountAbstract) GetTargetPosition

func (a *AccountAbstract) GetTargetPosition() *TargetPositions

func (*AccountAbstract) GetTinkoffClient

func (a *AccountAbstract) GetTinkoffClient() *Client

func (*AccountAbstract) GetType

func (a *AccountAbstract) GetType() proto.AccountType

func (*AccountAbstract) PostOrder

func (a *AccountAbstract) PostOrder(ctx context.Context, instrument alex.Instrument, quantity int64, price big.Decimal, direction proto.OrderDirection, orderType proto.OrderType, orderId string) (alex.Order, error)

func (*AccountAbstract) PostOrderWithBestPrice

func (a *AccountAbstract) PostOrderWithBestPrice(ctx context.Context, instrument alex.Instrument, quantity int64, priceIncrement big.Decimal) (alex.Order, error)

func (*AccountAbstract) String

func (a *AccountAbstract) String() string

type Accounts

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

func NewAccounts

func NewAccounts(client *Client) *Accounts

func (*Accounts) GetOrDie

func (aa *Accounts) GetOrDie(ctx context.Context, accountId string) alex.Account

func (*Accounts) GetRealAccounts

func (aa *Accounts) GetRealAccounts(ctx context.Context) (map[string]alex.Account, error)

func (*Accounts) GetRealAccountsStrings

func (aa *Accounts) GetRealAccountsStrings() (result []string)

func (*Accounts) GetSandboxAccounts

func (aa *Accounts) GetSandboxAccounts(ctx context.Context) (map[string]alex.Account, error)

type BaseOrder

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

func NewBaseOrder

func NewBaseOrder(o OrderFromAPI, a Account, orderDate time.Time) BaseOrder

func (*BaseOrder) Cancel

func (o *BaseOrder) Cancel(ctx context.Context) (time.Time, error)

Метод отмены торгового поручения в песочнице.

func (*BaseOrder) GetDirection

func (o *BaseOrder) GetDirection() proto.OrderDirection

func (*BaseOrder) GetExecutionReportStatus

func (o *BaseOrder) GetExecutionReportStatus() proto.OrderExecutionReportStatus

func (*BaseOrder) GetFigi

func (o *BaseOrder) GetFigi() string

func (*BaseOrder) GetInitialOrderPrice

func (o *BaseOrder) GetInitialOrderPrice() *alex.Money

func (*BaseOrder) GetLotsExecuted

func (o *BaseOrder) GetLotsExecuted() int64

func (*BaseOrder) GetLotsRequested

func (o *BaseOrder) GetLotsRequested() int64

func (*BaseOrder) GetOrderDate

func (o *BaseOrder) GetOrderDate() time.Time

func (*BaseOrder) GetOrderId

func (o *BaseOrder) GetOrderId() string

func (*BaseOrder) IsActive

func (o *BaseOrder) IsActive() bool

Определить, является ли ордер активной.

func (*BaseOrder) IsBestInOrderBook

func (o *BaseOrder) IsBestInOrderBook(ctx context.Context) bool

type Candles

type Candles struct {
	Figi   string
	Period time.Duration
	Series *techan.TimeSeries
	// contains filtered or unexported fields
}

func NewCandles

func NewCandles(client *Client, figi string, period time.Duration) *Candles

func (*Candles) GetFigi

func (cs *Candles) GetFigi() string

func (*Candles) GetPeriod

func (cs *Candles) GetPeriod() time.Duration

func (*Candles) GetSeries

func (cs *Candles) GetSeries() *techan.TimeSeries

func (*Candles) Load

func (cs *Candles) Load(ctx context.Context, from time.Time, to time.Time) error

func (*Candles) LoadFromData

func (cs *Candles) LoadFromData() error

func (*Candles) MergeApiCandles

func (cs *Candles) MergeApiCandles(apiCandles []*proto.HistoricCandle)

func (*Candles) RemoveSubscriber

func (cs *Candles) RemoveSubscriber(candleChan alex.CandleChan) bool

func (*Candles) Save

func (cs *Candles) Save() error

func (*Candles) Subscribe

func (cs *Candles) Subscribe() (candleChan alex.CandleChan, err error)

func (*Candles) Unsubscribe

func (cs *Candles) Unsubscribe(candleChan alex.CandleChan) (err error)

func (*Candles) Upsert

func (cs *Candles) Upsert(newCandle *techan.Candle)

type Client

type Client struct {
	Instruments *Instruments
	Accounts    *Accounts
	// contains filtered or unexported fields
}

func NewClient

func NewClient(endpoint string, token string, dataDir string) *Client

func (*Client) Close

func (c *Client) Close() error

func (*Client) CloseSandboxAccount

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

func (*Client) Etfs

func (c *Client) Etfs(ctx context.Context, status proto.InstrumentStatus) ([]*proto.Etf, error)

func (*Client) GetAccounts

func (c *Client) GetAccounts(ctx context.Context, engine alex.EngineType) (map[string]alex.Account, error)

func (*Client) GetDataDir

func (c *Client) GetDataDir() string

func (*Client) GetInstrument

func (c *Client) GetInstrument(figi string) alex.Instrument

func (*Client) GetMarketDataServiceClient

func (c *Client) GetMarketDataServiceClient() proto.MarketDataServiceClient

func (*Client) GetOperationsServiceClient

func (c *Client) GetOperationsServiceClient() proto.OperationsServiceClient

func (*Client) GetOrdersServiceClient

func (c *Client) GetOrdersServiceClient() proto.OrdersServiceClient

func (*Client) GetOrdersStreamServiceClient

func (c *Client) GetOrdersStreamServiceClient() proto.OrdersStreamServiceClient

func (*Client) GetPortfolio

func (c *Client) GetPortfolio(ctx context.Context, accountId string) (*Portfolio, error)

func (*Client) GetSandboxServiceClient

func (c *Client) GetSandboxServiceClient() proto.SandboxServiceClient

func (*Client) GetUsersServiceClient

func (c *Client) GetUsersServiceClient() proto.UsersServiceClient

func (*Client) InitOrderStream

func (c *Client) InitOrderStream(accounts []string) (err error)

func (*Client) Now

func (c *Client) Now() time.Time

func (*Client) Open

func (c *Client) Open(ctx context.Context) (err error)

func (*Client) OpenSandboxAccount

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

func (*Client) Printf

func (c *Client) Printf(format string, arg ...any) (n int, err error)

Перенаправляем вывод робота в лог, в режиме Info + в консоль

func (*Client) SandboxPayIn

func (c *Client) SandboxPayIn(ctx context.Context, accountId string, rub big.Decimal) (*alex.Money, error)

func (*Client) SaveCandles

func (c *Client) SaveCandles(candles alex.Candles) error

func (*Client) Shares

func (c *Client) Shares(ctx context.Context, status proto.InstrumentStatus) ([]*proto.Share, error)

func (*Client) SubscribeCandles

func (c *Client) SubscribeCandles(cs *Candles) alex.CandleChan

type FromGetOrder

type FromGetOrder struct {
	BaseOrder
	AveragePositionPrice *alex.Money  //Средняя цена позиции по сделке.
	Stages               []OrderStage //Стадии выполнения заявки.
	ServiceCommission    *alex.Money  //Сервисная комиссия.
	Currency             string       //Валюта заявки.
}

Структура, получаемая из GetOrderState / GetOrders

func NewOrderFromGet

func NewOrderFromGet(a Account, o *proto.OrderState) *FromGetOrder

type FromPostOrder

type FromPostOrder struct {
	BaseOrder
	AciValue            *alex.Money //Значение НКД (накопленного купонного дохода) на дату. Подробнее: [НКД при выставлении торговых поручений](https://tinkoff.github.io/proto/head-orders#coupon)
	Message             string      //Дополнительные данные об исполнении заявки.
	InitialOrderPricePt big.Decimal //Начальная цена заявки в пунктах (для фьючерсов).
}

следующие атрибуты заполняется только в PostOrder

func NewOrderFromPost

func NewOrderFromPost(a Account, o *proto.PostOrderResponse) *FromPostOrder

type Instrument

type Instrument struct {
	InstrumentDescriptionLink InstrumentAdditionDescriptionInAPI
	OrderBookCache            OrderBookCache
	// contains filtered or unexported fields
}

func NewInstrument

func NewInstrument(client *Client, instDesc InstrumentAdditionDescriptionInAPI) *Instrument

func (*Instrument) GetCandles

func (i *Instrument) GetCandles(period time.Duration) alex.Candles

Получить объект свечей уникальный в рамках соединения к АПИ

func (*Instrument) GetClassCode

func (i *Instrument) GetClassCode() string

func (*Instrument) GetClient

func (i *Instrument) GetClient() *Client

func (*Instrument) GetCurrency

func (i *Instrument) GetCurrency() string

func (*Instrument) GetExchange

func (i *Instrument) GetExchange() string

func (*Instrument) GetFigi

func (i *Instrument) GetFigi() string

func (*Instrument) GetIsin

func (i *Instrument) GetIsin() string

func (*Instrument) GetLastPrices

func (i *Instrument) GetLastPrices(ctx context.Context) ([]*alex.LastPrice, error)

Метод запроса последних цен по инструментам.

func (*Instrument) GetLot

func (i *Instrument) GetLot() int32

func (*Instrument) GetMinPriceIncrement

func (i *Instrument) GetMinPriceIncrement() big.Decimal

func (*Instrument) GetName

func (i *Instrument) GetName() string

func (*Instrument) GetOrderBook

func (i *Instrument) GetOrderBook(ctx context.Context, depth int32) (*alex.OrderBook, error)

Метод получения стакана по инструменту.

func (*Instrument) GetTicker

func (i *Instrument) GetTicker() string

func (*Instrument) IsLimitOrderAvailable

func (i *Instrument) IsLimitOrderAvailable() bool

func (*Instrument) IsMarketOrderAvailable

func (i *Instrument) IsMarketOrderAvailable() bool

func (*Instrument) IsStatus

func (i *Instrument) IsStatus(tradingStatus ...proto.SecurityTradingStatus) bool

func (*Instrument) Now

func (i *Instrument) Now() time.Time

func (*Instrument) SetOrderAvailable

func (i *Instrument) SetOrderAvailable(limitOrderAvailable bool, marketOrderAvailable bool)

func (*Instrument) SetStatus

func (i *Instrument) SetStatus(tradingStatus proto.SecurityTradingStatus)

type InstrumentAdditionDescriptionInAPI

type InstrumentAdditionDescriptionInAPI interface {
	InstrumentGeneralDescription
	GetMinPriceIncrement() *proto.Quotation
}

type InstrumentGeneralDescription

type InstrumentGeneralDescription interface {
	GetFigi() string
	GetExchange() string
	GetClassCode() string
	GetIsin() string
	GetTicker() string
	GetCurrency() string
	GetName() string
	GetLot() int32
}

type Instruments

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

func NewInstruments

func NewInstruments(client *Client) *Instruments

func (*Instruments) Get

func (ii *Instruments) Get(figi string) *Instrument

func (*Instruments) LoadNew

func (ii *Instruments) LoadNew(ctx context.Context) error

type Limits

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

func (*Limits) Load

func (limits *Limits) Load(ctx context.Context, conn grpc.ClientConnInterface) error

type MarketDataStream

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

func NewMarketDataStream

func NewMarketDataStream(client *Client) *MarketDataStream

func (*MarketDataStream) GetCandles

func (s *MarketDataStream) GetCandles(figi string, interval proto.SubscriptionInterval) (alex.Candles, alex.CandleChan)

func (*MarketDataStream) Subscribe

func (s *MarketDataStream) Subscribe(candles *Candles) alex.CandleChan

func (*MarketDataStream) Unsubscribe

func (s *MarketDataStream) Unsubscribe(candles *Candles) error

type OrderBookCache

type OrderBookCache struct {
	LiveTime time.Duration

	OrderBooks map[int32]OrderBookCacheItem
	// contains filtered or unexported fields
}

type OrderBookCacheItem

type OrderBookCacheItem struct {
	Time      time.Time
	OrderBook *alex.OrderBook
}

type OrderFromAPI

type OrderFromAPI interface {
	GetOrderId() string
	GetExecutionReportStatus() proto.OrderExecutionReportStatus
	GetLotsRequested() int64
	GetLotsExecuted() int64
	GetInitialOrderPrice() *proto.MoneyValue
	GetExecutedOrderPrice() *proto.MoneyValue
	GetTotalOrderAmount() *proto.MoneyValue
	GetInitialCommission() *proto.MoneyValue
	GetExecutedCommission() *proto.MoneyValue
	GetFigi() string
	GetDirection() proto.OrderDirection
	GetInitialSecurityPrice() *proto.MoneyValue
	GetOrderType() proto.OrderType
}

type OrderStage

type OrderStage struct {
	BaseOrder
	Price    *alex.Money //Цена за 1 инструмент. Для получения стоимости лота требуется умножить на лотность инструмента..
	Quantity int64       //Количество лотов.
	TradeId  string      //Идентификатор торговой операции.
}

Сделки в рамках торгового поручения.

type OrderTrades

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

func NewOrderTrades

func NewOrderTrades(c *Client) *OrderTrades

func (*OrderTrades) SetAccounts

func (ot *OrderTrades) SetAccounts(accounts []string)

func (*OrderTrades) Subscribe

func (ot *OrderTrades) Subscribe() (OrderTradesChan, error)

func (*OrderTrades) Unsubscribe

func (ot *OrderTrades) Unsubscribe(ch OrderTradesChan) (err error)

type OrderTradesChan

type OrderTradesChan chan *proto.OrderTrades

type Portfolio

type Portfolio struct {
	TotalAmountShares     *alex.Money          //Общая стоимость акций в портфеле в рублях.
	TotalAmountBonds      *alex.Money          //Общая стоимость облигаций в портфеле в рублях.
	TotalAmountEtf        *alex.Money          //Общая стоимость фондов в портфеле в рублях.
	TotalAmountCurrencies *alex.Money          //Общая стоимость валют в портфеле в рублях.
	TotalAmountFutures    *alex.Money          //Общая стоимость фьючерсов в портфеле в рублях.
	ExpectedYield         big.Decimal          //Текущая относительная доходность портфеля, в %.
	Positions             []*PortfolioPosition //Список позиций портфеля.
}

Портфель по счёту.

func NewPortfolio

func NewPortfolio(responce *proto.PortfolioResponse) *Portfolio

type PortfolioPosition

type PortfolioPosition struct {
	Figi                     string      //Figi-идентификатора инструмента.
	InstrumentType           string      //Тип инструмента.
	Quantity                 big.Decimal //Количество инструмента в портфеле в штуках.
	AveragePositionPrice     *alex.Money //Средневзвешенная цена позиции. **Возможна задержка до секунды для пересчёта**.
	ExpectedYield            big.Decimal //Текущая рассчитанная относительная доходность позиции, в %.
	CurrentNkd               *alex.Money // Текущий НКД.
	AveragePositionPricePt   big.Decimal //Средняя цена лота в позиции в пунктах (для фьючерсов). **Возможна задержка до секунды для пересчёта**.
	CurrentPrice             *alex.Money //Текущая цена за 1 инструмент. Для получения стоимости лота требуется умножить на лотность инструмента..
	AveragePositionPriceFifo *alex.Money //Средняя цена лота в позиции по методу FIFO. **Возможна задержка до секунды для пересчёта**.
	QuantityLots             big.Decimal //Количество лотов в портфеле.
}

Позиции портфеля.

func NewPortfolioPosition

func NewPortfolioPosition(responce *proto.PortfolioPosition) *PortfolioPosition

type PrometheusService

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

func (*PrometheusService) Start

func (s *PrometheusService) Start(addr string) error

Start the prometheus service.

func (*PrometheusService) Stop

func (s *PrometheusService) Stop() error

Stop the service gracefully.

type RealAccount

type RealAccount struct {
	*AccountAbstract
}

func (*RealAccount) CancelOrder

func (ra *RealAccount) CancelOrder(ctx context.Context, orderId string) (time.Time, error)

Метод отмены торгового поручения.

func (*RealAccount) GetEngineType

func (ra *RealAccount) GetEngineType() alex.EngineType

func (*RealAccount) GetOrders

func (ra *RealAccount) GetOrders(ctx context.Context) ([]alex.Order, error)

Метод получения списка активных заявок по счёту в песочнице.

func (*RealAccount) GetPositions

func (ra *RealAccount) GetPositions(ctx context.Context) (*alex.Positions, error)

Метод получения позиций по счёту.

func (*RealAccount) PostOrder

func (ra *RealAccount) PostOrder(ctx context.Context, instrument alex.Instrument, quantity int64, price big.Decimal, direction proto.OrderDirection, orderType proto.OrderType, orderId string) (alex.Order, error)

type SandboxAccount

type SandboxAccount struct {
	*AccountAbstract
}

func (SandboxAccount) CancelOrder

func (sa SandboxAccount) CancelOrder(ctx context.Context, orderId string) (time.Time, error)

Метод отмены торгового поручения в песочнице.

func (*SandboxAccount) GetEngineType

func (sa *SandboxAccount) GetEngineType() alex.EngineType

func (*SandboxAccount) GetOrders

func (sa *SandboxAccount) GetOrders(ctx context.Context) ([]alex.Order, error)

Метод получения списка активных заявок по счёту в песочнице.

func (*SandboxAccount) GetPositions

func (sa *SandboxAccount) GetPositions(ctx context.Context) (*alex.Positions, error)

Метод получения позиций по виртуальному счёту песочницы.

func (*SandboxAccount) PostOrder

func (sa *SandboxAccount) PostOrder(ctx context.Context, instrument alex.Instrument, quantity int64, price big.Decimal, direction proto.OrderDirection, orderType proto.OrderType, orderId string) (alex.Order, error)

type TargetPosition

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

func (*TargetPosition) Error

func (tpi *TargetPosition) Error() string

func (*TargetPosition) GetError

func (tpi *TargetPosition) GetError() error

func (*TargetPosition) IsLimitError

func (tpi *TargetPosition) IsLimitError() bool

type TargetPositions

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

func NewTargetPositions

func NewTargetPositions() *TargetPositions

Directories

Path Synopsis
proto

Jump to

Keyboard shortcuts

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