studiosdk

package module
v0.1.0-alpha.3 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2024 License: Apache-2.0 Imports: 14 Imported by: 0

README

Studio SDK Go API Library

Go Reference

The Studio SDK Go library provides convenient access to the Studio SDK REST API from applications written in Go. The full API of this library can be found in api.md.

It is generated with Stainless.

Installation

import (
	"github.com/clear-street/studio-sdk-go" // imported as studiosdk
)

Or to pin the version:

go get -u 'github.com/clear-street/studio-sdk-go@v0.1.0-alpha.3'

Requirements

This library requires Go 1.18+.

Usage

The full API of this library can be found in api.md.

package main

import (
	"context"
	"fmt"

	"github.com/clear-street/studio-sdk-go"
	"github.com/clear-street/studio-sdk-go/option"
)

func main() {
	client := studiosdk.NewClient(
		option.WithBearerToken("My Bearer Token"), // defaults to os.LookupEnv("STUDIO_SDK_BEARER_TOKEN")
	)
	entity, err := client.Entities.Get(context.TODO(), "<your_entity_id>")
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", entity.EntityID)
}

Request fields

All request parameters are wrapped in a generic Field type, which we use to distinguish zero values from null or omitted fields.

This prevents accidentally sending a zero value if you forget a required parameter, and enables explicitly sending null, false, '', or 0 on optional parameters. Any field not specified is not sent.

To construct fields with values, use the helpers String(), Int(), Float(), or most commonly, the generic F[T](). To send a null, use Null[T](), and to send a nonconforming value, use Raw[T](any). For example:

params := FooParams{
	Name: studiosdk.F("hello"),

	// Explicitly send `"description": null`
	Description: studiosdk.Null[string](),

	Point: studiosdk.F(studiosdk.Point{
		X: studiosdk.Int(0),
		Y: studiosdk.Int(1),

		// In cases where the API specifies a given type,
		// but you want to send something else, use `Raw`:
		Z: studiosdk.Raw[int64](0.01), // sends a float
	}),
}
Response objects

All fields in response structs are value types (not pointers or wrappers).

If a given field is null, not present, or invalid, the corresponding field will simply be its zero value.

All response structs also include a special JSON field, containing more detailed information about each property, which you can use like so:

if res.Name == "" {
	// true if `"name"` is either not present or explicitly null
	res.JSON.Name.IsNull()

	// true if the `"name"` key was not present in the repsonse JSON at all
	res.JSON.Name.IsMissing()

	// When the API returns data that cannot be coerced to the expected type:
	if res.JSON.Name.IsInvalid() {
		raw := res.JSON.Name.Raw()

		legacyName := struct{
			First string `json:"first"`
			Last  string `json:"last"`
		}{}
		json.Unmarshal([]byte(raw), &legacyName)
		name = legacyName.First + " " + legacyName.Last
	}
}

These .JSON structs also include an Extras map containing any properties in the json response that were not specified in the struct. This can be useful for API features not yet present in the SDK.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
RequestOptions

This library uses the functional options pattern. Functions defined in the option package return a RequestOption, which is a closure that mutates a RequestConfig. These options can be supplied to the client or at individual requests. For example:

client := studiosdk.NewClient(
	// Adds a header to every request made by the client
	option.WithHeader("X-Some-Header", "custom_header_info"),
)

client.Entities.Get(context.TODO(), ...,
	// Override the header
	option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
	// Add an undocumented field to the request body, using sjson syntax
	option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
)

See the full list of request options.

Pagination

This library provides some conveniences for working with paginated list endpoints.

You can use .ListAutoPaging() methods to iterate through items across all pages:

Or you can use simple .List() methods to fetch a single page and receive a standard response object with additional helper methods like .GetNextPage(), e.g.:

Errors

When the API returns a non-success status code, we return an error with type *studiosdk.Error. This contains the StatusCode, *http.Request, and *http.Response values of the request, as well as the JSON of the error body (much like other response objects in the SDK).

To handle errors, we recommend that you use the errors.As pattern:

_, err := client.Entities.Get(context.TODO(), "<your_entity_id>")
if err != nil {
	var apierr *studiosdk.Error
	if errors.As(err, &apierr) {
		println(string(apierr.DumpRequest(true)))  // Prints the serialized HTTP request
		println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
	}
	panic(err.Error()) // GET "/entities/{entity_id}": 400 Bad Request { ... }
}

When other errors occur, they are returned unwrapped; for example, if HTTP transport fails, you might receive *url.Error wrapping *net.OpError.

Timeouts

Requests do not time out by default; use context to configure a timeout for a request lifecycle.

Note that if a request is retried, the context timeout does not start over. To set a per-retry timeout, use option.WithRequestTimeout().

// This sets the timeout for the request, including all the retries.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client.Entities.Get(
	ctx,
	"<your_entity_id>",
	// This sets the per-retry timeout
	option.WithRequestTimeout(20*time.Second),
)
File uploads

Request parameters that correspond to file uploads in multipart requests are typed as param.Field[io.Reader]. The contents of the io.Reader will by default be sent as a multipart form part with the file name of "anonymous_file" and content-type of "application/octet-stream".

The file name and content-type can be customized by implementing Name() string or ContentType() string on the run-time type of io.Reader. Note that os.File implements Name() string, so a file returned by os.Open will be sent with the file name on disk.

We also provide a helper studiosdk.FileParam(reader io.Reader, filename string, contentType string) which can be used to wrap any io.Reader with the appropriate file name and content type.

Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff. We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors.

You can use the WithMaxRetries option to configure or disable this:

// Configure the default for all requests:
client := studiosdk.NewClient(
	option.WithMaxRetries(0), // default is 2
)

// Override per-request:
client.Entities.Get(
	context.TODO(),
	"<your_entity_id>",
	option.WithMaxRetries(5),
)
Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can use client.Get, client.Post, and other HTTP verbs. RequestOptions on the client, such as retries, will be respected when making these requests.

var (
    // params can be an io.Reader, a []byte, an encoding/json serializable object,
    // or a "…Params" struct defined in this library.
    params map[string]interface{}

    // result can be an []byte, *http.Response, a encoding/json deserializable object,
    // or a model defined in this library.
    result *http.Response
)
err := client.Post(context.Background(), "/unspecified", params, &result)
if err != nil {
    …
}
Undocumented request params

To make requests using undocumented parameters, you may use either the option.WithQuerySet() or the option.WithJSONSet() methods.

params := FooNewParams{
    ID:   studiosdk.F("id_xxxx"),
    Data: studiosdk.F(FooNewParamsData{
        FirstName: studiosdk.F("John"),
    }),
}
client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))
Undocumented response properties

To access undocumented response properties, you may either access the raw JSON of the response as a string with result.JSON.RawJSON(), or get the raw JSON of a particular field on the result with result.JSON.Foo.Raw().

Any fields that are not present on the response struct will be saved and can be accessed by result.JSON.ExtraFields() which returns the extra fields as a map[string]Field.

Middleware

We provide option.WithMiddleware which applies the given middleware to requests.

func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) {
	// Before the request
	start := time.Now()
	LogReq(req)

	// Forward the request to the next handler
	res, err = next(req)

	// Handle stuff after the request
	end := time.Now()
	LogRes(res, err, start - end)

    return res, err
}

client := studiosdk.NewClient(
	option.WithMiddleware(Logger),
)

When multiple middlewares are provided as variadic arguments, the middlewares are applied left to right. If option.WithMiddleware is given multiple times, for example first in the client then the method, the middleware in the client will run first and the middleware given in the method will run next.

You may also replace the default http.Client with option.WithHTTPClient(client). Only one http client is accepted (this overwrites any previous client) and receives requests after any middleware has been applied.

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals).
  2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Documentation

Index

Constants

View Source
const LocateOrderStatusCancelled = shared.LocateOrderStatusCancelled

This is an alias to an internal value.

View Source
const LocateOrderStatusDeclined = shared.LocateOrderStatusDeclined

This is an alias to an internal value.

View Source
const LocateOrderStatusExpired = shared.LocateOrderStatusExpired

This is an alias to an internal value.

View Source
const LocateOrderStatusFilled = shared.LocateOrderStatusFilled

This is an alias to an internal value.

View Source
const LocateOrderStatusOffered = shared.LocateOrderStatusOffered

This is an alias to an internal value.

View Source
const LocateOrderStatusPending = shared.LocateOrderStatusPending

This is an alias to an internal value.

View Source
const LocateOrderStatusRejected = shared.LocateOrderStatusRejected

This is an alias to an internal value.

View Source
const OrderOrderTypeLimit = shared.OrderOrderTypeLimit

This is an alias to an internal value.

View Source
const OrderOrderTypeMarket = shared.OrderOrderTypeMarket

This is an alias to an internal value.

View Source
const OrderOrderUpdateReasonCancel = shared.OrderOrderUpdateReasonCancel

This is an alias to an internal value.

View Source
const OrderOrderUpdateReasonCancelReject = shared.OrderOrderUpdateReasonCancelReject

This is an alias to an internal value.

View Source
const OrderOrderUpdateReasonExecutionReport = shared.OrderOrderUpdateReasonExecutionReport

This is an alias to an internal value.

View Source
const OrderOrderUpdateReasonModify = shared.OrderOrderUpdateReasonModify

This is an alias to an internal value.

View Source
const OrderOrderUpdateReasonPlace = shared.OrderOrderUpdateReasonPlace

This is an alias to an internal value.

View Source
const OrderSideBuy = shared.OrderSideBuy

This is an alias to an internal value.

View Source
const OrderSideSell = shared.OrderSideSell

This is an alias to an internal value.

View Source
const OrderSideSellShort = shared.OrderSideSellShort

This is an alias to an internal value.

View Source
const OrderStateClosed = shared.OrderStateClosed

This is an alias to an internal value.

View Source
const OrderStateOpen = shared.OrderStateOpen

This is an alias to an internal value.

View Source
const OrderStateRejected = shared.OrderStateRejected

This is an alias to an internal value.

View Source
const OrderStatusAcceptedForBidding = shared.OrderStatusAcceptedForBidding

This is an alias to an internal value.

View Source
const OrderStatusCalculated = shared.OrderStatusCalculated

This is an alias to an internal value.

View Source
const OrderStatusCanceled = shared.OrderStatusCanceled

This is an alias to an internal value.

View Source
const OrderStatusDoneForDay = shared.OrderStatusDoneForDay

This is an alias to an internal value.

View Source
const OrderStatusExpired = shared.OrderStatusExpired

This is an alias to an internal value.

View Source
const OrderStatusFilled = shared.OrderStatusFilled

This is an alias to an internal value.

View Source
const OrderStatusNew = shared.OrderStatusNew

This is an alias to an internal value.

View Source
const OrderStatusPartiallyFilled = shared.OrderStatusPartiallyFilled

This is an alias to an internal value.

View Source
const OrderStatusPendingCancel = shared.OrderStatusPendingCancel

This is an alias to an internal value.

View Source
const OrderStatusPendingNew = shared.OrderStatusPendingNew

This is an alias to an internal value.

View Source
const OrderStatusPendingReplace = shared.OrderStatusPendingReplace

This is an alias to an internal value.

View Source
const OrderStatusRejected = shared.OrderStatusRejected

This is an alias to an internal value.

View Source
const OrderStatusReplaced = shared.OrderStatusReplaced

This is an alias to an internal value.

View Source
const OrderStatusStopped = shared.OrderStatusStopped

This is an alias to an internal value.

View Source
const OrderStatusSuspended = shared.OrderStatusSuspended

This is an alias to an internal value.

View Source
const OrderStrategyTypeAp = shared.OrderStrategyTypeAp

This is an alias to an internal value.

View Source
const OrderStrategyTypeDark = shared.OrderStrategyTypeDark

This is an alias to an internal value.

View Source
const OrderStrategyTypePov = shared.OrderStrategyTypePov

This is an alias to an internal value.

View Source
const OrderStrategyTypeSor = shared.OrderStrategyTypeSor

This is an alias to an internal value.

View Source
const OrderStrategyTypeTwap = shared.OrderStrategyTypeTwap

This is an alias to an internal value.

View Source
const OrderStrategyTypeVwap = shared.OrderStrategyTypeVwap

This is an alias to an internal value.

View Source
const OrderTimeInForceAtClose = shared.OrderTimeInForceAtClose

This is an alias to an internal value.

View Source
const OrderTimeInForceAtOpen = shared.OrderTimeInForceAtOpen

This is an alias to an internal value.

View Source
const OrderTimeInForceDay = shared.OrderTimeInForceDay

This is an alias to an internal value.

View Source
const OrderTimeInForceDayPlus = shared.OrderTimeInForceDayPlus

This is an alias to an internal value.

View Source
const OrderTimeInForceIoc = shared.OrderTimeInForceIoc

This is an alias to an internal value.

View Source
const TradeSideBuy = shared.TradeSideBuy

This is an alias to an internal value.

View Source
const TradeSideSell = shared.TradeSideSell

This is an alias to an internal value.

View Source
const TradeSideSellShort = shared.TradeSideSellShort

This is an alias to an internal value.

Variables

This section is empty.

Functions

func Bool

func Bool(value bool) param.Field[bool]

Bool is a param field helper which helps specify bools.

func F

func F[T any](value T) param.Field[T]

F is a param field helper used to initialize a param.Field generic struct. This helps specify null, zero values, and overrides, as well as normal values. You can read more about this in our README.

func FileParam

func FileParam(reader io.Reader, filename string, contentType string) param.Field[io.Reader]

FileParam is a param field helper which helps files with a mime content-type.

func Float

func Float(value float64) param.Field[float64]

Float is a param field helper which helps specify floats.

func Int

func Int(value int64) param.Field[int64]

Int is a param field helper which helps specify integers. This is particularly helpful when specifying integer constants for fields.

func Null

func Null[T any]() param.Field[T]

Null is a param field helper which explicitly sends null to the API.

func Raw

func Raw[T any](value any) param.Field[T]

Raw is a param field helper for specifying values for fields when the type you are looking to send is different from the type that is specified in the SDK. For example, if the type of the field is an integer, but you want to send a float, you could do that by setting the corresponding field with Raw[int](0.5).

func String

func String(value string) param.Field[string]

String is a param field helper which helps specify strings.

Types

type Account

type Account struct {
	// Account ID for the account.
	AccountID string `json:"account_id,required"`
	// Entity ID for the legal entity.
	EntityID string      `json:"entity_id,required"`
	Name     string      `json:"name,required"`
	JSON     accountJSON `json:"-"`
}

func (*Account) UnmarshalJSON

func (r *Account) UnmarshalJSON(data []byte) (err error)

type AccountBulkOrderNewParams

type AccountBulkOrderNewParams struct {
	// An array of orders to create.
	Orders param.Field[[]AccountBulkOrderNewParamsOrder] `json:"orders,required"`
}

func (AccountBulkOrderNewParams) MarshalJSON

func (r AccountBulkOrderNewParams) MarshalJSON() (data []byte, err error)

type AccountBulkOrderNewParamsOrder

type AccountBulkOrderNewParamsOrder struct {
	// The type of order, can be one of the following:
	//
	//   - `limit`: A limit order will execute at-or-better than the limit price you
	//     specify
	//   - `market`: An order that will execute at the prevailing market prices
	OrderType param.Field[AccountBulkOrderNewParamsOrdersOrderType] `json:"order_type,required"`
	// The maximum quantity to be executed.
	Quantity param.Field[string] `json:"quantity,required"`
	// Buy, sell, sell-short indicator.
	Side param.Field[AccountBulkOrderNewParamsOrdersSide] `json:"side,required"`
	// Strategy type used for execution, can be one of below. Note, we use sensible
	// defaults for strategy parameters at the moment. In future, we will provide a way
	// to provide specify these parameters.
	//
	// - `sor`: Smart order router
	// - `dark`: Dark pool
	// - `ap`: Arrival price
	// - `pov`: Percentage of volume
	// - `twap`: Time weighted average price
	// - `vwap`: Volume weighted average price
	//
	// For more information on these strategies, please refer to our
	// [documentation](https://docs.clearstreet.io/studio/docs/execution-strategies).
	StrategyType param.Field[AccountBulkOrderNewParamsOrdersStrategyType] `json:"strategy_type,required"`
	// The symbol this order is for. See `symbol_format` for supported symbol formats.
	Symbol param.Field[string] `json:"symbol,required"`
	// The lifecycle enforcement of this order.
	//
	//   - `day`: The order will exist for the duration of the current trading session
	//   - `ioc`: The order will immediately be executed or cancelled
	//   - `day-plus`: The order will exist only for the duration the current trading
	//     session plus extended hours, if applicable
	//   - `at-open`: The order will exist only for the opening auction of the next
	//     session
	//   - `at-close`: The order will exist only for the closing auction of the current
	//     session
	TimeInForce param.Field[AccountBulkOrderNewParamsOrdersTimeInForce] `json:"time_in_force,required"`
	// Name of the broker that provided you inventory for a short-sale. Required if
	// `side` is `sell-short`. If you procured inventory through us, you can use
	// `CLST`.
	LocateBroker param.Field[string] `json:"locate_broker"`
	// The price to execute at-or-better.
	Price param.Field[string] `json:"price"`
	// An ID that you provide.
	ReferenceID param.Field[string] `json:"reference_id"`
	// Denotes the format of the provided `symbol` field.
	SymbolFormat param.Field[AccountBulkOrderNewParamsOrdersSymbolFormat] `json:"symbol_format"`
}

func (AccountBulkOrderNewParamsOrder) MarshalJSON

func (r AccountBulkOrderNewParamsOrder) MarshalJSON() (data []byte, err error)

type AccountBulkOrderNewParamsOrdersOrderType

type AccountBulkOrderNewParamsOrdersOrderType string

The type of order, can be one of the following:

  • `limit`: A limit order will execute at-or-better than the limit price you specify
  • `market`: An order that will execute at the prevailing market prices
const (
	AccountBulkOrderNewParamsOrdersOrderTypeLimit  AccountBulkOrderNewParamsOrdersOrderType = "limit"
	AccountBulkOrderNewParamsOrdersOrderTypeMarket AccountBulkOrderNewParamsOrdersOrderType = "market"
)

func (AccountBulkOrderNewParamsOrdersOrderType) IsKnown

type AccountBulkOrderNewParamsOrdersSide

type AccountBulkOrderNewParamsOrdersSide string

Buy, sell, sell-short indicator.

const (
	AccountBulkOrderNewParamsOrdersSideBuy       AccountBulkOrderNewParamsOrdersSide = "buy"
	AccountBulkOrderNewParamsOrdersSideSell      AccountBulkOrderNewParamsOrdersSide = "sell"
	AccountBulkOrderNewParamsOrdersSideSellShort AccountBulkOrderNewParamsOrdersSide = "sell-short"
)

func (AccountBulkOrderNewParamsOrdersSide) IsKnown

type AccountBulkOrderNewParamsOrdersStrategyType

type AccountBulkOrderNewParamsOrdersStrategyType string

Strategy type used for execution, can be one of below. Note, we use sensible defaults for strategy parameters at the moment. In future, we will provide a way to provide specify these parameters.

- `sor`: Smart order router - `dark`: Dark pool - `ap`: Arrival price - `pov`: Percentage of volume - `twap`: Time weighted average price - `vwap`: Volume weighted average price

For more information on these strategies, please refer to our [documentation](https://docs.clearstreet.io/studio/docs/execution-strategies).

const (
	AccountBulkOrderNewParamsOrdersStrategyTypeSor  AccountBulkOrderNewParamsOrdersStrategyType = "sor"
	AccountBulkOrderNewParamsOrdersStrategyTypeDark AccountBulkOrderNewParamsOrdersStrategyType = "dark"
	AccountBulkOrderNewParamsOrdersStrategyTypeAp   AccountBulkOrderNewParamsOrdersStrategyType = "ap"
	AccountBulkOrderNewParamsOrdersStrategyTypePov  AccountBulkOrderNewParamsOrdersStrategyType = "pov"
	AccountBulkOrderNewParamsOrdersStrategyTypeTwap AccountBulkOrderNewParamsOrdersStrategyType = "twap"
	AccountBulkOrderNewParamsOrdersStrategyTypeVwap AccountBulkOrderNewParamsOrdersStrategyType = "vwap"
)

func (AccountBulkOrderNewParamsOrdersStrategyType) IsKnown

type AccountBulkOrderNewParamsOrdersSymbolFormat

type AccountBulkOrderNewParamsOrdersSymbolFormat string

Denotes the format of the provided `symbol` field.

const (
	AccountBulkOrderNewParamsOrdersSymbolFormatCms AccountBulkOrderNewParamsOrdersSymbolFormat = "cms"
	AccountBulkOrderNewParamsOrdersSymbolFormatOsi AccountBulkOrderNewParamsOrdersSymbolFormat = "osi"
)

func (AccountBulkOrderNewParamsOrdersSymbolFormat) IsKnown

type AccountBulkOrderNewParamsOrdersTimeInForce

type AccountBulkOrderNewParamsOrdersTimeInForce string

The lifecycle enforcement of this order.

  • `day`: The order will exist for the duration of the current trading session
  • `ioc`: The order will immediately be executed or cancelled
  • `day-plus`: The order will exist only for the duration the current trading session plus extended hours, if applicable
  • `at-open`: The order will exist only for the opening auction of the next session
  • `at-close`: The order will exist only for the closing auction of the current session
const (
	AccountBulkOrderNewParamsOrdersTimeInForceDay     AccountBulkOrderNewParamsOrdersTimeInForce = "day"
	AccountBulkOrderNewParamsOrdersTimeInForceIoc     AccountBulkOrderNewParamsOrdersTimeInForce = "ioc"
	AccountBulkOrderNewParamsOrdersTimeInForceDayPlus AccountBulkOrderNewParamsOrdersTimeInForce = "day-plus"
	AccountBulkOrderNewParamsOrdersTimeInForceAtOpen  AccountBulkOrderNewParamsOrdersTimeInForce = "at-open"
	AccountBulkOrderNewParamsOrdersTimeInForceAtClose AccountBulkOrderNewParamsOrdersTimeInForce = "at-close"
)

func (AccountBulkOrderNewParamsOrdersTimeInForce) IsKnown

type AccountBulkOrderNewResponse

type AccountBulkOrderNewResponse struct {
	// Array indicating whether each respective order was submitted or not. This array
	// is guaranteed to be sorted in the same order as the orders you provided in your
	// request.
	Data []AccountBulkOrderNewResponseData `json:"data,required"`
	// Total number of orders rejected
	Rejected int64 `json:"rejected,required"`
	// Total number of orders submitted
	Submitted int64                           `json:"submitted,required"`
	JSON      accountBulkOrderNewResponseJSON `json:"-"`
}

func (*AccountBulkOrderNewResponse) UnmarshalJSON

func (r *AccountBulkOrderNewResponse) UnmarshalJSON(data []byte) (err error)

type AccountBulkOrderNewResponseData

type AccountBulkOrderNewResponseData struct {
	// True if the order was submitted successfully, false otherwise.
	Submitted bool `json:"submitted,required"`
	// If the order was submitted, the order ID assigned to this order. Empty if the
	// order was rejected.
	OrderID string `json:"order_id"`
	// If the order rejected, the reason for rejection. Empty if the order was
	// accepted.
	Reason string                              `json:"reason"`
	JSON   accountBulkOrderNewResponseDataJSON `json:"-"`
}

func (*AccountBulkOrderNewResponseData) UnmarshalJSON

func (r *AccountBulkOrderNewResponseData) UnmarshalJSON(data []byte) (err error)

type AccountBulkOrderService

type AccountBulkOrderService struct {
	Options []option.RequestOption
}

AccountBulkOrderService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountBulkOrderService method instead.

func NewAccountBulkOrderService

func NewAccountBulkOrderService(opts ...option.RequestOption) (r *AccountBulkOrderService)

NewAccountBulkOrderService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountBulkOrderService) New

Creates multiple orders in a single request, up to 1000. Note that a successful call to this endpoint does not necessarily mean your orders have been accepted, e.g. a downstream venue might reject your order. You should therefore utilize our WebSocket APIs to listen for changes in order lifecycle events.

The response will contain an array of objects, indicating whether your order was submitted. If the order was submitted, the `order_id` field will be populated with the order ID assigned to this order. If the order was rejected, the `reason` field will be populated with the reason for rejection. The data array returned in the response object is guaranteed to be ordered in the same order as the orders you provided in the request. Again, note that even if your order was submitted, that doesn't mean it was _accepted_, and may still be rejected by downstream venues.

type AccountEasyBorrowListResponse

type AccountEasyBorrowListResponse struct {
	Data []string                          `json:"data,required"`
	JSON accountEasyBorrowListResponseJSON `json:"-"`
}

func (*AccountEasyBorrowListResponse) UnmarshalJSON

func (r *AccountEasyBorrowListResponse) UnmarshalJSON(data []byte) (err error)

type AccountEasyBorrowService

type AccountEasyBorrowService struct {
	Options []option.RequestOption
}

AccountEasyBorrowService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountEasyBorrowService method instead.

func NewAccountEasyBorrowService

func NewAccountEasyBorrowService(opts ...option.RequestOption) (r *AccountEasyBorrowService)

NewAccountEasyBorrowService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountEasyBorrowService) List

List all current easy-to-borrow stock symbols. This list changes dynamically daily.

type AccountListResponse

type AccountListResponse struct {
	Data []Account               `json:"data"`
	JSON accountListResponseJSON `json:"-"`
}

func (*AccountListResponse) UnmarshalJSON

func (r *AccountListResponse) UnmarshalJSON(data []byte) (err error)

type AccountLocateOrderListResponse

type AccountLocateOrderListResponse struct {
	Data []shared.LocateOrder               `json:"data,required"`
	JSON accountLocateOrderListResponseJSON `json:"-"`
}

func (*AccountLocateOrderListResponse) UnmarshalJSON

func (r *AccountLocateOrderListResponse) UnmarshalJSON(data []byte) (err error)

type AccountLocateOrderNewParams

type AccountLocateOrderNewParams struct {
	// The market participant where the locate will be sent.
	Mpid param.Field[string] `json:"mpid,required"`
	// String representation of quantity.
	Quantity param.Field[string] `json:"quantity,required"`
	// Your unique ID for this locate order.
	ReferenceID param.Field[string] `json:"reference_id,required"`
	Symbol      param.Field[string] `json:"symbol,required"`
	// Any additional comments for the locate request.
	Comments param.Field[string] `json:"comments"`
}

func (AccountLocateOrderNewParams) MarshalJSON

func (r AccountLocateOrderNewParams) MarshalJSON() (data []byte, err error)

type AccountLocateOrderService

type AccountLocateOrderService struct {
	Options []option.RequestOption
}

AccountLocateOrderService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountLocateOrderService method instead.

func NewAccountLocateOrderService

func NewAccountLocateOrderService(opts ...option.RequestOption) (r *AccountLocateOrderService)

NewAccountLocateOrderService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountLocateOrderService) Get

func (r *AccountLocateOrderService) Get(ctx context.Context, accountID string, locateOrderID string, opts ...option.RequestOption) (res *shared.LocateOrder, err error)

Get locate order by its unique locate order ID.

func (*AccountLocateOrderService) List

List all locate orders

func (*AccountLocateOrderService) New

Create locate order to borrow inventory for short-selling.

func (*AccountLocateOrderService) Update

func (r *AccountLocateOrderService) Update(ctx context.Context, accountID string, locateOrderID string, body AccountLocateOrderUpdateParams, opts ...option.RequestOption) (err error)

Accept or decline locate order that has been offered.

type AccountLocateOrderUpdateParams

type AccountLocateOrderUpdateParams struct {
	// Accept or decline the locate order.
	Accept param.Field[bool] `json:"accept,required"`
}

func (AccountLocateOrderUpdateParams) MarshalJSON

func (r AccountLocateOrderUpdateParams) MarshalJSON() (data []byte, err error)

type AccountOrderDeleteParams

type AccountOrderDeleteParams struct {
	// Cancel orders only for this specific symbol. If this is omitted, all open orders
	// will be cancelled.
	Symbol param.Field[string] `query:"symbol"`
	// Format of the provided symbol.
	SymbolFormat param.Field[AccountOrderDeleteParamsSymbolFormat] `query:"symbol_format"`
}

func (AccountOrderDeleteParams) URLQuery

func (r AccountOrderDeleteParams) URLQuery() (v url.Values)

URLQuery serializes AccountOrderDeleteParams's query parameters as `url.Values`.

type AccountOrderDeleteParamsSymbolFormat

type AccountOrderDeleteParamsSymbolFormat string

Format of the provided symbol.

const (
	AccountOrderDeleteParamsSymbolFormatCms AccountOrderDeleteParamsSymbolFormat = "cms"
	AccountOrderDeleteParamsSymbolFormatOsi AccountOrderDeleteParamsSymbolFormat = "osi"
)

func (AccountOrderDeleteParamsSymbolFormat) IsKnown

type AccountOrderDeleteResponse

type AccountOrderDeleteResponse struct {
	// Array of order IDs that were attempted to be cancelled.
	Data []string                       `json:"data,required"`
	JSON accountOrderDeleteResponseJSON `json:"-"`
}

func (*AccountOrderDeleteResponse) UnmarshalJSON

func (r *AccountOrderDeleteResponse) UnmarshalJSON(data []byte) (err error)

type AccountOrderGetResponse

type AccountOrderGetResponse struct {
	Order shared.Order                `json:"order,required"`
	JSON  accountOrderGetResponseJSON `json:"-"`
}

func (*AccountOrderGetResponse) UnmarshalJSON

func (r *AccountOrderGetResponse) UnmarshalJSON(data []byte) (err error)

type AccountOrderListParams

type AccountOrderListParams struct {
	// Milliseconds since epoch timestamp. This will constrain the search for orders
	// created after this timestamp, inclusively. Timestamps for orders prior the
	// current trading day will be ignored.
	From param.Field[int64] `query:"from"`
	// Number of orders to return per page.
	PageSize param.Field[int64] `query:"page_size"`
	// Cursor for the page to return.
	PageToken param.Field[string] `query:"page_token"`
	// Milliseconds since epoch timestamp. This will constrain the search for orders
	// created before this timestamp, inclusively. Timestamps for orders beyond the
	// current trading day will be ignored.
	To param.Field[int64] `query:"to"`
}

func (AccountOrderListParams) URLQuery

func (r AccountOrderListParams) URLQuery() (v url.Values)

URLQuery serializes AccountOrderListParams's query parameters as `url.Values`.

type AccountOrderListResponse

type AccountOrderListResponse struct {
	Data []shared.Order `json:"data,required"`
	// Cursor for the next page of results.
	NextPageToken string                       `json:"next_page_token"`
	JSON          accountOrderListResponseJSON `json:"-"`
}

func (*AccountOrderListResponse) UnmarshalJSON

func (r *AccountOrderListResponse) UnmarshalJSON(data []byte) (err error)

type AccountOrderNewParams

type AccountOrderNewParams struct {
	// The type of order, can be one of the following:
	//
	//   - `limit`: A limit order will execute at-or-better than the limit price you
	//     specify
	//   - `market`: An order that will execute at the prevailing market prices
	OrderType param.Field[AccountOrderNewParamsOrderType] `json:"order_type,required"`
	// The maximum quantity to be executed.
	Quantity param.Field[string] `json:"quantity,required"`
	// Buy, sell, sell-short indicator.
	Side param.Field[AccountOrderNewParamsSide] `json:"side,required"`
	// Strategy type used for execution, can be one of below. Note, we use sensible
	// defaults for strategy parameters at the moment. In future, we will provide a way
	// to provide specify these parameters.
	//
	// - `sor`: Smart order router
	// - `dark`: Dark pool
	// - `ap`: Arrival price
	// - `pov`: Percentage of volume
	// - `twap`: Time weighted average price
	// - `vwap`: Volume weighted average price
	//
	// For more information on these strategies, please refer to our
	// [documentation](https://docs.clearstreet.io/studio/docs/execution-strategies).
	StrategyType param.Field[AccountOrderNewParamsStrategyType] `json:"strategy_type,required"`
	// The symbol this order is for. See `symbol_format` for supported symbol formats.
	Symbol param.Field[string] `json:"symbol,required"`
	// The lifecycle enforcement of this order.
	//
	//   - `day`: The order will exist for the duration of the current trading session
	//   - `ioc`: The order will immediately be executed or cancelled
	//   - `day-plus`: The order will exist only for the duration the current trading
	//     session plus extended hours, if applicable
	//   - `at-open`: The order will exist only for the opening auction of the next
	//     session
	//   - `at-close`: The order will exist only for the closing auction of the current
	//     session
	TimeInForce param.Field[AccountOrderNewParamsTimeInForce] `json:"time_in_force,required"`
	// Name of the broker that provided you inventory for a short-sale. Required if
	// `side` is `sell-short`. If you procured inventory through us, you can use
	// `CLST`.
	LocateBroker param.Field[string] `json:"locate_broker"`
	// The price to execute at-or-better.
	Price param.Field[string] `json:"price"`
	// An ID that you provide.
	ReferenceID param.Field[string] `json:"reference_id"`
	// Denotes the format of the provided `symbol` field.
	SymbolFormat param.Field[AccountOrderNewParamsSymbolFormat] `json:"symbol_format"`
}

func (AccountOrderNewParams) MarshalJSON

func (r AccountOrderNewParams) MarshalJSON() (data []byte, err error)

type AccountOrderNewParamsOrderType

type AccountOrderNewParamsOrderType string

The type of order, can be one of the following:

  • `limit`: A limit order will execute at-or-better than the limit price you specify
  • `market`: An order that will execute at the prevailing market prices
const (
	AccountOrderNewParamsOrderTypeLimit  AccountOrderNewParamsOrderType = "limit"
	AccountOrderNewParamsOrderTypeMarket AccountOrderNewParamsOrderType = "market"
)

func (AccountOrderNewParamsOrderType) IsKnown

type AccountOrderNewParamsSide

type AccountOrderNewParamsSide string

Buy, sell, sell-short indicator.

const (
	AccountOrderNewParamsSideBuy       AccountOrderNewParamsSide = "buy"
	AccountOrderNewParamsSideSell      AccountOrderNewParamsSide = "sell"
	AccountOrderNewParamsSideSellShort AccountOrderNewParamsSide = "sell-short"
)

func (AccountOrderNewParamsSide) IsKnown

func (r AccountOrderNewParamsSide) IsKnown() bool

type AccountOrderNewParamsStrategyType

type AccountOrderNewParamsStrategyType string

Strategy type used for execution, can be one of below. Note, we use sensible defaults for strategy parameters at the moment. In future, we will provide a way to provide specify these parameters.

- `sor`: Smart order router - `dark`: Dark pool - `ap`: Arrival price - `pov`: Percentage of volume - `twap`: Time weighted average price - `vwap`: Volume weighted average price

For more information on these strategies, please refer to our [documentation](https://docs.clearstreet.io/studio/docs/execution-strategies).

const (
	AccountOrderNewParamsStrategyTypeSor  AccountOrderNewParamsStrategyType = "sor"
	AccountOrderNewParamsStrategyTypeDark AccountOrderNewParamsStrategyType = "dark"
	AccountOrderNewParamsStrategyTypeAp   AccountOrderNewParamsStrategyType = "ap"
	AccountOrderNewParamsStrategyTypePov  AccountOrderNewParamsStrategyType = "pov"
	AccountOrderNewParamsStrategyTypeTwap AccountOrderNewParamsStrategyType = "twap"
	AccountOrderNewParamsStrategyTypeVwap AccountOrderNewParamsStrategyType = "vwap"
)

func (AccountOrderNewParamsStrategyType) IsKnown

type AccountOrderNewParamsSymbolFormat

type AccountOrderNewParamsSymbolFormat string

Denotes the format of the provided `symbol` field.

const (
	AccountOrderNewParamsSymbolFormatCms AccountOrderNewParamsSymbolFormat = "cms"
	AccountOrderNewParamsSymbolFormatOsi AccountOrderNewParamsSymbolFormat = "osi"
)

func (AccountOrderNewParamsSymbolFormat) IsKnown

type AccountOrderNewParamsTimeInForce

type AccountOrderNewParamsTimeInForce string

The lifecycle enforcement of this order.

  • `day`: The order will exist for the duration of the current trading session
  • `ioc`: The order will immediately be executed or cancelled
  • `day-plus`: The order will exist only for the duration the current trading session plus extended hours, if applicable
  • `at-open`: The order will exist only for the opening auction of the next session
  • `at-close`: The order will exist only for the closing auction of the current session
const (
	AccountOrderNewParamsTimeInForceDay     AccountOrderNewParamsTimeInForce = "day"
	AccountOrderNewParamsTimeInForceIoc     AccountOrderNewParamsTimeInForce = "ioc"
	AccountOrderNewParamsTimeInForceDayPlus AccountOrderNewParamsTimeInForce = "day-plus"
	AccountOrderNewParamsTimeInForceAtOpen  AccountOrderNewParamsTimeInForce = "at-open"
	AccountOrderNewParamsTimeInForceAtClose AccountOrderNewParamsTimeInForce = "at-close"
)

func (AccountOrderNewParamsTimeInForce) IsKnown

type AccountOrderNewResponse

type AccountOrderNewResponse struct {
	// An internally generated unique ID for this order.
	OrderID string                      `json:"order_id,required"`
	JSON    accountOrderNewResponseJSON `json:"-"`
}

func (*AccountOrderNewResponse) UnmarshalJSON

func (r *AccountOrderNewResponse) UnmarshalJSON(data []byte) (err error)

type AccountOrderService

type AccountOrderService struct {
	Options []option.RequestOption
}

AccountOrderService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountOrderService method instead.

func NewAccountOrderService

func NewAccountOrderService(opts ...option.RequestOption) (r *AccountOrderService)

NewAccountOrderService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountOrderService) Cancel

func (r *AccountOrderService) Cancel(ctx context.Context, accountID string, orderID string, opts ...option.RequestOption) (err error)

Attempts to cancel an existing order. Cancelling an order cannot be guaranteed as there might be in-flight executions.

func (*AccountOrderService) Delete

Attempts to cancel all open orders for a given account. Cancelling an order cannot be guaranteed as there might be in-flight executions.

func (*AccountOrderService) Get

func (r *AccountOrderService) Get(ctx context.Context, accountID string, orderID string, opts ...option.RequestOption) (res *AccountOrderGetResponse, err error)

Get an order that was previously created.

func (*AccountOrderService) List

List orders for a given account for the current trading day, filtered on the given query parameters.

func (*AccountOrderService) New

Creates a new order and sends to our internal systems for execution. Note that a successful call to this endpoint does not necessarily mean your order has been accepted, e.g. a downstream venue might reject your order. You should therefore utilize our WebSocket APIs to listen for changes in order lifecycle events.

type AccountPnlDetailListResponse

type AccountPnlDetailListResponse struct {
	Data []AccountPnlDetailListResponseData `json:"data,required"`
	JSON accountPnlDetailListResponseJSON   `json:"-"`
}

func (*AccountPnlDetailListResponse) UnmarshalJSON

func (r *AccountPnlDetailListResponse) UnmarshalJSON(data []byte) (err error)

type AccountPnlDetailListResponseData

type AccountPnlDetailListResponseData struct {
	// Account ID for the account.
	AccountID string `json:"account_id,required"`
	// The asset class of the symbol.
	AssetClass AccountPnlDetailListResponseDataAssetClass `json:"asset_class,required"`
	// Quantity of a given instrument bought.
	BoughtQuantity string `json:"bought_quantity,required"`
	// Total buys of a given instrument.
	Buys int64 `json:"buys,required"`
	// Profit and loss from intraday trading activities.
	DayPnl float64 `json:"day_pnl,required"`
	// Name of the legal entity.
	EntityID string `json:"entity_id,required"`
	// Absolute market value of long and short market values.
	GrossMarketValue float64 `json:"gross_market_value,required"`
	// Market value net of long and short market values.
	NetMarketValue float64 `json:"net_market_value,required"`
	// Profit and loss from previous trading date.
	OvernightPnl float64 `json:"overnight_pnl,required"`
	// Price used in this pnl calculation.
	Price float64 `json:"price,required"`
	// String representation of quantity.
	Quantity string `json:"quantity,required"`
	// Profit and loss realized from position closing trading activity.
	RealizedPnl float64 `json:"realized_pnl,required"`
	// Total sells of a given instrument.
	Sells int64 `json:"sells,required"`
	// Market value of a given instrument a the start of a trading day.
	SodMarketValue float64 `json:"sod_market_value,required"`
	// Price at the start of a trading day.
	SodPrice float64 `json:"sod_price,required"`
	// Quantity of a given instrument at the start of a trading day.
	SodQuantity string `json:"sod_quantity,required"`
	// Quantity of a given instrument sold.
	SoldQuantity string `json:"sold_quantity,required"`
	Symbol       string `json:"symbol,required"`
	// Description of the symbol.
	SymbolDescription string `json:"symbol_description,required"`
	// Milliseconds since epoch.
	Timestamp int64 `json:"timestamp,required"`
	// Total fees incurred from trading activities.
	TotalFees float64 `json:"total_fees,required"`
	// `realized_pnl + unrealized_pnl`
	TotalPnl float64 `json:"total_pnl,required"`
	// The underlying instrument.
	Underlier string `json:"underlier,required"`
	// Profit and loss from market changes.
	UnrealizedPnl float64                              `json:"unrealized_pnl,required"`
	JSON          accountPnlDetailListResponseDataJSON `json:"-"`
}

func (*AccountPnlDetailListResponseData) UnmarshalJSON

func (r *AccountPnlDetailListResponseData) UnmarshalJSON(data []byte) (err error)

type AccountPnlDetailListResponseDataAssetClass

type AccountPnlDetailListResponseDataAssetClass string

The asset class of the symbol.

const (
	AccountPnlDetailListResponseDataAssetClassOther  AccountPnlDetailListResponseDataAssetClass = "other"
	AccountPnlDetailListResponseDataAssetClassEquity AccountPnlDetailListResponseDataAssetClass = "equity"
	AccountPnlDetailListResponseDataAssetClassOption AccountPnlDetailListResponseDataAssetClass = "option"
	AccountPnlDetailListResponseDataAssetClassDebt   AccountPnlDetailListResponseDataAssetClass = "debt"
)

func (AccountPnlDetailListResponseDataAssetClass) IsKnown

type AccountPnlDetailService

type AccountPnlDetailService struct {
	Options []option.RequestOption
}

AccountPnlDetailService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountPnlDetailService method instead.

func NewAccountPnlDetailService

func NewAccountPnlDetailService(opts ...option.RequestOption) (r *AccountPnlDetailService)

NewAccountPnlDetailService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountPnlDetailService) List

List PNL details for a given account.

type AccountPnlSummaryService

type AccountPnlSummaryService struct {
	Options []option.RequestOption
}

AccountPnlSummaryService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountPnlSummaryService method instead.

func NewAccountPnlSummaryService

func NewAccountPnlSummaryService(opts ...option.RequestOption) (r *AccountPnlSummaryService)

NewAccountPnlSummaryService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountPnlSummaryService) Get

Get PNL summary for a given account.

type AccountPositionListParams

type AccountPositionListParams struct {
	// Number of positions to return per page.
	PageSize param.Field[int64] `query:"page_size"`
	// Cursor for the page to return.
	PageToken param.Field[string] `query:"page_token"`
}

func (AccountPositionListParams) URLQuery

func (r AccountPositionListParams) URLQuery() (v url.Values)

URLQuery serializes AccountPositionListParams's query parameters as `url.Values`.

type AccountPositionListResponse

type AccountPositionListResponse struct {
	Data []shared.Position `json:"data,required"`
	// Cursor for the next page of results.
	NextPageToken string                          `json:"next_page_token"`
	JSON          accountPositionListResponseJSON `json:"-"`
}

func (*AccountPositionListResponse) UnmarshalJSON

func (r *AccountPositionListResponse) UnmarshalJSON(data []byte) (err error)

type AccountPositionService

type AccountPositionService struct {
	Options []option.RequestOption
}

AccountPositionService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountPositionService method instead.

func NewAccountPositionService

func NewAccountPositionService(opts ...option.RequestOption) (r *AccountPositionService)

NewAccountPositionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountPositionService) Get

func (r *AccountPositionService) Get(ctx context.Context, accountID string, symbol string, opts ...option.RequestOption) (res *shared.Position, err error)

Get current positions for a given account for a given symbol.

func (*AccountPositionService) List

List current positions for a given account.

type AccountService

type AccountService struct {
	Options      []option.RequestOption
	BulkOrders   *AccountBulkOrderService
	Orders       *AccountOrderService
	Trades       *AccountTradeService
	Positions    *AccountPositionService
	LocateOrders *AccountLocateOrderService
	EasyBorrows  *AccountEasyBorrowService
	PnlSummary   *AccountPnlSummaryService
	PnlDetails   *AccountPnlDetailService
}

AccountService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountService method instead.

func NewAccountService

func NewAccountService(opts ...option.RequestOption) (r *AccountService)

NewAccountService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountService) Get

func (r *AccountService) Get(ctx context.Context, accountID string, opts ...option.RequestOption) (res *Account, err error)

Get an account by its ID.

func (*AccountService) List

func (r *AccountService) List(ctx context.Context, opts ...option.RequestOption) (res *AccountListResponse, err error)

List all available accounts.

type AccountTradeListParams

type AccountTradeListParams struct {
	// Number of trades to return per page.
	PageSize param.Field[int64] `query:"page_size"`
	// Cursor for the page to return.
	PageToken param.Field[string] `query:"page_token"`
}

func (AccountTradeListParams) URLQuery

func (r AccountTradeListParams) URLQuery() (v url.Values)

URLQuery serializes AccountTradeListParams's query parameters as `url.Values`.

type AccountTradeListResponse

type AccountTradeListResponse struct {
	Data []shared.Trade `json:"data,required"`
	// Cursor for the next page of results.
	NextPageToken string                       `json:"next_page_token"`
	JSON          accountTradeListResponseJSON `json:"-"`
}

func (*AccountTradeListResponse) UnmarshalJSON

func (r *AccountTradeListResponse) UnmarshalJSON(data []byte) (err error)

type AccountTradeService

type AccountTradeService struct {
	Options []option.RequestOption
}

AccountTradeService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAccountTradeService method instead.

func NewAccountTradeService

func NewAccountTradeService(opts ...option.RequestOption) (r *AccountTradeService)

NewAccountTradeService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AccountTradeService) Get

func (r *AccountTradeService) Get(ctx context.Context, accountID string, tradeID string, opts ...option.RequestOption) (res *shared.Trade, err error)

Get trade a trade by its unique trade ID.

func (*AccountTradeService) List

List trades for a given account for the current trading day.

type Client

type Client struct {
	Options     []option.RequestOption
	Entities    *EntityService
	Accounts    *AccountService
	Instruments *InstrumentService
}

Client creates a struct with services and top level methods that help with interacting with the studio-sdk API. You should not instantiate this client directly, and instead use the NewClient method instead.

func NewClient

func NewClient(opts ...option.RequestOption) (r *Client)

NewClient generates a new client with the default option read from the environment (STUDIO_SDK_BEARER_TOKEN). The option passed in as arguments are applied after these default arguments, and all option will be passed down to the services and requests that this client makes.

func (*Client) Delete

func (r *Client) Delete(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Delete makes a DELETE request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Execute

func (r *Client) Execute(ctx context.Context, method string, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Execute makes a request with the given context, method, URL, request params, response, and request options. This is useful for hitting undocumented endpoints while retaining the base URL, auth, retries, and other options from the client.

If a byte slice or an io.Reader is supplied to params, it will be used as-is for the request body.

The params is by default serialized into the body using encoding/json. If your type implements a MarshalJSON function, it will be used instead to serialize the request. If a URLQuery method is implemented, the returned url.Values will be used as query strings to the url.

If your params struct uses param.Field, you must provide either [MarshalJSON], [URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use a struct uses param.Field without specifying how it is serialized.

Any "…Params" object defined in this library can be used as the request argument. Note that 'path' arguments will not be forwarded into the url.

The response body will be deserialized into the res variable, depending on its type:

  • A pointer to a *http.Response is populated by the raw response.
  • A pointer to a byte array will be populated with the contents of the request body.
  • A pointer to any other type uses this library's default JSON decoding, which respects UnmarshalJSON if it is defined on the type.
  • A nil value will not read the response body.

For even greater flexibility, see option.WithResponseInto and option.WithResponseBodyInto.

func (*Client) Get

func (r *Client) Get(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Get makes a GET request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Patch

func (r *Client) Patch(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Patch makes a PATCH request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Post

func (r *Client) Post(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Post makes a POST request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Put

func (r *Client) Put(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Put makes a PUT request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

type Entity

type Entity struct {
	ClientCode string `json:"client_code,required"`
	// Entity ID for the legal entity.
	EntityID  string     `json:"entity_id,required"`
	LegalName string     `json:"legal_name"`
	JSON      entityJSON `json:"-"`
}

func (*Entity) UnmarshalJSON

func (r *Entity) UnmarshalJSON(data []byte) (err error)

type EntityListResponse

type EntityListResponse struct {
	Data []Entity               `json:"data"`
	JSON entityListResponseJSON `json:"-"`
}

func (*EntityListResponse) UnmarshalJSON

func (r *EntityListResponse) UnmarshalJSON(data []byte) (err error)

type EntityPnlSummaryService

type EntityPnlSummaryService struct {
	Options []option.RequestOption
}

EntityPnlSummaryService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEntityPnlSummaryService method instead.

func NewEntityPnlSummaryService

func NewEntityPnlSummaryService(opts ...option.RequestOption) (r *EntityPnlSummaryService)

NewEntityPnlSummaryService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EntityPnlSummaryService) Get

func (r *EntityPnlSummaryService) Get(ctx context.Context, entityID string, opts ...option.RequestOption) (res *PnlSummary, err error)

Get PNL summary for all accounts in an entity.

type EntityPortfolioMarginService

type EntityPortfolioMarginService struct {
	Options []option.RequestOption
}

EntityPortfolioMarginService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEntityPortfolioMarginService method instead.

func NewEntityPortfolioMarginService

func NewEntityPortfolioMarginService(opts ...option.RequestOption) (r *EntityPortfolioMarginService)

NewEntityPortfolioMarginService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EntityPortfolioMarginService) Get

func (r *EntityPortfolioMarginService) Get(ctx context.Context, entityID string, opts ...option.RequestOption) (res *PortfolioMargin, err error)

Get latest portfolio margin calculation for the given entity

type EntityRegtMarginService

type EntityRegtMarginService struct {
	Options []option.RequestOption
}

EntityRegtMarginService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEntityRegtMarginService method instead.

func NewEntityRegtMarginService

func NewEntityRegtMarginService(opts ...option.RequestOption) (r *EntityRegtMarginService)

NewEntityRegtMarginService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EntityRegtMarginService) Get

func (r *EntityRegtMarginService) Get(ctx context.Context, entityID string, opts ...option.RequestOption) (res *RegtMargin, err error)

Get the latest Reg-T margin calculation for the given entity

type EntityRegtMarginSimulationNewParams

type EntityRegtMarginSimulationNewParams struct {
	// A name for this simulation for reference.
	Name param.Field[string] `json:"name,required"`
	// If true, the simulation will ignore any existing positions and balances in the
	// account. Set to true if you want to simulate from a clean slate, i.e. an empty
	// account.
	IgnoreExisting param.Field[bool] `json:"ignore_existing"`
	// List of prices to use in the simulation, i.e. fair-market-values you specify for
	// each symbol. If this is not provided, current market prices will be used, if
	// they are available.
	Prices param.Field[[]EntityRegtMarginSimulationNewParamsPrice] `json:"prices"`
	// List of hypothetical trades to include in the simulation, if any.
	Trades param.Field[[]EntityRegtMarginSimulationNewParamsTrade] `json:"trades"`
}

func (EntityRegtMarginSimulationNewParams) MarshalJSON

func (r EntityRegtMarginSimulationNewParams) MarshalJSON() (data []byte, err error)

type EntityRegtMarginSimulationNewParamsPrice

type EntityRegtMarginSimulationNewParamsPrice struct {
	// The price to use in the simulation.
	Price param.Field[string] `json:"price,required"`
	// The symbol for the instrument.
	Symbol param.Field[string] `json:"symbol,required"`
	// Denotes the format of the provided `symbol` field.
	SymbolFormat param.Field[EntityRegtMarginSimulationNewParamsPricesSymbolFormat] `json:"symbol_format"`
}

func (EntityRegtMarginSimulationNewParamsPrice) MarshalJSON

func (r EntityRegtMarginSimulationNewParamsPrice) MarshalJSON() (data []byte, err error)

type EntityRegtMarginSimulationNewParamsPricesSymbolFormat

type EntityRegtMarginSimulationNewParamsPricesSymbolFormat string

Denotes the format of the provided `symbol` field.

const (
	EntityRegtMarginSimulationNewParamsPricesSymbolFormatCms EntityRegtMarginSimulationNewParamsPricesSymbolFormat = "cms"
	EntityRegtMarginSimulationNewParamsPricesSymbolFormatOsi EntityRegtMarginSimulationNewParamsPricesSymbolFormat = "osi"
)

func (EntityRegtMarginSimulationNewParamsPricesSymbolFormat) IsKnown

type EntityRegtMarginSimulationNewParamsTrade

type EntityRegtMarginSimulationNewParamsTrade struct {
	// The price of the simulated trade.
	Price param.Field[string] `json:"price,required"`
	// The quantity of the simulated trade.
	Quantity param.Field[string] `json:"quantity,required"`
	// The side of the simulated trade.
	Side param.Field[EntityRegtMarginSimulationNewParamsTradesSide] `json:"side,required"`
	// The symbol for the instrument.
	Symbol param.Field[string] `json:"symbol,required"`
	// Denotes the format of the provided `symbol` field.
	SymbolFormat param.Field[EntityRegtMarginSimulationNewParamsTradesSymbolFormat] `json:"symbol_format"`
}

func (EntityRegtMarginSimulationNewParamsTrade) MarshalJSON

func (r EntityRegtMarginSimulationNewParamsTrade) MarshalJSON() (data []byte, err error)

type EntityRegtMarginSimulationNewParamsTradesSide

type EntityRegtMarginSimulationNewParamsTradesSide string

The side of the simulated trade.

const (
	EntityRegtMarginSimulationNewParamsTradesSideBuy  EntityRegtMarginSimulationNewParamsTradesSide = "buy"
	EntityRegtMarginSimulationNewParamsTradesSideSell EntityRegtMarginSimulationNewParamsTradesSide = "sell"
)

func (EntityRegtMarginSimulationNewParamsTradesSide) IsKnown

type EntityRegtMarginSimulationNewParamsTradesSymbolFormat

type EntityRegtMarginSimulationNewParamsTradesSymbolFormat string

Denotes the format of the provided `symbol` field.

const (
	EntityRegtMarginSimulationNewParamsTradesSymbolFormatCms EntityRegtMarginSimulationNewParamsTradesSymbolFormat = "cms"
	EntityRegtMarginSimulationNewParamsTradesSymbolFormatOsi EntityRegtMarginSimulationNewParamsTradesSymbolFormat = "osi"
)

func (EntityRegtMarginSimulationNewParamsTradesSymbolFormat) IsKnown

type EntityRegtMarginSimulationNewResponse

type EntityRegtMarginSimulationNewResponse struct {
	// Unique ID for a simulation.
	SimulationID SimulationID                              `json:"simulation_id,required" format:"uuid"`
	JSON         entityRegtMarginSimulationNewResponseJSON `json:"-"`
}

func (*EntityRegtMarginSimulationNewResponse) UnmarshalJSON

func (r *EntityRegtMarginSimulationNewResponse) UnmarshalJSON(data []byte) (err error)

type EntityRegtMarginSimulationService

type EntityRegtMarginSimulationService struct {
	Options []option.RequestOption
}

EntityRegtMarginSimulationService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEntityRegtMarginSimulationService method instead.

func NewEntityRegtMarginSimulationService

func NewEntityRegtMarginSimulationService(opts ...option.RequestOption) (r *EntityRegtMarginSimulationService)

NewEntityRegtMarginSimulationService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EntityRegtMarginSimulationService) Get

Get a Reg-T margin simluation that was previously created. Note, simulations are automatically deleted after 48-hours.

func (*EntityRegtMarginSimulationService) New

Simulate Reg-T margin calculation for a given hypothetical set of prices and/or trades. This is useful for understanding the impact of price fluctuations or trades on margin requirements. Once a simulation is created, it remains available for 48-hours, after which it will automatically be deleted.

Simulations created through the API are visible in the Studio UI under the Risk & Margin section, after enabling the "Risk Simulations" toggle.

type EntityService

type EntityService struct {
	Options               []option.RequestOption
	PnlSummaries          *EntityPnlSummaryService
	RegtMargins           *EntityRegtMarginService
	PortfolioMargins      *EntityPortfolioMarginService
	RegtMarginSimulations *EntityRegtMarginSimulationService
}

EntityService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEntityService method instead.

func NewEntityService

func NewEntityService(opts ...option.RequestOption) (r *EntityService)

NewEntityService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EntityService) Get

func (r *EntityService) Get(ctx context.Context, entityID string, opts ...option.RequestOption) (res *Entity, err error)

Get an entity by its ID.

func (*EntityService) List

func (r *EntityService) List(ctx context.Context, opts ...option.RequestOption) (res *EntityListResponse, err error)

List all available entities.

type Error

type Error = apierror.Error

type Instrument

type Instrument struct {
	// The asset class of the symbol.
	AssetClass InstrumentAssetClass `json:"asset_class,required"`
	// A description of the instrument.
	Description string `json:"description,required"`
	// The primary exchange for the instrument.
	PrimaryExchange string             `json:"primary_exchange,required"`
	Symbols         []InstrumentSymbol `json:"symbols,required"`
	JSON            instrumentJSON     `json:"-"`
}

func (*Instrument) UnmarshalJSON

func (r *Instrument) UnmarshalJSON(data []byte) (err error)

type InstrumentAssetClass

type InstrumentAssetClass string

The asset class of the symbol.

const (
	InstrumentAssetClassOther  InstrumentAssetClass = "other"
	InstrumentAssetClassEquity InstrumentAssetClass = "equity"
	InstrumentAssetClassOption InstrumentAssetClass = "option"
	InstrumentAssetClassDebt   InstrumentAssetClass = "debt"
)

func (InstrumentAssetClass) IsKnown

func (r InstrumentAssetClass) IsKnown() bool

type InstrumentGetParams

type InstrumentGetParams struct {
	// The format of the provided symbol.
	SymbolFormat param.Field[InstrumentGetParamsSymbolFormat] `query:"symbol_format"`
}

func (InstrumentGetParams) URLQuery

func (r InstrumentGetParams) URLQuery() (v url.Values)

URLQuery serializes InstrumentGetParams's query parameters as `url.Values`.

type InstrumentGetParamsSymbolFormat

type InstrumentGetParamsSymbolFormat string

The format of the provided symbol.

const (
	InstrumentGetParamsSymbolFormatCms InstrumentGetParamsSymbolFormat = "cms"
	InstrumentGetParamsSymbolFormatOsi InstrumentGetParamsSymbolFormat = "osi"
)

func (InstrumentGetParamsSymbolFormat) IsKnown

type InstrumentService

type InstrumentService struct {
	Options []option.RequestOption
}

InstrumentService contains methods and other services that help with interacting with the studio-sdk API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewInstrumentService method instead.

func NewInstrumentService

func NewInstrumentService(opts ...option.RequestOption) (r *InstrumentService)

NewInstrumentService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*InstrumentService) Get

func (r *InstrumentService) Get(ctx context.Context, symbol string, query InstrumentGetParams, opts ...option.RequestOption) (res *Instrument, err error)

Get an instrument by the given symbol

type InstrumentSymbol

type InstrumentSymbol struct {
	Symbol string `json:"symbol"`
	// Denotes the format of the provided `symbol` field.
	SymbolFormat InstrumentSymbolsSymbolFormat `json:"symbol_format"`
	JSON         instrumentSymbolJSON          `json:"-"`
}

func (*InstrumentSymbol) UnmarshalJSON

func (r *InstrumentSymbol) UnmarshalJSON(data []byte) (err error)

type InstrumentSymbolsSymbolFormat

type InstrumentSymbolsSymbolFormat string

Denotes the format of the provided `symbol` field.

const (
	InstrumentSymbolsSymbolFormatCms InstrumentSymbolsSymbolFormat = "cms"
	InstrumentSymbolsSymbolFormatOsi InstrumentSymbolsSymbolFormat = "osi"
)

func (InstrumentSymbolsSymbolFormat) IsKnown

func (r InstrumentSymbolsSymbolFormat) IsKnown() bool

type LocateOrder

type LocateOrder = shared.LocateOrder

This is an alias to an internal type.

type LocateOrderStatus

type LocateOrderStatus = shared.LocateOrderStatus

The status of the locate order.

This is an alias to an internal type.

type Order

type Order = shared.Order

This is an alias to an internal type.

type OrderOrderType

type OrderOrderType = shared.OrderOrderType

The type of order, can be one of the following:

  • `limit`: A limit order will execute at-or-better than the limit price you specify
  • `market`: An order that will execute at the prevailing market prices

This is an alias to an internal type.

type OrderOrderUpdateReason

type OrderOrderUpdateReason = shared.OrderOrderUpdateReason

The last reason why this order was updated

This is an alias to an internal type.

type OrderSide

type OrderSide = shared.OrderSide

Buy, sell, sell-short indicator.

This is an alias to an internal type.

type OrderState

type OrderState = shared.OrderState

Simplified order state, which is inferred from `OrderStatus`. Makes it easier to determine whether an order can be executed against.

  • `open`: Order _can_ potentially be executed against.
  • `rejected`: Order _cannot_ be executed against because it was rejected. This is a terminal state.
  • `closed`: Order _cannot_ be executed against. This is a terminal state.

This is an alias to an internal type.

type OrderStatus

type OrderStatus = shared.OrderStatus

Granular order status using [standard values come FIX tag 39](https://www.fixtrading.org/online-specification/order-state-changes).

This is an alias to an internal type.

type OrderStrategyType

type OrderStrategyType = shared.OrderStrategyType

Strategy type used for execution, can be one of below. Note, we use sensible defaults for strategy parameters at the moment. In future, we will provide a way to provide specify these parameters.

- `sor`: Smart order router - `dark`: Dark pool - `ap`: Arrival price - `pov`: Percentage of volume - `twap`: Time weighted average price - `vwap`: Volume weighted average price

For more information on these strategies, please refer to our [documentation](https://docs.clearstreet.io/studio/docs/execution-strategies).

This is an alias to an internal type.

type OrderTimeInForce

type OrderTimeInForce = shared.OrderTimeInForce

The lifecycle enforcement of this order.

  • `day`: The order will exist for the duration of the current trading session
  • `ioc`: The order will immediately be executed or cancelled
  • `day-plus`: The order will exist only for the duration the current trading session plus extended hours, if applicable
  • `at-open`: The order will exist only for the opening auction of the next session
  • `at-close`: The order will exist only for the closing auction of the current session

This is an alias to an internal type.

type PnlSummary

type PnlSummary struct {
	// Profit and loss from intraday trading activities.
	DayPnl float64 `json:"day_pnl,required"`
	// Entity ID for the legal entity.
	EntityID string `json:"entity_id,required"`
	// Net value of instruments held in the portfolio.
	Equity float64 `json:"equity,required"`
	// Absolute market value of long and short market values.
	GrossMarketValue float64 `json:"gross_market_value,required"`
	// Market value of securities positioned long.
	LongMarketValue float64 `json:"long_market_value,required"`
	// Market value net of long and short market values.
	NetMarketValue float64 `json:"net_market_value,required"`
	// `total_pnl + total_fees`
	NetPnl float64 `json:"net_pnl,required"`
	// Profit and loss from previous trading date.
	OvernightPnl float64 `json:"overnight_pnl,required"`
	// Profit and loss realized from position closing trading activity
	RealizedPnl float64 `json:"realized_pnl,required"`
	// Market value of securities positioned short.
	ShortMarketValue float64 `json:"short_market_value,required"`
	// Net value of instruments held in the portfolio at the start of a trading day.
	SodEquity float64 `json:"sod_equity,required"`
	// Absolute market value at the start of a trading day.
	SodGrossMarketValue float64 `json:"sod_gross_market_value,required"`
	// Market value of securities positioned long at the start of a trading day.
	SodLongMarketValue float64 `json:"sod_long_market_value,required"`
	// Market value of securities positioned short at the start of a trading day.
	SodShortMarketValue float64 `json:"sod_short_market_value,required"`
	// Milliseconds since epoch.
	Timestamp int64 `json:"timestamp,required"`
	// Total fees incurred from trading activities.
	TotalFees float64 `json:"total_fees,required"`
	// `realized_pnl + unrealized_pnl`
	TotalPnl float64 `json:"total_pnl,required"`
	// Profit and loss from market changes.
	UnrealizedPnl float64        `json:"unrealized_pnl,required"`
	JSON          pnlSummaryJSON `json:"-"`
}

func (*PnlSummary) UnmarshalJSON

func (r *PnlSummary) UnmarshalJSON(data []byte) (err error)

type PnlSummaryForAccount

type PnlSummaryForAccount = shared.PnlSummaryForAccount

This is an alias to an internal type.

type PortfolioMargin

type PortfolioMargin struct {
	// Sum of add-on margin requirements. Formula:
	// `liquidity_add_on + concentration_add_on + discretionary_requirement`
	AddOnRequirement float64 `json:"add_on_requirement"`
	// The percentage add-on margin requirements in terms of total house requirement.
	// Formula: `add_on_requirement / house_requirement`
	AddOnRequirementPercent float64 `json:"add_on_requirement_percent"`
	// A component margin requirement that captures risk based on gross exposure to
	// total equity.
	ConcentrationAddOn float64 `json:"concentration_add_on"`
	// The percentage concentration add-on margin requirements in terms of total house
	// requirement. Formula: `concentration_add_on / house_requirement`
	ConcentrationAddOnPercent float64 `json:"concentration_add_on_percent"`
	// A component margin requirement that captures miscellaneous risk factors.
	DiscretionaryRequirement float64 `json:"discretionary_requirement"`
	// The percentage discretionary margin requirements in terms of total house
	// requirement Formula: `discretionary_requirement / house_requirement`
	DiscretionaryRequirementPercent float64 `json:"discretionary_requirement_percent"`
	// The maring amount by taking the difference between total equity and the
	// effective requirement. A negative number reflects an effective margin deficit.
	EffeciveExcess float64 `json:"effecive_excess"`
	// The enforced margin requirement in effect.
	EffectiveRequirement float64 `json:"effective_requirement"`
	// Portfolio margin groups
	Groups []PortfolioMarginGroup `json:"groups"`
	// The margin amount by taking the difference between total equity and the house
	// requirement. A negative number reflects a house margin deficit.
	HouseExcess float64 `json:"house_excess"`
	// Margin requirements based on Clear Street's house margin methodology.
	HouseRequirement float64 `json:"house_requirement"`
	// A component margin requirement that captures risk based on liquidity, Market
	// Cap, and Average Daily Volume factors.
	LiquidityAddOn float64 `json:"liquidity_add_on"`
	// The percentage liquidity add-on margin requirements in terms of total house
	// requirement. Formula: `liquidity_add_on / house_requirement`
	LiquidityAddOnPercent float64 `json:"liquidity_add_on_percent"`
	// Sum of market values across all positions.
	NetMarketValue float64 `json:"net_market_value"`
	// A component margin requirement that captures risk for security instruments that
	// are not margin eligible.
	NonMarginableRequirement float64 `json:"non_marginable_requirement"`
	// The percentage non-marginable requirement in terms of total house requirement
	// Formula: `non_marginable_requirement / house_requirement`
	NonMarginableRequirementPercent float64 `json:"non_marginable_requirement_percent"`
	// A component margin requirement that captures base-case risk under house margin
	// methodology.
	RiskBasedRequirement float64 `json:"risk_based_requirement"`
	// The percentage risk_base margin requirement in terms of total house requirement
	// Formula: `risk_based_requirement / house_requirement`
	RiskBasedRequirementPercent float64 `json:"risk_based_requirement_percent"`
	// Timestamp of when this margin was calculated.
	Timestamp int64 `json:"timestamp"`
	// A component margin requirement that captures risk based on vega.
	VegaRequirement float64 `json:"vega_requirement"`
	// Unique identifier for this margin calculation.
	Version string              `json:"version"`
	JSON    portfolioMarginJSON `json:"-"`
}

func (*PortfolioMargin) UnmarshalJSON

func (r *PortfolioMargin) UnmarshalJSON(data []byte) (err error)

type PortfolioMarginGroup

type PortfolioMarginGroup struct {
	// The enforced margin requirement in effect for the group.
	EffectiveRequirement float64 `json:"effective_requirement,required"`
	// The percentage effective margin requirement in terms of the group market value.
	// Formula: `(effective_requirement / net_market_value)`
	MarginPercent float64 `json:"margin_percent,required"`
	// The percentage effective margin requirement in terms of the total effective
	// requirement. Formula: `(effective_requirement / sum(effective_requirement))`
	MarginPercentContribution float64 `json:"margin_percent_contribution,required"`
	// The aggregated market value of all instruments for the group.
	MarketValue float64 `json:"market_value,required"`
	// The percentage market value of the group in terms of the total net_market_value
	// of all positions. Formula: `(market_value / net_market_value)`
	MarketValuePercent float64 `json:"market_value_percent,required"`
	// A list of securities that comprise this group.
	Members []PortfolioMarginGroupsMember `json:"members,required"`
	// Unique name of the group, typically the symbol of the underlier.
	Name string `json:"name,required"`
	// A component margin requirement that captures risk for the group based on gross
	// exposure to total equity
	ConcentrationRequirement float64 `json:"concentration_requirement"`
	// A component margin requirement that captures miscellaneous risk factors for the
	// group.
	DiscretionaryRequirement float64 `json:"discretionary_requirement"`
	// A component margin requirement that captures risk for the group based on
	// liquidity, Market Cap, and Average Daily Volume factors.
	LiquidityRequirement float64 `json:"liquidity_requirement"`
	// A component margin requirement that captures risk for the group that are not
	// margin eligible.
	NonMarginableRequirement float64 `json:"non_marginable_requirement"`
	// Margin requirements based on OCC TIMS regulatory margin methodology
	RegulatoryRequirement float64 `json:"regulatory_requirement"`
	// A component margin requirement that captures base-case risk for the group under
	// house margin methodology
	RiskBasedRequirement float64 `json:"risk_based_requirement"`
	// Maps shock scenarios to their resulting pnl.
	Shocks map[string]float64 `json:"shocks"`
	// Margin requirements based on value-at-risk over any 5-day period in a 2 year
	// historic lookback
	VarRequirement float64                  `json:"var_requirement"`
	JSON           portfolioMarginGroupJSON `json:"-"`
}

func (*PortfolioMarginGroup) UnmarshalJSON

func (r *PortfolioMarginGroup) UnmarshalJSON(data []byte) (err error)

type PortfolioMarginGroupsMember

type PortfolioMarginGroupsMember struct {
	// The asset class of the symbol.
	AssetClass PortfolioMarginGroupsMembersAssetClass `json:"asset_class"`
	// Market value of the instrument.
	MarketValue float64 `json:"market_value"`
	// The percentage market value of the instrument in terms of the total
	// `net_market_value` of all positions held. Formula:
	// `market_value / net_market_value`
	MarketValuePercent float64 `json:"market_value_percent"`
	// The quantity held for this instrument.
	Quantity string `json:"quantity"`
	// Maps shock scenarios to their resulting pnl.
	Shocks map[string]float64 `json:"shocks"`
	// The symbol for the instrument.
	Symbol string                          `json:"symbol"`
	JSON   portfolioMarginGroupsMemberJSON `json:"-"`
}

func (*PortfolioMarginGroupsMember) UnmarshalJSON

func (r *PortfolioMarginGroupsMember) UnmarshalJSON(data []byte) (err error)

type PortfolioMarginGroupsMembersAssetClass

type PortfolioMarginGroupsMembersAssetClass string

The asset class of the symbol.

const (
	PortfolioMarginGroupsMembersAssetClassOther  PortfolioMarginGroupsMembersAssetClass = "other"
	PortfolioMarginGroupsMembersAssetClassEquity PortfolioMarginGroupsMembersAssetClass = "equity"
	PortfolioMarginGroupsMembersAssetClassOption PortfolioMarginGroupsMembersAssetClass = "option"
	PortfolioMarginGroupsMembersAssetClassDebt   PortfolioMarginGroupsMembersAssetClass = "debt"
)

func (PortfolioMarginGroupsMembersAssetClass) IsKnown

type Position

type Position = shared.Position

This is an alias to an internal type.

type RegtMargin

type RegtMargin struct {
	// The remaining amount of start_of_day_buying_power that captures any day-trading
	// activity.
	DayTradeBuyingPower float64 `json:"day_trade_buying_power,required"`
	// The enforced margin requirement in effect.
	EffectiveRequirement float64 `json:"effective_requirement,required"`
	// Margin requirements based on regulatory rules.
	ExchangeRequirement float64 `json:"exchange_requirement,required"`
	// Reg-T margin groups
	Groups []RegtMarginGroup `json:"groups,required"`
	// The margin amount by taking the difference between total equity and the house
	// requirement. A negative number reflects a house margin deficit.
	HouseExcess float64 `json:"house_excess,required"`
	// Margin requirements based on Clear Street's house margin methodology.
	HouseRequirement float64 `json:"house_requirement,required"`
	// Market value net of long and short market values.
	NetMarketValue float64 `json:"net_market_value,required"`
	// The limit, or "up-to" amount, of securities value that can be purchased and held
	// overnight.
	OvernightBuyingPower float64 `json:"overnight_buying_power,required"`
	// Special Memorandum Account (SMA). The regulatory line of credit amount for
	// margin trading based on market value, trading activity, and available cash.
	Sma float64 `json:"sma,required"`
	// The limit, or "up-to" amount, of securities value that can be day-traded for a
	// given trading day.
	SodBuyingPower float64 `json:"sod_buying_power,required"`
	// Timestamp of when this margin was calculated.
	Timestamp int64 `json:"timestamp,required"`
	// Unique identifier for this margin calculation.
	Version string `json:"version,required"`
	// The maring amount by taking the difference between total equity and the
	// effective requirement. A negative number reflects an effective margin deficit.
	EffectiveExcess float64 `json:"effective_excess"`
	// The margin amount by taking the difference between total equity and the exchange
	// requirement. A negative number reflects an regulatory margin deficit.
	ExchangeExcess float64        `json:"exchange_excess"`
	JSON           regtMarginJSON `json:"-"`
}

func (*RegtMargin) UnmarshalJSON

func (r *RegtMargin) UnmarshalJSON(data []byte) (err error)

type RegtMarginGroup

type RegtMarginGroup struct {
	// The enforced margin requirement in effect for the symbol group.
	EffectiveRequirement float64 `json:"effective_requirement,required"`
	// Margin requirements based on regulatory rules for the symbol group.
	ExchangeRequirement float64 `json:"exchange_requirement,required"`
	// Margin requirements based on Clear Street's house margin methodology for the
	// symbol group.
	HouseRequirement float64 `json:"house_requirement,required"`
	// The percentage effective margin requirement in terms of the symbol group market
	// value. Formula: `(effective_requirement / net_market_value)`
	MarginPercent float64 `json:"margin_percent,required"`
	// The percentage effective margin requirement in terms of the total effective
	// requirement. Formula: `(effective_requirement / sum(effective_requirement))`
	MarginPercentContribution float64 `json:"margin_percent_contribution,required"`
	// The aggregated market value of all instruments for the symbol group.
	MarketValue float64 `json:"market_value,required"`
	// The percentage market value of the symbol group in terms of the total
	// net_market_value of all positions. Formula: `(market_value / net_market_value)`
	MarketValuePercent float64 `json:"market_value_percent,required"`
	// A list of securities that comprise this group.
	Members []RegtMarginGroupsMember `json:"members,required"`
	// Unique name of the group, typically the symbol of the underlier.
	Name string              `json:"name,required"`
	JSON regtMarginGroupJSON `json:"-"`
}

func (*RegtMarginGroup) UnmarshalJSON

func (r *RegtMarginGroup) UnmarshalJSON(data []byte) (err error)

type RegtMarginGroupsMember

type RegtMarginGroupsMember struct {
	// The asset class of the symbol.
	AssetClass RegtMarginGroupsMembersAssetClass `json:"asset_class,required"`
	// Market value of the instrument.
	MarketValue float64 `json:"market_value,required"`
	// The percentage market value of the instrument in terms of the total
	// `net_market_value` of all positions held. Formula:
	// `market_value / net_market_value`
	MarketValuePercent float64 `json:"market_value_percent,required"`
	// The quantity held for this instrument.
	Quantity string `json:"quantity,required"`
	// The symbol for the instrument.
	Symbol string                     `json:"symbol,required"`
	JSON   regtMarginGroupsMemberJSON `json:"-"`
}

func (*RegtMarginGroupsMember) UnmarshalJSON

func (r *RegtMarginGroupsMember) UnmarshalJSON(data []byte) (err error)

type RegtMarginGroupsMembersAssetClass

type RegtMarginGroupsMembersAssetClass string

The asset class of the symbol.

const (
	RegtMarginGroupsMembersAssetClassOther  RegtMarginGroupsMembersAssetClass = "other"
	RegtMarginGroupsMembersAssetClassEquity RegtMarginGroupsMembersAssetClass = "equity"
	RegtMarginGroupsMembersAssetClassOption RegtMarginGroupsMembersAssetClass = "option"
	RegtMarginGroupsMembersAssetClassDebt   RegtMarginGroupsMembersAssetClass = "debt"
)

func (RegtMarginGroupsMembersAssetClass) IsKnown

type RegtMarginSimulation

type RegtMarginSimulation = shared.RegtMarginSimulation

This is an alias to an internal type.

type SimulationID

type SimulationID = string

type SimulationIDParam

type SimulationIDParam = string

type Trade

type Trade = shared.Trade

This is an alias to an internal type.

type TradeSide

type TradeSide = shared.TradeSide

The side this trade occurred on.

This is an alias to an internal type.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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