tasty

package module
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2023 License: MIT Imports: 13 Imported by: 0

README

tasty-go

Go Reference GitHub go.mod Go version Go Report Card codecov

This library provides unofficial Go clients for tastytrade API.

You will need to opt into tastytrade's API here

tastytrade

tastytrade pioneered options trading technology for retail traders.

Create your account if you don't already have one to begin trading with tastytrade.

Dependencies

There are very few direct dependencies for this lightweight API wrapper.

Untested endpoints

  • Order reconfirm
    • tastytrade API support has informed me that this endpoint is for Equity Offering orders only.

Installation

go get github.com/austinbspencer.com/tasty-go

Example Usage

Simple usage to get you started.

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient = http.Client{Timeout: time.Duration(30) * time.Second}
	client  *tasty.Client
)

var certCreds = tasty.LoginInfo{Login: os.Getenv("certUsername"), Password: os.Getenv("certPassword")}

func main() {
	client, _ = tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	accounts, err := client.GetMyAccounts()
	if err != nil {
		log.Fatal(err)
	}

	balances, err := client.GetAccountBalances(accounts[0].AccountNumber)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(balances.CashBalance)
}

Basic API Usage

Check out tastytrade's documentation

Auth Patterns (Token, session lifetime)

docs

  • Create / validate / create from remember token
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.ValidateSession()
	if err != nil {
		_, err = client.
			CreateSession(tasty.LoginInfo{
				Login:    client.Session.User.Email,
				Password: *client.Session.RememberToken,
			}, nil)
		if err != nil {
			log.Fatal(err)
		}
	}

	fmt.Println("Session is valid")

	// Destroy the session
	err = client.DestroySession()
	if err != nil {
		log.Fatal(err)
	}
}

User Management

docs

Password Reset

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	err = client.RequestPasswordResetEmail(client.Session.User.Email)
	if err != nil {
		log.Fatal(err)
	}

	// You will get an email with a reset link after the above request
	// This link will have a token in the query
	// https://developer.tastytrade.com/password/reset/?token=this-is-your-token

	// Attach the token along with new password in change request
	// Password change will invalidate all current sessions
	err = client.ChangePassword(tasty.PasswordReset{
		Password:             "newPassword",
		PasswordConfirmation: "newPassword",
		ResetPasswordToken:   "this-is-your-token",
	})
	if err != nil {
		log.Fatal(err)
	}
}

Customer Account Information

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	accounts, err := client.GetMyAccounts()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("I have access to %d accounts!", len(accounts))
}

Account Positions

View all current account positions

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	positions, err := client.GetAccountPositions(accountNumber, tasty.AccountPositionQuery{})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("You have %d positions on your account!", len(positions))
}

Account Balances

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	balances, err := client.GetAccountBalances(accountNumber)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Your account %s has a cash balance of %f.", balances.AccountNumber, balances.CashBalance)
}

Watchlists

docs

Public Watchlists

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	countsOnly := false

	watchlists, err := client.GetPublicWatchlists(countsOnly)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("There are %d public watchlists!", len(watchlists))
}

Instruments

docs and Open API Spec

Equity Options

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	eoSymbol := tasty.EquityOptionsSymbology{
		Symbol:     "AMD",
		OptionType: tasty.Call,
		Strike:     180,
		Expiration: time.Date(2023, 06, 23, 0, 0, 0, 0, time.UTC),
	}

	equityOptions, err := client.GetEquityOptions(tasty.EquityOptionsQuery{Symbols: []string{eoSymbol.Build()}})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Your equity option with underlying symbol: %s", equityOptions[0].UnderlyingSymbol)
}

Future Options

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	future := tasty.FutureSymbology{ProductCode: "ES", MonthCode: tasty.December, YearDigit: 9}

	expiry := time.Date(2019, 9, 27, 0, 0, 0, 0, time.Local)
	fcc := tasty.FutureOptionsSymbology{
		OptionContractCode: "EW4U9",
		FutureContractCode: future.Build(),
		OptionType:         tasty.Put,
		Strike:             2975,
		Expiration:         expiry,
	}

	query := tasty.FutureOptionsQuery{
		Symbols: []string{fcc.Build()},
	}

	futureOptions, err := client.GetFutureOptions(query)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Your future option with underlying symbol: %s", futureOptions[0].UnderlyingSymbol)
}

Transaction History All transactions impacting an accounts balances or positions are available at this endpoint.

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	transactions, _, err := client.GetAccountTransactions(accountNumber, tasty.TransactionsQuery{PerPage: 2})
	if err != nil {
		log.Fatal(err)
	}

	latest := transactions[0]

	fmt.Printf("Your latest transaction was a %s of %s!", latest.TransactionType, latest.UnderlyingSymbol)
}

With Pagination Handling

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	query := tasty.TransactionsQuery{PerPage: 25}

	transactions, pagination, err := client.GetAccountTransactions(accountNumber, query)
	if err != nil {
		log.Fatal(err)
	}

	for pagination.PageOffset < (pagination.TotalPages - 1) {
		query.PageOffset += 1
		moreTransactions, newPagination, err := client.GetAccountTransactions(accountNumber, query)
		if err != nil {
			log.Fatal(err)
		}

		transactions = append(transactions, moreTransactions...)
		pagination = newPagination
	}

	latest := transactions[0]

	fmt.Printf("Your latest transaction was a %s of %s!", latest.TransactionType, latest.UnderlyingSymbol)
}

Order Management

Check out tastytrade's documentation

Search Orders

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	// Query for narrowing search of orders
	query := tasty.OrdersQuery{Status: []tasty.OrderStatus{tasty.Filled}}

	orders, _, err := client.GetAccountOrders(accountNumber, query)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Your account has %d live orders!", len(orders))
}
Search Orders

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	liveOrders, err := client.GetAccountLiveOrders(accountNumber)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Your account has %d live orders!", len(liveOrders))
}

Order Dry Run

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	symbol := "AMD"
	quantity := 1
	action := tasty.BTO

	order := tasty.NewOrder{
		TimeInForce: tasty.Day,
		OrderType:   tasty.Market,
		Legs: []tasty.NewOrderLeg{
			{
				InstrumentType: tasty.EquityIT,
				Symbol:         symbol,
				Quantity:       quantity,
				Action:         action,
			},
		},
	}

	resp, orderErr, err := client.SubmitOrderDryRun(accountNumber, order)
	if err != nil {
		log.Fatal(err)
	} else if orderErr != nil {
		log.Fatal(orderErr)
	}

	fmt.Printf("Your dry run order status is %s!", resp.Order.Status)
}

Submit Order

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	symbol := "RIVN"
	quantity := 1
	action1 := tasty.BTC

	symbol1 := tasty.EquityOptionsSymbology{
		Symbol:     symbol,
		OptionType: tasty.Call,
		Strike:     15,
		Expiration: time.Date(2023, 6, 23, 0, 0, 0, 0, time.Local),
	}

	order := tasty.NewOrder{
		TimeInForce: tasty.GTC,
		OrderType:   tasty.Limit,
		PriceEffect: tasty.Debit,
		Price:       0.04,
		Legs: []tasty.NewOrderLeg{
			{
				InstrumentType: tasty.EquityOptionIT,
				Symbol:         symbol1.Build(),
				Quantity:       quantity,
				Action:         action1,
			},
		},
		Rules: tasty.NewOrderRules{Conditions: []tasty.NewOrderCondition{
			{
				Action:         tasty.Route,
				Symbol:         symbol,
				InstrumentType: "Equity",
				Indicator:      tasty.Last,
				Comparator:     tasty.LTE,
				Threshold:      0.01,
			},
		}},
	}

	resp, orderErr, err := client.SubmitOrder(accountNumber, order)
	if err != nil {
		log.Fatal(err)
	} else if orderErr != nil {
		log.Fatal(orderErr)
	}

	fmt.Printf("Your order with id: %d has a status of %s!", resp.Order.ID, resp.Order.Status)
}

Cancel Order

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"
const orderID = 123456

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	if _, err := client.CancelOrder(accountNumber, orderID); err != nil {
		log.Fatal(err)
	}

	fmt.Println("Order has been cancelled!")
}

Cancel Replace

docs

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	orderID := 68678

	orderECR := tasty.NewOrderECR{
		TimeInForce: tasty.Day,
		Price:       185.45,
		OrderType:   tasty.Limit,
		PriceEffect: tasty.Debit,
		ValueEffect: tasty.Debit,
	}

	newOrder, err := client.ReplaceOrder(accountNumber, orderID, orderECR)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Your order was replaced with order with id: %d has a status of %s!", newOrder.ID, newOrder.Status)
}

Examples

docs

Market Order

order := tasty.NewOrder{
	TimeInForce: tasty.Day,
	OrderType:   tasty.Market,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.EquityIT,
			Symbol: "AMD",
			Quantity: 1,
			Action: tasty.BTO,
		},
	},
}

GTC Closing Order

order := tasty.NewOrder{
	TimeInForce: tasty.GTC,
	Price: 150.25,
	PriceEffect: tasty.Credit,
	OrderType:   tasty.Limit,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.EquityIT,
			Symbol: "AMD",
			Quantity: 1,
			Action: tasty.STC,
		},
	},
}

Short Futures Limit Order

order := tasty.NewOrder{
	TimeInForce: tasty.Day,
	Price: 90.03,
	PriceEffect: tasty.Credit,
	OrderType:   tasty.Limit,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.FutureIT,
			Symbol: "/CLZ2",
			Quantity: 1,
			Action: tasty.STO,
		},
	},
}

Bear Call Spread

eoSymbolShort := tasty.EquityOptionsSymbology{
	Symbol:     "AMD",
	OptionType: tasty.Call,
	Strike:     185,
	Expiration: time.Date(2023, 06, 23, 0, 0, 0, 0, time.UTC),
}

eoSymbolLong := tasty.EquityOptionsSymbology{
	Symbol:     "AMD",
	OptionType: tasty.Call,
	Strike:     187.5,
	Expiration: time.Date(2023, 06, 23, 0, 0, 0, 0, time.UTC),
}

order := tasty.NewOrder{
	TimeInForce: tasty.Day,
	Price:       0.85,
	PriceEffect: tasty.Credit,
	OrderType:   tasty.Limit,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.EquityOptionIT,
			Symbol:         eoSymbolShort.Build(),
			Quantity:       1,
			Action:         tasty.STO,
		},
		{
			InstrumentType: tasty.EquityOptionIT,
			Symbol:         eoSymbolLong.Build(),
			Quantity:       1,
			Action:         tasty.BTO,
		},
	},
}

GTD Order

order := tasty.NewOrder{
	TimeInForce: tasty.GTD,
	GtcDate:     "2023-06-23",
	Price:       0.85,
	PriceEffect: tasty.Credit,
	OrderType:   tasty.Limit,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.EquityIT,
			Symbol:         "AMD",
			Quantity:       1,
			Action:         tasty.BTO,
		},
	},
}

Stop Limit Order

order := tasty.NewOrder{
	TimeInForce: tasty.Day,
	Price:       180.0,
	PriceEffect: tasty.Debit,
	OrderType:   tasty.Limit,
	StopTrigger: 180.0,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.EquityIT,
			Symbol:         "AMD",
			Quantity:       1,
			Action:         tasty.BTO,
		},
	},
}

Notional Cryptocurrency Order

order := tasty.NewOrder{
	TimeInForce: tasty.GTC,
	OrderType:   tasty.NotionalMarket,
	Value:       10.0,
	ValueEffect: tasty.Debit,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.Crypto,
			Symbol:         string(tasty.Bitcoin),
			Action:         tasty.BTO,
		},
	},
}
Example Order Requests

Tastytrade only supports fractional trading of certain equity products.

  • To determine if an equity can be fractionally traded, fetch the equity instrument and check the is-fractional-quantity-eligible field

Check out tastytrade's documentation

Fractional Quantity Order

// Fractional orders must have a minimum monetary value of $5.
// Buy orders for 0.5 shares of a $1 stock will be rejected.
order := tasty.NewOrder{
	TimeInForce: tasty.Day,
	OrderType:   tasty.Market,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.EquityIT,
			Symbol:         "AMD",
			Quantity:       0.5,
			Action:         tasty.BTO,
		},
	},
}

Notional Amount Order

// To buy $10 of AMD stock, submit a Notional Market order with a value
// instead of a price. Omit the quantity field from the legs:
order := tasty.NewOrder{
	TimeInForce: tasty.Day,
	OrderType:   tasty.NotionalMarket,
	Value: 10.0,
	ValueEffect: tasty.Debit,
	Legs: []tasty.NewOrderLeg{
		{
			InstrumentType: tasty.EquityIT,
			Symbol:         "AMD",
			Action:         tasty.BTO,
		},
	},
}

Streaming Market Data

Check out tastytrade's documentation

Get a Streamer Token

This requires using the DXFeed Streamer which isn't supported by tastytrade or this unofficial tastytrade API wrapper.

Check out tastytrade's documentation

package main

import (
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client, _ := tasty.NewCertClient(&hClient)
	_, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	dxFeedData, err := client.GetQuoteStreamerTokens()
	if err != nil {
		log.Fatal(err)
	}

	// Do something with the streamer data
}

Streaming Account Data

Check out tastytrade's documentation

Simple Websocket Account Streamer

This is an oversimplified websocket connection example for streaming account data

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/austinbspencer/tasty-go"
	"golang.org/x/net/websocket"
)

var (
	hClient   = http.Client{Timeout: time.Duration(30) * time.Second}
	certCreds = tasty.LoginInfo{
		Login:      os.Getenv("certUsername"),
		Password:   os.Getenv("certPassword"),
		RememberMe: true,
	}
)

const accountNumber = "5WV48989"

func main() {
	client := tasty.NewCertClient(&hClient)
	_, _, err := client.CreateSession(certCreds, nil)
	if err != nil {
		log.Fatal(err)
	}

	protocol := ""
	origin := "http://localhost:8080"

	// Open Websocket connection
	ws, err := websocket.Dial(client.GetWebsocketURL(), protocol, origin)
	if err != nil {
		log.Fatal(err)
	}

	incomingMessages := make(chan string)
	go readClientMessages(ws, incomingMessages)

	// Send connect message
	response := new(tasty.WebsocketMessage)
	response.Action = "connect"
	response.Value = []string{accountNumber}
	response.AuthToken = *client.Session.SessionToken
	err = websocket.JSON.Send(ws, response)
	if err != nil {
		fmt.Printf("Send failed: %s\n", err.Error())
		os.Exit(1)
	}

	// Subscribe to notifications
	// Add notification subscription message here
	// All available -> https://developer.tastytrade.com/streaming-account-data/#available-actions

	// Await responses and send heartbeats
	i := 0
	for {
		select {
		case <-time.After(time.Duration(time.Second * 15)):
			// Send heartbeat every 15 seconds to keep connection alive
			fmt.Println("sending heartbeat")
			i++
			response := new(tasty.WebsocketMessage)
			response.Action = "heartbeat"
			response.AuthToken = *client.Session.SessionToken
			err = websocket.JSON.Send(ws, response)
			if err != nil {
				fmt.Printf("Send failed: %s\n", err.Error())
				os.Exit(1)
			}
		case message := <-incomingMessages:
			fmt.Println(`Message Received:`, message)
		}
	}
}

func readClientMessages(ws *websocket.Conn, incomingMessages chan string) {
	for {
		var message string
		err := websocket.Message.Receive(ws, &message)
		if err != nil {
			fmt.Printf("Error::: %s\n", err.Error())
			return
		}
		incomingMessages <- message
	}
}

Testing

Nearly 100% code coverage testing.

Run all tests

go test .

Run all tests with code coverage information

go test -race -covermode=atomic -coverprofile=coverage.out -v .

Contributing

Please consider opening an issue if you notice any bugs or areas of possible improvement. You can also fork this repo and open a pull request with your own changes. Be sure that all changes have adequate testing in a similar fashion to the rest of the repository.

Documentation

Index

Constants

View Source
const (
	// InstrumentType.
	Bond           InstrumentType = "Bond"
	Crypto         InstrumentType = "Cryptocurrency"
	CurrencyPair   InstrumentType = "Currency Pair"
	EquityIT       InstrumentType = "Equity"
	EquityOffering InstrumentType = "Equity Offering"
	EquityOptionIT InstrumentType = "Equity Option"
	FutureIT       InstrumentType = "Future"
	FutureOptionIT InstrumentType = "Future Option"
	Index          InstrumentType = "Index"
	Unknown        InstrumentType = "Unknown"
	WarrantIT      InstrumentType = "Warrant"
	// TimeOfDay.
	EndOfDay       TimeOfDay = "EOD"
	BeginningOfDay TimeOfDay = "BOD"
	// TimeInForce.
	Day    TimeInForce = "Day"
	GTC    TimeInForce = "GTC"
	GTD    TimeInForce = "GTD"
	Ext    TimeInForce = "Ext"
	GTCExt TimeInForce = "GTC Ext"
	IOC    TimeInForce = "IOC"
	// OrderType.
	Limit           OrderType = "Limit"
	Market          OrderType = "Market"
	MarketableLimit OrderType = "Marketable Limit"
	Stop            OrderType = "Stop"
	StopLimit       OrderType = "Stop Limit"
	NotionalMarket  OrderType = "Notional Market"
	// PriceEffect.
	Credit PriceEffect = "Credit"
	Debit  PriceEffect = "Debit"
	None   PriceEffect = "None"
	// OrderAction.
	STO  OrderAction = "Sell to Open"
	STC  OrderAction = "Sell to Close"
	BTO  OrderAction = "Buy to Open"
	BTC  OrderAction = "Buy to Close"
	Sell OrderAction = "Sell"
	Buy  OrderAction = "Buy"
	// Direction.
	Long  Direction = "Long"
	Short Direction = "Short"
	// Indicator.
	Last Indicator = "last"
	// Comparator.
	GTE Comparator = "gte"
	LTE Comparator = "lte"
	// OrderRuleAction.
	Route  OrderRuleAction = "route"
	Cancel OrderRuleAction = "cancel"
	// TimeBack.
	OneDay      TimeBack = "1d"
	OneWeek     TimeBack = "1w"
	OneMonth    TimeBack = "1m"
	ThreeMonths TimeBack = "3m"
	SixMonths   TimeBack = "6m"
	OneYear     TimeBack = "1y"
	All         TimeBack = "all"
	// Cryptocurrency.
	Cardano     Cryptocurrency = "ADA/USD"
	Bitcoin     Cryptocurrency = "BTC/USD"
	BitcoinCash Cryptocurrency = "BCH/USD"
	Polkadot    Cryptocurrency = "DOT/USD"
	Dogecoin    Cryptocurrency = "DOGE/USD"
	Ethereum    Cryptocurrency = "ETH/USD"
	Litecoin    Cryptocurrency = "LTC/USD"
	Solana      Cryptocurrency = "SOL/USD"
	// Lendability.
	EasyToBorrow   Lendability = "Easy To Borrow"
	LocateRequired Lendability = "Locate Required"
	Preborrow      Lendability = "Preborrow"
	// OptionType.
	Call OptionType = "C"
	Put  OptionType = "P"
	// MonthCode.
	January   MonthCode = "F"
	February  MonthCode = "G"
	March     MonthCode = "H"
	April     MonthCode = "J"
	May       MonthCode = "K"
	June      MonthCode = "M"
	July      MonthCode = "N"
	August    MonthCode = "Q"
	September MonthCode = "U"
	October   MonthCode = "V"
	November  MonthCode = "X"
	December  MonthCode = "Z"
	// Exchange.
	CME    Exchange = "CME"
	SMALLS Exchange = "SMALLS"
	CFE    Exchange = "CFE"
	CBOED  Exchange = "CBOED"

	// Initial order state.
	Received OrderStatus = "Received"
	// Order is on its way out of Tastytrade's system.
	Routed OrderStatus = "Routed"
	// Order is en route to the exchange.
	InFlight OrderStatus = "In Flight"
	// Order is live at the exchange.
	Live OrderStatus = "Live"
	// Customer has requested to cancel the order.
	// Awaiting a 'cancelled' message from the exchange.
	CancelRequested OrderStatus = "Cancel Requested"
	// Customer has submitted a replacement order.
	// This order is awaiting a 'cancelled' message from the exchange.
	ReplaceRequested OrderStatus = "Replace Requested"
	// This pertains to replacement orders. It means the replacement order
	// is awaiting a 'cancelled' message for the order it is replacing.
	Contingent OrderStatus = "Contingent"
	// Order has been fully filled.
	Filled OrderStatus = "Filled"
	// Order is cancelled.
	Cancelled OrderStatus = "Cancelled"
	// Order has expired. Usually applies to an option order.
	Expired OrderStatus = "Expired"
	// Order has been rejected by either Tastytrade or the exchange.
	Rejected OrderStatus = "Rejected"
	// Administrator has manually removed this order from customer account.
	Removed OrderStatus = "Removed"
	// Administrator has manually removed part of this order from customer account.
	PartiallyRemoved OrderStatus = "Partially Removed"
	// SortOrder.
	Asc  SortOrder = "Asc"
	Desc SortOrder = "Desc"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Account added in v0.2.0

type Account struct {
	AccountNumber         string    `json:"account-number"`
	ExternalID            string    `json:"external-id"`
	OpenedAt              time.Time `json:"opened-at"`
	Nickname              string    `json:"nickname"`
	AccountTypeName       string    `json:"account-type-name"`
	DayTraderStatus       bool      `json:"day-trader-status"`
	ClosedAt              time.Time `json:"closed-at"`
	IsClosed              bool      `json:"is-closed"`
	IsFirmError           bool      `json:"is-firm-error"`
	IsFirmProprietary     bool      `json:"is-firm-proprietary"`
	IsFuturesApproved     bool      `json:"is-futures-approved"`
	IsTestDrive           bool      `json:"is-test-drive"`
	MarginOrCash          string    `json:"margin-or-cash"`
	IsForeign             bool      `json:"is-foreign"`
	FundingDate           string    `json:"funding-date"`
	InvestmentObjective   string    `json:"investment-objective"`
	LiquidityNeeds        string    `json:"liquidity-needs"`
	RiskTolerance         string    `json:"risk-tolerance"`
	InvestmentTimeHorizon string    `json:"investment-time-horizon"`
	FuturesAccountPurpose string    `json:"futures-account-purpose"`
	ExternalFDID          string    `json:"external-fdid"`
	SuitableOptionsLevel  string    `json:"suitable-options-level"`
	CreatedAt             time.Time `json:"created-at"`
	SubmittingUserID      string    `json:"submitting-user-id"`
	AuthorityLevel        string    `json:"authority-level"`
}

type AccountAuthorityDecorator added in v0.2.0

type AccountAuthorityDecorator struct {
	Account        Account `json:"account"`
	AuthorityLevel string  `json:"authority-level"`
}

type AccountBalance added in v0.2.0

type AccountBalance struct {
	AccountNumber                      string          `json:"account-number"`
	CashBalance                        decimal.Decimal `json:"cash-balance"`
	LongEquityValue                    decimal.Decimal `json:"long-equity-value"`
	ShortEquityValue                   decimal.Decimal `json:"short-equity-value"`
	LongDerivativeValue                decimal.Decimal `json:"long-derivative-value"`
	ShortDerivativeValue               decimal.Decimal `json:"short-derivative-value"`
	LongFuturesValue                   decimal.Decimal `json:"long-futures-value"`
	ShortFuturesValue                  decimal.Decimal `json:"short-futures-value"`
	LongFuturesDerivativeValue         decimal.Decimal `json:"long-futures-derivative-value"`
	ShortFuturesDerivativeValue        decimal.Decimal `json:"short-futures-derivative-value"`
	LongMargineableValue               decimal.Decimal `json:"long-margineable-value"`
	ShortMargineableValue              decimal.Decimal `json:"short-margineable-value"`
	MarginEquity                       decimal.Decimal `json:"margin-equity"`
	EquityBuyingPower                  decimal.Decimal `json:"equity-buying-power"`
	DerivativeBuyingPower              decimal.Decimal `json:"derivative-buying-power"`
	DayTradingBuyingPower              decimal.Decimal `json:"day-trading-buying-power"`
	FuturesMarginRequirement           decimal.Decimal `json:"futures-margin-requirement"`
	AvailableTradingFunds              decimal.Decimal `json:"available-trading-funds"`
	MaintenanceRequirement             decimal.Decimal `json:"maintenance-requirement"`
	MaintenanceCallValue               decimal.Decimal `json:"maintenance-call-value"`
	RegTCallValue                      decimal.Decimal `json:"reg-t-call-value"`
	DayTradingCallValue                decimal.Decimal `json:"day-trading-call-value"`
	DayEquityCallValue                 decimal.Decimal `json:"day-equity-call-value"`
	NetLiquidatingValue                decimal.Decimal `json:"net-liquidating-value"`
	CashAvailableToWithdraw            decimal.Decimal `json:"cash-available-to-withdraw"`
	DayTradeExcess                     decimal.Decimal `json:"day-trade-excess"`
	PendingCash                        decimal.Decimal `json:"pending-cash"`
	PendingCashEffect                  PriceEffect     `json:"pending-cash-effect"`
	LongCryptocurrencyValue            decimal.Decimal `json:"long-cryptocurrency-value"`
	ShortCryptocurrencyValue           decimal.Decimal `json:"short-cryptocurrency-value"`
	CryptocurrencyMarginRequirement    decimal.Decimal `json:"cryptocurrency-margin-requirement"`
	UnsettledCryptocurrencyFiatAmount  decimal.Decimal `json:"unsettled-cryptocurrency-fiat-amount"`
	UnsettledCryptocurrencyFiatEffect  PriceEffect     `json:"unsettled-cryptocurrency-fiat-effect"`
	ClosedLoopAvailableBalance         decimal.Decimal `json:"closed-loop-available-balance"`
	EquityOfferingMarginRequirement    decimal.Decimal `json:"equity-offering-margin-requirement"`
	LongBondValue                      decimal.Decimal `json:"long-bond-value"`
	BondMarginRequirement              decimal.Decimal `json:"bond-margin-requirement"`
	SnapshotDate                       string          `json:"snapshot-date"`
	TimeOfDay                          string          `json:"time-of-day"`
	RegTMarginRequirement              decimal.Decimal `json:"reg-t-margin-requirement"`
	FuturesOvernightMarginRequirement  decimal.Decimal `json:"futures-overnight-margin-requirement"`
	FuturesIntradayMarginRequirement   decimal.Decimal `json:"futures-intraday-margin-requirement"`
	MaintenanceExcess                  decimal.Decimal `json:"maintenance-excess"`
	PendingMarginInterest              decimal.Decimal `json:"pending-margin-interest"`
	ApexStartingDayMarginEquity        decimal.Decimal `json:"apex-starting-day-margin-equity"`
	BuyingPowerAdjustment              decimal.Decimal `json:"buying-power-adjustment"`
	BuyingPowerAdjustmentEffect        PriceEffect     `json:"buying-power-adjustment-effect"`
	EffectiveCryptocurrencyBuyingPower decimal.Decimal `json:"effective-cryptocurrency-buying-power"`
	UpdatedAt                          time.Time       `json:"updated-at"`
}

type AccountBalanceSnapshots added in v0.2.0

type AccountBalanceSnapshots struct {
	AccountNumber                      string          `json:"account-number"`
	CashBalance                        decimal.Decimal `json:"cash-balance"`
	LongEquityValue                    decimal.Decimal `json:"long-equity-value"`
	ShortEquityValue                   decimal.Decimal `json:"short-equity-value"`
	LongDerivativeValue                decimal.Decimal `json:"long-derivative-value"`
	ShortDerivativeValue               decimal.Decimal `json:"short-derivative-value"`
	LongFuturesValue                   decimal.Decimal `json:"long-futures-value"`
	ShortFuturesValue                  decimal.Decimal `json:"short-futures-value"`
	LongFuturesDerivativeValue         decimal.Decimal `json:"long-futures-derivative-value"`
	ShortFuturesDerivativeValue        decimal.Decimal `json:"short-futures-derivative-value"`
	LongMargineableValue               decimal.Decimal `json:"long-margineable-value"`
	ShortMargineableValue              decimal.Decimal `json:"short-margineable-value"`
	MarginEquity                       decimal.Decimal `json:"margin-equity"`
	EquityBuyingPower                  decimal.Decimal `json:"equity-buying-power"`
	DerivativeBuyingPower              decimal.Decimal `json:"derivative-buying-power"`
	DayTradingBuyingPower              decimal.Decimal `json:"day-trading-buying-power"`
	FuturesMarginRequirement           decimal.Decimal `json:"futures-margin-requirement"`
	AvailableTradingFunds              decimal.Decimal `json:"available-trading-funds"`
	MaintenanceRequirement             decimal.Decimal `json:"maintenance-requirement"`
	MaintenanceCallValue               decimal.Decimal `json:"maintenance-call-value"`
	RegTCallValue                      decimal.Decimal `json:"reg-t-call-value"`
	DayTradingCallValue                decimal.Decimal `json:"day-trading-call-value"`
	DayEquityCallValue                 decimal.Decimal `json:"day-equity-call-value"`
	NetLiquidatingValue                decimal.Decimal `json:"net-liquidating-value"`
	CashAvailableToWithdraw            decimal.Decimal `json:"cash-available-to-withdraw"`
	DayTradeExcess                     decimal.Decimal `json:"day-trade-excess"`
	PendingCash                        decimal.Decimal `json:"pending-cash"`
	PendingCashEffect                  PriceEffect     `json:"pending-cash-effect"`
	LongCryptocurrencyValue            decimal.Decimal `json:"long-cryptocurrency-value"`
	ShortCryptocurrencyValue           decimal.Decimal `json:"short-cryptocurrency-value"`
	CryptocurrencyMarginRequirement    decimal.Decimal `json:"cryptocurrency-margin-requirement"`
	UnsettledCryptocurrencyFiatAmount  decimal.Decimal `json:"unsettled-cryptocurrency-fiat-amount"`
	UnsettledCryptocurrencyFiatEffect  PriceEffect     `json:"unsettled-cryptocurrency-fiat-effect"`
	ClosedLoopAvailableBalance         decimal.Decimal `json:"closed-loop-available-balance"`
	EquityOfferingMarginRequirement    decimal.Decimal `json:"equity-offering-margin-requirement"`
	LongBondValue                      decimal.Decimal `json:"long-bond-value"`
	BondMarginRequirement              decimal.Decimal `json:"bond-margin-requirement"`
	SnapshotDate                       string          `json:"snapshot-date"`
	RegTMarginRequirement              decimal.Decimal `json:"reg-t-margin-requirement"`
	FuturesOvernightMarginRequirement  decimal.Decimal `json:"futures-overnight-margin-requirement"`
	FuturesIntradayMarginRequirement   decimal.Decimal `json:"futures-intraday-margin-requirement"`
	MaintenanceExcess                  decimal.Decimal `json:"maintenance-excess"`
	PendingMarginInterest              decimal.Decimal `json:"pending-margin-interest"`
	EffectiveCryptocurrencyBuyingPower decimal.Decimal `json:"effective-cryptocurrency-buying-power"`
	UpdatedAt                          time.Time       `json:"updated-at"`
}

type AccountBalanceSnapshotsQuery added in v0.2.0

type AccountBalanceSnapshotsQuery struct {
	// SnapshotDate The day of the balance snapshot to retrieve
	SnapshotDate time.Time `layout:"2006-01-02" url:"snapshot-date,omitempty"`
	// TimeOfDay The abbreviation for the time of day. Default value: EOD
	// Available values: EOD, BOD.
	TimeOfDay TimeOfDay `url:"time-of-day"`
}

Filtering for the account balance snapshots endpoint.

type AccountPosition added in v0.2.0

type AccountPosition struct {
	AccountNumber                 string          `json:"account-number"`
	Symbol                        string          `json:"symbol"`
	InstrumentType                InstrumentType  `json:"instrument-type"`
	UnderlyingSymbol              string          `json:"underlying-symbol"`
	Quantity                      int             `json:"quantity"`
	QuantityDirection             Direction       `json:"quantity-direction"`
	ClosePrice                    decimal.Decimal `json:"close-price"`
	AverageOpenPrice              decimal.Decimal `json:"average-open-price"`
	AverageYearlyMarketClosePrice decimal.Decimal `json:"average-yearly-market-close-price"`
	AverageDailyMarketClosePrice  decimal.Decimal `json:"average-daily-market-close-price"`
	Mark                          decimal.Decimal `json:"mark"`
	MarkPrice                     decimal.Decimal `json:"mark-price"`
	Multiplier                    int             `json:"multiplier"`
	CostEffect                    PriceEffect     `json:"cost-effect"`
	IsSuppressed                  bool            `json:"is-suppressed"`
	IsFrozen                      bool            `json:"is-frozen"`
	RestrictedQuantity            int             `json:"restricted-quantity"`
	ExpiresAt                     time.Time       `json:"expires-at"`
	FixingPrice                   decimal.Decimal `json:"fixing-price"`
	DeliverableType               string          `json:"deliverable-type"`
	RealizedDayGain               decimal.Decimal `json:"realized-day-gain"`
	RealizedDayGainEffect         PriceEffect     `json:"realized-day-gain-effect"`
	RealizedDayGainDate           string          `json:"realized-day-gain-date"`
	RealizedToday                 decimal.Decimal `json:"realized-today"`
	RealizedTodayEffect           PriceEffect     `json:"realized-today-effect"`
	RealizedTodayDate             string          `json:"realized-today-date"`
	CreatedAt                     time.Time       `json:"created-at"`
	UpdatedAt                     time.Time       `json:"updated-at"`
}

type AccountPositionQuery added in v0.2.0

type AccountPositionQuery struct {
	// UnderlyingSymbol An array of Underlying symbol(s) for positions
	UnderlyingSymbol []string `url:"underlying-symbol[],omitempty"`
	// Symbol A single symbol. Stock Ticker Symbol AAPL,
	// OCC Option Symbol AAPL 191004P00275000,
	// TW Future Symbol /ESZ9, or
	// TW Future Option Symbol ./ESZ9 EW4U9 190927P2975
	Symbol string `url:"symbol,omitempty"`
	// InstrumentType The type of Instrument
	InstrumentType InstrumentType `url:"instrument-type,omitempty"`
	// IncludeClosedPositions If closed positions should be included in the query
	IncludeClosedPositions bool `url:"include-closed-positions,omitempty"`
	// UnderlyingProductCode The underlying Future's Product code. i.e ES
	UnderlyingProductCode string `url:"underlying-product-code,omitempty"`
	// PartitionKeys Account partition keys
	PartitionKeys []string `url:"partition-keys[],omitempty"`
	// NetPositions Returns net positions grouped by instrument type and symbol
	NetPositions bool `url:"net-positions,omitempty"`
	// IncludeMarks Include current quote mark (note: can decrease performance)
	IncludeMarks bool `url:"include-marks,omitempty"`
}

Optional filtering available for position endpoint.

type AccountTradingStatus added in v0.2.0

type AccountTradingStatus struct {
	AccountNumber                            string          `json:"account-number"`
	AutotradeAccountType                     string          `json:"autotrade-account-type"`
	ClearingAccountNumber                    string          `json:"clearing-account-number"`
	ClearingAggregationIdentifier            string          `json:"clearing-aggregation-identifier"`
	DayTradeCount                            int             `json:"day-trade-count"`
	EquitiesMarginCalculationType            string          `json:"equities-margin-calculation-type"`
	FeeScheduleName                          string          `json:"fee-schedule-name"`
	FuturesMarginRateMultiplier              decimal.Decimal `json:"futures-margin-rate-multiplier"`
	HasIntradayEquitiesMargin                bool            `json:"has-intraday-equities-margin"`
	ID                                       int             `json:"id"`
	IsAggregatedAtClearing                   bool            `json:"is-aggregated-at-clearing"`
	IsClosed                                 bool            `json:"is-closed"`
	IsClosingOnly                            bool            `json:"is-closing-only"`
	IsCryptocurrencyClosingOnly              bool            `json:"is-cryptocurrency-closing-only"`
	IsCryptocurrencyEnabled                  bool            `json:"is-cryptocurrency-enabled"`
	IsFrozen                                 bool            `json:"is-frozen"`
	IsFullEquityMarginRequired               bool            `json:"is-full-equity-margin-required"`
	IsFuturesClosingOnly                     bool            `json:"is-futures-closing-only"`
	IsFuturesIntraDayEnabled                 bool            `json:"is-futures-intra-day-enabled"`
	IsFuturesEnabled                         bool            `json:"is-futures-enabled"`
	IsInDayTradeEquityMaintenanceCall        bool            `json:"is-in-day-trade-equity-maintenance-call"`
	IsInMarginCall                           bool            `json:"is-in-margin-call"`
	IsPatternDayTrader                       bool            `json:"is-pattern-day-trader"`
	IsPortfolioMarginEnabled                 bool            `json:"is-portfolio-margin-enabled"`
	IsRiskReducingOnly                       bool            `json:"is-risk-reducing-only"`
	IsSmallNotionalFuturesIntraDayEnabled    bool            `json:"is-small-notional-futures-intra-day-enabled"`
	IsRollTheDayForwardEnabled               bool            `json:"is-roll-the-day-forward-enabled"`
	AreFarOtmNetOptionsRestricted            bool            `json:"are-far-otm-net-options-restricted"`
	OptionsLevel                             string          `json:"options-level"`
	PdtResetOn                               string          `json:"pdt-reset-on"`
	ShortCallsEnabled                        bool            `json:"short-calls-enabled"`
	SmallNotionalFuturesMarginRateMultiplier decimal.Decimal `json:"small-notional-futures-margin-rate-multiplier"`
	CMTAOverride                             int             `json:"cmta-override"`
	IsEquityOfferingEnabled                  bool            `json:"is-equity-offering-enabled"`
	IsEquityOfferingClosingOnly              bool            `json:"is-equity-offering-closing-only"`
	EnhancedFraudSafeguardsEnabledAt         time.Time       `json:"enhanced-fraud-safeguards-enabled-at"`
	UpdatedAt                                time.Time       `json:"updated-at"`
}

type AccountType added in v0.2.0

type AccountType struct {
	Name                string       `json:"name"`
	Description         string       `json:"description"`
	IsTaxAdvantaged     bool         `json:"is-tax-advantaged"`
	HasMultipleOwners   bool         `json:"has-multiple-owners"`
	IsPubliclyAvailable bool         `json:"is-publicly-available"`
	MarginTypes         []MarginType `json:"margin-types"`
}

type ActiveEquitiesQuery added in v0.2.0

type ActiveEquitiesQuery struct {
	// PerPage equities to return per page. Default: 1000
	PerPage int `url:"per-page"`
	// PageOffset defaults to 0
	PageOffset int `url:"page-offset"`
	// Lendability Available values : Easy To Borrow, Locate Required, Preborrow
	Lendability Lendability `url:"lendability"`
}

type Address added in v0.2.0

type Address struct {
	StreetOne   string `json:"street-one"`
	StreetTwo   string `json:"street-two"`
	StreetThree string `json:"street-three"`
	City        string `json:"city"`
	StateRegion string `json:"state-region"`
	PostalCode  string `json:"postal-code"`
	Country     string `json:"country"`
	IsForeign   bool   `json:"is-foreign"`
	IsDomestic  bool   `json:"is-domestic"`
}

type BuyingPowerEffect added in v0.2.0

type BuyingPowerEffect struct {
	ChangeInMarginRequirement            decimal.Decimal `json:"change-in-margin-requirement"`
	ChangeInMarginRequirementEffect      PriceEffect     `json:"change-in-margin-requirement-effect"`
	ChangeInBuyingPower                  decimal.Decimal `json:"change-in-buying-power"`
	ChangeInBuyingPowerEffect            PriceEffect     `json:"change-in-buying-power-effect"`
	CurrentBuyingPower                   decimal.Decimal `json:"current-buying-power"`
	CurrentBuyingPowerEffect             PriceEffect     `json:"current-buying-power-effect"`
	NewBuyingPower                       decimal.Decimal `json:"new-buying-power"`
	NewBuyingPowerEffect                 PriceEffect     `json:"new-buying-power-effect"`
	IsolatedOrderMarginRequirement       decimal.Decimal `json:"isolated-order-margin-requirement"`
	IsolatedOrderMarginRequirementEffect PriceEffect     `json:"isolated-order-margin-requirement-effect"`
	IsSpread                             bool            `json:"is-spread"`
	Impact                               decimal.Decimal `json:"impact"`
	Effect                               PriceEffect     `json:"effect"`
}

type Client

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

Client for the tasty api wrapper.

func NewCertClient

func NewCertClient(httpClient *http.Client) *Client

NewCertClient creates a new Tasty Cert Client.

func NewClient

func NewClient(httpClient *http.Client) *Client

NewClient creates a new Tasty Client.

func (*Client) CancelOrder

func (c *Client) CancelOrder(accountNumber string, id int) (Order, *http.Response, error)

Requests order cancellation.

func (*Client) ChangePassword added in v0.3.0

func (c *Client) ChangePassword(resetInfo PasswordReset) (*http.Response, error)

Request a password reset email.

func (*Client) CreateSession

func (c *Client) CreateSession(login LoginInfo, twoFactorCode *string) (Session, *http.Response, error)

Create a new user session.

func (*Client) CreateWatchlist

func (c *Client) CreateWatchlist(watchlist NewWatchlist) (Watchlist, *http.Response, error)

Create an account watchlist.

func (*Client) DeleteWatchlist

func (c *Client) DeleteWatchlist(name string) (RemovedWatchlist, *http.Response, error)

Delete a watchlist for the given account.

func (*Client) DestroySession

func (c *Client) DestroySession() (*http.Response, error)

Destroy the user session and invalidate the token.

func (*Client) EditWatchlist

func (c *Client) EditWatchlist(name string, watchlist NewWatchlist) (Watchlist, *http.Response, error)

Replace all properties of an account watchlist.

func (*Client) GetAccountBalanceSnapshots

func (c *Client) GetAccountBalanceSnapshots(accountNumber string, query AccountBalanceSnapshotsQuery) ([]AccountBalanceSnapshots, *http.Response, error)

Returns most recent snapshot and current balance for an account.

func (*Client) GetAccountBalances

func (c *Client) GetAccountBalances(accountNumber string) (AccountBalance, *http.Response, error)

Returns the current balance values for an account.

func (*Client) GetAccountLiveOrders

func (c *Client) GetAccountLiveOrders(accountNumber string) ([]Order, *http.Response, error)

Returns a list of live orders for the resource.

func (*Client) GetAccountNetLiqHistory

func (c *Client) GetAccountNetLiqHistory(accountNumber string, query HistoricLiquidityQuery) ([]NetLiqOHLC, *http.Response, error)

Returns a list of account net liquidating value snapshots.

func (*Client) GetAccountOrders

func (c *Client) GetAccountOrders(accountNumber string, query OrdersQuery) ([]Order, Pagination, *http.Response, error)

Returns a paginated list of the account's orders (as identified by the provided authentication token) based on sort param. If no sort is passed in, it defaults to descending order.

func (*Client) GetAccountPositionLimit

func (c *Client) GetAccountPositionLimit(accountNumber string) (PositionLimit, *http.Response, error)

Get the position limit.

func (*Client) GetAccountPositions

func (c *Client) GetAccountPositions(accountNumber string, query AccountPositionQuery) ([]AccountPosition, *http.Response, error)

Returns a list of the account's positions. Can be filtered by symbol, underlying_symbol.

func (*Client) GetAccountTradingStatus

func (c *Client) GetAccountTradingStatus(accountNumber string) (AccountTradingStatus, *http.Response, error)

Returns current trading status for an account.

func (*Client) GetAccountTransaction

func (c *Client) GetAccountTransaction(accountNumber string, id int) (Transaction, *http.Response, error)

Retrieve a transaction by account number and ID.

func (*Client) GetAccountTransactionFees

func (c *Client) GetAccountTransactionFees(accountNumber string, date *time.Time) (TransactionFees, *http.Response, error)

Return the total fees for an account for a given day the day will default to today.

func (*Client) GetAccountTransactions

func (c *Client) GetAccountTransactions(accountNumber string, query TransactionsQuery) ([]Transaction, Pagination, *http.Response, error)

Returns a paginated list of the account's transactions (as identified by the provided authentication token) based on sort param. If no sort is passed in, it defaults to descending order.

func (*Client) GetActiveEquities

func (c *Client) GetActiveEquities(query ActiveEquitiesQuery) ([]Equity, Pagination, *http.Response, error)

Returns all active equities in a paginated fashion.

func (*Client) GetCompactEquityOptionChains

func (c *Client) GetCompactEquityOptionChains(symbol string) ([]CompactOptionChains, *http.Response, error)

Returns an option chain given an underlying symbol, i.e. AAPL in a compact form to minimize content size.

func (*Client) GetCryptocurrencies

func (c *Client) GetCryptocurrencies(symbols []string) ([]CryptocurrencyInfo, *http.Response, error)

Retrieve a set of cryptocurrencies given an array of one or more symbols.

func (*Client) GetCryptocurrency

func (c *Client) GetCryptocurrency(symbol Cryptocurrency) (CryptocurrencyInfo, *http.Response, error)

Retrieve a cryptocurrency given a symbol.

func (*Client) GetCustomer

func (c *Client) GetCustomer(customerID string) (Customer, *http.Response, error)

Get a full customer resource.

func (*Client) GetCustomerAccount added in v0.1.1

func (c *Client) GetCustomerAccount(customerID, accountNumber string) (Account, *http.Response, error)

Get a full customer account resource.

func (*Client) GetCustomerAccounts

func (c *Client) GetCustomerAccounts(customerID string) ([]Account, *http.Response, error)

Get a list of all the customer account resources attached to the current customer.

func (*Client) GetCustomerLiveOrders

func (c *Client) GetCustomerLiveOrders(customerID string, query OrdersQuery) ([]Order, *http.Response, error)

Returns a list of live orders for the resource. Requires account numbers param to pull orders from.

func (*Client) GetCustomerOrders

func (c *Client) GetCustomerOrders(customerID string, query OrdersQuery) ([]Order, *http.Response, error)

Returns a paginated list of the customer's orders (as identified by the provided authentication token) based on sort param. If no sort is passed in, it defaults to descending order. Requires account numbers param to pull orders from.

func (*Client) GetEffectiveMarginRequirements

func (c *Client) GetEffectiveMarginRequirements(accountNumber, underlyingSymbol string) (EffectiveMarginRequirements, *http.Response, error)

Get effective margin requirements for account.

func (*Client) GetEquities

func (c *Client) GetEquities(query EquitiesQuery) ([]Equity, *http.Response, error)

Returns a set of equity definitions given an array of one or more symbols.

func (*Client) GetEquity

func (c *Client) GetEquity(symbol string) (Equity, *http.Response, error)

Returns a single equity definition for the provided symbol.

func (*Client) GetEquityOption

func (c *Client) GetEquityOption(sym EquityOptionsSymbology, active bool) (EquityOption, *http.Response, error)

Returns a set of equity options given one or more symbols.

func (*Client) GetEquityOptionChains

func (c *Client) GetEquityOptionChains(symbol string) ([]EquityOption, *http.Response, error)

Returns an option chain given an underlying symbol, i.e. AAPL.

func (*Client) GetEquityOptions

func (c *Client) GetEquityOptions(query EquityOptionsQuery) ([]EquityOption, *http.Response, error)

Returns a set of equity options given one or more symbols.

func (*Client) GetFuture

func (c *Client) GetFuture(symbol string) (Future, *http.Response, error)

Returns an outright future given a symbol.

func (*Client) GetFutureOption

func (c *Client) GetFutureOption(symbol string) (FutureOption, *http.Response, error)

Returns a future option given a symbol. Uses TW symbology: ./ESZ9 EW4U9 190927P2975.

func (*Client) GetFutureOptionProduct

func (c *Client) GetFutureOptionProduct(exchange, rootSymbol string) (FutureOptionProduct, *http.Response, error)

Get a future option product by exchange and root symbol.

func (*Client) GetFutureOptionProducts

func (c *Client) GetFutureOptionProducts() ([]FutureOptionProduct, *http.Response, error)

Returns metadata for all supported future option products.

func (*Client) GetFutureOptions

func (c *Client) GetFutureOptions(query FutureOptionsQuery) ([]FutureOption, *http.Response, error)

Returns a set of future option(s) given an array of one or more symbols. Uses TW symbology: [./ESZ9 EW4U9 190927P2975].

func (*Client) GetFutureProduct

func (c *Client) GetFutureProduct(exchange Exchange, productCode string) (FutureProduct, *http.Response, error)

Get future product from exchange and product code.

func (*Client) GetFutureProducts

func (c *Client) GetFutureProducts() ([]FutureProduct, *http.Response, error)

Returns metadata for all supported futures products.

func (*Client) GetFutures

func (c *Client) GetFutures(query FuturesQuery) ([]Future, *http.Response, error)

Returns a set of outright futures given an array of one or more symbols.

func (*Client) GetFuturesOptionChains

func (c *Client) GetFuturesOptionChains(productCode string) ([]FutureOption, *http.Response, error)

Returns a futures option chain given a futures product code, i.e. ES.

func (*Client) GetHistoricDividends

func (c *Client) GetHistoricDividends(symbol string) ([]DividendInfo, *http.Response, error)

Get historical dividend data.

func (*Client) GetHistoricEarnings

func (c *Client) GetHistoricEarnings(symbol string, startDate time.Time) ([]EarningsInfo, *http.Response, error)

Get historical earnings data.

func (*Client) GetMarginRequirements

func (c *Client) GetMarginRequirements(accountNumber string) (MarginRequirements, *http.Response, error)

Fetch current margin/capital requirements report for an account.

func (*Client) GetMarginRequirementsPublicConfiguration added in v0.7.1

func (c *Client) GetMarginRequirementsPublicConfiguration() (MarginRequirementsGlobalConfiguration,
	*http.Response, error)

Publicly accessible, read only margin configuration.

func (*Client) GetMarketMetrics

func (c *Client) GetMarketMetrics(symbols []string) ([]MarketMetricVolatility, *http.Response, error)

Returns an array of volatility data for given symbols.

func (*Client) GetMyAccount added in v0.1.1

func (c *Client) GetMyAccount(accountNumber string) (Account, *http.Response, error)

Get authenticated user's full account resource.

func (*Client) GetMyAccounts

func (c *Client) GetMyAccounts() ([]Account, *http.Response, error)

Get the accounts for the authenticated client.

func (*Client) GetMyCustomerInfo

func (c *Client) GetMyCustomerInfo() (Customer, *http.Response, error)

Get authenticated customer.

func (*Client) GetMyWatchlist

func (c *Client) GetMyWatchlist(name string) (Watchlist, *http.Response, error)

Returns a requested account watchlist.

func (*Client) GetMyWatchlists

func (c *Client) GetMyWatchlists() ([]Watchlist, *http.Response, error)

Returns a list of all watchlists for the given account.

func (*Client) GetNestedEquityOptionChains

func (c *Client) GetNestedEquityOptionChains(symbol string) ([]NestedOptionChains, *http.Response, error)

Returns an option chain given an underlying symbol, i.e. AAPL in a nested form to minimize redundant processing.

func (*Client) GetNestedFuturesOptionChains

func (c *Client) GetNestedFuturesOptionChains(productCode string) (NestedFuturesOptionChains, *http.Response, error)

Returns a futures option chain given a futures product code in a nested form to minimize redundant processing.

func (*Client) GetOrder

func (c *Client) GetOrder(accountNumber string, id int) (Order, *http.Response, error)

Returns a single order based on the id.

func (*Client) GetPairsWatchlist

func (c *Client) GetPairsWatchlist(name string) (PairsWatchlist, *http.Response, error)

Returns a requested tastytrade pairs watchlist.

func (*Client) GetPairsWatchlists

func (c *Client) GetPairsWatchlists() ([]PairsWatchlist, *http.Response, error)

Returns a list of all tastytrade pairs watchlists.

func (*Client) GetPublicWatchlist

func (c *Client) GetPublicWatchlist(name string) (Watchlist, *http.Response, error)

Returns a requested tastytrade watchlist.

func (*Client) GetPublicWatchlists

func (c *Client) GetPublicWatchlists(countsOnly bool) ([]PublicWatchlist, *http.Response, error)

Returns a list of all tastytrade watchlists.

func (*Client) GetQuantityDecimalPrecisions

func (c *Client) GetQuantityDecimalPrecisions() ([]QuantityDecimalPrecision, *http.Response, error)

Retrieve all quantity decimal precisions.

func (*Client) GetQuoteStreamerTokens

func (c *Client) GetQuoteStreamerTokens() (QuoteStreamerTokenAuthResult, *http.Response, error)

Returns the appropriate API quote streamer endpoint, level and identification token for the current customer to receive market data.

func (*Client) GetWarrant

func (c *Client) GetWarrant(symbol string) (Warrant, *http.Response, error)

Returns a single warrant definition for the provided symbol.

func (*Client) GetWarrants

func (c *Client) GetWarrants(symbols []string) ([]Warrant, *http.Response, error)

Returns a set of warrant definitions that can be filtered by parameters.

func (Client) GetWebsocketURL added in v0.7.2

func (c Client) GetWebsocketURL() string

Getter for the tastytrade account streaming websocket url.

func (*Client) PatchOrder

func (c *Client) PatchOrder(accountNumber string, id int, orderECR NewOrderECR) (Order, *http.Response, error)

Edit price and execution properties of a live order by replacement. Subsequent fills of the original order will abort the replacement.

func (*Client) ReconfirmOrder

func (c *Client) ReconfirmOrder(accountNumber string, id int) (Order, *http.Response, error)

Reconfirm an order ** This is currently untested. Requires the order to be an Equity Offering Unable to submit equity offering orders even in cert environment equity_offering_not_supported.

func (*Client) ReplaceOrder

func (c *Client) ReplaceOrder(accountNumber string, id int, orderECR NewOrderECR) (Order, *http.Response, error)

Replaces a live order with a new one. Subsequent fills of the original order will abort the replacement.

func (*Client) RequestPasswordResetEmail added in v0.3.0

func (c *Client) RequestPasswordResetEmail(email string) (*http.Response, error)

Request a password reset email.

func (*Client) SubmitOrder

func (c *Client) SubmitOrder(accountNumber string, order NewOrder) (OrderResponse, *OrderErrorResponse, *http.Response, error)

Create an order for the client.

func (*Client) SubmitOrderDryRun

func (c *Client) SubmitOrderDryRun(accountNumber string, order NewOrder) (OrderResponse, *OrderErrorResponse, *http.Response, error)

Create an order and then runs the preflights without placing the order.

func (*Client) SubmitOrderECRDryRun

func (c *Client) SubmitOrderECRDryRun(accountNumber string, id int, orderECR NewOrderECR) (OrderResponse, *http.Response, error)

Runs through preflights for cancel-replace and edit without routing.

func (*Client) SymbolSearch

func (c *Client) SymbolSearch(symbol string) ([]SymbolData, *http.Response, error)

Returns an array of symbol data.

func (*Client) ValidateSession

func (c *Client) ValidateSession() (User, *http.Response, error)

Validate the user session.

type CompactOptionChains added in v0.2.0

type CompactOptionChains struct {
	UnderlyingSymbol  string        `json:"underlying-symbol"`
	RootSymbol        string        `json:"root-symbol"`
	OptionChainType   string        `json:"option-chain-type"`
	SettlementType    string        `json:"settlement-type"`
	SharesPerContract int           `json:"shares-per-contract"`
	ExpirationType    string        `json:"expiration-type"`
	Deliverables      []Deliverable `json:"deliverables"`
	Symbols           []string      `json:"symbols"`
	StreamerSymbols   []string      `json:"streamer-symbols"`
}

type Comparator added in v0.2.0

type Comparator string

type ComplexOrder added in v0.2.0

type ComplexOrder struct {
	ID                                   int             `json:"id"`
	AccountNumber                        string          `json:"account-number"`
	Type                                 string          `json:"type"`
	TerminalAt                           string          `json:"terminal-at"`
	RatioPriceThreshold                  decimal.Decimal `json:"ratio-price-threshold"`
	RatioPriceComparator                 string          `json:"ratio-price-comparator"`
	RatioPriceIsThresholdBasedOnNotional bool            `json:"ratio-price-is-threshold-based-on-notional"`
	// RelatedOrders Non-current orders. This includes replaced orders, unfilled orders, and terminal orders.
	RelatedOrders []RelatedOrder `json:"related-orders"`
	// Orders with complex-order-tag: '::order'. For example, 'OTO::order' for OTO complex orders.
	Orders []Order `json:"orders"`
	// TriggerOrder Order with complex-order-tag: '::trigger-order'. For example, 'OTO::trigger-order for OTO complex orders.
	TriggerOrder Order `json:"trigger-order"`
}

type Cryptocurrency added in v0.2.0

type Cryptocurrency string

type CryptocurrencyInfo added in v0.2.0

type CryptocurrencyInfo struct {
	ID                      int                      `json:"id"`
	Symbol                  string                   `json:"symbol"`
	InstrumentType          InstrumentType           `json:"instrument-type"`
	ShortDescription        string                   `json:"short-description"`
	Description             string                   `json:"description"`
	IsClosingOnly           bool                     `json:"is-closing-only"`
	Active                  bool                     `json:"active"`
	TickSize                decimal.Decimal          `json:"tick-size"`
	StreamerSymbol          string                   `json:"streamer-symbol"`
	DestinationVenueSymbols []DestinationVenueSymbol `json:"destination-venue-symbols"`
}

type Customer added in v0.2.0

type Customer struct {
	ID                              string              `json:"id"`
	PrefixName                      string              `json:"prefix-name"`
	FirstName                       string              `json:"first-name"`
	MiddleName                      string              `json:"middle-name"`
	LastName                        string              `json:"last-name"`
	SuffixName                      string              `json:"suffix-name"`
	FirstSurname                    string              `json:"first-surname"`
	SecondSurname                   string              `json:"second-surname"`
	Address                         Address             `json:"address"`
	MailingAddress                  Address             `json:"mailing-address"`
	CustomerSuitability             CustomerSuitability `json:"customer-suitability"`
	UsaCitizenshipType              string              `json:"usa-citizenship-type"`
	IsForeign                       bool                `json:"is-foreign"`
	MobilePhoneNumber               string              `json:"mobile-phone-number"`
	WorkPhoneNumber                 string              `json:"work-phone-number"`
	HomePhoneNumber                 string              `json:"home-phone-number"`
	Email                           string              `json:"email"`
	TaxNumberType                   string              `json:"tax-number-type"`
	TaxNumber                       string              `json:"tax-number"`
	ForeignTaxNumber                string              `json:"foreign-tax-number"`
	BirthDate                       string              `json:"birth-date"`
	ExternalID                      string              `json:"external-id"`
	CitizenshipCountry              string              `json:"citizenship-country"`
	BirthCountry                    string              `json:"birth-country"`
	VisaType                        string              `json:"visa-type"`
	VisaExpirationDate              string              `json:"visa-expiration-date"`
	SubjectToTaxWithholding         bool                `json:"subject-to-tax-withholding"`
	AgreedToMargining               bool                `json:"agreed-to-margining"`
	AgreedToTerms                   bool                `json:"agreed-to-terms"`
	SignatureOfAgreement            bool                `json:"signature-of-agreement"`
	Gender                          string              `json:"gender"`
	HasIndustryAffiliation          bool                `json:"has-industry-affiliation"`
	IndustryAffiliationFirm         string              `json:"industry-affiliation-firm"`
	HasPoliticalAffiliation         bool                `json:"has-political-affiliation"`
	PoliticalOrganization           string              `json:"political-organization"`
	FamilyMemberNames               string              `json:"family-member-names"`
	HasListedAffiliation            bool                `json:"has-listed-affiliation"`
	ListedAffiliationSymbol         string              `json:"listed-affiliation-symbol"`
	IsInvestmentAdviser             bool                `json:"is-investment-adviser"`
	HasInstitutionalAssets          bool                `json:"has-institutional-assets"`
	DeskCustomerID                  string              `json:"desk-customer-id"`
	UserID                          string              `json:"user-id"`
	IsProfessional                  bool                `json:"is-professional"`
	HasDelayedQuotes                bool                `json:"has-delayed-quotes"`
	HasPendingOrApprovedApplication bool                `json:"has-pending-or-approved-application"`
	PermittedAccountTypes           []AccountType       `json:"permitted-account-types"`
	IdentifiableType                string              `json:"identifiable-type"`
	Person                          Person              `json:"person"`
	Entity                          Entity              `json:"entity"`
}

type CustomerSuitability added in v0.2.0

type CustomerSuitability struct {
	ID                                int    `json:"id"`
	CustomerID                        int    `json:"customer-id"`
	MaritalStatus                     string `json:"marital-status"`
	NumberOfDependents                int    `json:"number-of-dependents"`
	EmploymentStatus                  string `json:"employment-status"`
	Occupation                        string `json:"occupation"`
	EmployerName                      string `json:"employer-name"`
	JobTitle                          string `json:"job-title"`
	AnnualNetIncome                   int    `json:"annual-net-income"`
	NetWorth                          int    `json:"net-worth"`
	LiquidNetWorth                    int    `json:"liquid-net-worth"`
	StockTradingExperience            string `json:"stock-trading-experience"`
	CoveredOptionsTradingExperience   string `json:"covered-options-trading-experience"`
	UncoveredOptionsTradingExperience string `json:"uncovered-options-trading-experience"`
	FuturesTradingExperience          string `json:"futures-trading-experience"`
	TaxBracket                        string `json:"tax-bracket"`
}

type Deliverable added in v0.2.0

type Deliverable struct {
	ID              int             `json:"id"`
	RootSymbol      string          `json:"root-symbol"`
	DeliverableType string          `json:"deliverable-type"`
	Description     string          `json:"description"`
	Amount          decimal.Decimal `json:"amount"`
	Symbol          string          `json:"symbol"`
	InstrumentType  InstrumentType  `json:"instrument-type"`
	Percent         decimal.Decimal `json:"percent"`
}

type DestinationVenueSymbol added in v0.2.0

type DestinationVenueSymbol struct {
	ID                   int    `json:"id"`
	Symbol               string `json:"symbol"`
	DestinationVenue     string `json:"destination-venue"`
	MaxQuantityPrecision int    `json:"max-quantity-precision"`
	MaxPricePrecision    int    `json:"max-price-precision"`
	Routable             bool   `json:"routable"`
}

type Direction added in v0.2.0

type Direction string

type DividendInfo added in v0.2.0

type DividendInfo struct {
	OccurredDate string          `json:"occurred-date"`
	Amount       decimal.Decimal `json:"amount"`
}

type Earnings added in v0.2.0

type Earnings struct {
	Visible            bool            `json:"visible"`
	ExpectedReportDate string          `json:"expected-report-date"`
	Estimated          bool            `json:"estimated"`
	LateFlag           int             `json:"late-flag"`
	QuarterEndDate     string          `json:"quarter-end-date"`
	ActualEPS          decimal.Decimal `json:"actual-eps"`
	ConsensusEstimate  decimal.Decimal `json:"consensus-estimate"`
	UpdatedAt          time.Time       `json:"updated-at"`
}

type EarningsInfo added in v0.2.0

type EarningsInfo struct {
	OccurredDate string          `json:"occurred-date"`
	Eps          decimal.Decimal `json:"eps"`
}

type EffectiveMarginRequirements added in v0.2.0

type EffectiveMarginRequirements struct {
	UnderlyingSymbol       string          `json:"underlying-symbol"`
	LongEquityInitial      decimal.Decimal `json:"long-equity-initial"`
	ShortEquityInitial     decimal.Decimal `json:"short-equity-initial"`
	LongEquityMaintenance  decimal.Decimal `json:"long-equity-maintenance"`
	ShortEquityMaintenance decimal.Decimal `json:"short-equity-maintenance"`
	NakedOptionStandard    decimal.Decimal `json:"naked-option-standard"`
	NakedOptionMinimum     decimal.Decimal `json:"naked-option-minimum"`
	NakedOptionFloor       decimal.Decimal `json:"naked-option-floor"`
	ClearingIDentifier     string          `json:"clearing-identifier"`
	IsDeleted              bool            `json:"is-deleted"`
}

type Entity added in v0.2.0

type Entity struct {
	ID                               string            `json:"id"`
	LegalName                        string            `json:"legal-name"`
	TaxNumber                        string            `json:"tax-number"`
	IsDomestic                       bool              `json:"is-domestic"`
	EntityType                       string            `json:"entity-type"`
	Email                            string            `json:"email"`
	PhoneNumber                      string            `json:"phone-number"`
	BusinessNature                   string            `json:"business-nature"`
	HasForeignInstitutionAffiliation bool              `json:"has-foreign-institution-affiliation"`
	ForeignInstitution               string            `json:"foreign-institution"`
	HasForeignBankAffiliation        bool              `json:"has-foreign-bank-affiliation"`
	GrantorFirstName                 string            `json:"grantor-first-name"`
	GrantorMiddleName                string            `json:"grantor-middle-name"`
	GrantorLastName                  string            `json:"grantor-last-name"`
	GrantorEmail                     string            `json:"grantor-email"`
	GrantorBirthDate                 string            `json:"grantor-birth-date"`
	GrantorTaxNumber                 string            `json:"grantor-tax-number"`
	Address                          Address           `json:"address"`
	EntitySuitability                EntitySuitability `json:"entity-suitability"`
	EntityOfficers                   []EntityOfficer   `json:"entity-officers"`
}

type EntityOfficer added in v0.2.0

type EntityOfficer struct {
	ID                   string  `json:"id"`
	ExternalID           string  `json:"external-id"`
	PrefixName           string  `json:"prefix-name"`
	FirstName            string  `json:"first-name"`
	MiddleName           string  `json:"middle-name"`
	LastName             string  `json:"last-name"`
	SuffixName           string  `json:"suffix-name"`
	BirthDate            string  `json:"birth-date"`
	BirthCountry         string  `json:"birth-country"`
	CitizenshipCountry   string  `json:"citizenship-country"`
	UsaCitizenshipType   string  `json:"usa-citizenship-type"`
	IsForeign            bool    `json:"is-foreign"`
	VisaType             string  `json:"visa-type"`
	VisaExpirationDate   string  `json:"visa-expiration-date"`
	TaxNumberType        string  `json:"tax-number-type"`
	TaxNumber            string  `json:"tax-number"`
	MobilePhoneNumber    string  `json:"mobile-phone-number"`
	HomePhoneNumber      string  `json:"home-phone-number"`
	WorkPhoneNumber      string  `json:"work-phone-number"`
	Email                string  `json:"email"`
	MaritalStatus        string  `json:"marital-status"`
	NumberOfDependents   int     `json:"number-of-dependents"`
	EmploymentStatus     string  `json:"employment-status"`
	EmployerName         string  `json:"employer-name"`
	Occupation           string  `json:"occupation"`
	JobTitle             string  `json:"job-title"`
	RelationshipToEntity string  `json:"relationship-to-entity"`
	OwnerOfRecord        bool    `json:"owner-of-record"`
	Address              Address `json:"address"`
}

type EntitySuitability added in v0.2.0

type EntitySuitability struct {
	ID                                string `json:"id"`
	EntityID                          int    `json:"entity-id"`
	AnnualNetIncome                   int    `json:"annual-net-income"`
	NetWorth                          int    `json:"net-worth"`
	LiquidNetWorth                    int    `json:"liquid-net-worth"`
	StockTradingExperience            string `json:"stock-trading-experience"`
	TaxBracket                        string `json:"tax-bracket"`
	CoveredOptionsTradingExperience   string `json:"covered-options-trading-experience"`
	UncoveredOptionsTradingExperience string `json:"uncovered-options-trading-experience"`
	FuturesTradingExperience          string `json:"futures-trading-experience"`
}

type EquitiesQuery added in v0.2.0

type EquitiesQuery struct {
	// The symbols of the equity(s), i.e AAPL
	Symbols []string `url:"symbol[]"`
	// Available values : Easy To Borrow, Locate Required, Preborrow
	Lendability Lendability `url:"lendability"`
	// Flag indicating if equity is an index instrument
	IsIndex bool `url:"is-index"`
	// Flag indicating if equity is an etf instrument
	IsETF bool `url:"is-etf"`
}

type Equity added in v0.2.0

type Equity struct {
	ID                             int             `json:"id"`
	Symbol                         string          `json:"symbol"`
	InstrumentType                 InstrumentType  `json:"instrument-type"`
	Cusip                          string          `json:"cusip"`
	ShortDescription               string          `json:"short-description"`
	IsIndex                        bool            `json:"is-index"`
	ListedMarket                   string          `json:"listed-market"`
	Description                    string          `json:"description"`
	Lendability                    string          `json:"lendability"`
	BorrowRate                     decimal.Decimal `json:"borrow-rate"`
	HaltedAt                       string          `json:"halted-at"`
	StopsTradingAt                 time.Time       `json:"stops-trading-at"`
	MarketTimeInstrumentCollection string          `json:"market-time-instrument-collection"`
	IsClosingOnly                  bool            `json:"is-closing-only"`
	IsOptionsClosingOnly           bool            `json:"is-options-closing-only"`
	Active                         bool            `json:"active"`
	IsFractionalQuantityEligible   bool            `json:"is-fractional-quantity-eligible"`
	IsIlliquid                     bool            `json:"is-illiquid"`
	IsEtf                          bool            `json:"is-etf"`
	StreamerSymbol                 string          `json:"streamer-symbol"`
	TickSizes                      []TickSize      `json:"tick-sizes"`
	OptionTickSizes                []TickSize      `json:"option-tick-sizes"`
}

type EquityOption added in v0.2.0

type EquityOption struct {
	Symbol                         string          `json:"symbol"`
	InstrumentType                 InstrumentType  `json:"instrument-type"`
	Active                         bool            `json:"active"`
	ListedMarket                   string          `json:"listed-market"`
	StrikePrice                    decimal.Decimal `json:"strike-price"`
	RootSymbol                     string          `json:"root-symbol"`
	UnderlyingSymbol               string          `json:"underlying-symbol"`
	ExpirationDate                 string          `json:"expiration-date"`
	ExerciseStyle                  string          `json:"exercise-style"`
	SharesPerContract              int             `json:"shares-per-contract"`
	OptionType                     OptionType      `json:"option-type"`
	OptionChainType                string          `json:"option-chain-type"`
	ExpirationType                 string          `json:"expiration-type"`
	SettlementType                 string          `json:"settlement-type"`
	HaltedAt                       string          `json:"halted-at"`
	StopsTradingAt                 time.Time       `json:"stops-trading-at"`
	MarketTimeInstrumentCollection string          `json:"market-time-instrument-collection"`
	DaysToExpiration               int             `json:"days-to-expiration"`
	ExpiresAt                      time.Time       `json:"expires-at"`
	IsClosingOnly                  bool            `json:"is-closing-only"`
	OldSecurityNumber              string          `json:"old-security-number"`
	StreamerSymbol                 string          `json:"streamer-symbol"`
}

type EquityOptionsQuery added in v0.2.0

type EquityOptionsQuery struct {
	// The symbol(s) of the equity option(s) using OCC Symbology, i.e. [FB 180629C00200000]
	Symbols []string `url:"symbol[]"`
	// Whether an option is available for trading with the broker.
	// Terminology is somewhat misleading as this is generally used
	// to filter non-standard / flex options out.
	Active bool `url:"active"`
	// Include expired options
	WithExpired bool `url:"with-expired"`
}

type EquityOptionsSymbology added in v0.2.0

type EquityOptionsSymbology struct {
	Symbol     string
	OptionType OptionType
	Strike     float32
	Expiration time.Time
}

EquityOptionsSymbology is a struct to help build option symbol in correct OCC Symbology Root symbol of the underlying stock or ETF, padded with spaces to 6 characters. Expiration date, 6 digits in the format yymmdd. Option type, either P or C, for put or call.

func NewOCCFromString added in v0.5.1

func NewOCCFromString(occSymbol string) (EquityOptionsSymbology, error)

Parse occ symbol into EquityOptionsSymbology struct.

func (EquityOptionsSymbology) Build added in v0.2.0

func (sym EquityOptionsSymbology) Build() string

Builds the equity option into correct symbology.

type Error

type Error struct {
	// Simple code error string
	Code string `json:"code"`
	// A short description of the error.
	Message string `json:"message"`
	// Slice of errors
	Errors []ErrorResponse `json:"errors"`
	// The HTTP status code.
	StatusCode int `json:"error,omitempty"`
}

Error represents an error returned by the tastytrade API.

func (Error) Error

func (e Error) Error() string

Error ...

type ErrorResponse added in v0.1.1

type ErrorResponse struct {
	Domain string `json:"domain"`
	Reason string `json:"reason"`
}

Error reasoning given by tastytrade.

type Exchange added in v0.2.0

type Exchange string

type Expiration added in v0.2.0

type Expiration struct {
	ExpirationType   string   `json:"expiration-type"`
	ExpirationDate   string   `json:"expiration-date"`
	DaysToExpiration int      `json:"days-to-expiration"`
	SettlementType   string   `json:"settlement-type"`
	Strikes          []Strike `json:"strikes"`
}

type FeeCalculation added in v0.2.0

type FeeCalculation struct {
	RegulatoryFees                   decimal.Decimal `json:"regulatory-fees"`
	RegulatoryFeesEffect             PriceEffect     `json:"regulatory-fees-effect"`
	ClearingFees                     decimal.Decimal `json:"clearing-fees"`
	ClearingFeesEffect               PriceEffect     `json:"clearing-fees-effect"`
	Commission                       decimal.Decimal `json:"commission"`
	CommissionEffect                 PriceEffect     `json:"commission-effect"`
	ProprietaryIndexOptionFees       decimal.Decimal `json:"proprietary-index-option-fees"`
	ProprietaryIndexOptionFeesEffect PriceEffect     `json:"proprietary-index-option-fees-effect"`
	TotalFees                        decimal.Decimal `json:"total-fees"`
	TotalFeesEffect                  PriceEffect     `json:"total-fees-effect"`
}

type Future added in v0.2.0

type Future struct {
	Symbol                       string              `json:"symbol"`
	ProductCode                  string              `json:"product-code"`
	ContractSize                 decimal.Decimal     `json:"contract-size"`
	TickSize                     decimal.Decimal     `json:"tick-size"`
	NotionalMultiplier           decimal.Decimal     `json:"notional-multiplier"`
	MainFraction                 decimal.Decimal     `json:"main-fraction"`
	SubFraction                  decimal.Decimal     `json:"sub-fraction"`
	DisplayFactor                decimal.Decimal     `json:"display-factor"`
	LastTradeDate                string              `json:"last-trade-date"`
	ExpirationDate               string              `json:"expiration-date"`
	ClosingOnlyDate              string              `json:"closing-only-date"`
	Active                       bool                `json:"active"`
	ActiveMonth                  bool                `json:"active-month"`
	NextActiveMonth              bool                `json:"next-active-month"`
	IsClosingOnly                bool                `json:"is-closing-only"`
	FirstNoticeDate              string              `json:"first-notice-date"`
	StopsTradingAt               time.Time           `json:"stops-trading-at"`
	ExpiresAt                    time.Time           `json:"expires-at"`
	ProductGroup                 string              `json:"product-group"`
	Exchange                     string              `json:"exchange"`
	RollTargetSymbol             string              `json:"roll-target-symbol"`
	StreamerExchangeCode         string              `json:"streamer-exchange-code"`
	StreamerSymbol               string              `json:"streamer-symbol"`
	BackMonthFirstCalendarSymbol bool                `json:"back-month-first-calendar-symbol"`
	IsTradeable                  bool                `json:"is-tradeable"`
	TrueUnderlyingSymbol         string              `json:"true-underlying-symbol"`
	FutureETFEquivalent          FutureETFEquivalent `json:"future-etf-equivalent"`
	FutureProduct                FutureProduct       `json:"future-product"`
	TickSizes                    []TickSize          `json:"tick-sizes"`
	OptionTickSizes              []TickSize          `json:"option-tick-sizes"`
	SpreadTickSizes              []TickSize          `json:"spread-tick-sizes"`
}

type FutureETFEquivalent added in v0.2.0

type FutureETFEquivalent struct {
	Symbol        string `json:"symbol"`
	ShareQuantity int    `json:"share-quantity"`
}

type FutureOption added in v0.2.0

type FutureOption struct {
	Symbol               string              `json:"symbol"`
	UnderlyingSymbol     string              `json:"underlying-symbol"`
	ProductCode          string              `json:"product-code"`
	ExpirationDate       string              `json:"expiration-date"`
	RootSymbol           string              `json:"root-symbol"`
	OptionRootSymbol     string              `json:"option-root-symbol"`
	StrikePrice          decimal.Decimal     `json:"strike-price"`
	Exchange             string              `json:"exchange"`
	ExchangeSymbol       string              `json:"exchange-symbol"`
	StreamerSymbol       string              `json:"streamer-symbol"`
	OptionType           OptionType          `json:"option-type"`
	ExerciseStyle        string              `json:"exercise-style"`
	IsVanilla            bool                `json:"is-vanilla"`
	IsPrimaryDeliverable bool                `json:"is-primary-deliverable"`
	FuturePriceRatio     decimal.Decimal     `json:"future-price-ratio"`
	Multiplier           decimal.Decimal     `json:"multiplier"`
	UnderlyingCount      decimal.Decimal     `json:"underlying-count"`
	IsConfirmed          bool                `json:"is-confirmed"`
	NotionalValue        decimal.Decimal     `json:"notional-value"`
	DisplayFactor        decimal.Decimal     `json:"display-factor"`
	SecurityExchange     string              `json:"security-exchange"`
	SxID                 string              `json:"sx-id"`
	SettlementType       string              `json:"settlement-type"`
	StrikeFactor         decimal.Decimal     `json:"strike-factor"`
	MaturityDate         string              `json:"maturity-date"`
	IsExercisableWeekly  bool                `json:"is-exercisable-weekly"`
	LastTradeTime        string              `json:"last-trade-time"`
	DaysToExpiration     int                 `json:"days-to-expiration"`
	IsClosingOnly        bool                `json:"is-closing-only"`
	Active               bool                `json:"active"`
	StopsTradingAt       time.Time           `json:"stops-trading-at"`
	ExpiresAt            time.Time           `json:"expires-at"`
	FutureOptionProduct  FutureOptionProduct `json:"future-option-product"`
}

type FutureOptionProduct added in v0.2.0

type FutureOptionProduct struct {
	RootSymbol              string          `json:"root-symbol"`
	CashSettled             bool            `json:"cash-settled"`
	Code                    string          `json:"code"`
	LegacyCode              string          `json:"legacy-code"`
	ClearportCode           string          `json:"clearport-code"`
	ClearingCode            string          `json:"clearing-code"`
	ClearingExchangeCode    string          `json:"clearing-exchange-code"`
	ClearingPriceMultiplier decimal.Decimal `json:"clearing-price-multiplier"`
	DisplayFactor           decimal.Decimal `json:"display-factor"`
	Exchange                string          `json:"exchange"`
	ProductType             string          `json:"product-type"`
	ExpirationType          string          `json:"expiration-type"`
	SettlementDelayDays     int             `json:"settlement-delay-days"`
	IsRollover              bool            `json:"is-rollover"`
	ProductSubtype          string          `json:"product-subtype"`
	MarketSector            string          `json:"market-sector"`
	FutureProduct           FutureProduct   `json:"future-product"`
}

type FutureOptionsQuery added in v0.2.0

type FutureOptionsQuery struct {
	// The symbol(s) of the future(s), i.e. symbol[]=ESZ9. Leading forward slash is not required.
	Symbols []string `url:"symbol[]"`
	// Future option root, i.e. EW3 or SO
	OptionRootSymbol string `url:"option-root-symbol,omitempty"`
	// Expiration date
	ExpirationDate time.Time `layout:"2006-01-02" url:"expiration-date,omitempty"`
	// P(ut) or C(all)
	OptionType OptionType `url:"option-type,omitempty"`
	// Strike price using display factor
	StrikePrice float32 `url:"strike-price,omitempty"`
}

type FutureOptionsSymbology added in v0.2.0

type FutureOptionsSymbology struct {
	OptionContractCode string
	// Should start with / (You can use the FutureSymbology struct's Build method)
	FutureContractCode string
	OptionType         OptionType
	Strike             int
	Expiration         time.Time
}

FutureOptionsSymbology is a struct to help build option symbol in correct Future Options Symbology Both the future product code and the future option product code will be present in a future option symbol. The future option symbol will always start with a ./, followed by the future contract code, the option contract code, the expiration date, option type (C/P), and strike price.

func NewFOSFromString added in v0.5.1

func NewFOSFromString(symbol string) (FutureOptionsSymbology, error)

Parse the future options symbol into FutureOptionsSymbology struct.

func (FutureOptionsSymbology) Build added in v0.2.0

func (foSym FutureOptionsSymbology) Build() string

Builds the future option into correct symbology.

type FutureProduct added in v0.2.0

type FutureProduct struct {
	RootSymbol                   string                `json:"root-symbol"`
	Code                         string                `json:"code"`
	Description                  string                `json:"description"`
	ClearingCode                 string                `json:"clearing-code"`
	ClearingExchangeCode         string                `json:"clearing-exchange-code"`
	ClearportCode                string                `json:"clearport-code"`
	LegacyCode                   string                `json:"legacy-code"`
	Exchange                     string                `json:"exchange"`
	LegacyExchangeCode           string                `json:"legacy-exchange-code"`
	ProductType                  string                `json:"product-type"`
	ListedMonths                 []string              `json:"listed-months"`
	ActiveMonths                 []string              `json:"active-months"`
	NotionalMultiplier           decimal.Decimal       `json:"notional-multiplier"`
	TickSize                     decimal.Decimal       `json:"tick-size"`
	DisplayFactor                decimal.Decimal       `json:"display-factor"`
	BaseTick                     int                   `json:"base-tick"`
	SubTick                      int                   `json:"sub-tick"`
	StreamerExchangeCode         string                `json:"streamer-exchange-code"`
	SmallNotional                bool                  `json:"small-notional"`
	BackMonthFirstCalendarSymbol bool                  `json:"back-month-first-calendar-symbol"`
	FirstNotice                  bool                  `json:"first-notice"`
	CashSettled                  bool                  `json:"cash-settled"`
	ContractLimit                int                   `json:"contract-limit"`
	SecurityGroup                string                `json:"security-group"`
	ProductSubtype               string                `json:"product-subtype"`
	TrueUnderlyingCode           string                `json:"true-underlying-code"`
	MarketSector                 string                `json:"market-sector"`
	OptionProducts               []FutureOptionProduct `json:"option-products"`
	Roll                         Roll                  `json:"roll"`
}

type FutureSymbology added in v0.2.0

type FutureSymbology struct {
	// Don't include the / in the symbol i.e. ES
	ProductCode string
	MonthCode   MonthCode
	YearDigit   int
}

FutureSymbology is a struct to help build future contract codes Futures symbols always start with a slash followed by the contract code. The contract code consists of 3 things: the product code (A-Z), the month code, and a 1-2 digit number for the year. For a full list of futures products that we support, you can hit GET /instruments/future-products. Each item in the response has a code, which is the product code.

func NewFSFromString added in v0.5.1

func NewFSFromString(symbol string) (FutureSymbology, error)

Parse the future symbol into FutureSymbology struct.

func (FutureSymbology) Build added in v0.2.0

func (fcc FutureSymbology) Build() string

Builds the future symbol into correct symbology.

type FuturesExpiration added in v0.2.0

type FuturesExpiration struct {
	UnderlyingSymbol     string          `json:"underlying-symbol"`
	RootSymbol           string          `json:"root-symbol"`
	OptionRootSymbol     string          `json:"option-root-symbol"`
	OptionContractSymbol string          `json:"option-contract-symbol"`
	Asset                string          `json:"asset"`
	ExpirationDate       string          `json:"expiration-date"`
	DaysToExpiration     int             `json:"days-to-expiration"`
	ExpirationType       string          `json:"expiration-type"`
	SettlementType       string          `json:"settlement-type"`
	NotionalValue        decimal.Decimal `json:"notional-value"`
	DisplayFactor        decimal.Decimal `json:"display-factor"`
	StrikeFactor         decimal.Decimal `json:"strike-factor"`
	StopsTradingAt       time.Time       `json:"stops-trading-at"`
	ExpiresAt            time.Time       `json:"expires-at"`
	TickSizes            []TickSize      `json:"tick-sizes"`
	Strikes              []Strike        `json:"strikes"`
}

type FuturesQuery added in v0.2.0

type FuturesQuery struct {
	// The symbol(s) of the future(s), i.e. symbol[]=ESZ9. Leading forward slash is not required.
	Symbols []string `url:"symbol[],omitempty"`
	// The product code of the future(s), i.e. ES or 6A
	// Ignored if Symbols parameter is given
	ProductCode []string `url:"product-code[],omitempty"`
}

type HistoricLiquidityQuery added in v0.2.0

type HistoricLiquidityQuery struct {
	// If given, will return data for a specific period of time with a pre-defined
	// time interval. Passing 1d will return the previous day of data in 5 minute
	// intervals. This param is required if start-time is not given. 1d - If
	// equities market is open, this will return data starting from market open in
	// 5 minute intervals. If market is closed, will return data from previous
	// market open.
	TimeBack TimeBack `url:"time-back,omitempty"`
	// StartTime is The start point for this query. This param is required is
	// time-back is not given. If given, will take precedence over time-back.
	StartTime time.Time `layout:"2006-01-02T15:04:05Z" url:"start-time,omitempty"`
}

type Holding added in v0.2.0

type Holding struct {
	Description                  string          `json:"description"`
	MarginRequirement            decimal.Decimal `json:"margin-requirement"`
	MarginRequirementEffect      PriceEffect     `json:"margin-requirement-effect"`
	InitialRequirement           decimal.Decimal `json:"initial-requirement"`
	InitialRequirementEffect     PriceEffect     `json:"initial-requirement-effect"`
	MaintenanceRequirement       decimal.Decimal `json:"maintenance-requirement"`
	MaintenanceRequirementEffect PriceEffect     `json:"maintenance-requirement-effect"`
	IncludesWorkingOrder         bool            `json:"includes-working-order"`
	BuyingPower                  decimal.Decimal `json:"buying-power"`
	BuyingPowerEffect            PriceEffect     `json:"buying-power-effect"`
	PositionEntries              []PositionEntry `json:"position-entries"`
}

type Indicator added in v0.2.0

type Indicator string

type InstrumentType added in v0.2.0

type InstrumentType string

type Lendability added in v0.2.0

type Lendability string

type LiquidityRunningState added in v0.2.0

type LiquidityRunningState struct {
	Sum       decimal.Decimal `json:"sum"`
	Count     int             `json:"count"`
	StartedAt time.Time       `json:"started-at"`
	UpdatedAt time.Time       `json:"updated-at"`
}

type LoginInfo

type LoginInfo struct {
	// The user name or email of the user.
	Login string `json:"login"`
	// The password for the user's account
	Password string `json:"password"`
	// If the session should be extended for longer than normal
	// via remember token. Defaults to false.
	RememberMe bool `json:"remember-me"`
	// Valid for 28 days
	// Allows skipping for 2 factor with in its window.
	RememberToken string `json:"remember-token"`
}

type Lot added in v0.4.3

type Lot struct {
	ID                string          `json:"id"`
	TransactionID     int             `json:"transaction-id"`
	Quantity          decimal.Decimal `json:"quantity"`
	Price             decimal.Decimal `json:"price"`
	QuantityDirection string          `json:"quantity-direction"`
	ExecutedAt        time.Time       `json:"executed-at"`
	TransactionDate   string          `json:"transaction-date"`
}

type MarginGroup added in v0.2.0

type MarginGroup struct {
	Description                   string          `json:"description"`
	Code                          string          `json:"code"`
	UnderlyingSymbol              string          `json:"underlying-symbol"`
	UnderlyingType                string          `json:"underlying-type"`
	ExpectedPriceRangeUpPercent   decimal.Decimal `json:"expected-price-range-up-percent"`
	ExpectedPriceRangeDownPercent decimal.Decimal `json:"expected-price-range-down-percent"`
	PointOfNoReturnPercent        decimal.Decimal `json:"point-of-no-return-percent"`
	MarginCalculationType         string          `json:"margin-calculation-type"`
	MarginRequirement             decimal.Decimal `json:"margin-requirement"`
	MarginRequirementEffect       PriceEffect     `json:"margin-requirement-effect"`
	InitialRequirement            decimal.Decimal `json:"initial-requirement"`
	InitialRequirementEffect      PriceEffect     `json:"initial-requirement-effect"`
	MaintenanceRequirement        decimal.Decimal `json:"maintenance-requirement"`
	MaintenanceRequirementEffect  PriceEffect     `json:"maintenance-requirement-effect"`
	BuyingPower                   decimal.Decimal `json:"buying-power"`
	BuyingPowerEffect             PriceEffect     `json:"buying-power-effect"`
	Holdings                      []Holding       `json:"groups"`
	PriceIncreasePercent          decimal.Decimal `json:"price-increase-percent"`
	PriceDecreasePercent          decimal.Decimal `json:"price-decrease-percent"`
}

type MarginRequirements added in v0.2.0

type MarginRequirements struct {
	AccountNumber                string          `json:"account-number"`
	Description                  string          `json:"description"`
	MarginCalculationType        string          `json:"margin-calculation-type"`
	OptionLevel                  string          `json:"option-level"`
	MarginRequirement            decimal.Decimal `json:"margin-requirement"`
	MarginRequirementEffect      PriceEffect     `json:"margin-requirement-effect"`
	InitialRequirement           decimal.Decimal `json:"initial-requirement"`
	InitialRequirementEffect     PriceEffect     `json:"initial-requirement-effect"`
	MaintenanceRequirement       decimal.Decimal `json:"maintenance-requirement"`
	MaintenanceRequirementEffect PriceEffect     `json:"maintenance-requirement-effect"`
	MarginEquity                 decimal.Decimal `json:"margin-equity"`
	MarginEquityEffect           PriceEffect     `json:"margin-equity-effect"`
	OptionBuyingPower            decimal.Decimal `json:"option-buying-power"`
	OptionBuyingPowerEffect      PriceEffect     `json:"option-buying-power-effect"`
	RegTMarginRequirement        decimal.Decimal `json:"reg-t-margin-requirement"`
	RegTMarginRequirementEffect  PriceEffect     `json:"reg-t-margin-requirement-effect"`
	RegTOptionBuyingPower        decimal.Decimal `json:"reg-t-option-buying-power"`
	RegTOptionBuyingPowerEffect  PriceEffect     `json:"reg-t-option-buying-power-effect"`
	MaintenanceExcess            decimal.Decimal `json:"maintenance-excess"`
	MaintenanceExcessEffect      PriceEffect     `json:"maintenance-excess-effect"`
	MarginGroups                 []MarginGroup   `json:"groups"`
	LastStateTimestamp           int             `json:"last-state-timestamp"`
}

type MarginRequirementsGlobalConfiguration added in v0.7.1

type MarginRequirementsGlobalConfiguration struct {
	RiskFreeRate decimal.Decimal `json:"risk-free-rate"`
}

Response object for the margin requirements public configuration request.

type MarginType added in v0.2.0

type MarginType struct {
	Name     string `json:"name"`
	IsMargin bool   `json:"is-margin"`
}

type MarketMetricInfo added in v0.2.0

type MarketMetricInfo struct {
	Symbol                              string                              `json:"symbol"`
	ImpliedVolatilityIndex              decimal.Decimal                     `json:"implied-volatility-index"`
	ImpliedVolatilityIndex5DayChange    decimal.Decimal                     `json:"implied-volatility-index-5-day-change"`
	ImpliedVolatilityRank               decimal.Decimal                     `json:"implied-volatility-rank"`
	ImpliedVolatilityPercentile         decimal.Decimal                     `json:"implied-volatility-percentile"`
	Liquidity                           decimal.Decimal                     `json:"liquidity"`
	LiquidityRank                       decimal.Decimal                     `json:"liquidity-rank"`
	LiquidityRating                     int                                 `json:"liquidity-rating"`
	OptionExpirationImpliedVolatilities []OptionExpirationImpliedVolatility `json:"option-expiration-implied-volatilities"`
}

type MarketMetricVolatility added in v0.2.0

type MarketMetricVolatility struct {
	Symbol                                 string                              `json:"symbol"`
	ImpliedVolatilityIndex                 decimal.Decimal                     `json:"implied-volatility-index"`
	ImpliedVolatilityIndex5DayChange       decimal.Decimal                     `json:"implied-volatility-index-5-day-change"`
	ImpliedVolatilityIndexRank             decimal.Decimal                     `json:"implied-volatility-index-rank"`
	TosImpliedVolatilityIndexRank          decimal.Decimal                     `json:"tos-implied-volatility-index-rank"`
	TwImpliedVolatilityIndexRank           decimal.Decimal                     `json:"tw-implied-volatility-index-rank"`
	TosImpliedVolatilityIndexRankUpdatedAt time.Time                           `json:"tos-implied-volatility-index-rank-updated-at"`
	ImpliedVolatilityIndexRankSource       string                              `json:"implied-volatility-index-rank-source"`
	ImpliedVolatilityPercentile            decimal.Decimal                     `json:"implied-volatility-percentile"`
	ImpliedVolatilityUpdatedAt             time.Time                           `json:"implied-volatility-updated-at"`
	LiquidityValue                         decimal.Decimal                     `json:"liquidity-value"`
	LiquidityRank                          decimal.Decimal                     `json:"liquidity-rank"`
	LiquidityRating                        int                                 `json:"liquidity-rating"`
	CreatedAt                              string                              `json:"created-at"`
	UpdatedAt                              time.Time                           `json:"updated-at"`
	OptionExpirationImpliedVolatilities    []OptionExpirationImpliedVolatility `json:"option-expiration-implied-volatilities"`
	LiquidityRunningState                  LiquidityRunningState               `json:"liquidity-running-state"`
	Beta                                   decimal.Decimal                     `json:"beta"`
	BetaUpdatedAt                          time.Time                           `json:"beta-updated-at"`
	CorrSpy3month                          decimal.Decimal                     `json:"corr-spy-3month"`
	DividendRatePerShare                   decimal.Decimal                     `json:"dividend-rate-per-share"`
	AnnualDividendPerShare                 decimal.Decimal                     `json:"annual-dividend-per-share"`
	DividendYield                          decimal.Decimal                     `json:"dividend-yield"`
	DividendExDate                         string                              `json:"dividend-ex-date"`
	DividendNextDate                       string                              `json:"dividend-next-date"`
	DividendPayDate                        string                              `json:"dividend-pay-date"`
	DividendUpdatedAt                      time.Time                           `json:"dividend-updated-at"`
	Earnings                               Earnings                            `json:"earnings"`
	ListedMarket                           string                              `json:"listed-market"`
	Lendability                            string                              `json:"lendability"`
	BorrowRate                             decimal.Decimal                     `json:"borrow-rate"`
	MarketCap                              int                                 `json:"market-cap"`
	ImpliedVolatility30Day                 decimal.Decimal                     `json:"implied-volatility-30-day"`
	HistoricalVolatility30Day              decimal.Decimal                     `json:"historical-volatility-30-day"`
	HistoricalVolatility60Day              decimal.Decimal                     `json:"historical-volatility-60-day"`
	HistoricalVolatility90Day              decimal.Decimal                     `json:"historical-volatility-90-day"`
	IvHv30DayDifference                    decimal.Decimal                     `json:"iv-hv-30-day-difference"`
	PriceEarningsRatio                     decimal.Decimal                     `json:"price-earnings-ratio"`
	EarningsPerShare                       decimal.Decimal                     `json:"earnings-per-share"`
}

type MonthCode added in v0.2.0

type MonthCode string

type NestedFuture added in v0.2.0

type NestedFuture struct {
	Symbol           string    `json:"symbol"`
	RootSymbol       string    `json:"root-symbol"`
	ExpirationDate   string    `json:"expiration-date"`
	DaysToExpiration int       `json:"days-to-expiration"`
	ActiveMonth      bool      `json:"active-month"`
	NextActiveMonth  bool      `json:"next-active-month"`
	StopsTradingAt   time.Time `json:"stops-trading-at"`
	ExpiresAt        time.Time `json:"expires-at"`
}

type NestedFuturesOptionChains added in v0.2.0

type NestedFuturesOptionChains struct {
	Futures      []NestedFuture `json:"futures"`
	OptionChains []OptionChains `json:"option-chains"`
}

type NestedOptionChains added in v0.2.0

type NestedOptionChains struct {
	UnderlyingSymbol  string        `json:"underlying-symbol"`
	RootSymbol        string        `json:"root-symbol"`
	OptionChainType   string        `json:"option-chain-type"`
	SharesPerContract int           `json:"shares-per-contract"`
	TickSizes         []TickSize    `json:"tick-sizes"`
	Deliverables      []Deliverable `json:"deliverables"`
	Expirations       []Expiration  `json:"expirations"`
}

type NetLiqOHLC added in v0.2.0

type NetLiqOHLC struct {
	Open             decimal.Decimal `json:"open"`
	High             decimal.Decimal `json:"high"`
	Low              decimal.Decimal `json:"low"`
	Close            decimal.Decimal `json:"close"`
	PendingCashOpen  decimal.Decimal `json:"pending-cash-open"`
	PendingCashHigh  decimal.Decimal `json:"pending-cash-high"`
	PendingCashLow   decimal.Decimal `json:"pending-cash-low"`
	PendingCashClose decimal.Decimal `json:"pending-cash-close"`
	TotalOpen        decimal.Decimal `json:"total-open"`
	TotalHigh        decimal.Decimal `json:"total-high"`
	TotalLow         decimal.Decimal `json:"total-low"`
	TotalClose       decimal.Decimal `json:"total-close"`
	Time             string          `json:"time"`
}

NetLiqOHLC Represents the open, high, low, close values for a time interval. The close value is the value at time. Also includes pending cash values and a sum of the two for convenience.

type NewOrder added in v0.2.0

type NewOrder struct {
	TimeInForce  TimeInForce   `json:"time-in-force"`
	GtcDate      string        `json:"gtc-date"`
	OrderType    OrderType     `json:"order-type"`
	StopTrigger  float32       `json:"stop-trigger,omitempty"`
	Price        float32       `json:"price,omitempty"`
	PriceEffect  PriceEffect   `json:"price-effect,omitempty"`
	Value        float32       `json:"value,omitempty"`
	ValueEffect  PriceEffect   `json:"value-effect,omitempty"`
	Source       string        `json:"source,omitempty"`
	PartitionKey string        `json:"partition-key,omitempty"`
	PreflightID  string        `json:"preflight-id,omitempty"`
	Legs         []NewOrderLeg `json:"legs"`
	Rules        NewOrderRules `json:"rules,omitempty"`
}

type NewOrderCondition added in v0.2.0

type NewOrderCondition struct {
	// The action in which the trigger is enacted. i.e. route and cancel
	Action OrderRuleAction `json:"action"`
	// The symbol to apply the condition to.
	Symbol string `json:"symbol"`
	// The instrument's type in relation to the condition.
	InstrumentType string `json:"instrument-type"`
	// The indicator for the trigger, currently only supports last
	Indicator Indicator `json:"indicator"`
	// How to compare against the threshold.
	Comparator Comparator `json:"comparator"`
	// The price at which the condition triggers.
	Threshold       float32                  `json:"threshold"`
	PriceComponents []NewOrderPriceComponent `json:"price-components"`
}

type NewOrderECR added in v0.2.0

type NewOrderECR struct {
	// (Required) The length in time before the order expires.
	TimeInForce TimeInForce `json:"time-in-force"`
	GtcDate     string      `json:"gtc-date,omitempty"`
	// (Required) The type of order in regards to the price.
	OrderType   OrderType `json:"order-type"`
	StopTrigger float32   `json:"stop-trigger,omitempty"`
	Price       float32   `json:"price,omitempty"`
	// (Required) If pay or receive payment for placing the order.
	PriceEffect PriceEffect `json:"price-effect"`
	Value       float32     `json:"value,omitempty"`
	// If pay or receive payment for placing the notional market order.
	// i.e. Credit or Debit
	ValueEffect  PriceEffect   `json:"value-effect"`
	Source       string        `json:"source,omitempty"`
	PartitionKey string        `json:"partition-key,omitempty"`
	PreflightID  string        `json:"preflight-id,omitempty"`
	Legs         []NewOrderLeg `json:"legs,omitempty"`
}

type NewOrderLeg added in v0.2.0

type NewOrderLeg struct {
	InstrumentType InstrumentType `json:"instrument-type"`
	Symbol         string         `json:"symbol"`
	Quantity       float32        `json:"quantity,omitempty"`
	Action         OrderAction    `json:"action"`
}

type NewOrderPriceComponent added in v0.2.0

type NewOrderPriceComponent struct {
	// The symbol to apply the condition to.
	Symbol string `json:"symbol"`
	// The instrument's type in relation to the symbol.
	InstrumentType InstrumentType `json:"instrument-type"`
	// The Ratio quantity in relation to the symbol
	Quantity float32 `json:"quantity"`
	// The quantity direction(ie Long or Short) in relation to the symbol
	QuantityDirection Direction `json:"quantity-direction"`
}

type NewOrderRules added in v0.2.0

type NewOrderRules struct {
	// RouteAfter Earliest time an order should route at
	RouteAfter string `json:"route-after"`
	// CancelAt Latest time an order should be canceled at
	CancelAt   string              `json:"cancel-at"`
	Conditions []NewOrderCondition `json:"conditions"`
}

type NewWatchlist added in v0.2.0

type NewWatchlist struct {
	Name             string           `json:"name"`
	WatchlistEntries []WatchlistEntry `json:"watchlist-entries"`
	GroupName        string           `json:"group-name,omitempty"`
	OrderIndex       int              `json:"order-index,omitempty"`
}

type OptionChains added in v0.2.0

type OptionChains struct {
	UnderlyingSymbol string              `json:"underlying-symbol"`
	RootSymbol       string              `json:"root-symbol"`
	ExerciseStyle    string              `json:"exercise-style"`
	Expirations      []FuturesExpiration `json:"expirations"`
}

type OptionExpirationImpliedVolatility added in v0.2.0

type OptionExpirationImpliedVolatility struct {
	ExpirationDate    string          `json:"expiration-date"`
	SettlementType    string          `json:"settlement-type"`
	OptionChainType   string          `json:"option-chain-type"`
	ImpliedVolatility decimal.Decimal `json:"implied-volatility"`
}

type OptionType added in v0.2.0

type OptionType string

type Order added in v0.2.0

type Order struct {
	ID                       int             `json:"id"`
	AccountNumber            string          `json:"account-number"`
	TimeInForce              TimeInForce     `json:"time-in-force"`
	GtcDate                  string          `json:"gtc-date"`
	OrderType                OrderType       `json:"order-type"`
	Size                     int             `json:"size"`
	UnderlyingSymbol         string          `json:"underlying-symbol"`
	UnderlyingInstrumentType InstrumentType  `json:"underlying-instrument-type"`
	Price                    decimal.Decimal `json:"price"`
	PriceEffect              PriceEffect     `json:"price-effect"`
	Value                    decimal.Decimal `json:"value"`
	ValueEffect              PriceEffect     `json:"value-effect"`
	StopTrigger              decimal.Decimal `json:"stop-trigger"`
	Status                   OrderStatus     `json:"status"`
	ContingentStatus         string          `json:"contingent-status"`
	ConfirmationStatus       string          `json:"confirmation-status"`
	Cancellable              bool            `json:"cancellable"`
	CancelledAt              time.Time       `json:"cancelled-at"`
	CancelUserID             string          `json:"cancel-user-id"`
	CancelUsername           string          `json:"cancel-username"`
	Editable                 bool            `json:"editable"`
	Edited                   bool            `json:"edited"`
	ExtExchangeOrderNumber   string          `json:"ext-exchange-order-number"`
	ExtClientOrderID         string          `json:"ext-client-order-id"`
	ExtGlobalOrderNumber     int             `json:"ext-global-order-number"`
	ReplacingOrderID         string          `json:"replacing-order-id"`
	ReplacesOrderID          string          `json:"replaces-order-id"`
	ReceivedAt               time.Time       `json:"received-at"`
	UpdatedAt                int             `json:"updated-at"`
	InFlightAt               string          `json:"in-flight-at"`
	LiveAt                   string          `json:"live-at"`
	RejectReason             string          `json:"reject-reason"`
	UserID                   string          `json:"user-id"`
	Username                 string          `json:"username"`
	TerminalAt               time.Time       `json:"terminal-at"`
	ComplexOrderID           int             `json:"complex-order-id"`
	ComplexOrderTag          string          `json:"complex-order-tag"`
	PreflightID              string          `json:"preflight-id"`
	Legs                     []OrderLeg      `json:"legs"`
	Rules                    OrderRules      `json:"rules"`
}

type OrderAction added in v0.2.0

type OrderAction string

type OrderCondition added in v0.2.0

type OrderCondition struct {
	ID                         int                   `json:"id"`
	Action                     OrderRuleAction       `json:"action"`
	Symbol                     string                `json:"symbol"`
	InstrumentType             InstrumentType        `json:"instrument-type"`
	Indicator                  Indicator             `json:"indicator"`
	Comparator                 Comparator            `json:"comparator"`
	Threshold                  decimal.Decimal       `json:"threshold"`
	IsThresholdBasedOnNotional bool                  `json:"is-threshold-based-on-notional"`
	TriggeredAt                string                `json:"triggered-at"`
	TriggeredValue             decimal.Decimal       `json:"triggered-value"`
	PriceComponents            []OrderPriceComponent `json:"price-components"`
}

type OrderErrorResponse added in v0.2.0

type OrderErrorResponse struct {
	Code    string      `json:"code"`
	Message string      `json:"message"`
	Errors  []OrderInfo `json:"errors"`
}

type OrderFill added in v0.2.0

type OrderFill struct {
	ExtGroupFillID   string          `json:"ext-group-fill-id"`
	ExtExecID        string          `json:"ext-exec-id"`
	FillID           string          `json:"fill-id"`
	Quantity         float32         `json:"quantity"`
	FillPrice        decimal.Decimal `json:"fill-price"`
	FilledAt         time.Time       `json:"filled-at"`
	DestinationVenue string          `json:"destination-venue"`
}

type OrderInfo added in v0.2.0

type OrderInfo struct {
	Code        string `json:"code"`
	Message     string `json:"message"`
	PreflightID string `json:"preflight-id"`
}

type OrderLeg added in v0.2.0

type OrderLeg struct {
	InstrumentType    InstrumentType `json:"instrument-type"`
	Symbol            string         `json:"symbol"`
	Quantity          float32        `json:"quantity"`
	RemainingQuantity float32        `json:"remaining-quantity"`
	Action            OrderAction    `json:"action"`
	Fills             []OrderFill    `json:"fills"`
}

type OrderPriceComponent added in v0.2.0

type OrderPriceComponent struct {
	Symbol            string         `json:"symbol"`
	InstrumentType    InstrumentType `json:"instrument-type"`
	Quantity          float32        `json:"quantity"`
	QuantityDirection Direction      `json:"quantity-direction"`
}

type OrderReplacement added in v0.2.0

type OrderReplacement struct {
	// TimeInForce The length in time before the order expires.
	TimeInForce TimeInForce `json:"time-in-force"`
	GtcDate     string      `json:"gtc-date"`
	// OrderType The type of order in regards to the price.
	OrderType   OrderType       `json:"order-type"`
	StopTrigger decimal.Decimal `json:"stop-trigger,omitempty"`
	Price       decimal.Decimal `json:"price,omitempty"`
	// PriceEffect If pay or receive payment for placing the order.
	PriceEffect PriceEffect     `json:"price-effect,omitempty"`
	Value       decimal.Decimal `json:"value,omitempty"`
	// ValueEffect If pay or receive payment for placing the notional market order.
	ValueEffect  PriceEffect `json:"value-effect,omitempty"`
	Source       string      `json:"source,omitempty"`
	PartitionKey string      `json:"partition-key,omitempty"`
	PreflightID  string      `json:"preflight-id,omitempty"`
}

OrderReplacement Replaces a live order with a new one. Subsequent fills of the original order will abort the replacement.

type OrderResponse added in v0.2.0

type OrderResponse struct {
	Order             Order             `json:"order"`
	ComplexOrder      ComplexOrder      `json:"complex-order"`
	Warnings          []OrderInfo       `json:"warnings"`
	Errors            []OrderInfo       `json:"errors"`
	BuyingPowerEffect BuyingPowerEffect `json:"buying-power-effect"`
	FeeCalculation    FeeCalculation    `json:"fee-calculation"`
}

type OrderRuleAction added in v0.2.0

type OrderRuleAction string

type OrderRules added in v0.2.0

type OrderRules struct {
	RouteAfter  string           `json:"route-after"`
	RoutedAt    string           `json:"routed-at"`
	CancelAt    string           `json:"cancel-at"`
	CancelledAt string           `json:"cancelled-at"`
	Conditions  []OrderCondition `json:"conditions"`
}

type OrderStatus added in v0.2.0

type OrderStatus string

The normal flow for a filled order would be Received -> Routed -> In Flight -> Live -> Filled. Order status updates come in real-time to websocket clients that have sent the account-subscribe message.

type OrderType added in v0.2.0

type OrderType string

type OrdersQuery added in v0.2.0

type OrdersQuery struct {
	// Account numbers to get orders from (customer must have at least
	// viewing access over the account)
	AccountNumbers []string `url:"account-numbers[],omitempty"`
	// Default value 10
	PerPage int `url:"per-page,omitempty"`
	// Default value 0
	PageOffset int `url:"page-offset,omitempty"`
	// The start date of orders to query.
	StartDate time.Time `layout:"2006-01-02" url:"start-date,omitempty"`
	// The end date of orders to query.
	EndDate time.Time `layout:"2006-01-02" url:"end-date,omitempty"`
	// The Underlying Symbol. The Ticker Symbol FB or
	// TW Future Symbol with out date component /M6E or
	// the full TW Future Symbol /ESU9
	UnderlyingSymbol string `url:"underlying-symbol,omitempty"`
	// Status of the order
	Status []OrderStatus `url:"status[],omitempty"`
	// The full TW Future Symbol /ESZ9 or
	// /NGZ19 if two year digit are appropriate
	FuturesSymbol string `url:"futures-symbol"`
	// Underlying instrument type i.e. InstrumentType
	UnderlyingInstrumentType InstrumentType `url:"underlying-instrument-type,omitempty"`
	// The order to sort results in. Defaults to Desc, Accepts Desc or Asc.
	Sort SortOrder `url:"sort,omitempty"`
	// DateTime start range for filtering transactions in full date-time
	StartAt time.Time `layout:"2006-01-02T15:04:05Z" url:"start-at,omitempty"`
	// DateTime end range for filtering transactions in full date-time
	EndAt time.Time `layout:"2006-01-02T15:04:05Z" url:"end-at,omitempty"`
}

The query for account orders.

type Pagination added in v0.2.0

type Pagination struct {
	PerPage            int     `json:"per-page"`
	PageOffset         int     `json:"page-offset"`
	ItemOffset         int     `json:"item-offset"`
	TotalItems         int     `json:"total-items"`
	TotalPages         int     `json:"total-pages"`
	CurrentItemCount   int     `json:"current-item-count"`
	PreviousLink       *string `json:"previous-link"`
	NextLink           *string `json:"next-link"`
	PagingLinkTemplate *string `json:"paging-link-template"`
}

type PairsEquation added in v0.2.0

type PairsEquation struct {
	LeftAction    string `json:"left-action"`
	LeftSymbol    string `json:"left-symbol"`
	LeftQuantity  int    `json:"left-quantity"`
	RightAction   string `json:"right-action"`
	RightSymbol   string `json:"right-symbol"`
	RightQuantity int    `json:"right-quantity"`
}

type PairsWatchlist added in v0.2.0

type PairsWatchlist struct {
	Name           string          `json:"name"`
	PairsEquations []PairsEquation `json:"pairs-equations"`
	OrderIndex     int             `json:"order-index,omitempty"`
}

type PasswordReset added in v0.3.0

type PasswordReset struct {
	Password             string `json:"password"`
	PasswordConfirmation string `json:"password-confirmation"`
	ResetPasswordToken   string `json:"reset-password-token"`
}

type Person added in v0.2.0

type Person struct {
	ExternalID         string `json:"external-id"`
	PrefixName         string `json:"prefix-name"`
	FirstName          string `json:"first-name"`
	MiddleName         string `json:"middle-name"`
	LastName           string `json:"last-name"`
	SuffixName         string `json:"suffix-name"`
	BirthDate          string `json:"birth-date"`
	BirthCountry       string `json:"birth-country"`
	CitizenshipCountry string `json:"citizenship-country"`
	UsaCitizenshipType string `json:"usa-citizenship-type"`
	VisaType           string `json:"visa-type"`
	VisaExpirationDate string `json:"visa-expiration-date"`
	MaritalStatus      string `json:"marital-status"`
	NumberOfDependents int    `json:"number-of-dependents"`
	EmploymentStatus   string `json:"employment-status"`
	Occupation         string `json:"occupation"`
	EmployerName       string `json:"employer-name"`
	JobTitle           string `json:"job-title"`
}

type PositionEntry added in v0.2.0

type PositionEntry struct {
	InstrumentSymbol    string          `json:"instrument-symbol"`
	InstrumentType      InstrumentType  `json:"instrument-type"`
	Quantity            decimal.Decimal `json:"quantity"`
	AverageOpenPrice    StringToFloat32 `json:"average-open-price"`
	ClosePrice          decimal.Decimal `json:"close-price"`
	FixingPrice         StringToFloat32 `json:"fixing-price"`
	StrikePrice         decimal.Decimal `json:"strike-price,omitempty"`
	OptionType          OptionType      `json:"option-type,omitempty"`
	DeliverableQuantity decimal.Decimal `json:"deliverable-quantity,omitempty"`
	ExpirationDate      string          `json:"expiration-date,omitempty"`
}

type PositionLimit added in v0.2.0

type PositionLimit struct {
	ID                          int    `json:"id"`
	AccountNumber               string `json:"account-number"`
	EquityOrderSize             int    `json:"equity-order-size"`
	EquityOptionOrderSize       int    `json:"equity-option-order-size"`
	FutureOrderSize             int    `json:"future-order-size"`
	FutureOptionOrderSize       int    `json:"future-option-order-size"`
	UnderlyingOpeningOrderLimit int    `json:"underlying-opening-order-limit"`
	EquityPositionSize          int    `json:"equity-position-size"`
	EquityOptionPositionSize    int    `json:"equity-option-position-size"`
	FuturePositionSize          int    `json:"future-position-size"`
	FutureOptionPositionSize    int    `json:"future-option-position-size"`
}

PositionLimit model.

type PriceEffect added in v0.2.0

type PriceEffect string

type PublicWatchlist added in v0.2.0

type PublicWatchlist struct {
	ID                  *int                   `json:"id"`
	Name                string                 `json:"name"`
	WatchlistEntries    []PublicWatchlistEntry `json:"watchlist-entries"`
	GroupName           string                 `json:"group-name"`
	OrderIndex          int                    `json:"order-index"`
	WatchlistEntryCount *int                   `json:"watchlist-entry-count"`
}

type PublicWatchlistEntry added in v0.2.0

type PublicWatchlistEntry struct {
	Symbol         string         `json:"symbol"`
	InstrumentType InstrumentType `json:"instrument_type"`
}

Something weird here in the api where instrument_type instead of instrument-type.

type QuantityDecimalPrecision added in v0.2.0

type QuantityDecimalPrecision struct {
	InstrumentType            InstrumentType `json:"instrument-type"`
	Symbol                    string         `json:"symbol"`
	Value                     int            `json:"value"`
	MinimumIncrementPrecision int            `json:"minimum-increment-precision"`
}

type QuoteStreamerTokenAuthResult added in v0.2.0

type QuoteStreamerTokenAuthResult struct {
	// API quote token unique to the customer identified by the session
	// Quote streamer tokens are valid for 24 hours.
	Token     string `json:"token"`
	DXLinkURL string `json:"dxlink-url"`
	Level     string `json:"level"`
}

Response from the API quote streamer request.

type RelatedOrder added in v0.2.0

type RelatedOrder struct {
	ID               int    `json:"id"`
	ComplexOrderID   int    `json:"complex-order-id"`
	ComplexOrderTag  string `json:"complex-order-tag"`
	ReplacesOrderID  string `json:"replaces-order-id"`
	ReplacingOrderID string `json:"replacing-order-id"`
	Status           string `json:"status"`
}

type RemovedWatchlist added in v0.2.0

type RemovedWatchlist struct {
	ID               *int             `json:"id"`
	UserID           *int             `json:"user_id"`
	Name             string           `json:"name"`
	CreatedAt        time.Time        `json:"created_at"`
	UpdatedAt        time.Time        `json:"updated_at"`
	WatchlistEntries []WatchlistEntry `json:"watchlist_entries"`
	GroupName        string           `json:"group_name"`
	OrderIndex       int              `json:"order_index"`
	CmsID            *string          `json:"cms_id"`
}

type Roll added in v0.2.0

type Roll struct {
	Name               string `json:"name"`
	ActiveCount        int    `json:"active-count"`
	CashSettled        bool   `json:"cash-settled"`
	BusinessDaysOffset int    `json:"business-days-offset"`
	FirstNotice        bool   `json:"first-notice"`
}

type Session

type Session struct {
	User          User    `json:"user"`
	SessionToken  *string `json:"session-token"`
	RememberToken *string `json:"remember-token"`
}

type SortOrder added in v0.2.0

type SortOrder string

type Strike added in v0.2.0

type Strike struct {
	StrikePrice        decimal.Decimal `json:"strike-price"`
	Call               string          `json:"call"`
	CallStreamerSymbol string          `json:"call-streamer-symbol"`
	Put                string          `json:"put"`
	PutStreamerSymbol  string          `json:"put-streamer-symbol"`
}

type StringToFloat32 added in v0.2.0

type StringToFloat32 float32

func (StringToFloat32) MarshalJSON added in v0.2.0

func (foe StringToFloat32) MarshalJSON() ([]byte, error)

MarshalJSON is the custom marshaler interface.

func (*StringToFloat32) UnmarshalJSON added in v0.2.0

func (foe *StringToFloat32) UnmarshalJSON(data []byte) error

UnmarshalJSON is the custom unmarshaler interface.

type SymbolData added in v0.2.0

type SymbolData struct {
	// Symbol is the stock ticker symbol
	Symbol string `json:"symbol"`
	// Description is the company name
	Description string `json:"description"`
}

SymbolData model.

type TickSize added in v0.2.0

type TickSize struct {
	Value     decimal.Decimal `json:"value"`
	Threshold decimal.Decimal `json:"threshold"`
	Symbol    string          `json:"symbol"`
}

type TimeBack added in v0.2.0

type TimeBack string

type TimeInForce added in v0.2.0

type TimeInForce string

type TimeOfDay added in v0.2.0

type TimeOfDay string

type Transaction added in v0.2.0

type Transaction struct {
	ID                               int             `json:"id"`
	AccountNumber                    string          `json:"account-number"`
	Symbol                           string          `json:"symbol"`
	InstrumentType                   InstrumentType  `json:"instrument-type"`
	UnderlyingSymbol                 string          `json:"underlying-symbol"`
	TransactionType                  string          `json:"transaction-type"`
	TransactionSubType               OrderAction     `json:"transaction-sub-type"`
	Description                      string          `json:"description"`
	Action                           OrderAction     `json:"action"`
	Quantity                         decimal.Decimal `json:"quantity"`
	Price                            decimal.Decimal `json:"price"`
	ExecutedAt                       time.Time       `json:"executed-at"`
	TransactionDate                  string          `json:"transaction-date"`
	Value                            decimal.Decimal `json:"value"`
	ValueEffect                      PriceEffect     `json:"value-effect"`
	RegulatoryFees                   decimal.Decimal `json:"regulatory-fees"`
	RegulatoryFeesEffect             PriceEffect     `json:"regulatory-fees-effect"`
	ClearingFees                     decimal.Decimal `json:"clearing-fees"`
	ClearingFeesEffect               PriceEffect     `json:"clearing-fees-effect"`
	OtherCharge                      decimal.Decimal `json:"other-charge"`
	OtherChargeEffect                PriceEffect     `json:"other-charge-effect"`
	OtherChargeDescription           string          `json:"other-charge-description"`
	NetValue                         decimal.Decimal `json:"net-value"`
	NetValueEffect                   PriceEffect     `json:"net-value-effect"`
	Commission                       decimal.Decimal `json:"commission"`
	CommissionEffect                 PriceEffect     `json:"commission-effect"`
	ProprietaryIndexOptionFees       decimal.Decimal `json:"proprietary-index-option-fees"`
	ProprietaryIndexOptionFeesEffect PriceEffect     `json:"proprietary-index-option-fees-effect"`
	IsEstimatedFee                   bool            `json:"is-estimated-fee"`
	ExtExchangeOrderNumber           string          `json:"ext-exchange-order-number"`
	ExtGlobalOrderNumber             int             `json:"ext-global-order-number"`
	ExtGroupID                       string          `json:"ext-group-id"`
	ExtGroupFillID                   string          `json:"ext-group-fill-id"`
	ExtExecID                        string          `json:"ext-exec-id"`
	ExecID                           string          `json:"exec-id"`
	Exchange                         string          `json:"exchange"`
	OrderID                          int             `json:"order-id"`
	ReversesID                       int             `json:"reverses-id"`
	ExchangeAffiliationIDentifier    string          `json:"exchange-affiliation-identifier"`
	CostBasisReconciliationDate      string          `json:"cost-basis-reconciliation-date"`
	Lots                             []Lot           `json:"lots"`
	LegCount                         int             `json:"leg-count"`
	DestinationVenue                 string          `json:"destination-venue"`
	AgencyPrice                      decimal.Decimal `json:"agency-price"`
	PrincipalPrice                   decimal.Decimal `json:"principal-price"`
}

type TransactionFees added in v0.2.0

type TransactionFees struct {
	TotalFees       decimal.Decimal `json:"total-fees"`
	TotalFeesEffect PriceEffect     `json:"total-fees-effect"`
}

type TransactionsQuery added in v0.2.0

type TransactionsQuery struct {
	// Default value 250
	PerPage int `url:"per-page,omitempty"`
	// Default value 0
	PageOffset int `url:"page-offset,omitempty"`
	// The order to sort results in. Defaults to Desc, Accepts Desc or Asc.
	Sort SortOrder `url:"sort,omitempty"`
	// Filter based on transaction_type
	Type string `url:"type,omitempty"`
	// Allows filtering on multiple transaction_types
	Types []string `url:"types[],omitempty"`
	// Filter based on transaction_sub_type
	SubTypes []string `url:"sub-type[],omitempty"`
	// The start date of transactions to query.
	StartDate time.Time `layout:"2006-01-02" url:"start-date,omitempty"`
	// The end date of transactions to query. Defaults to now.
	EndDate time.Time `layout:"2006-01-02" url:"end-date,omitempty"`
	// The type of instrument i.e. InstrumentType
	InstrumentType InstrumentType `url:"instrument-type,omitempty"`
	// The Stock Ticker Symbol AAPL, OCC Option Symbol AAPL 191004P00275000,
	// TW Future Symbol /ESZ9, or TW Future Option Symbol ./ESZ9 EW4U9 190927P2975
	Symbol string `url:"symbol,omitempty"`
	// The Underlying Symbol. The Ticker Symbol FB or
	// TW Future Symbol with out date component /M6E or
	// the full TW Future Symbol /ESU9
	UnderlyingSymbol string `url:"underlying-symbol,omitempty"`
	// The action of the transaction. i.e. OrderAction
	Action OrderAction `url:"action,omitempty"`
	// Account partition key
	PartitionKey string `url:"partition-key,omitempty"`
	// The full TW Future Symbol /ESZ9 or
	// /NGZ19 if two year digit are appropriate
	FuturesSymbol string `url:"futures-symbol"`
	// DateTime start range for filtering transactions in full date-time
	StartAt time.Time `layout:"2006-01-02T15:04:05Z" url:"start-at,omitempty"`
	// DateTime end range for filtering transactions in full date-time
	EndAt time.Time `layout:"2006-01-02T15:04:05Z" url:"end-at,omitempty"`
}

The query for account transactions.

type User

type User struct {
	Email      string `json:"email"`
	Username   string `json:"username"`
	ExternalID string `json:"external-id"`
	ID         *int   `json:"id"`
}

type Warrant added in v0.2.0

type Warrant struct {
	Symbol         string         `json:"symbol"`
	InstrumentType InstrumentType `json:"instrument-type"`
	Cusip          string         `json:"cusip"`
	ListedMarket   string         `json:"listed-market"`
	Description    string         `json:"description"`
	IsClosingOnly  bool           `json:"is-closing-only"`
	Active         bool           `json:"active"`
}

type Watchlist added in v0.2.0

type Watchlist struct {
	ID                  *int             `json:"id"`
	Name                string           `json:"name"`
	WatchlistEntries    []WatchlistEntry `json:"watchlist-entries"`
	GroupName           string           `json:"group-name"`
	OrderIndex          int              `json:"order-index"`
	CmsID               *string          `json:"cms-id"`
	WatchlistEntryCount *int             `json:"watchlist-entry-count"`
}

type WatchlistEntry added in v0.2.0

type WatchlistEntry struct {
	Symbol         string         `json:"symbol"`
	InstrumentType InstrumentType `json:"instrument-type"`
}

Jump to

Keyboard shortcuts

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