finam

package module
v0.0.0-...-8ea3f4a Latest Latest
Warning

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

Go to latest
Published: May 7, 2024 License: MIT Imports: 12 Imported by: 0

README

Библиотека, которая позволяет работать с функционалом Finam Trade API через REST IP брокера Финам из GO

Установка

go get github.com/Ruvad39/go-finam-http

api реализован на текущий момент:

// проверка подлинности токена
AccessTokens(ctx context.Context) (ok bool, err error)
// Посмотреть портфель
GetPortfolio(ctx context.Context, opts ...Option) (Portfolio, error)
// список инструментов (Максимальное Количество запросов в минуту = 1 )
GetSecurity(ctx context.Context, board string, seccode string) ( Securities, error)
// получить свечи
GetCandles(ctx context.Context, board, symbol string, timeFrame TimeFrame, from, to string, count int) ([]Candle, error)
// получить список заявок
GetOrders(ctx context.Context, opts ...Option) ( []Order, error)
// отменить заявку
DeleteOrder(ctx context.Context, transactionId int64) error
// создать новую заявку
// купить по рынку
BuyMarket(ctx context.Context, board, symbol string, lot int32 ) (int64 , error)
// продать по рынку
SellMarket(ctx context.Context, board, symbol string, lot int32 ) (int64 , error)
// выставить лимитную заявку на покупку
BuyLimit(ctx context.Context, board, symbol string, lot int32, price float64 ) (int64 , error)
// выставить лимитную заявку на продажу
SellLimit(ctx context.Context, board, symbol string, lot int32, price float64 ) (int64 , error)

// TODO
// стоп-завки

Примеры

создание клиента
token := "token"
clientId := "client_id"

client, err := finam.NewClient(token, clientId)
if err != nil {
    slog.Error("main", slog.Any("ошибка создания finam.client", err))
}

ctx := context.Background()
// проверка токена
ok, err := client.AccessTokens(ctx)
if err != nil{
slog.Info("main.AccessTokens", "ошибка проверки токена:", err.Error())
return
}
slog.Info("main.AccessTokens", "ok", ok)
Пример получения данных о портфеле
// запрос через создание сервиса
portfolio, err := client.NewGetPortfolioService().
    IncludeCurrencies(true).
    IncludePositions(true).
    IncludeMoney(true).
    IncludeMaxBuySell(true).Do(ctx)

// запрос через вызов метода
//portfolio, err := client.GetPortfolio(ctx,
//    finam.WithIncludePositions(true),
//    finam.WithIncludeCurrencies(true),
//    finam.WithIncludeMoney(true),
//    finam.WithIncludeMaxBuySell(true))

if err != nil {
    slog.Info("main.GetPortfolio", "err", err.Error())
return
}

// баланс счета
slog.Info("Balance", "Equity", portfolio.Equity, "Balance", portfolio.Balance)

// список позиций
for _, pos := range portfolio.Positions {
    slog.Info("position", slog.Any("pos", pos))
}
// список валют счета
slog.Info("portfolio.Currencies", slog.Any("Currencies", portfolio.Currencies))
// список денег
slog.Info("portfolio.Money", slog.Any("Money", portfolio.Money))

Пример получения свечей
board := "TQBR"  // FUT TQBR
symbol := "SBER" // "SiM4"
// дневные свечи
tf := finam.TimeFrame_D1
from, _ := time.Parse("2006-01-02", "2024-03-01")
to, _ := time.Parse("2006-01-02", "2024-04-20")

// через создание сервиса
// candles, err := client.NewCandlesService(board, symbol, tf).StartTime(from).EndTime(to).Do(ctx)

// через вызов метода
candles, err := client.GetCandles(ctx, board, symbol, tf, finam.WithStartTime(from), finam.WithEndTime(to))
if err != nil {
    slog.Info("main.candles", "err", err.Error())
    return
}
slog.Info("GetCandles", "кол-во", len(candles))
//список свечей
for n, candle := range candles {
    slog.Info("candles",
        "row", n,
        "datetime", candle.GetDateTimeToTime().String(),
        "candle", candle.String(),
    )
}

// внутредневные:
// выберем последние 5 минутных свечей
tf = finam.TimeFrame_M1
time_to := time.Now()
count := 5

// через создание сервиса
// candles, err = client.NewCandlesService(board, symbol, tf).EndTime(time_to).Count(count).Do(ctx)

// через вызов метода
candles, err = client.GetCandles(ctx, board, symbol, tf, finam.WithEndTime(time_to), finam.WithCount(count))

if err != nil {
    slog.Info("main.GetCandles", "err", err.Error())
}
slog.Info("GetCandles", "кол-во", len(candles))
//список свечей
for n, candle := range candles {
    slog.Info("candle",
        "row", n,
        "datetime", candle.GetDateTimeToTime().String(),
        "candle", candle.String(),
    )
}

Другие примеры смотрите тут

Многие идеи по организации структуры клиента принадлежат adshao
из его проекта go-binance за что ему большое спасибо

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Moscow = initMoscow()

Functions

func IsAPIError

func IsAPIError(e error) bool

Types

type APIError

type APIError struct {
	ResponseError ResponseError `json:"error"`
}

func (APIError) Error

func (e APIError) Error() string

type CancelOrderService

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

CancelOrderService удалить заявку по ее ID

func (CancelOrderService) Do

Do sends the request.

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) GetClose

func (k *Candle) GetClose() float64

GetClose расчитаем и вернем цену закрытия

func (*Candle) GetDateTime

func (k *Candle) GetDateTime() string

func (*Candle) GetDateTimeToTime

func (k *Candle) GetDateTimeToTime() time.Time

func (*Candle) GetHigh

func (k *Candle) GetHigh() float64

func (*Candle) GetLow

func (k *Candle) GetLow() float64

func (*Candle) GetOpen

func (k *Candle) GetOpen() float64

func (*Candle) GetVolume

func (k *Candle) GetVolume() int64

func (*Candle) String

func (k *Candle) String() string

type Candles

type Candles []Candle //`json:"candles"`

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 NewClient

func NewClient(token, clientId string) *Client

NewClient создание нового клиента

func (*Client) AccessTokens

func (c *Client) AccessTokens(ctx context.Context) (ok bool, err error)

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) BuyMarket

func (c *Client) BuyMarket(ctx context.Context, board, symbol string, lot int32) (int64, error)

BuyMarket купить по рынку

func (*Client) DeleteOrder

func (c *Client) DeleteOrder(ctx context.Context, transactionId int64) error

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) GetOrders

func (c *Client) GetOrders(ctx context.Context, opts ...Option) ([]Order, error)

получить список заявок

func (*Client) GetPortfolio

func (c *Client) GetPortfolio(ctx context.Context, opts ...Option) (Portfolio, error)

GetPortfolio получить данные по портфелю

func (*Client) GetSecurity

func (c *Client) GetSecurity(ctx context.Context, board, symbol string) (Securities, error)

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

func (c *Client) SellMarket(ctx context.Context, board, symbol string, lot int32) (int64, error)

SellMarket продать по рынку

func (*Client) Version

func (c *Client) Version() string

(debug) вернем текущую версию

type CreateOrderService

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

CreateOrderService создать новую заявку (ордер)

func (*CreateOrderService) Do

func (*CreateOrderService) Price

Price установим цену Для рыночной заявки указать значение null (или не передавать это поле). Для условной заявки необходимо указать цену исполнения;

func (*CreateOrderService) Quantity

func (s *CreateOrderService) Quantity(quantity int32) *CreateOrderService

Quantity установим объем заявки в лотах;

func (*CreateOrderService) Side

установим направление ордера

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) Do

func (s *GetOrderService) Do(ctx context.Context) ([]Order, error)

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) 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 WithCount

func WithCount(param int) Option

Limit Для запроса количества свечей

func WithEndTime

func WithEndTime(param time.Time) Option

endTime Для запроса свечей: конечная дата

func WithIncludeActive

func WithIncludeActive(param bool) Option

(true) IncludeActive вернуть активные заявки.

func WithIncludeCanceled

func WithIncludeCanceled(param bool) Option

(true) вернуть отмененные заявки;

func WithIncludeCurrencies

func WithIncludeCurrencies(param bool) Option

(true) запросить информацию по валютам портфеля;

func WithIncludeMatched

func WithIncludeMatched(param bool) Option

(true) вернуть исполненные заявки;

func WithIncludeMaxBuySell

func WithIncludeMaxBuySell(param bool) Option

(true) запросить информацию о максимальном доступном объеме на покупку/продажу.

func WithIncludeMoney

func WithIncludeMoney(param bool) Option

(true) запросить информацию по денежным позициям портфеля;

func WithIncludePositions

func WithIncludePositions(param bool) Option

(true) запросить информацию по позициям портфеля;

func WithStartTime

func WithStartTime(param time.Time) Option

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 OrderValidBefore struct {
	Type string  `json:"type"`
	Time *string `json:"time,omitempty"` // может быть null
}

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 Securities

type Securities []Security //`json:"securities"`

список инструментов

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) Определяет тип операции: покупка или продажа.

const (
	SideBuy  SideType = "Buy"  // покупка,
	SideSell SideType = "Sell" // продажа
)

func (SideType) String

func (side SideType) String() string

type TimeFrame

type TimeFrame string

TimeFrame период свечей

const (
	TimeFrame_M1  TimeFrame = "M1"
	TimeFrame_M5  TimeFrame = "M5"
	TimeFrame_M15 TimeFrame = "M15"
	TimeFrame_H1  TimeFrame = "H1"
	TimeFrame_D1  TimeFrame = "D1"
	TimeFrame_W1  TimeFrame = "W1"
)

func (TimeFrame) IsDay

func (t TimeFrame) IsDay() bool

IsDay вернем признак дневных свечей

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"` // нереализованная прибыль/убыток.
}

валюта портфеля

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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