Documentation
¶
Index ¶
- Variables
- func IsAPIError(e error) bool
- type APIError
- type CancelOrderService
- type Candle
- type Candles
- type CandlesService
- type Client
- func (c *Client) AccessTokens(ctx context.Context) (ok bool, err error)
- func (c *Client) BuyLimit(ctx context.Context, board, symbol string, lot int32, price float64) (int64, error)
- func (c *Client) BuyMarket(ctx context.Context, board, symbol string, lot int32) (int64, error)
- func (c *Client) DeleteOrder(ctx context.Context, transactionId int64) error
- func (c *Client) GetCandles(ctx context.Context, board, symbol string, timeFrame TimeFrame, opts ...Option) ([]Candle, error)
- func (c *Client) GetOrders(ctx context.Context, opts ...Option) ([]Order, error)
- func (c *Client) GetPortfolio(ctx context.Context, opts ...Option) (Portfolio, error)
- func (c *Client) GetSecurity(ctx context.Context, board, symbol string) (Securities, error)
- func (c *Client) NewCancelOrderService(transactionId int64) *CancelOrderService
- func (c *Client) NewCandlesService(board, symbol string, timeFrame TimeFrame) *CandlesService
- func (c *Client) NewCreateOrderService(board, symbol string, sideType SideType, lot int32) *CreateOrderService
- func (c *Client) NewGetOrderService() *GetOrderService
- func (c *Client) NewGetPortfolioService() *GetPortfolioService
- func (c *Client) NewSecurityService() *SecurityService
- func (c *Client) SellLimit(ctx context.Context, board, symbol string, lot int32, price float64) (int64, error)
- func (c *Client) SellMarket(ctx context.Context, board, symbol string, lot int32) (int64, error)
- func (c *Client) Version() string
- type CreateOrderService
- func (s *CreateOrderService) Do(ctx context.Context) (int64, error)
- func (s *CreateOrderService) Price(price float64) *CreateOrderService
- func (s *CreateOrderService) Quantity(quantity int32) *CreateOrderService
- func (s *CreateOrderService) Side(side SideType) *CreateOrderService
- func (s *CreateOrderService) TimeInForce(timeInForce TimeInForceType) *CreateOrderService
- type Decimal
- type GetOrderService
- type GetPortfolioService
- func (s *GetPortfolioService) Do(ctx context.Context) (Portfolio, error)
- func (s *GetPortfolioService) IncludeCurrencies(param bool) *GetPortfolioService
- func (s *GetPortfolioService) IncludeMaxBuySell(param bool) *GetPortfolioService
- func (s *GetPortfolioService) IncludeMoney(param bool) *GetPortfolioService
- func (s *GetPortfolioService) IncludePositions(param bool) *GetPortfolioService
- type IFinamClient
- type Money
- type Option
- func WithCount(param int) Option
- func WithEndTime(param time.Time) Option
- func WithIncludeActive(param bool) Option
- func WithIncludeCanceled(param bool) Option
- func WithIncludeCurrencies(param bool) Option
- func WithIncludeMatched(param bool) Option
- func WithIncludeMaxBuySell(param bool) Option
- func WithIncludeMoney(param bool) Option
- func WithIncludePositions(param bool) Option
- func WithStartTime(param time.Time) Option
- type Options
- type Order
- type OrderCondition
- type OrderRequest
- type OrderStatus
- type OrderValidBefore
- type Portfolio
- type Position
- type RequestOption
- type ResponseError
- type Securities
- type Security
- type SecurityService
- type SideType
- type TimeFrame
- type TimeInForceType
- type Сurrency
Constants ¶
This section is empty.
Variables ¶
var Moscow = initMoscow()
Functions ¶
func IsAPIError ¶
Types ¶
type APIError ¶
type APIError struct {
ResponseError ResponseError `json:"error"`
}
type CancelOrderService ¶
type CancelOrderService struct {
// contains filtered or unexported fields
}
CancelOrderService удалить заявку по ее ID
type Candle ¶
type Candle struct { Date string `json:"date"` // дневная свеча дата свечи в формате yyyy-MM-dd (в локальном времени биржи); Timestamp string `json:"timestamp"` // внутридневная свеча дата и время свечи в формате yyyy-MM-ddTHH:mm:ssZ в поясе UTC; Open Decimal `json:"open"` // цена открытия (тип Decimal); Close Decimal `json:"close"` // цена закрытия (тип Decimal); High Decimal `json:"high"` // максимальная цена (тип Decimal); Low Decimal `json:"low"` // минимальная цена (тип Decimal); Volume int64 `json:"volume"` // объем торгов. }
Candle структура свечи
func (*Candle) GetDateTime ¶
func (*Candle) GetDateTimeToTime ¶
type CandlesService ¶
type CandlesService struct {
// contains filtered or unexported fields
}
получить исторические свечи https://finamweb.github.io/trade-api-docs/rest-api/candles Обязательные параметры securityCode, securityBoard и timeFrame. Запросить можно как определенное количество свечей, так и за интервал. Для запроса количества свечей в запросе необходимо указать count и либо from (начиная с указанной даты) либо to (до указанной даты). Для запроса за интервал необходимо указать from и to. Запрос дневных/недельных свечей Максимальный интервал: 365 дней Максимальное кол-во запросов в минуту: 120 Дата начала (окончания) в формате yyyy-MM-dd в часовом поясе UTC Запрос внутридневных свечей Максимальный интервал: 30 дней Максимальное кол-во запросов в минуту: 120 Дата начала (окончания) в формате yyyy-MM-ddTHH:mm:ssZ в часовом поясе UTC
func (*CandlesService) Count ¶
func (s *CandlesService) Count(param int) *CandlesService
Limit set limit
func (*CandlesService) Do ¶
func (s *CandlesService) Do(ctx context.Context) ([]Candle, error)
Do send request
func (*CandlesService) EndTime ¶
func (s *CandlesService) EndTime(endTime time.Time) *CandlesService
EndTime set endTime
func (*CandlesService) StartTime ¶
func (s *CandlesService) StartTime(startTime time.Time) *CandlesService
StartTime set startTime
type Client ¶
type Client struct { BaseURL string UserAgent string HTTPClient *http.Client Debug bool Logger *log.Logger TimeOffset int64 // contains filtered or unexported fields }
Client define API client
func (*Client) AccessTokens ¶
https://trade-api.finam.ru/public/api/v1/access-tokens/check проверка токена
func (*Client) BuyLimit ¶
func (c *Client) BuyLimit(ctx context.Context, board, symbol string, lot int32, price float64) (int64, error)
BuyLimit купить по рынку
func (*Client) DeleteOrder ¶
DeleteOrder удаление заявки clientId - торговый код клиента (обязательный) transactionId int64 (обязательный)
func (*Client) GetCandles ¶
func (c *Client) GetCandles(ctx context.Context, board, symbol string, timeFrame TimeFrame, opts ...Option) ([]Candle, error)
GetCandles получить свечи Для запроса количества свечей в запросе необходимо указать count и либо from (начиная с указанной даты) либо to (до указанной даты). Для запроса за интервал необходимо указать from и to.
func (*Client) GetPortfolio ¶
GetPortfolio получить данные по портфелю
func (*Client) GetSecurity ¶
GetSecurity получить список инструментов (Максимальное Количество запросов в минуту = 1 )
func (*Client) NewCancelOrderService ¶
func (c *Client) NewCancelOrderService(transactionId int64) *CancelOrderService
NewCancelOrderService init CancelOrder Service обязательные параметры: id
func (*Client) NewCandlesService ¶
func (c *Client) NewCandlesService(board, symbol string, timeFrame TimeFrame) *CandlesService
NewCandlesService init candles service обязательные параметры: board, symbol, timeFrame
func (*Client) NewCreateOrderService ¶
func (c *Client) NewCreateOrderService(board, symbol string, sideType SideType, lot int32) *CreateOrderService
NewCreateOrderService init creating order service какие обязательные параметры?
func (*Client) NewGetOrderService ¶
func (c *Client) NewGetOrderService() *GetOrderService
NewGetOrderService init GetOrder Service
func (*Client) NewGetPortfolioService ¶
func (c *Client) NewGetPortfolioService() *GetPortfolioService
NewGetPortfolioService init portfоlio service
func (*Client) NewSecurityService ¶
func (c *Client) NewSecurityService() *SecurityService
NewSecurityService init security service
func (*Client) SellLimit ¶
func (c *Client) SellLimit(ctx context.Context, board, symbol string, lot int32, price float64) (int64, error)
SellLimit продать по рынку
func (*Client) SellMarket ¶
SellMarket продать по рынку
type CreateOrderService ¶
type CreateOrderService struct {
// contains filtered or unexported fields
}
CreateOrderService создать новую заявку (ордер)
func (*CreateOrderService) Price ¶
func (s *CreateOrderService) Price(price float64) *CreateOrderService
Price установим цену Для рыночной заявки указать значение null (или не передавать это поле). Для условной заявки необходимо указать цену исполнения;
func (*CreateOrderService) Quantity ¶
func (s *CreateOrderService) Quantity(quantity int32) *CreateOrderService
Quantity установим объем заявки в лотах;
func (*CreateOrderService) Side ¶
func (s *CreateOrderService) Side(side SideType) *CreateOrderService
установим направление ордера
func (*CreateOrderService) TimeInForce ¶
func (s *CreateOrderService) TimeInForce(timeInForce TimeInForceType) *CreateOrderService
TimeInForce установим условие по времени действия заявки TillEndSession - заявка действует до конца сессии; TillCancelled - заявка действует, пока не будет отменена; ExactTime - заявка действует до указанного времени. Параметр time должен быть задан (где его указать?)
type Decimal ¶
type Decimal struct { Num int `json:"num"` // мантисса; Scale int `json:"scale"` // экспонента по основанию 10. }
Decimal Представляет десятичное число с плавающей запятой: Итоговое значение вычисляется по формуле: num * 10^(-scale). Где ^ оператор возведение в степень.
type GetOrderService ¶
type GetOrderService struct {
// contains filtered or unexported fields
}
GetOrderService получить список ордеров
func (*GetOrderService) IncludeActive ¶
func (s *GetOrderService) IncludeActive(param bool) *GetOrderService
IncludeActive Вернуть активные заявки
func (*GetOrderService) IncludeCanceled ¶
func (s *GetOrderService) IncludeCanceled(param bool) *GetOrderService
IncludeCanceled Вернуть исполненные заявки
func (*GetOrderService) IncludeMatched ¶
func (s *GetOrderService) IncludeMatched(param bool) *GetOrderService
IncludeMatched Вернуть исполненные заявки
type GetPortfolioService ¶
type GetPortfolioService struct {
// contains filtered or unexported fields
}
GetPortfolioService получим информацию по портфелю https://finamweb.github.io/trade-api-docs/rest-api/portfolios clientId - торговый код клиента (обязательный); includeCurrencies - запросить информацию по валютам портфеля; includeMoney - запросить информацию по денежным позициям портфеля; includePositions - запросить информацию по позициям портфеля; includeMaxBuySell - запросить информацию о максимальном доступном объеме на покупку/продажу.
func (*GetPortfolioService) Do ¶
func (s *GetPortfolioService) Do(ctx context.Context) (Portfolio, error)
https://trade-api.finam.ru/public/api/v1/portfolio?Content.IncludeCurrencies=true&Content.IncludeMoney=true&Content.IncludePositions=true&Content.IncludeMaxBuySell=true Do sends the request.
func (*GetPortfolioService) IncludeCurrencies ¶
func (s *GetPortfolioService) IncludeCurrencies(param bool) *GetPortfolioService
IncludeCurrencies запросить информацию по валютам портфеля
func (*GetPortfolioService) IncludeMaxBuySell ¶
func (s *GetPortfolioService) IncludeMaxBuySell(param bool) *GetPortfolioService
IncludeMaxBuySell запросить информацию о максимальном доступном объеме на покупку/продажу
func (*GetPortfolioService) IncludeMoney ¶
func (s *GetPortfolioService) IncludeMoney(param bool) *GetPortfolioService
IncludeMoney запросить информацию по денежным позициям портфеля
func (*GetPortfolioService) IncludePositions ¶
func (s *GetPortfolioService) IncludePositions(param bool) *GetPortfolioService
IncludePositions запросить информацию по позициям портфеля
type IFinamClient ¶
type IFinamClient interface { // AccessTokens проверка подлинности токена AccessTokens(ctx context.Context) (ok bool, err error) // GetPortfolio получить данные по портфелю GetPortfolio(ctx context.Context, opts ...Option) (Portfolio, error) // GetSecurity получить список инструментов (Максимальное Количество запросов в минуту = 1 ) GetSecurity(ctx context.Context, board, symbol string) (Securities, error) // GetCandles получить свечи GetCandles(ctx context.Context, board, symbol string, timeFrame TimeFrame, opts ...Option) ([]Candle, error) // получить список заявок GetOrders(ctx context.Context, opts ...Option) ([]Order, error) // отменить заявку DeleteOrder(ctx context.Context, transactionId int64) error //// создать новую заявку //SendOrder(ctx context.Context, order NewOrderRequest) (int64, error) //// купить по рынку BuyMarket(ctx context.Context, symbol, board string, lot int32) (int64, error) // выставить лимитную заявку на покупку BuyLimit(ctx context.Context, board, symbol string, lot int32, price float64) (int64, error) // продать по рынку SellMarket(ctx context.Context, board, symbol string, lot int32) (int64, error) // выставить лимитную заявку на продажу SellLimit(ctx context.Context, board, symbol string, lot int32, price float64) (int64, error) }
какой api реализован
type Money ¶
type Money struct { Market string `json:"market"` // рынок. Тип Market; Currency string `json:"currency"` // код валюты; Balance float64 `json:"balance"` // текущая позиция. }
денежные позиции
type Option ¶
type Option func(o *Options)
func WithEndTime ¶
endTime Для запроса свечей: конечная дата
func WithIncludeActive ¶
(true) IncludeActive вернуть активные заявки.
func WithIncludeCanceled ¶
(true) вернуть отмененные заявки;
func WithIncludeCurrencies ¶
(true) запросить информацию по валютам портфеля;
func WithIncludeMatched ¶
(true) вернуть исполненные заявки;
func WithIncludeMaxBuySell ¶
(true) запросить информацию о максимальном доступном объеме на покупку/продажу.
func WithIncludeMoney ¶
(true) запросить информацию по денежным позициям портфеля;
func WithIncludePositions ¶
(true) запросить информацию по позициям портфеля;
func WithStartTime ¶
startTime Для запроса свечей: начальная дата
type Options ¶
type Options struct { // для запроса портфеля IncludeCurrencies bool // запросить информацию по валютам портфеля; IncludeMoney bool // запросить информацию по денежным позициям портфеля; IncludePositions bool // запросить информацию по позициям портфеля; IncludeMaxBuySell bool // запросить информацию о максимальном доступном объеме на покупку/продажу. // для запроса ордеров IncludeMatched bool // вернуть исполненные заявки; IncludeCanceled bool // вернуть отмененные заявки; IncludeActive bool // вернуть активные заявки. // для запроса свечей Count int StartTime *time.Time EndTime *time.Time }
func NewOptions ¶
func NewOptions() *Options
type Order ¶
type Order struct { OrderNo int64 `json:"orderNo"` // уникальный идентификатор заявки на бирже. Задается после того, как заявка будет принята биржей (см. поле status); TransactionId int64 `json:"transactionId"` // внутренний идентификатор заявки в системе TRANSAQ (для чужой заявки значение всегда равно 0); ClientId string `json:"clientId"` // торговый код клиента; SecurityCode string `json:"securityCode"` // код инструмента; SecurityBoard string `json:"securityBoard"` // основной режим торгов инструмента; Market string `json:"market"` // рынок инструмента. Тип Market. Status string `json:"status"` // текущий статус заявки. Тип OrderStatus; BuySell string `json:"buySell"` // тип BuySell ( SideType); CreatedAt string `json:"createdAt"` // время регистрации заявки на бирже (UTC); Price float64 `json:"price"` // цена исполнения условной заявки. Для рыночной заявки значение всегда равно 0; Quantity int `json:"quantity"` // объем заявки в лотах; Balance int `json:"balance"` // неисполненный остаток, в лотах. Изначально равен quantity, но по мере исполнения заявки (совершения сделок) будет уменьшаться на объем сделки. Значение 0 будет соответствовать полностью исполненной заявке (см. поле status); Message string `json:"message"` // содержит сообщение об ошибке, возникшей при обработке заявки. Заявка может быть отклонена по разным причинам сервером TRANSAQ или биржей с выставлением поля status; Currency string `json:"currency"` // код валюты цены AcceptedAt string `json:"acceptedAt"` // время регистрации заявки на сервере TRANSAQ (UTC); Condition *OrderCondition `json:"condition"` // может быть null/ свойства выставления заявок. Тип OrderCondition; ValidBefore OrderValidBefore `json:"validBefore"` // условие по времени действия заявки. Тип OrderValidBefore; }
Order структура ордера
type OrderCondition ¶
type OrderCondition struct { Type string `json:"type"` Price float64 `json:"price"` Time string `json:"time,omitempty"` }
Свойства выставления заявок. Тип условия определяет значение поля type, которое принимает следующие значения: Bid - лучшая цена покупки; BidOrLast- лучшая цена покупки или сделка по заданной цене и выше; Ask - лучшая цена продажи; AskOrLast - лучшая цена продажи или сделка по заданной цене и ниже; Time - время выставления заявки на Биржу (параметр time должен быть установлен); CovDown - обеспеченность ниже заданной; CovUp - обеспеченность выше заданной; LastUp - сделка на рынке по заданной цене или выше; LastDown- сделка на рынке по заданной цене или ниже.
type OrderRequest ¶
type OrderRequest struct { ClientId string `json:"clientId,omitempty"` // Идентификатор торгового счёта. SecurityBoard string `json:"securityBoard,omitempty"` // Trading Board. Режим торгов. SecurityCode string `json:"securityCode,omitempty"` // Security Code. Тикер инструмента. BuySell SideType `json:"buySell,omitempty"` // Направление сделки. Quantity int32 `json:"quantity,omitempty"` // Объем заявки в лотах; UseCredit bool `json:"useCredit,omitempty"` // Использовать кредит. Недоступно для срочного рынка. Price *float64 `json:"price"` // Цена заявки. Используйте "null", чтобы выставить рыночную заявку. Property string `json:"property,omitempty"` // Свойства исполнения частично исполненных заявок. Condition *OrderCondition `json:"condition,omitempty"` // Свойства выставления заявок. ValidBefore *OrderValidBefore `json:"validBefore,omitempty"` // Условие по времени действия заявки. }
OrderRequest Запрос на создание заявки.
type OrderStatus ¶
type OrderStatus string
Тип OrderStatus Статус заявки.
const ( OrderStatusNone OrderStatus = "None" // принята сервером TRANSAQ, и заявке присвоен transactionId; OrderStatusActive OrderStatus = "Active" // принята биржей, и заявке присвоен orderNo; OrderStatusMatched OrderStatus = "Matched" // полностью исполнилась (выполнилась); OrderStatusCancelled OrderStatus = "Cancelled" // была отменена (снята) пользователем или биржей. )
type OrderValidBefore ¶
type Portfolio ¶
type Portfolio struct { ClientId string `json:"clientId"` // торговый код клиента; Equity float64 `json:"equity"` // текущая оценка портфеля; Balance float64 `json:"balance"` // входящая оценка стоимости портфеля; Positions []Position `json:"positions"` // позиции портфеля Currencies []Сurrency `json:"currencies"` // валюта портфеля Money []Money `json:"money"` // денежные позиции }
структура Портфеля
type Position ¶
type Position struct { SecurityCode string `json:"securityCode"` // код инструмента Market string `json:"market"` // рынок инструмента. Тип Market; Balance float64 `json:"balance"` // текущая позиция; CurrentPrice float64 `json:"currentPrice"` // текущая цена в валюте инструмента; Equity float64 `json:"equity"` // текущая оценка инструмента; AveragePrice float64 `json:"averagePrice"` // средняя цена; Currency string `json:"currency"` // код валюты риска; AccumulatedProfit float64 `json:"accumulatedProfit"` // прибыль/убыток по входящим; TodayProfit float64 `json:"todayProfit"` // прибыль/убыток по сделкам; UnrealizedProfit float64 `json:"unrealizedProfit"` // нереализованная прибыль/убыток; Profit float64 `json:"profit"` // прибыль/убыток; MaxBuy float64 `json:"maxBuy"` // максимально возможное количество лотов на покупку/продажу (вычисляется, если указать флаг includeMaxBuySell в true, иначе значение будет равно 0); MaxSell float64 `json:"maxSell"` PriceCurrency string `json:"priceCurrency"` // priceCurrency AverageRate float64 `json:"averageRate"` // код валюты балансовой цены; AveragePriceCurrency string `json:"averagePriceCurrency"` // кросс-курс валюты балансовой цены к валюте риска. }
позиции портфеля
type RequestOption ¶
type RequestOption func(*request)
RequestOption define option type for request
func WithHeader ¶
func WithHeader(key, value string, replace bool) RequestOption
WithHeader set or add a header value to the request
func WithHeaders ¶
func WithHeaders(header http.Header) RequestOption
WithHeaders set or replace the headers of the request
type ResponseError ¶
type ResponseError struct { Code string `json:"code"` Message string `json:"message"` Data interface{} `json:"data"` }
структура ошибки
type Security ¶
type Security struct { Code string `json:"code"` // код инструмента; Board string `json:"board"` // основной режим торгов инструмента; Market string `json:"market"` // рынок инструмента. Тип Market; ShortName string `json:"shortName"` // название инструмента; Ticker string `json:"ticker"` // тикер инструмента на биржевой площадке листинга; Decimals int `json:"decimals"` // количество знаков в дробной части цены; LotSize int `json:"lotSize"` // размер лота; MinStep float32 `json:"minStep"` // минимальный шаг цены; Currency string `json:"currency"` // код валюты номинала цены; Properties int `json:"properties"` // параметры инструмента. Значение представлено в виде битовой маски: TimeZoneName string `json:"timeZoneName"` // имя таймзоны; BpCost float64 `json:"bpCost"` // стоимость пункта цены одного инструмента (не лота), без учета НКД; AccruedInterest float64 `json:"accruedInterest"` // текущий НКД; PriceSign string `json:"priceSign"` // допустимая цена инструмента. Принимает следующие значения: LotDivider int `json:"lotDivider"` // коэффициент дробления ценной бумаги в одном стандартном лоте. }
Инструмент
type SecurityService ¶
type SecurityService struct {
// contains filtered or unexported fields
}
SecurityService запросить список инструментов Максимальное Количество запросов в минуту = 1 https://finamweb.github.io/trade-api-docs/rest-api/securities
func (*SecurityService) Board ¶
func (s *SecurityService) Board(board string) *SecurityService
Board set board
func (*SecurityService) Do ¶
func (s *SecurityService) Do(ctx context.Context) ([]Security, error)
Do send request
func (*SecurityService) Symbol ¶
func (s *SecurityService) Symbol(symbol string) *SecurityService
Symbol set symbol
type SideType ¶
type SideType string
тип SideType (BuySell) Определяет тип операции: покупка или продажа.
type TimeInForceType ¶
type TimeInForceType string
условие по времени действия заявки TillEndSession - заявка действует до конца сессии; TillCancelled - заявка действует, пока не будет отменена; ExactTime - заявка действует до указанного времени. Параметр time должен быть задан.
const ( TimeInForceGTC TimeInForceType = "TillCancelled" //"GTC" // Ордер будет находится в очереди до тех пор, пока не будет снят TimeInForceDAY TimeInForceType = "TillEndSession" // "DAY" // Ордер будет действовать только в течение текущего торгового дня (до конца сессии) TimeInForceExactTime TimeInForceType = "ExactTime" // заявка действует до указанного времени. Параметр time должен быть задан. )
func (TimeInForceType) String ¶
func (t TimeInForceType) String() string
type Сurrency ¶
type Сurrency struct { Name string `json:"name"` // код валюты; Equity float64 `json:"equity"` // оценка позиции; Balance float64 `json:"balance"` // текущая позиция; CrossRate float64 `json:"crossRate"` // курс валюты; UnrealizedProfit float64 `json:"unrealizedProfit"` // нереализованная прибыль/убыток. }
валюта портфеля