t212

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: MIT Imports: 14 Imported by: 0

README

t212

Unofficial Go client for the Trading 212 public API.

Disclaimer. This project is not affiliated with, endorsed by, or otherwise connected to Trading 212. The Trading 212 API is in beta and may change without notice; use at your own risk.

Features

  • All non-deprecated endpoints in the spec wrapped: orders, account summary, positions, history (orders / dividends / transactions), metadata (instruments / exchanges), report exports.
  • Background position watcherNewClient starts polling /equity/positions automatically, fires open / close / error callbacks, and exposes a thread-safe Snapshot().
  • Pagination iterators for the cursor-based history endpoints (Go 1.23+ range-over-func).
  • Report poller (WaitForReport) that blocks until a requested CSV export is Finished.
  • Pluggable http.Client / Transport, configurable timeout, custom User-Agent.
  • Generated request/response types come with hand-written safe accessors (*AccountSummary.GetCurrency() string etc.) and constructors (NewMarketRequest("AAPL_US_EQ", 5)).

Install

go get github.com/kludw/t212

Requires Go 1.23+ (uses iter.Seq2).

Getting started

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/kludw/t212"
)

func main() {
    c, err := t212.NewClient(&t212.ClientOpts{
        Env:       "demo", // or "live"
        APIKeyID:  "...",
        APISecret: "...",
    })
    if err != nil {
        log.Fatal(err)
    }
    defer c.Close()

    summary, err := c.AccountSummary(context.Background())
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("account %d (%s) total: %.2f\n",
        summary.GetID(), summary.GetCurrency(), summary.GetTotalValue())
}

Demo and live API keys are issued separately from the Trading 212 dashboard.

Placing orders

order, err := c.PlaceMarketOrder(ctx, t212.NewMarketRequest("AAPL_US_EQ", 5))
// negative quantity sells:
sell, err := c.PlaceMarketOrder(ctx, t212.NewMarketRequest("AAPL_US_EQ", -5))

// limit / stop / stop-limit have similar constructors:
lim, err := c.PlaceLimitOrder(ctx, t212.NewLimitRequest("AAPL_US_EQ", 5, 150, "DAY"))

The Trading 212 API is not idempotent — retrying a failed order request may create duplicates.

Watching positions

The position watcher is owned by the Client and runs from the moment NewClient returns. Wire callbacks via ClientOpts, then read c.Snapshot() whenever you want the latest known set:

c, err := t212.NewClient(&t212.ClientOpts{
    Env: "demo", APIKeyID: "...", APISecret: "...",

    OnPositionOpen:  func(p *t212.Position) { log.Printf("OPEN  %s", p.GetTicker()) },
    OnPositionClose: func(p *t212.Position) { log.Printf("CLOSE %s", p.GetTicker()) },
    OnPollError:     func(err error) { log.Printf("poll: %v", err) },

    WatcherInterval: 5 * time.Second, // optional; default 3s
})
defer c.Close()

for _, p := range c.Snapshot() {
    fmt.Println(p.GetTicker(), p.GetQuantity())
}

Polling errors are passed to OnPollError (if set) and silently retried — the watcher keeps running. Close stops the watcher and waits for its goroutine to exit.

Walking history

The history endpoints are cursor-paginated. Use the *Iter helpers to walk every page:

for order, err := range c.HistoricalOrdersIter(ctx, nil) {
    if err != nil {
        return err // page fetch failed
    }
    process(order)
}

DividendsIter and TransactionsIter work the same way. Filters in the params struct (Ticker, Limit, etc.) are preserved across pages; the Cursor field is overwritten as the iterator advances.

Generating reports

enq, _ := c.RequestReport(ctx, &t212.PublicReportRequest{ /* ... */ })

report, err := c.WaitForReport(ctx, *enq.ReportId, &t212.WaitForReportOpts{
    PollInterval: 30 * time.Second,
    MaxWait:      10 * time.Minute,
})
if err != nil { return err }
fmt.Println(report.GetDownloadLink())

WaitForReport swallows transient ErrRateLimited responses and retries; non-rate-limit errors are returned. MaxWait returns ErrReportTimeout if exceeded.

Custom transports / timeouts

c, err := t212.NewClient(&t212.ClientOpts{
    APIKeyID: "...", APISecret: "...",

    HTTPClient: &http.Client{
        Timeout:   60 * time.Second,
        Transport: myInstrumentedTransport,
    },
    UserAgent: "my-strategy/1.0",
})

If HTTPClient is nil, a fresh client is constructed with RequestTimeout (or DefaultTimeout when zero).

Errors

Endpoint helpers wrap HTTP errors with a sentinel from errors.go. Match with errors.Is:

_, err := c.AccountSummary(ctx)
switch {
case errors.Is(err, t212.ErrUnauthorized):
    // bad credentials
case errors.Is(err, t212.ErrRateLimited):
    // back off and retry
}

Retry / backoff is not built in — wrap calls in your preferred retry loop (or supply an instrumented HTTPClient).

Examples

See example/:

  • example/main.go — minimal smoke test.
  • example/watcher/ — long-running position watcher with callbacks.
  • example/pagination/ — historical-orders iterator.
  • example/report/ — request and wait for a CSV export.

Run any with go run ./example/<name>. Each loads .env (see .env.example).

Pies

The /equity/pies endpoints are marked deprecated upstream and are intentionally not wrapped. File an issue if you need them.

Contributing

See CLAUDE.md for build/test/regen instructions.

Documentation

Overview

Package t212 is a Go client for the Trading 212 public API.

Trading 212's API is currently in beta. See https://docs.trading212.com for the upstream specification.

Package t212 provides primitives to interact with the openapi HTTP API.

Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.7.0 DO NOT EDIT.

Index

Constants

View Source
const (
	AuthWithSecretKeyScopes  authWithSecretKeyContextKey  = "authWithSecretKey.Scopes"
	LegacyApiKeyHeaderScopes legacyApiKeyHeaderContextKey = "legacyApiKeyHeader.Scopes"
)
View Source
const DefaultTimeout = 15 * time.Second

DefaultTimeout is the default per-request HTTP timeout used when a Client is constructed via NewClient with no HTTPClient or RequestTimeout override.

View Source
const DefaultWatcherInterval = 3 * time.Second

DefaultWatcherInterval is the default polling interval for the position watcher.

Variables

View Source
var (
	// ErrNilOpts is returned when ClientOpts is nil.
	ErrNilOpts = errors.New("nil client opts")
	// ErrInvalidEnv is returned when ClientOpts.Env is set to a value
	// other than "demo" or "live" (case-insensitive).
	ErrInvalidEnv = errors.New("invalid env")
	// ErrEmptyAPIKeyID is returned when ClientOpts.APIKeyID is empty.
	ErrEmptyAPIKeyID = errors.New("empty api key id")
	// ErrEmptyAPISecret is returned when ClientOpts.APISecret is empty.
	ErrEmptyAPISecret = errors.New("empty api secret")

	// ErrRequest wraps any failure to build or execute the underlying
	// HTTP request (e.g. transport errors, context cancellation).
	ErrRequest = errors.New("request failed")
	// ErrEncode wraps a JSON marshal failure on the request body.
	ErrEncode = errors.New("encode failed")
	// ErrDecode wraps a JSON unmarshal failure on the response body.
	ErrDecode = errors.New("decode failed")

	// ErrBadRequest is returned for HTTP 400 responses.
	ErrBadRequest = errors.New("bad request")
	// ErrUnauthorized is returned for HTTP 401 responses.
	ErrUnauthorized = errors.New("unauthorized")
	// ErrForbidden is returned for HTTP 403 responses.
	ErrForbidden = errors.New("forbidden")
	// ErrNotFound is returned for HTTP 404 responses.
	ErrNotFound = errors.New("not found")
	// ErrTimeout is returned for HTTP 408 responses.
	ErrTimeout = errors.New("timeout")
	// ErrRateLimited is returned for HTTP 429 responses.
	ErrRateLimited = errors.New("rate limited")
	// ErrUnexpectedStatus is returned for any other non-2xx status.
	ErrUnexpectedStatus = errors.New("unexpected status")

	// ErrReportTimeout is returned by WaitForReport when the configured
	// MaxWait is exceeded before the report reaches "Finished".
	ErrReportTimeout = errors.New("report did not finish before timeout")
)

Sentinel errors returned by the package. Match with errors.Is.

Functions

This section is empty.

Types

type AccountBucketDetailedResponse

type AccountBucketDetailedResponse struct {
	CreationDate       *time.Time                                       `json:"creationDate,omitempty"`
	DividendCashAction *AccountBucketDetailedResponseDividendCashAction `json:"dividendCashAction,omitempty"`
	EndDate            *time.Time                                       `json:"endDate,omitempty"`
	Goal               *float32                                         `json:"goal,omitempty"`
	Icon               *string                                          `json:"icon,omitempty"`
	Id                 *int64                                           `json:"id,omitempty"`
	InitialInvestment  *float32                                         `json:"initialInvestment,omitempty"`
	InstrumentShares   *map[string]float32                              `json:"instrumentShares,omitempty"`
	Name               *string                                          `json:"name,omitempty"`
	PublicUrl          *string                                          `json:"publicUrl,omitempty"`
}

AccountBucketDetailedResponse defines model for AccountBucketDetailedResponse.

type AccountBucketDetailedResponseDividendCashAction

type AccountBucketDetailedResponseDividendCashAction string

AccountBucketDetailedResponseDividendCashAction defines model for AccountBucketDetailedResponse.DividendCashAction.

const (
	AccountBucketDetailedResponseDividendCashActionREINVEST      AccountBucketDetailedResponseDividendCashAction = "REINVEST"
	AccountBucketDetailedResponseDividendCashActionTOACCOUNTCASH AccountBucketDetailedResponseDividendCashAction = "TO_ACCOUNT_CASH"
)

Defines values for AccountBucketDetailedResponseDividendCashAction.

func (AccountBucketDetailedResponseDividendCashAction) Valid

Valid indicates whether the value is a known member of the AccountBucketDetailedResponseDividendCashAction enum.

type AccountBucketInstrumentResult

type AccountBucketInstrumentResult struct {
	CurrentShare  *float32           `json:"currentShare,omitempty"`
	ExpectedShare *float32           `json:"expectedShare,omitempty"`
	Issues        *[]InstrumentIssue `json:"issues,omitempty"`
	OwnedQuantity *float32           `json:"ownedQuantity,omitempty"`
	Result        *InvestmentResult  `json:"result,omitempty"`
	Ticker        *string            `json:"ticker,omitempty"`
}

AccountBucketInstrumentResult defines model for AccountBucketInstrumentResult.

type AccountBucketInstrumentsDetailedResponse

type AccountBucketInstrumentsDetailedResponse struct {
	Instruments *[]AccountBucketInstrumentResult `json:"instruments,omitempty"`
	Settings    *AccountBucketDetailedResponse   `json:"settings,omitempty"`
}

AccountBucketInstrumentsDetailedResponse defines model for AccountBucketInstrumentsDetailedResponse.

type AccountBucketResultResponse

type AccountBucketResultResponse struct {
	// Cash Amount of money put into the pie in account currency
	Cash            *float32         `json:"cash,omitempty"`
	DividendDetails *DividendDetails `json:"dividendDetails,omitempty"`
	Id              *int64           `json:"id,omitempty"`

	// Progress Progress of the pie based on the set goal
	Progress *float32          `json:"progress,omitempty"`
	Result   *InvestmentResult `json:"result,omitempty"`

	// Status Status of the pie based on the set goal
	Status *AccountBucketResultResponseStatus `json:"status,omitempty"`
}

AccountBucketResultResponse defines model for AccountBucketResultResponse.

type AccountBucketResultResponseStatus

type AccountBucketResultResponseStatus string

AccountBucketResultResponseStatus Status of the pie based on the set goal

const (
	AHEAD   AccountBucketResultResponseStatus = "AHEAD"
	BEHIND  AccountBucketResultResponseStatus = "BEHIND"
	ONTRACK AccountBucketResultResponseStatus = "ON_TRACK"
)

Defines values for AccountBucketResultResponseStatus.

func (AccountBucketResultResponseStatus) Valid

Valid indicates whether the value is a known member of the AccountBucketResultResponseStatus enum.

type AccountSummary

type AccountSummary struct {
	Cash *Cash `json:"cash,omitempty"`

	// Currency Primary account currency in ISO 4217 format.
	Currency *string `json:"currency,omitempty"`

	// Id Primary trading account number. This is the same account ID you would see in the Trading 212 web or mobile application.
	Id          *int64       `json:"id,omitempty"`
	Investments *Investments `json:"investments,omitempty"`

	// TotalValue Investments value in your account's primary currency.
	TotalValue *float32 `json:"totalValue,omitempty"`
}

AccountSummary defines model for AccountSummary.

func (*AccountSummary) GetCash added in v0.3.0

func (a *AccountSummary) GetCash() Cash

GetCash returns a copy of the cash breakdown, or a zero Cash if unknown.

func (*AccountSummary) GetCurrency added in v0.3.0

func (a *AccountSummary) GetCurrency() string

GetCurrency returns the account's primary currency, or "" if unknown.

func (*AccountSummary) GetID added in v0.3.0

func (a *AccountSummary) GetID() int64

GetID returns the account ID, or 0 if unknown.

func (*AccountSummary) GetInvestments added in v0.3.0

func (a *AccountSummary) GetInvestments() Investments

GetInvestments returns a copy of the investments breakdown, or a zero Investments if unknown.

func (*AccountSummary) GetTotalValue added in v0.3.0

func (a *AccountSummary) GetTotalValue() float32

GetTotalValue returns the account's total value, or 0 if unknown.

type Cash

type Cash struct {
	// AvailableToTrade Funds available for investing.
	AvailableToTrade *float32 `json:"availableToTrade,omitempty"`

	// InPies It’s the sum of the cash inside of all pies that is not yet invested.
	InPies *float32 `json:"inPies,omitempty"`

	// ReservedForOrders The amount of cash reserved for pending orders. This cash is not available for placing new trades.
	ReservedForOrders *float32 `json:"reservedForOrders,omitempty"`
}

Cash defines model for Cash.

func (*Cash) GetAvailableToTrade added in v0.3.0

func (c *Cash) GetAvailableToTrade() float32

GetAvailableToTrade returns the cash available to trade, or 0.

func (*Cash) GetInPies added in v0.3.0

func (c *Cash) GetInPies() float32

GetInPies returns the uninvested cash held inside pies, or 0.

func (*Cash) GetReservedForOrders added in v0.3.0

func (c *Cash) GetReservedForOrders() float32

GetReservedForOrders returns the cash reserved for pending orders, or 0.

type Client

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

Client is the Trading 212 API client. Construct one via NewClient. The client owns a background goroutine that polls /equity/positions and maintains a snapshot reachable via Snapshot. Call Close when done to stop the goroutine.

func NewClient

func NewClient(opts *ClientOpts) (*Client, error)

NewClient constructs a Client and starts its background position watcher. It performs an initial synchronous Positions fetch so Snapshot returns fresh data on return; transient rate-limit errors during that initial fetch are tolerated, but other errors are returned.

func (*Client) AccountSummary

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

AccountSummary fetches the equity account summary: account ID, primary currency, total value, and the cash and investments breakdown.

GET /api/v0/equity/account/summary (rate limit: 1 req / 5s).

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, id int64) error

CancelOrder requests cancellation of an active order. Cancellation is not guaranteed if the order is already in the process of being filled.

DELETE /api/v0/equity/orders/{id} (rate limit: 50 req / 1m).

func (*Client) Close added in v0.3.0

func (c *Client) Close()

Close stops the background position watcher and waits for it to exit. Subsequent calls are no-ops. Close does not block in-flight API calls initiated by other callers.

func (*Client) Dividends

Dividends fetches a page of dividend history. For ergonomic full-history iteration, see DividendsIter.

GET /api/v0/equity/history/dividends (rate limit: 50 req / 1m).

func (*Client) DividendsIter added in v0.3.0

func (c *Client) DividendsIter(ctx context.Context, params *DividendsParams) iter.Seq2[HistoryDividendItem, error]

DividendsIter returns a Go 1.23+ iterator over every dividend item in the account's history. See HistoricalOrdersIter for shape and semantics.

func (*Client) Exchanges

func (c *Client) Exchanges(ctx context.Context) ([]Exchange, error)

Exchanges fetches exchange metadata, including each exchange's working schedule (market open/close events).

GET /api/v0/equity/metadata/exchanges (rate limit: 1 req / 30s).

func (*Client) HistoricalOrders

func (c *Client) HistoricalOrders(ctx context.Context, params *Orders1Params) (*PaginatedResponseHistoricalOrder, error)

HistoricalOrders fetches a page of historical orders. Use params for cursor-based pagination, ticker filtering, and per-page limit. For ergonomic full-history iteration, see HistoricalOrdersIter.

GET /api/v0/equity/history/orders (rate limit: 50 req / 1m).

func (*Client) HistoricalOrdersIter added in v0.3.0

func (c *Client) HistoricalOrdersIter(ctx context.Context, params *Orders1Params) iter.Seq2[HistoricalOrder, error]

HistoricalOrdersIter returns a Go 1.23+ iterator that walks every page of historical orders, yielding each order one at a time. Iteration stops on the first error or when the caller breaks. The starting page respects the fields in params (cursor, ticker, limit); subsequent pages reuse ticker and limit while advancing cursor.

Example:

for o, err := range client.HistoricalOrdersIter(ctx, nil) {
    if err != nil { return err }
    process(o)
}

func (*Client) Instruments

func (c *Client) Instruments(ctx context.Context) ([]TradableInstrument, error)

Instruments fetches all instruments tradable on the account. The list is large (~5MB) and refreshed every 10 minutes server-side; consider caching.

GET /api/v0/equity/metadata/instruments (rate limit: 1 req / 50s).

func (*Client) OrderByID

func (c *Client) OrderByID(ctx context.Context, id int64) (*Order, error)

OrderByID fetches a single pending order by its numeric ID.

GET /api/v0/equity/orders/{id} (rate limit: 1 req / 1s).

func (*Client) Orders

func (c *Client) Orders(ctx context.Context) ([]Order, error)

Orders fetches all currently active (pending) orders.

GET /api/v0/equity/orders (rate limit: 1 req / 5s).

func (*Client) PlaceLimitOrder

func (c *Client) PlaceLimitOrder(ctx context.Context, req *LimitRequest) (*Order, error)

PlaceLimitOrder places a limit order.

POST /api/v0/equity/orders/limit (rate limit: 1 req / 2s).

func (*Client) PlaceMarketOrder

func (c *Client) PlaceMarketOrder(ctx context.Context, req *MarketRequest) (*Order, error)

PlaceMarketOrder places a market order. A positive Quantity buys; a negative Quantity sells.

Note: the Trading 212 API is not idempotent — sending the same request twice may create duplicate orders.

POST /api/v0/equity/orders/market (rate limit: 50 req / 1m).

func (*Client) PlaceStopLimitOrder

func (c *Client) PlaceStopLimitOrder(ctx context.Context, req *StopLimitRequest) (*Order, error)

PlaceStopLimitOrder places a stop-limit order, which becomes a limit order once StopPrice is reached.

POST /api/v0/equity/orders/stop_limit (rate limit: 1 req / 2s).

func (*Client) PlaceStopOrder

func (c *Client) PlaceStopOrder(ctx context.Context, req *StopRequest) (*Order, error)

PlaceStopOrder places a stop order, which becomes a market order once StopPrice is reached.

POST /api/v0/equity/orders/stop (rate limit: 1 req / 2s).

func (*Client) Positions

func (c *Client) Positions(ctx context.Context, params *GetPositionsParams) ([]Position, error)

Positions fetches all open positions, optionally filtered by ticker via params.Ticker. Pass nil for params to fetch all positions.

GET /api/v0/equity/positions (rate limit: 1 req / 1s).

func (*Client) Reports

func (c *Client) Reports(ctx context.Context) ([]ReportResponse, error)

Reports lists all requested CSV reports and their current status. When a report's status is "Finished", its DownloadLink is populated.

GET /api/v0/equity/history/exports (rate limit: 1 req / 1m).

func (*Client) RequestReport

func (c *Client) RequestReport(ctx context.Context, req *PublicReportRequest) (*EnqueuedReportResponse, error)

RequestReport asynchronously kicks off generation of a CSV report covering the requested data range. Use Reports to poll for completion and obtain the download link, or WaitForReport for a one-shot helper.

POST /api/v0/equity/history/exports (rate limit: 1 req / 30s).

func (*Client) Snapshot added in v0.3.0

func (c *Client) Snapshot() []Position

Snapshot returns the most recently observed open positions, keyed by ticker. The returned slice is a copy and safe to mutate.

func (*Client) Transactions

Transactions fetches a page of cash transactions (deposits, withdrawals, fees, internal transfers). For ergonomic full-history iteration, see TransactionsIter.

GET /api/v0/equity/history/transactions (rate limit: 50 req / 1m).

func (*Client) TransactionsIter added in v0.3.0

func (c *Client) TransactionsIter(ctx context.Context, params *TransactionsParams) iter.Seq2[HistoryTransactionItem, error]

TransactionsIter returns a Go 1.23+ iterator over every cash transaction in the account's history. See HistoricalOrdersIter for shape and semantics.

func (*Client) WaitForReport added in v0.3.0

func (c *Client) WaitForReport(ctx context.Context, reportID int64, opts *WaitForReportOpts) (*ReportResponse, error)

WaitForReport polls the Reports endpoint until the report identified by reportID reaches status "Finished" and returns the final ReportResponse (with DownloadLink populated). Cancellation via ctx is honoured; ErrRateLimited responses are swallowed and retried on the next interval.

type ClientOpts

type ClientOpts struct {
	// Env selects which Trading 212 environment to talk to. Empty defaults to
	// "demo". "live" routes to the production API. Ignored when BaseURL is set.
	Env string

	// BaseURL overrides Env's default URL. Useful for sandboxes, proxies, and
	// tests. Should not include a trailing slash and should already include
	// the API version segment (e.g. http://localhost:8080/api/v0).
	BaseURL string

	// APIKeyID and APISecret authenticate via HTTP Basic.
	APIKeyID  string
	APISecret string

	// UserAgent overrides the default User-Agent. Empty uses defaultUserAgent.
	UserAgent string

	// HTTPClient is the underlying HTTP client used for all requests. If nil,
	// a new http.Client is constructed with timeout RequestTimeout (or
	// DefaultTimeout when RequestTimeout is zero).
	HTTPClient *http.Client

	// RequestTimeout overrides DefaultTimeout when HTTPClient is nil.
	// Ignored when HTTPClient is provided.
	RequestTimeout time.Duration

	// OnPositionOpen and OnPositionClose receive the position whenever the
	// watcher detects a transition. Both are optional — the watcher always
	// runs so Snapshot stays current.
	OnPositionOpen  PositionCallback
	OnPositionClose PositionCallback

	// OnPollError is invoked with any error returned by the watcher's
	// background polling loop. The watcher does not stop on errors.
	OnPollError PollErrorCallback

	// WatcherInterval overrides DefaultWatcherInterval. Must be >= 0; zero
	// uses the default.
	WatcherInterval time.Duration
}

ClientOpts configures a Client. All fields except APIKeyID and APISecret are optional.

func (*ClientOpts) Validate

func (opts *ClientOpts) Validate() error

Validate checks that ClientOpts has the minimum required fields.

type CreateJSONRequestBody

type CreateJSONRequestBody = PieRequest

CreateJSONRequestBody defines body for Create for application/json ContentType.

type DividendDetails

type DividendDetails struct {
	Gained     *float32 `json:"gained,omitempty"`
	InCash     *float32 `json:"inCash,omitempty"`
	Reinvested *float32 `json:"reinvested,omitempty"`
}

DividendDetails defines model for DividendDetails.

type DividendsParams

type DividendsParams struct {
	// Cursor Pagination cursor
	Cursor *int64 `form:"cursor,omitempty" json:"cursor,omitempty"`

	// Ticker Ticker filter
	Ticker *string `form:"ticker,omitempty" json:"ticker,omitempty"`

	// Limit Max items: 50
	Limit *int32 `form:"limit,omitempty" json:"limit,omitempty"`
}

DividendsParams defines parameters for Dividends.

type DuplicateBucketRequest

type DuplicateBucketRequest struct {
	Icon *string `json:"icon,omitempty"`
	Name *string `json:"name,omitempty"`
}

DuplicateBucketRequest defines model for DuplicateBucketRequest.

type DuplicatePieJSONRequestBody

type DuplicatePieJSONRequestBody = DuplicateBucketRequest

DuplicatePieJSONRequestBody defines body for DuplicatePie for application/json ContentType.

type EnqueuedReportResponse

type EnqueuedReportResponse struct {
	ReportId *int64 `json:"reportId,omitempty"`
}

EnqueuedReportResponse defines model for EnqueuedReportResponse.

type Exchange

type Exchange struct {
	Id               *int64             `json:"id,omitempty"`
	Name             *string            `json:"name,omitempty"`
	WorkingSchedules *[]WorkingSchedule `json:"workingSchedules,omitempty"`
}

Exchange defines model for Exchange.

type Fill

type Fill struct {
	FilledAt      *time.Time         `json:"filledAt,omitempty"`
	Id            *int64             `json:"id,omitempty"`
	Price         *float32           `json:"price,omitempty"`
	Quantity      *float32           `json:"quantity,omitempty"`
	TradingMethod *FillTradingMethod `json:"tradingMethod,omitempty"`
	Type          *FillType          `json:"type,omitempty"`
	WalletImpact  *FillWalletImpact  `json:"walletImpact,omitempty"`
}

Fill defines model for Fill.

type FillTradingMethod

type FillTradingMethod string

FillTradingMethod defines model for Fill.TradingMethod.

const (
	OTC  FillTradingMethod = "OTC"
	TOTV FillTradingMethod = "TOTV"
)

Defines values for FillTradingMethod.

func (FillTradingMethod) Valid

func (e FillTradingMethod) Valid() bool

Valid indicates whether the value is a known member of the FillTradingMethod enum.

type FillType

type FillType string

FillType defines model for Fill.Type.

const (
	CASHANDSTOCKACQUISITION FillType = "CASH_AND_STOCK_ACQUISITION"
	CUSTOMSTOCKDISTRIBUTION FillType = "CUSTOM_STOCK_DISTRIBUTION"
	EQUITYRIGHTS            FillType = "EQUITY_RIGHTS"
	FOP                     FillType = "FOP"
	FOPCORRECTION           FillType = "FOP_CORRECTION"
	SCRIPSTOCKDIVIDENDS     FillType = "SCRIP_STOCK_DIVIDENDS"
	SPINOFF                 FillType = "SPIN_OFF"
	STOCKACQUISITION        FillType = "STOCK_ACQUISITION"
	STOCKDISTRIBUTION       FillType = "STOCK_DISTRIBUTION"
	STOCKDIVIDENDS          FillType = "STOCK_DIVIDENDS"
	STOCKSPLIT              FillType = "STOCK_SPLIT"
	TRADE                   FillType = "TRADE"
)

Defines values for FillType.

func (FillType) Valid

func (e FillType) Valid() bool

Valid indicates whether the value is a known member of the FillType enum.

type FillWalletImpact

type FillWalletImpact struct {
	Currency           *string  `json:"currency,omitempty"`
	FxRate             *float32 `json:"fxRate,omitempty"`
	NetValue           *float32 `json:"netValue,omitempty"`
	RealisedProfitLoss *float32 `json:"realisedProfitLoss,omitempty"`
	Taxes              *[]Tax   `json:"taxes,omitempty"`
}

FillWalletImpact defines model for FillWalletImpact.

type GetPositionsParams

type GetPositionsParams struct {
	Ticker *string `form:"ticker,omitempty" json:"ticker,omitempty"`
}

GetPositionsParams defines parameters for GetPositions.

type HistoricalOrder

type HistoricalOrder struct {
	Fill  *Fill  `json:"fill,omitempty"`
	Order *Order `json:"order,omitempty"`
}

HistoricalOrder defines model for HistoricalOrder.

type HistoryDividendItem

type HistoryDividendItem struct {
	// Amount In account's primary currency.
	Amount       *float32 `json:"amount,omitempty"`
	AmountInEuro *float32 `json:"amountInEuro,omitempty"`

	// Currency The account's primary currency.
	Currency *string `json:"currency,omitempty"`

	// GrossAmountPerShare In instrument currency
	GrossAmountPerShare *float32 `json:"grossAmountPerShare,omitempty"`

	// Instrument Instrument information as given by /instruments endpoint.
	Instrument     *Instrument              `json:"instrument,omitempty"`
	PaidOn         *time.Time               `json:"paidOn,omitempty"`
	Quantity       *float32                 `json:"quantity,omitempty"`
	Reference      *string                  `json:"reference,omitempty"`
	Ticker         *string                  `json:"ticker,omitempty"`
	TickerCurrency *string                  `json:"tickerCurrency,omitempty"`
	Type           *HistoryDividendItemType `json:"type,omitempty"`
}

HistoryDividendItem defines model for HistoryDividendItem.

type HistoryDividendItemType

type HistoryDividendItemType string

HistoryDividendItemType defines model for HistoryDividendItem.Type.

const (
	BONUS                                                             HistoryDividendItemType = "BONUS"
	BONUSMANUFACTUREDPAYMENT                                          HistoryDividendItemType = "BONUS_MANUFACTURED_PAYMENT"
	CAPITALGAINS                                                      HistoryDividendItemType = "CAPITAL_GAINS"
	CAPITALGAINSDISTRIBUTION                                          HistoryDividendItemType = "CAPITAL_GAINS_DISTRIBUTION"
	CAPITALGAINSDISTRIBUTIONMANUFACTUREDPAYMENT                       HistoryDividendItemType = "CAPITAL_GAINS_DISTRIBUTION_MANUFACTURED_PAYMENT"
	CAPITALGAINSDISTRIBUTIONNONUS                                     HistoryDividendItemType = "CAPITAL_GAINS_DISTRIBUTION_NON_US"
	CAPITALGAINSDISTRIBUTIONNONUSMANUFACTUREDPAYMENT                  HistoryDividendItemType = "CAPITAL_GAINS_DISTRIBUTION_NON_US_MANUFACTURED_PAYMENT"
	CAPITALGAINSMANUFACTUREDPAYMENT                                   HistoryDividendItemType = "CAPITAL_GAINS_MANUFACTURED_PAYMENT"
	DEMERGER                                                          HistoryDividendItemType = "DEMERGER"
	DEMERGERMANUFACTUREDPAYMENT                                       HistoryDividendItemType = "DEMERGER_MANUFACTURED_PAYMENT"
	DIVIDEND                                                          HistoryDividendItemType = "DIVIDEND"
	DIVIDENDMANUFACTUREDPAYMENT                                       HistoryDividendItemType = "DIVIDEND_MANUFACTURED_PAYMENT"
	DIVIDENDSPAIDBYFOREIGNCORPORATIONS                                HistoryDividendItemType = "DIVIDENDS_PAID_BY_FOREIGN_CORPORATIONS"
	DIVIDENDSPAIDBYFOREIGNCORPORATIONSMANUFACTUREDPAYMENT             HistoryDividendItemType = "DIVIDENDS_PAID_BY_FOREIGN_CORPORATIONS_MANUFACTURED_PAYMENT"
	DIVIDENDSPAIDBYUSCORPORATIONS                                     HistoryDividendItemType = "DIVIDENDS_PAID_BY_US_CORPORATIONS"
	DIVIDENDSPAIDBYUSCORPORATIONSMANUFACTUREDPAYMENT                  HistoryDividendItemType = "DIVIDENDS_PAID_BY_US_CORPORATIONS_MANUFACTURED_PAYMENT"
	INTEREST                                                          HistoryDividendItemType = "INTEREST"
	INTERESTMANUFACTUREDPAYMENT                                       HistoryDividendItemType = "INTEREST_MANUFACTURED_PAYMENT"
	INTERESTPAIDBYFOREIGNCORPORATIONS                                 HistoryDividendItemType = "INTEREST_PAID_BY_FOREIGN_CORPORATIONS"
	INTERESTPAIDBYFOREIGNCORPORATIONSMANUFACTUREDPAYMENT              HistoryDividendItemType = "INTEREST_PAID_BY_FOREIGN_CORPORATIONS_MANUFACTURED_PAYMENT"
	INTERESTPAIDBYUSOBLIGORS                                          HistoryDividendItemType = "INTEREST_PAID_BY_US_OBLIGORS"
	INTERESTPAIDBYUSOBLIGORSMANUFACTUREDPAYMENT                       HistoryDividendItemType = "INTEREST_PAID_BY_US_OBLIGORS_MANUFACTURED_PAYMENT"
	INTERIMLIQUIDATION                                                HistoryDividendItemType = "INTERIM_LIQUIDATION"
	INTERIMLIQUIDATIONMANUFACTUREDPAYMENT                             HistoryDividendItemType = "INTERIM_LIQUIDATION_MANUFACTURED_PAYMENT"
	LONGTERMCAPITALGAINS                                              HistoryDividendItemType = "LONG_TERM_CAPITAL_GAINS"
	LONGTERMCAPITALGAINSMANUFACTUREDPAYMENT                           HistoryDividendItemType = "LONG_TERM_CAPITAL_GAINS_MANUFACTURED_PAYMENT"
	MULTIPLE1042STAXCOMPONENTS                                        HistoryDividendItemType = "MULTIPLE_1042S_TAX_COMPONENTS"
	MULTIPLE1042STAXCOMPONENTSMANUFACTUREDPAYMENT                     HistoryDividendItemType = "MULTIPLE_1042S_TAX_COMPONENTS_MANUFACTURED_PAYMENT"
	ORDINARY                                                          HistoryDividendItemType = "ORDINARY"
	ORDINARYMANUFACTUREDPAYMENT                                       HistoryDividendItemType = "ORDINARY_MANUFACTURED_PAYMENT"
	OTHERDIVIDENDEQUIVALENT                                           HistoryDividendItemType = "OTHER_DIVIDEND_EQUIVALENT"
	OTHERDIVIDENDEQUIVALENTMANUFACTUREDPAYMENT                        HistoryDividendItemType = "OTHER_DIVIDEND_EQUIVALENT_MANUFACTURED_PAYMENT"
	OTHERINCOME                                                       HistoryDividendItemType = "OTHER_INCOME"
	OTHERINCOMEMANUFACTUREDPAYMENT                                    HistoryDividendItemType = "OTHER_INCOME_MANUFACTURED_PAYMENT"
	PROPERTYINCOME                                                    HistoryDividendItemType = "PROPERTY_INCOME"
	PROPERTYINCOMEDISTRIBUTION                                        HistoryDividendItemType = "PROPERTY_INCOME_DISTRIBUTION"
	PROPERTYINCOMEDISTRIBUTIONMANUFACTUREDPAYMENT                     HistoryDividendItemType = "PROPERTY_INCOME_DISTRIBUTION_MANUFACTURED_PAYMENT"
	PROPERTYINCOMEMANUFACTUREDPAYMENT                                 HistoryDividendItemType = "PROPERTY_INCOME_MANUFACTURED_PAYMENT"
	PTPUNCHARACTERISEDINCOME                                          HistoryDividendItemType = "PTP_UNCHARACTERISED_INCOME"
	PTPUNCHARACTERISEDINCOMEMANUFACTUREDPAYMENT                       HistoryDividendItemType = "PTP_UNCHARACTERISED_INCOME_MANUFACTURED_PAYMENT"
	PUBLICLYTRADEDPARTNERSHIPDISTRIBUTION                             HistoryDividendItemType = "PUBLICLY_TRADED_PARTNERSHIP_DISTRIBUTION"
	PUBLICLYTRADEDPARTNERSHIPDISTRIBUTIONMANUFACTUREDPAYMENT          HistoryDividendItemType = "PUBLICLY_TRADED_PARTNERSHIP_DISTRIBUTION_MANUFACTURED_PAYMENT"
	QUALIFIEDINVESTMENTENTITY                                         HistoryDividendItemType = "QUALIFIED_INVESTMENT_ENTITY"
	QUALIFIEDINVESTMENTENTITYMANUFACTUREDPAYMENT                      HistoryDividendItemType = "QUALIFIED_INVESTMENT_ENTITY_MANUFACTURED_PAYMENT"
	REALPROPERTYINCOMEANDNATURALRESOURCESROYALTIES                    HistoryDividendItemType = "REAL_PROPERTY_INCOME_AND_NATURAL_RESOURCES_ROYALTIES"
	REALPROPERTYINCOMEANDNATURALRESOURCESROYALTIESMANUFACTUREDPAYMENT HistoryDividendItemType = "REAL_PROPERTY_INCOME_AND_NATURAL_RESOURCES_ROYALTIES_MANUFACTURED_PAYMENT"
	RETURNOFCAPITAL                                                   HistoryDividendItemType = "RETURN_OF_CAPITAL"
	RETURNOFCAPITALMANUFACTUREDPAYMENT                                HistoryDividendItemType = "RETURN_OF_CAPITAL_MANUFACTURED_PAYMENT"
	RETURNOFCAPITALNONUS                                              HistoryDividendItemType = "RETURN_OF_CAPITAL_NON_US"
	RETURNOFCAPITALNONUSMANUFACTUREDPAYMENT                           HistoryDividendItemType = "RETURN_OF_CAPITAL_NON_US_MANUFACTURED_PAYMENT"
	SHORTTERMCAPITALGAINS                                             HistoryDividendItemType = "SHORT_TERM_CAPITAL_GAINS"
	SHORTTERMCAPITALGAINSMANUFACTUREDPAYMENT                          HistoryDividendItemType = "SHORT_TERM_CAPITAL_GAINS_MANUFACTURED_PAYMENT"
	TAXEVENT1446FFORPUBLICLYTRADEDSECURITIES                          HistoryDividendItemType = "TAX_EVENT_1446F_FOR_PUBLICLY_TRADED_SECURITIES"
	TAXEVENT1446FFORPUBLICLYTRADEDSECURITIESMANUFACTUREDPAYMENT       HistoryDividendItemType = "TAX_EVENT_1446F_FOR_PUBLICLY_TRADED_SECURITIES_MANUFACTURED_PAYMENT"
	TAXEXEMPTED                                                       HistoryDividendItemType = "TAX_EXEMPTED"
	TAXEXEMPTEDMANUFACTUREDPAYMENT                                    HistoryDividendItemType = "TAX_EXEMPTED_MANUFACTURED_PAYMENT"
	TRUSTDISTRIBUTION                                                 HistoryDividendItemType = "TRUST_DISTRIBUTION"
	TRUSTDISTRIBUTIONMANUFACTUREDPAYMENT                              HistoryDividendItemType = "TRUST_DISTRIBUTION_MANUFACTURED_PAYMENT"
)

Defines values for HistoryDividendItemType.

func (HistoryDividendItemType) Valid

func (e HistoryDividendItemType) Valid() bool

Valid indicates whether the value is a known member of the HistoryDividendItemType enum.

type HistoryTransactionItem

type HistoryTransactionItem struct {
	// Amount Amount in the currency of the transaction
	Amount *float32 `json:"amount,omitempty"`

	// Currency Currency of the transaction
	Currency *string    `json:"currency,omitempty"`
	DateTime *time.Time `json:"dateTime,omitempty"`

	// Reference ID
	Reference *string                     `json:"reference,omitempty"`
	Type      *HistoryTransactionItemType `json:"type,omitempty"`
}

HistoryTransactionItem defines model for HistoryTransactionItem.

type HistoryTransactionItemType

type HistoryTransactionItemType string

HistoryTransactionItemType defines model for HistoryTransactionItem.Type.

const (
	DEPOSIT  HistoryTransactionItemType = "DEPOSIT"
	FEE      HistoryTransactionItemType = "FEE"
	TRANSFER HistoryTransactionItemType = "TRANSFER"
	WITHDRAW HistoryTransactionItemType = "WITHDRAW"
)

Defines values for HistoryTransactionItemType.

func (HistoryTransactionItemType) Valid

func (e HistoryTransactionItemType) Valid() bool

Valid indicates whether the value is a known member of the HistoryTransactionItemType enum.

type Instrument

type Instrument struct {
	// Currency Instrument currency in ISO 4217 format.
	Currency *string `json:"currency,omitempty"`

	// Isin ISIN of the instrument.
	Isin *string `json:"isin,omitempty"`

	// Name Name of the instrument.
	Name *string `json:"name,omitempty"`

	// Ticker Unique instrument identifier.
	Ticker *string `json:"ticker,omitempty"`
}

Instrument Instrument information as given by /instruments endpoint.

func (*Instrument) GetCurrency added in v0.3.0

func (i *Instrument) GetCurrency() string

GetCurrency returns the instrument currency, or "" if unknown.

func (*Instrument) GetIsin added in v0.3.0

func (i *Instrument) GetIsin() string

GetIsin returns the instrument ISIN, or "" if unknown.

func (*Instrument) GetName added in v0.3.0

func (i *Instrument) GetName() string

GetName returns the instrument name, or "" if unknown.

func (*Instrument) GetTicker added in v0.3.0

func (i *Instrument) GetTicker() string

GetTicker returns the instrument ticker, or "" if unknown.

type InstrumentIssue

type InstrumentIssue struct {
	Name     *InstrumentIssueName     `json:"name,omitempty"`
	Severity *InstrumentIssueSeverity `json:"severity,omitempty"`
}

InstrumentIssue defines model for InstrumentIssue.

type InstrumentIssueName

type InstrumentIssueName string

InstrumentIssueName defines model for InstrumentIssue.Name.

const (
	APPROACHINGMAXPOSITIONSIZE       InstrumentIssueName = "APPROACHING_MAX_POSITION_SIZE"
	COMPLEXINSTRUMENTAPPTESTREQUIRED InstrumentIssueName = "COMPLEX_INSTRUMENT_APP_TEST_REQUIRED"
	DELISTED                         InstrumentIssueName = "DELISTED"
	MAXPOSITIONSIZEREACHED           InstrumentIssueName = "MAX_POSITION_SIZE_REACHED"
	NOLONGERTRADABLE                 InstrumentIssueName = "NO_LONGER_TRADABLE"
	PRICETOOLOW                      InstrumentIssueName = "PRICE_TOO_LOW"
	SUSPENDED                        InstrumentIssueName = "SUSPENDED"
)

Defines values for InstrumentIssueName.

func (InstrumentIssueName) Valid

func (e InstrumentIssueName) Valid() bool

Valid indicates whether the value is a known member of the InstrumentIssueName enum.

type InstrumentIssueSeverity

type InstrumentIssueSeverity string

InstrumentIssueSeverity defines model for InstrumentIssue.Severity.

const (
	INFORMATIVE  InstrumentIssueSeverity = "INFORMATIVE"
	IRREVERSIBLE InstrumentIssueSeverity = "IRREVERSIBLE"
	REVERSIBLE   InstrumentIssueSeverity = "REVERSIBLE"
)

Defines values for InstrumentIssueSeverity.

func (InstrumentIssueSeverity) Valid

func (e InstrumentIssueSeverity) Valid() bool

Valid indicates whether the value is a known member of the InstrumentIssueSeverity enum.

type InvestmentResult

type InvestmentResult struct {
	PriceAvgInvestedValue *float32 `json:"priceAvgInvestedValue,omitempty"`
	PriceAvgResult        *float32 `json:"priceAvgResult,omitempty"`
	PriceAvgResultCoef    *float32 `json:"priceAvgResultCoef,omitempty"`
	PriceAvgValue         *float32 `json:"priceAvgValue,omitempty"`
}

InvestmentResult defines model for InvestmentResult.

type Investments

type Investments struct {
	// CurrentValue Current value of all the investments.
	CurrentValue *float32 `json:"currentValue,omitempty"`

	// RealizedProfitLoss The all-time realised profit loss from all of the trades executed.
	RealizedProfitLoss *float32 `json:"realizedProfitLoss,omitempty"`

	// TotalCost The cost basis of your current investments. The total amount of funds you've invested in the shares you currently own.
	TotalCost *float32 `json:"totalCost,omitempty"`

	// UnrealizedProfitLoss The potential profit/loss of your current investments, showing how much you could gain or lose if you were to sell them now.
	UnrealizedProfitLoss *float32 `json:"unrealizedProfitLoss,omitempty"`
}

Investments defines model for Investments.

type LimitRequest

type LimitRequest struct {
	LimitPrice *float32 `json:"limitPrice,omitempty"`
	Quantity   *float32 `json:"quantity,omitempty"`
	Ticker     *string  `json:"ticker,omitempty"`

	// TimeValidity Specifies how long the order remains active:
	// * DAY: The order will automatically expire if not executed by midnight in the time zone of the instrument's exchange.
	// * GOOD_TILL_CANCEL: The order remains active indefinitely until it is either filled or explicitly cancelled by you.
	TimeValidity *TimeValidity `json:"timeValidity,omitempty"`
}

LimitRequest defines model for LimitRequest.

func NewLimitRequest added in v0.3.0

func NewLimitRequest(ticker string, quantity, limitPrice float32, validity TimeValidity) *LimitRequest

NewLimitRequest builds a LimitRequest with the required fields set.

type MarketRequest

type MarketRequest struct {
	ExtendedHours *bool    `json:"extendedHours,omitempty"`
	Quantity      *float32 `json:"quantity,omitempty"`
	Ticker        *string  `json:"ticker,omitempty"`
}

MarketRequest defines model for MarketRequest.

func NewMarketRequest added in v0.3.0

func NewMarketRequest(ticker string, quantity float32) *MarketRequest

NewMarketRequest builds a MarketRequest with the required fields set. A positive quantity buys; a negative quantity sells.

type Order

type Order struct {
	// CreatedAt The ISO 8601 formatted date of when the order was created.
	CreatedAt *time.Time `json:"createdAt,omitempty"`

	// Currency The currency used for the order in ISO 4217 format.
	Currency *string `json:"currency,omitempty"`

	// ExtendedHours If true, the order is eligible for execution outside regular trading hours.
	ExtendedHours *bool `json:"extendedHours,omitempty"`

	// FilledQuantity The number of shares that have been successfully executed. Applicable to quantity orders.
	FilledQuantity *float32 `json:"filledQuantity,omitempty"`

	// FilledValue The total monetary value of the executed portion of the order. Applicable to orders placed by value.Note: Placing orders by value is not currently supported via the API but can be done through other Trading 212 platforms.
	FilledValue *float32 `json:"filledValue,omitempty"`

	// Id A unique, system-generated identifier for the order.
	Id *int64 `json:"id,omitempty"`

	// InitiatedFrom How the order was initiated.
	InitiatedFrom *OrderInitiatedFrom `json:"initiatedFrom,omitempty"`

	// Instrument Instrument information as given by /instruments endpoint.
	Instrument *Instrument `json:"instrument,omitempty"`

	// LimitPrice Applicable to LIMIT and STOP_LIMIT orders.
	LimitPrice *float32 `json:"limitPrice,omitempty"`

	// Quantity The total number of shares requested. Applicable to quantity orders.
	Quantity *float32 `json:"quantity,omitempty"`

	// Side Indicates whether the order is BUY or SELL.
	Side *OrderSide `json:"side,omitempty"`

	// Status The current state of the order in its lifecycle.
	Status *OrderStatus `json:"status,omitempty"`

	// StopPrice Applicable to STOP and STOP_LIMIT orders.
	StopPrice *float32 `json:"stopPrice,omitempty"`

	// Strategy The strategy used to place the order, either by QUANTITY or VALUE. The API currently only supports placing orders by QUANTITY.
	Strategy *OrderStrategy `json:"strategy,omitempty"`

	// Ticker Unique instrument identifier. Get from the /instruments endpoint
	Ticker *string `json:"ticker,omitempty"`

	// TimeInForce Specifies how long the order remains active:
	// * DAY: The order will automatically expire if not executed by midnight in the time zone of the instrument's exchange.
	// * GOOD_TILL_CANCEL: The order remains active indefinitely until it is either filled or explicitly cancelled by you.
	TimeInForce *TimeValidity `json:"timeInForce,omitempty"`
	Type        *OrderType    `json:"type,omitempty"`

	// Value The total monetary value of the order. Applicable to value orders.
	Value *float32 `json:"value,omitempty"`
}

Order defines model for Order.

func (*Order) GetCreatedAt added in v0.3.0

func (o *Order) GetCreatedAt() time.Time

GetCreatedAt returns when the order was created, or the zero time.

func (*Order) GetFilledQuantity added in v0.3.0

func (o *Order) GetFilledQuantity() float32

GetFilledQuantity returns how many shares of the order have filled, or 0.

func (*Order) GetID added in v0.3.0

func (o *Order) GetID() int64

GetID returns the order ID, or 0 if unknown.

func (*Order) GetQuantity added in v0.3.0

func (o *Order) GetQuantity() float32

GetQuantity returns the order's requested share quantity, or 0.

func (*Order) GetSide added in v0.3.0

func (o *Order) GetSide() OrderSide

GetSide returns the order side (BUY / SELL), or "" if unknown.

func (*Order) GetStatus added in v0.3.0

func (o *Order) GetStatus() OrderStatus

GetStatus returns the order status, or "" if unknown.

func (*Order) GetTicker added in v0.3.0

func (o *Order) GetTicker() string

GetTicker returns the order's instrument ticker, or "" if unknown.

func (*Order) GetType added in v0.3.0

func (o *Order) GetType() OrderType

GetType returns the order type, or "" if unknown.

type OrderInitiatedFrom

type OrderInitiatedFrom string

OrderInitiatedFrom How the order was initiated.

const (
	ANDROID              OrderInitiatedFrom = "ANDROID"
	API                  OrderInitiatedFrom = "API"
	AUTOINVEST           OrderInitiatedFrom = "AUTOINVEST"
	INSTRUMENTAUTOINVEST OrderInitiatedFrom = "INSTRUMENT_AUTOINVEST"
	IOS                  OrderInitiatedFrom = "IOS"
	SYSTEM               OrderInitiatedFrom = "SYSTEM"
	WEB                  OrderInitiatedFrom = "WEB"
)

Defines values for OrderInitiatedFrom.

func (OrderInitiatedFrom) Valid

func (e OrderInitiatedFrom) Valid() bool

Valid indicates whether the value is a known member of the OrderInitiatedFrom enum.

type OrderSide

type OrderSide string

OrderSide Indicates whether the order is BUY or SELL.

const (
	BUY  OrderSide = "BUY"
	SELL OrderSide = "SELL"
)

Defines values for OrderSide.

func (OrderSide) Valid

func (e OrderSide) Valid() bool

Valid indicates whether the value is a known member of the OrderSide enum.

type OrderStatus

type OrderStatus string

OrderStatus The current state of the order in its lifecycle.

const (
	CANCELLED       OrderStatus = "CANCELLED"
	CANCELLING      OrderStatus = "CANCELLING"
	CONFIRMED       OrderStatus = "CONFIRMED"
	FILLED          OrderStatus = "FILLED"
	LOCAL           OrderStatus = "LOCAL"
	NEW             OrderStatus = "NEW"
	PARTIALLYFILLED OrderStatus = "PARTIALLY_FILLED"
	REJECTED        OrderStatus = "REJECTED"
	REPLACED        OrderStatus = "REPLACED"
	REPLACING       OrderStatus = "REPLACING"
	UNCONFIRMED     OrderStatus = "UNCONFIRMED"
)

Defines values for OrderStatus.

func (OrderStatus) Valid

func (e OrderStatus) Valid() bool

Valid indicates whether the value is a known member of the OrderStatus enum.

type OrderStrategy

type OrderStrategy string

OrderStrategy The strategy used to place the order, either by QUANTITY or VALUE. The API currently only supports placing orders by QUANTITY.

const (
	QUANTITY OrderStrategy = "QUANTITY"
	VALUE    OrderStrategy = "VALUE"
)

Defines values for OrderStrategy.

func (OrderStrategy) Valid

func (e OrderStrategy) Valid() bool

Valid indicates whether the value is a known member of the OrderStrategy enum.

type OrderType

type OrderType string

OrderType defines model for Order.Type.

const (
	LIMIT     OrderType = "LIMIT"
	MARKET    OrderType = "MARKET"
	STOP      OrderType = "STOP"
	STOPLIMIT OrderType = "STOP_LIMIT"
)

Defines values for OrderType.

func (OrderType) Valid

func (e OrderType) Valid() bool

Valid indicates whether the value is a known member of the OrderType enum.

type Orders1Params

type Orders1Params struct {
	// Cursor Pagination cursor
	Cursor *int64 `form:"cursor,omitempty" json:"cursor,omitempty"`

	// Ticker Ticker filter
	Ticker *string `form:"ticker,omitempty" json:"ticker,omitempty"`

	// Limit Max items: 50
	Limit *int32 `form:"limit,omitempty" json:"limit,omitempty"`
}

Orders1Params defines parameters for Orders1.

type PaginatedResponseHistoricalOrder

type PaginatedResponseHistoricalOrder struct {
	Items        *[]HistoricalOrder `json:"items,omitempty"`
	NextPagePath *string            `json:"nextPagePath,omitempty"`
}

PaginatedResponseHistoricalOrder defines model for PaginatedResponseHistoricalOrder.

type PaginatedResponseHistoryDividendItem

type PaginatedResponseHistoryDividendItem struct {
	Items        *[]HistoryDividendItem `json:"items,omitempty"`
	NextPagePath *string                `json:"nextPagePath,omitempty"`
}

PaginatedResponseHistoryDividendItem defines model for PaginatedResponseHistoryDividendItem.

type PaginatedResponseHistoryTransactionItem

type PaginatedResponseHistoryTransactionItem struct {
	Items        *[]HistoryTransactionItem `json:"items,omitempty"`
	NextPagePath *string                   `json:"nextPagePath,omitempty"`
}

PaginatedResponseHistoryTransactionItem defines model for PaginatedResponseHistoryTransactionItem.

type PieRequest

type PieRequest struct {
	DividendCashAction *PieRequestDividendCashAction `json:"dividendCashAction,omitempty"`
	EndDate            *time.Time                    `json:"endDate,omitempty"`

	// Goal Total desired value of the pie in account currency
	Goal             *float32            `json:"goal,omitempty"`
	Icon             *string             `json:"icon,omitempty"`
	InstrumentShares *map[string]float32 `json:"instrumentShares,omitempty"`
	Name             *string             `json:"name,omitempty"`
}

PieRequest defines model for PieRequest.

type PieRequestDividendCashAction

type PieRequestDividendCashAction string

PieRequestDividendCashAction defines model for PieRequest.DividendCashAction.

const (
	PieRequestDividendCashActionREINVEST      PieRequestDividendCashAction = "REINVEST"
	PieRequestDividendCashActionTOACCOUNTCASH PieRequestDividendCashAction = "TO_ACCOUNT_CASH"
)

Defines values for PieRequestDividendCashAction.

func (PieRequestDividendCashAction) Valid

Valid indicates whether the value is a known member of the PieRequestDividendCashAction enum.

type PlaceLimitOrderJSONRequestBody

type PlaceLimitOrderJSONRequestBody = LimitRequest

PlaceLimitOrderJSONRequestBody defines body for PlaceLimitOrder for application/json ContentType.

type PlaceMarketOrderJSONRequestBody

type PlaceMarketOrderJSONRequestBody = MarketRequest

PlaceMarketOrderJSONRequestBody defines body for PlaceMarketOrder for application/json ContentType.

type PlaceStopOrder1JSONRequestBody

type PlaceStopOrder1JSONRequestBody = StopRequest

PlaceStopOrder1JSONRequestBody defines body for PlaceStopOrder1 for application/json ContentType.

type PlaceStopOrderJSONRequestBody

type PlaceStopOrderJSONRequestBody = StopLimitRequest

PlaceStopOrderJSONRequestBody defines body for PlaceStopOrder for application/json ContentType.

type PollErrorCallback added in v0.3.0

type PollErrorCallback = func(err error)

PollErrorCallback is invoked by the position watcher when a polling tick fails. The watcher continues running regardless.

type Position

type Position struct {
	// AveragePricePaid Average price paid, in instrument currency, per share.
	AveragePricePaid *float32 `json:"averagePricePaid,omitempty"`

	// CreatedAt The ISO 8601 formatted date of when the position was opened.
	CreatedAt *time.Time `json:"createdAt,omitempty"`

	// CurrentPrice Current price, in instrument currency, of a single share.
	CurrentPrice *float32 `json:"currentPrice,omitempty"`

	// Instrument Instrument information as given by /instruments endpoint.
	Instrument *Instrument `json:"instrument,omitempty"`

	// Quantity Total quantity of shares owned.
	Quantity *float32 `json:"quantity,omitempty"`

	// QuantityAvailableForTrading Quantity of shares available for trading.
	QuantityAvailableForTrading *float32 `json:"quantityAvailableForTrading,omitempty"`

	// QuantityInPies Quantity of shares currently used in pie.
	QuantityInPies *float32              `json:"quantityInPies,omitempty"`
	WalletImpact   *PositionWalletImpact `json:"walletImpact,omitempty"`
}

Position defines model for Position.

func (*Position) GetAveragePricePaid added in v0.3.0

func (p *Position) GetAveragePricePaid() float32

GetAveragePricePaid returns the position's average price paid, or 0.

func (*Position) GetCreatedAt added in v0.3.0

func (p *Position) GetCreatedAt() time.Time

GetCreatedAt returns when the position was opened, or the zero time.

func (*Position) GetCurrentPrice added in v0.3.0

func (p *Position) GetCurrentPrice() float32

GetCurrentPrice returns the position's current market price, or 0.

func (*Position) GetQuantity added in v0.3.0

func (p *Position) GetQuantity() float32

GetQuantity returns the position's share quantity, or 0.

func (*Position) GetTicker added in v0.3.0

func (p *Position) GetTicker() string

GetTicker returns the position's instrument ticker, or "" if unknown.

type PositionCallback added in v0.2.0

type PositionCallback = func(p *Position)

PositionCallback is invoked by the position watcher when a position is detected as opened or closed.

type PositionWalletImpact

type PositionWalletImpact struct {
	// Currency The currency code used to represent all the wallet impact information.
	Currency *string `json:"currency,omitempty"`

	// CurrentValue The current market value of the position.
	CurrentValue *float32 `json:"currentValue,omitempty"`

	// FxImpact The positive or negative impact on the position's value due to currency rate changes.
	FxImpact *float32 `json:"fxImpact,omitempty"`

	// TotalCost The total cost paid for the position.
	TotalCost *float32 `json:"totalCost,omitempty"`

	// UnrealizedProfitLoss The unrealized profit & loss for the position. Calculated as currentValue - totalCost.
	UnrealizedProfitLoss *float32 `json:"unrealizedProfitLoss,omitempty"`
}

PositionWalletImpact defines model for PositionWalletImpact.

type PublicReportRequest

type PublicReportRequest struct {
	DataIncluded *ReportDataIncluded `json:"dataIncluded,omitempty"`
	TimeFrom     *time.Time          `json:"timeFrom,omitempty"`
	TimeTo       *time.Time          `json:"timeTo,omitempty"`
}

PublicReportRequest defines model for PublicReportRequest.

type ReportDataIncluded

type ReportDataIncluded struct {
	IncludeDividends    *bool `json:"includeDividends,omitempty"`
	IncludeInterest     *bool `json:"includeInterest,omitempty"`
	IncludeOrders       *bool `json:"includeOrders,omitempty"`
	IncludeTransactions *bool `json:"includeTransactions,omitempty"`
}

ReportDataIncluded defines model for ReportDataIncluded.

type ReportResponse

type ReportResponse struct {
	DataIncluded *ReportDataIncluded   `json:"dataIncluded,omitempty"`
	DownloadLink *string               `json:"downloadLink,omitempty"`
	ReportId     *int64                `json:"reportId,omitempty"`
	Status       *ReportResponseStatus `json:"status,omitempty"`
	TimeFrom     *time.Time            `json:"timeFrom,omitempty"`
	TimeTo       *time.Time            `json:"timeTo,omitempty"`
}

ReportResponse defines model for ReportResponse.

func (r *ReportResponse) GetDownloadLink() string

GetDownloadLink returns the report download link (populated once the status is "Finished"), or "" if not yet available.

func (*ReportResponse) GetReportID added in v0.3.0

func (r *ReportResponse) GetReportID() int64

GetReportID returns the report ID, or 0 if unknown.

func (*ReportResponse) GetStatus added in v0.3.0

func (r *ReportResponse) GetStatus() ReportResponseStatus

GetStatus returns the report's lifecycle status, or "" if unknown.

type ReportResponseStatus

type ReportResponseStatus string

ReportResponseStatus defines model for ReportResponse.Status.

const (
	Canceled   ReportResponseStatus = "Canceled"
	Failed     ReportResponseStatus = "Failed"
	Finished   ReportResponseStatus = "Finished"
	Processing ReportResponseStatus = "Processing"
	Queued     ReportResponseStatus = "Queued"
	Running    ReportResponseStatus = "Running"
)

Defines values for ReportResponseStatus.

func (ReportResponseStatus) Valid

func (e ReportResponseStatus) Valid() bool

Valid indicates whether the value is a known member of the ReportResponseStatus enum.

type RequestReportJSONRequestBody

type RequestReportJSONRequestBody = PublicReportRequest

RequestReportJSONRequestBody defines body for RequestReport for application/json ContentType.

type StopLimitRequest

type StopLimitRequest struct {
	LimitPrice *float32 `json:"limitPrice,omitempty"`
	Quantity   *float32 `json:"quantity,omitempty"`
	StopPrice  *float32 `json:"stopPrice,omitempty"`
	Ticker     *string  `json:"ticker,omitempty"`

	// TimeValidity Specifies how long the order remains active:
	// * DAY: The order will automatically expire if not executed by midnight in the time zone of the instrument's exchange.
	// * GOOD_TILL_CANCEL: The order remains active indefinitely until it is either filled or explicitly cancelled by you.
	TimeValidity *TimeValidity `json:"timeValidity,omitempty"`
}

StopLimitRequest defines model for StopLimitRequest.

func NewStopLimitRequest added in v0.3.0

func NewStopLimitRequest(ticker string, quantity, stopPrice, limitPrice float32, validity TimeValidity) *StopLimitRequest

NewStopLimitRequest builds a StopLimitRequest with the required fields set.

type StopRequest

type StopRequest struct {
	Quantity  *float32 `json:"quantity,omitempty"`
	StopPrice *float32 `json:"stopPrice,omitempty"`
	Ticker    *string  `json:"ticker,omitempty"`

	// TimeValidity Specifies how long the order remains active:
	// * DAY: The order will automatically expire if not executed by midnight in the time zone of the instrument's exchange.
	// * GOOD_TILL_CANCEL: The order remains active indefinitely until it is either filled or explicitly cancelled by you.
	TimeValidity *TimeValidity `json:"timeValidity,omitempty"`
}

StopRequest defines model for StopRequest.

func NewStopRequest added in v0.3.0

func NewStopRequest(ticker string, quantity, stopPrice float32, validity TimeValidity) *StopRequest

NewStopRequest builds a StopRequest with the required fields set.

type Tax

type Tax struct {
	ChargedAt *time.Time `json:"chargedAt,omitempty"`
	Currency  *string    `json:"currency,omitempty"`
	Name      *TaxName   `json:"name,omitempty"`
	Quantity  *float32   `json:"quantity,omitempty"`
}

Tax defines model for Tax.

type TaxName

type TaxName string

TaxName defines model for Tax.Name.

const (
	COMMISSIONTURNOVER    TaxName = "COMMISSION_TURNOVER"
	CURRENCYCONVERSIONFEE TaxName = "CURRENCY_CONVERSION_FEE"
	FINRAFEE              TaxName = "FINRA_FEE"
	FRENCHTRANSACTIONTAX  TaxName = "FRENCH_TRANSACTION_TAX"
	PTMLEVY               TaxName = "PTM_LEVY"
	STAMPDUTY             TaxName = "STAMP_DUTY"
	STAMPDUTYRESERVETAX   TaxName = "STAMP_DUTY_RESERVE_TAX"
	TRANSACTIONFEE        TaxName = "TRANSACTION_FEE"
)

Defines values for TaxName.

func (TaxName) Valid

func (e TaxName) Valid() bool

Valid indicates whether the value is a known member of the TaxName enum.

type TimeEvent

type TimeEvent struct {
	Date *time.Time     `json:"date,omitempty"`
	Type *TimeEventType `json:"type,omitempty"`
}

TimeEvent defines model for TimeEvent.

type TimeEventType

type TimeEventType string

TimeEventType defines model for TimeEvent.Type.

const (
	AFTERHOURSCLOSE TimeEventType = "AFTER_HOURS_CLOSE"
	AFTERHOURSOPEN  TimeEventType = "AFTER_HOURS_OPEN"
	BREAKEND        TimeEventType = "BREAK_END"
	BREAKSTART      TimeEventType = "BREAK_START"
	CLOSE           TimeEventType = "CLOSE"
	OPEN            TimeEventType = "OPEN"
	OVERNIGHTOPEN   TimeEventType = "OVERNIGHT_OPEN"
	PREMARKETOPEN   TimeEventType = "PRE_MARKET_OPEN"
)

Defines values for TimeEventType.

func (TimeEventType) Valid

func (e TimeEventType) Valid() bool

Valid indicates whether the value is a known member of the TimeEventType enum.

type TimeValidity

type TimeValidity string

TimeValidity Specifies how long the order remains active: * DAY: The order will automatically expire if not executed by midnight in the time zone of the instrument's exchange. * GOOD_TILL_CANCEL: The order remains active indefinitely until it is either filled or explicitly cancelled by you.

const (
	DAY            TimeValidity = "DAY"
	GOODTILLCANCEL TimeValidity = "GOOD_TILL_CANCEL"
)

Defines values for TimeValidity.

func (TimeValidity) Valid

func (e TimeValidity) Valid() bool

Valid indicates whether the value is a known member of the TimeValidity enum.

type TradableInstrument

type TradableInstrument struct {
	// AddedOn On the platform since
	AddedOn *time.Time `json:"addedOn,omitempty"`

	// CurrencyCode ISO 4217
	CurrencyCode    *string  `json:"currencyCode,omitempty"`
	ExtendedHours   *bool    `json:"extendedHours,omitempty"`
	Isin            *string  `json:"isin,omitempty"`
	MaxOpenQuantity *float32 `json:"maxOpenQuantity,omitempty"`
	Name            *string  `json:"name,omitempty"`
	ShortName       *string  `json:"shortName,omitempty"`

	// Ticker Unique identifier
	Ticker *string                 `json:"ticker,omitempty"`
	Type   *TradableInstrumentType `json:"type,omitempty"`

	// WorkingScheduleId Get items in the /exchanges endpoint
	WorkingScheduleId *int64 `json:"workingScheduleId,omitempty"`
}

TradableInstrument defines model for TradableInstrument.

func (*TradableInstrument) GetCurrencyCode added in v0.3.0

func (t *TradableInstrument) GetCurrencyCode() string

GetCurrencyCode returns the tradable instrument's currency code, or "".

func (*TradableInstrument) GetName added in v0.3.0

func (t *TradableInstrument) GetName() string

GetName returns the tradable instrument's name, or "" if unknown.

func (*TradableInstrument) GetTicker added in v0.3.0

func (t *TradableInstrument) GetTicker() string

GetTicker returns the tradable instrument's ticker, or "" if unknown.

type TradableInstrumentType

type TradableInstrumentType string

TradableInstrumentType defines model for TradableInstrument.Type.

const (
	CORPACT        TradableInstrumentType = "CORPACT"
	CRYPTO         TradableInstrumentType = "CRYPTO"
	CRYPTOCURRENCY TradableInstrumentType = "CRYPTOCURRENCY"
	CVR            TradableInstrumentType = "CVR"
	ETF            TradableInstrumentType = "ETF"
	FOREX          TradableInstrumentType = "FOREX"
	FUTURES        TradableInstrumentType = "FUTURES"
	INDEX          TradableInstrumentType = "INDEX"
	STOCK          TradableInstrumentType = "STOCK"
	WARRANT        TradableInstrumentType = "WARRANT"
)

Defines values for TradableInstrumentType.

func (TradableInstrumentType) Valid

func (e TradableInstrumentType) Valid() bool

Valid indicates whether the value is a known member of the TradableInstrumentType enum.

type TransactionsParams

type TransactionsParams struct {
	// Cursor Pagination cursor
	Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"`

	// Time Retrieve transactions starting from the specified time
	Time *time.Time `form:"time,omitempty" json:"time,omitempty"`

	// Limit Max items: 50
	Limit *int32 `form:"limit,omitempty" json:"limit,omitempty"`
}

TransactionsParams defines parameters for Transactions.

type UpdateJSONRequestBody

type UpdateJSONRequestBody = PieRequest

UpdateJSONRequestBody defines body for Update for application/json ContentType.

type WaitForReportOpts added in v0.3.0

type WaitForReportOpts struct {
	// PollInterval between Reports calls. Defaults to 10s. The Reports
	// endpoint is rate-limited at 1 req / 1m, so very short intervals will
	// produce ErrRateLimited errors that the helper transparently retries.
	PollInterval time.Duration

	// MaxWait caps the total time spent waiting. Zero means no cap (the
	// helper still respects ctx). When exceeded, ErrReportTimeout is
	// returned.
	MaxWait time.Duration
}

WaitForReportOpts tunes the polling behaviour of WaitForReport. Zero values fall back to sensible defaults.

type WorkingSchedule

type WorkingSchedule struct {
	Id         *int64       `json:"id,omitempty"`
	TimeEvents *[]TimeEvent `json:"timeEvents,omitempty"`
}

WorkingSchedule defines model for WorkingSchedule.

Directories

Path Synopsis
pagination command
report command
watcher command

Jump to

Keyboard shortcuts

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