broker

package
v0.14.1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Overview

Package broker defines the common interface and types shared across all broker adapters.

The central Broker interface provides methods for authentication, quotes, OHLCV data, balance/position queries, and order management. Concrete implementations live under internal/kis (and future brokers).

Types such as Quote, Balance, Position, Instrument, OHLCV, OrderRequest, and OrderResult are broker-agnostic and safe for external use.

Index

Constants

View Source
const (
	CodeKIS    = "kis"
	CodeKiwoom = "kiwoom"
)

Canonical broker identifiers used in config/routes.

View Source
const (
	NameKIS    = "KIS"
	NameKiwoom = "KIWOOM"
)

Broker display names returned by broker implementations.

Variables

View Source
var (
	// ErrUnauthorized indicates authentication failure
	ErrUnauthorized = errors.New("unauthorized")

	// ErrInvalidCredentials indicates invalid credentials
	ErrInvalidCredentials = errors.New("invalid credentials")

	// ErrTokenExpired indicates the token has expired
	ErrTokenExpired = errors.New("token expired")

	// ErrInvalidSymbol indicates an invalid symbol
	ErrInvalidSymbol = errors.New("invalid symbol")

	// ErrInvalidMarket indicates an invalid market
	ErrInvalidMarket = errors.New("invalid market")

	// ErrInsufficientBalance indicates insufficient balance
	ErrInsufficientBalance = errors.New("insufficient balance")

	// ErrOrderNotFound indicates order not found
	ErrOrderNotFound = errors.New("order not found")

	// ErrInstrumentNotFound indicates instrument not found
	ErrInstrumentNotFound = errors.New("instrument not found")

	// ErrInvalidOrderRequest indicates an invalid order request
	ErrInvalidOrderRequest = errors.New("invalid order request")

	// ErrRateLimitExceeded indicates rate limit exceeded
	ErrRateLimitExceeded = errors.New("rate limit exceeded")

	// ErrServerError indicates a server error
	ErrServerError = errors.New("server error")

	// ErrUpstreamBadRequest indicates the upstream API rejected the request
	ErrUpstreamBadRequest = errors.New("upstream bad request")
)

Functions

This section is empty.

Types

type AccountInfo

type AccountInfo struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Broker string `json:"broker"`
}

AccountInfo represents basic account information

type AccountSummary

type AccountSummary struct {
	TotalAssets     float64   `json:"total_assets"`
	TotalCash       float64   `json:"total_cash"`
	TotalProfitLoss float64   `json:"total_profit_loss"`
	Accounts        []Balance `json:"accounts"`
}

AccountSummary represents aggregated balance across multiple accounts

type AssetType

type AssetType string

AssetType represents the type of asset

const (
	AssetStock    AssetType = "stock"
	AssetBond     AssetType = "bond"
	AssetFund     AssetType = "fund"
	AssetCash     AssetType = "cash"
	AssetOverseas AssetType = "overseas"
)

type Balance

type Balance struct {
	AccountID        string  `json:"account_id"`
	Cash             float64 `json:"cash"`
	TotalAssets      float64 `json:"total_assets"`
	BuyingPower      float64 `json:"buying_power"`
	WithdrawableCash float64 `json:"withdrawable_cash,omitempty"`
	ReceivableAmount float64 `json:"receivable_amount,omitempty"`
	ProfitLoss       float64 `json:"profit_loss"`
	ProfitLossPct    float64 `json:"profit_loss_pct"`
	PositionCost     float64 `json:"position_cost,omitempty"`
	PositionValue    float64 `json:"position_value,omitempty"`
	SettlementT1     float64 `json:"settlement_t1,omitempty"`
	Unsettled        float64 `json:"unsettled,omitempty"`
	LoanBalance      float64 `json:"loan_balance,omitempty"`
}

Balance represents account balance

type Broker

type Broker interface {
	// Name returns the broker name
	Name() string

	// Authenticate authenticates with the broker and returns a token
	Authenticate(ctx context.Context, creds Credentials) (*Token, error)

	// GetQuote retrieves a quote for a given market and symbol
	GetQuote(ctx context.Context, market, symbol string) (*Quote, error)

	// GetOHLCV retrieves OHLCV data for a given market and symbol
	GetOHLCV(ctx context.Context, market, symbol string, opts OHLCVOpts) ([]OHLCV, error)

	// GetBalance retrieves account balance
	GetBalance(ctx context.Context, accountID string) (*Balance, error)

	// GetPositions retrieves account positions
	GetPositions(ctx context.Context, accountID string) ([]Position, error)

	// PlaceOrder places a new order
	PlaceOrder(ctx context.Context, req OrderRequest) (*OrderResult, error)

	// CancelOrder cancels an order
	CancelOrder(ctx context.Context, orderID string) error

	// ModifyOrder modifies an existing order
	ModifyOrder(ctx context.Context, orderID string, req ModifyOrderRequest) (*OrderResult, error)
}

Broker is the common interface for all broker adapters

type Credentials

type Credentials struct {
	AppKey    string `json:"app_key"`
	AppSecret string `json:"app_secret"`
}

Credentials holds broker authentication credentials

type Instrument

type Instrument struct {
	Symbol          string    `json:"symbol"`
	Market          string    `json:"market"`
	ISIN            string    `json:"isin,omitempty"`
	Name            string    `json:"name"`
	NameEn          string    `json:"name_en,omitempty"`
	ShortName       string    `json:"short_name,omitempty"`
	Exchange        string    `json:"exchange,omitempty"`
	Currency        string    `json:"currency,omitempty"`
	Country         string    `json:"country,omitempty"`
	AssetType       AssetType `json:"asset_type,omitempty"`
	ProductType     string    `json:"product_type,omitempty"`
	ProductTypeCode string    `json:"product_type_code,omitempty"`
	SecurityGroup   string    `json:"security_group,omitempty"`
	Sector          string    `json:"sector,omitempty"`
	ListedShares    int64     `json:"listed_shares,omitempty"`
	IsListed        bool      `json:"is_listed"`
	IsSuspended     bool      `json:"is_suspended"`
	ListingDate     string    `json:"listing_date,omitempty"`
	DelistingDate   string    `json:"delisting_date,omitempty"`
}

Instrument represents normalized instrument metadata.

type ModifyOrderRequest

type ModifyOrderRequest struct {
	Quantity int64   `json:"quantity,omitempty"`
	Price    float64 `json:"price,omitempty"`
}

ModifyOrderRequest represents an order modification request

type OHLCV

type OHLCV struct {
	Timestamp time.Time `json:"timestamp"`
	Open      float64   `json:"open"`
	High      float64   `json:"high"`
	Low       float64   `json:"low"`
	Close     float64   `json:"close"`
	Volume    int64     `json:"volume"`
}

OHLCV represents candlestick data

type OHLCVOpts

type OHLCVOpts struct {
	Interval string // "1d", "1h", "5m" etc.
	From     time.Time
	To       time.Time
	Limit    int
}

OHLCVOpts options for OHLCV data

type OrderFill

type OrderFill struct {
	OrderID   string    `json:"order_id"`
	Symbol    string    `json:"symbol,omitempty"`
	Market    string    `json:"market,omitempty"`
	Side      string    `json:"side,omitempty"`
	Quantity  int64     `json:"quantity"`
	Price     float64   `json:"price"`
	Amount    float64   `json:"amount,omitempty"`
	Currency  string    `json:"currency,omitempty"`
	FilledAt  time.Time `json:"filled_at,omitempty"`
	RawStatus string    `json:"raw_status,omitempty"`
}

OrderFill represents normalized fill execution data.

type OrderRequest

type OrderRequest struct {
	AccountID string    `json:"account_id"`
	Symbol    string    `json:"symbol"`
	Market    string    `json:"market"`
	Side      OrderSide `json:"side"`
	Type      OrderType `json:"type"`
	Quantity  int64     `json:"quantity"`
	Price     float64   `json:"price,omitempty"`
}

OrderRequest represents a new order request

type OrderResult

type OrderResult struct {
	OrderID        string      `json:"order_id"`
	Status         OrderStatus `json:"status"`
	FilledQuantity int64       `json:"filled_quantity,omitempty"`
	RemainingQty   int64       `json:"remaining_quantity,omitempty"`
	AvgFilledPrice float64     `json:"avg_filled_price,omitempty"`
	RejectedReason string      `json:"rejected_reason,omitempty"`
	Message        string      `json:"message,omitempty"`
	Timestamp      time.Time   `json:"timestamp"`
}

OrderResult represents the result of an order operation

type OrderSide

type OrderSide string

OrderSide represents buy or sell

const (
	OrderSideBuy  OrderSide = "buy"
	OrderSideSell OrderSide = "sell"
)

type OrderStatus

type OrderStatus string

OrderStatus represents order status

const (
	OrderStatusPending   OrderStatus = "pending"
	OrderStatusFilled    OrderStatus = "filled"
	OrderStatusCancelled OrderStatus = "cancelled"
	OrderStatusRejected  OrderStatus = "rejected"
)

type OrderType

type OrderType string

OrderType represents order type

const (
	OrderTypeLimit  OrderType = "limit"
	OrderTypeMarket OrderType = "market"
)

type Position

type Position struct {
	Symbol        string    `json:"symbol"`
	Name          string    `json:"name"`
	Market        string    `json:"market"`
	MarketCode    string    `json:"market_code,omitempty"`
	AssetType     AssetType `json:"asset_type"`
	Quantity      int64     `json:"quantity"`
	OrderableQty  int64     `json:"orderable_qty,omitempty"`
	UnsettledQty  int64     `json:"unsettled_qty,omitempty"`
	TodayBuyQty   int64     `json:"today_buy_qty,omitempty"`
	TodaySellQty  int64     `json:"today_sell_qty,omitempty"`
	AvgPrice      float64   `json:"avg_price"`
	CurrentPrice  float64   `json:"current_price"`
	PurchaseValue float64   `json:"purchase_value,omitempty"`
	MarketValue   float64   `json:"market_value,omitempty"`
	ProfitLoss    float64   `json:"profit_loss"`
	ProfitLossPct float64   `json:"profit_loss_pct"`
	WeightPct     float64   `json:"weight_pct,omitempty"`
	LoanDate      string    `json:"loan_date,omitempty"`
}

Position represents a stock position

type Quote

type Quote struct {
	Symbol      string    `json:"symbol"`
	Market      string    `json:"market"`
	Price       float64   `json:"price"`
	Open        float64   `json:"open"`
	High        float64   `json:"high"`
	Low         float64   `json:"low"`
	Close       float64   `json:"close"`
	PrevClose   float64   `json:"prev_close,omitempty"`
	Change      float64   `json:"change,omitempty"`
	ChangeRate  float64   `json:"change_rate,omitempty"`
	Volume      int64     `json:"volume"`
	Turnover    float64   `json:"turnover,omitempty"`
	UpperLimit  float64   `json:"upper_limit,omitempty"`
	LowerLimit  float64   `json:"lower_limit,omitempty"`
	BidPrice    float64   `json:"bid_price,omitempty"`
	AskPrice    float64   `json:"ask_price,omitempty"`
	BidSize     int64     `json:"bid_size,omitempty"`
	AskSize     int64     `json:"ask_size,omitempty"`
	MarketState string    `json:"market_state,omitempty"`
	Timestamp   time.Time `json:"timestamp"`
}

Quote represents a stock quote

type Token

type Token struct {
	AccessToken string    `json:"access_token"`
	TokenType   string    `json:"token_type"`
	ExpiresAt   time.Time `json:"expires_at"`
}

Token represents an authentication token

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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