tastytrade.streamer

class tastytrade.streamer.AlertStreamer(session: Session)

Bases: AsyncContextManagerMixin

Used to subscribe to account-level updates (balances, orders, positions), public watchlist updates, quote alerts, and user-level messages. It must always be initialized via its async context manager.

Example usage:

from tastytrade import Account, AlertStreamer
from tastytrade.order import PlacedOrder

async with AlertStreamer(session) as streamer:
    accounts = await Account.get(session)
    # updates to balances, orders, and positions
    await streamer.subscribe_accounts(accounts)
    # changes in public watchlists
    await streamer.subscribe_public_watchlists()
    # quote alerts configured by the user
    await streamer.subscribe_quote_alerts()

    async for order in streamer.listen(PlacedOrder):
        print(order)
base_url : str

The base url for the streamer websocket

async listen(alert_class: type[T]) AsyncIterator[T]

Iterate over non-heartbeat messages received from the streamer, mapping them to their appropriate data class and yielding them.

This is designed to be friendly for type checking; the return type will be the same class you pass in.

Parameters:
alert_class: type[T]

the type of alert to listen for, should be of AlertType

request_id

Counter used to track the request ID for the streamer

async subscribe_accounts(accounts: Iterable[Account]) None

Subscribes to account-level updates (balances, orders, positions).

Parameters:
accounts: Iterable[Account]

list of Account to subscribe to updates for

async subscribe_public_watchlists() None

Subscribes to public watchlist updates.

async subscribe_quote_alerts() None

Subscribes to quote alerts (which are configured at a user level).

tastytrade.streamer.AlertType : TypeAlias = tastytrade.account.AccountBalance | tastytrade.streamer.ExternalTransaction | tastytrade.order.PlacedComplexOrder | tastytrade.order.PlacedOrder | tastytrade.account.CurrentPosition | tastytrade.streamer.QuoteAlert | tastytrade.account.TradingStatus | tastytrade.streamer.UnderlyingYearGainSummary | tastytrade.watchlists.Watchlist

List of all possible types to stream with the alert streamer

class tastytrade.streamer.DXLinkStreamer(session: Session, ssl_context: SSLContext | None = None)

Bases: AsyncContextManagerMixin

A DXLinkStreamer object is used to fetch quotes or greeks for a given symbol or list of symbols. It must always be initialized via its async context manager.

Example usage:

from tastytrade import DXLinkStreamer
from tastytrade.dxfeed import Quote

# must be a production session
async with DXLinkStreamer(session) as streamer:
    subs = ['SPY']  # list of quotes to subscribe to
    await streamer.subscribe(Quote, subs)
    quote = await streamer.get_event(Quote)
    print(quote)
async get_event(event_class: type[U]) U

Using the existing subscription, pulls an event of the given type and returns it.

This is designed to be friendly for type checking; the return type will be the same class you pass in.

Parameters:
event_class: type[U]

the type of alert to listen for, should be of EventType

get_event_nowait(event_class: type[U]) U | None

Using the existing subscriptions, pulls an event of the given type and returns it. If the queue is empty None is returned.

This is designed to be friendly for type checking; the return type will be the same class you pass in.

Parameters:
event_class: type[U]

the type of alert to listen for, should be of EventType

async listen(event_class: type[U]) AsyncIterator[U]

Using the existing subscriptions, pulls events of the given type and yield returns them. Never exits unless there’s an error or the channel is closed.

This is designed to be friendly for type checking; the return type will be the same class you pass in.

Parameters:
event_class: type[U]

the type of alert to listen for, should be of EventType

session
async subscribe(event_class: type[Event], symbols: Iterable[str], refresh_interval: float = 0.1) None

Subscribes to quotes for given list of symbols. Used for recurring data feeds. For candles, use subscribe_candle() instead.

Parameters:
event_class: type[Event]

type of subscription to add, should be of EventType

symbols: Iterable[str]

list of symbols to subscribe for

refresh_interval: float = 0.1

Time in seconds between fetching new events from dxfeed for this event type. You can try a higher value if processing quote updates quickly is not a high priority. Once refresh_interval is set for this event type and channel is opened, it cannot be changed later.

async subscribe_candle(symbols: Iterable[str], interval: str, start_time: datetime | None = None, extended_trading_hours: bool = False, refresh_interval: float = 0.1) None

Subscribes to candle data for the given list of symbols.

Parameters:
symbols: Iterable[str]

list of symbols to get data for

interval: str

the width of each candle in time, e.g. ’15s’, ‘5m’, ‘1h’, ‘3d’, ‘1w’, ‘1mo’

start_time: datetime | None = None

starting time for the data range, defaults to 9/9/2001.

extended_trading_hours: bool = False

whether to include extended trading

refresh_interval: float = 0.1

Time in seconds between fetching new events from dxfeed for this event type. You can try a higher value if processing quote updates quickly is not a high priority. Once refresh_interval is set for this event type and channel is opened, it cannot be changed later.

async unsubscribe(event_class: type[Event], symbols: Iterable[str]) None

Removes existing subscription for given list of symbols. For candles, use unsubscribe_candle() instead.

Parameters:
event_class: type[Event]

type of subscription to remove

symbols: Iterable[str]

list of symbols to unsubscribe from

async unsubscribe_all(event_class: type[Event]) None

Unsubscribes to all events of the given event type.

Parameters:
event_class: type[Event]

type of event to unsubscribe from.

async unsubscribe_candle(ticker: str, interval: str | None = None, extended_trading_hours: bool = False) None

Removes existing subscription for a candle.

Parameters:
ticker: str

symbol to unsubscribe from

interval: str | None = None

candle width to unsubscribe from

extended_trading_hours: bool = False

whether candle to unsubscribe from contains extended trading hours

pydantic model tastytrade.streamer.ExternalTransaction(*, id: int, account_number: str, amount: Decimal, bank_account_type: str, banking_date: date, created_at: datetime, direction: str, disbursement_type: str, ext_transfer_id: str, funds_available_date: date, is_cancelable: bool, is_clearing_accepted: bool, state: str, transfer_method: str, updated_at: datetime)

Bases: TastytradeData

Dataclass containing information on an external transaction (eg money movement).

Show JSON schema
{
   "title": "ExternalTransaction",
   "description": "Dataclass containing information on an external transaction (eg money movement).",
   "type": "object",
   "properties": {
      "id": {
         "title": "Id",
         "type": "integer"
      },
      "account-number": {
         "title": "Account-Number",
         "type": "string"
      },
      "amount": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$",
               "type": "string"
            }
         ],
         "title": "Amount"
      },
      "bank-account-type": {
         "title": "Bank-Account-Type",
         "type": "string"
      },
      "banking-date": {
         "format": "date",
         "title": "Banking-Date",
         "type": "string"
      },
      "created-at": {
         "format": "date-time",
         "title": "Created-At",
         "type": "string"
      },
      "direction": {
         "title": "Direction",
         "type": "string"
      },
      "disbursement-type": {
         "title": "Disbursement-Type",
         "type": "string"
      },
      "ext-transfer-id": {
         "title": "Ext-Transfer-Id",
         "type": "string"
      },
      "funds-available-date": {
         "format": "date",
         "title": "Funds-Available-Date",
         "type": "string"
      },
      "is-cancelable": {
         "title": "Is-Cancelable",
         "type": "boolean"
      },
      "is-clearing-accepted": {
         "title": "Is-Clearing-Accepted",
         "type": "boolean"
      },
      "state": {
         "title": "State",
         "type": "string"
      },
      "transfer-method": {
         "title": "Transfer-Method",
         "type": "string"
      },
      "updated-at": {
         "format": "date-time",
         "title": "Updated-At",
         "type": "string"
      }
   },
   "required": [
      "id",
      "account-number",
      "amount",
      "bank-account-type",
      "banking-date",
      "created-at",
      "direction",
      "disbursement-type",
      "ext-transfer-id",
      "funds-available-date",
      "is-cancelable",
      "is-clearing-accepted",
      "state",
      "transfer-method",
      "updated-at"
   ]
}

Fields:
field account_number : str [Required] (alias 'account-number')
field amount : Decimal [Required]
field bank_account_type : str [Required] (alias 'bank-account-type')
field banking_date : date [Required] (alias 'banking-date')
field created_at : datetime [Required] (alias 'created-at')
field direction : str [Required]
field disbursement_type : str [Required] (alias 'disbursement-type')
field ext_transfer_id : str [Required] (alias 'ext-transfer-id')
field funds_available_date : date [Required] (alias 'funds-available-date')
field id : int [Required]
field is_cancelable : bool [Required] (alias 'is-cancelable')
field is_clearing_accepted : bool [Required] (alias 'is-clearing-accepted')
field state : str [Required]
field transfer_method : str [Required] (alias 'transfer-method')
field updated_at : datetime [Required] (alias 'updated-at')
pydantic model tastytrade.streamer.QuoteAlert(*, user_external_id: str, symbol: str, alert_external_id: str, expires_at: int, completed_at: datetime, created_at: datetime, triggered_at: datetime, field: str, operator: str, threshold: str, threshold_numeric: Decimal, dx_symbol: str)

Bases: TastytradeData

Dataclass that contains information about a quote alert

Show JSON schema
{
   "title": "QuoteAlert",
   "description": "Dataclass that contains information about a quote alert",
   "type": "object",
   "properties": {
      "user-external-id": {
         "title": "User-External-Id",
         "type": "string"
      },
      "symbol": {
         "title": "Symbol",
         "type": "string"
      },
      "alert-external-id": {
         "title": "Alert-External-Id",
         "type": "string"
      },
      "expires-at": {
         "title": "Expires-At",
         "type": "integer"
      },
      "completed-at": {
         "format": "date-time",
         "title": "Completed-At",
         "type": "string"
      },
      "created-at": {
         "format": "date-time",
         "title": "Created-At",
         "type": "string"
      },
      "triggered-at": {
         "format": "date-time",
         "title": "Triggered-At",
         "type": "string"
      },
      "field": {
         "title": "Field",
         "type": "string"
      },
      "operator": {
         "title": "Operator",
         "type": "string"
      },
      "threshold": {
         "title": "Threshold",
         "type": "string"
      },
      "threshold-numeric": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$",
               "type": "string"
            }
         ],
         "title": "Threshold-Numeric"
      },
      "dx-symbol": {
         "title": "Dx-Symbol",
         "type": "string"
      }
   },
   "required": [
      "user-external-id",
      "symbol",
      "alert-external-id",
      "expires-at",
      "completed-at",
      "created-at",
      "triggered-at",
      "field",
      "operator",
      "threshold",
      "threshold-numeric",
      "dx-symbol"
   ]
}

Fields:
field alert_external_id : str [Required] (alias 'alert-external-id')
field completed_at : datetime [Required] (alias 'completed-at')
field created_at : datetime [Required] (alias 'created-at')
field dx_symbol : str [Required] (alias 'dx-symbol')
field expires_at : int [Required] (alias 'expires-at')
field field : str [Required]
field operator : str [Required]
field symbol : str [Required]
field threshold : str [Required]
field threshold_numeric : Decimal [Required] (alias 'threshold-numeric')
field triggered_at : datetime [Required] (alias 'triggered-at')
field user_external_id : str [Required] (alias 'user-external-id')
class tastytrade.streamer.SubscriptionType(value)

Bases: StrEnum

Contains the subscription types for the alert streamer.

ACCOUNT = 'connect'
HEARTBEAT = 'heartbeat'
PUBLIC_WATCHLISTS = 'public-watchlists-subscribe'
QUOTE_ALERTS = 'quote-alerts-subscribe'
class tastytrade.streamer.U

List of all possible types to stream with the data streamer

alias of TypeVar(‘U’, bound=Event)

pydantic model tastytrade.streamer.UnderlyingYearGainSummary(*, year: int, account_number: str, symbol: str, instrument_type: InstrumentType, fees: Decimal, commissions: Decimal, yearly_realized_gain: Decimal, realized_lot_gain: Decimal)

Bases: TastytradeData

Dataclass that contains information about the yearly gain or loss for an underlying

Show JSON schema
{
   "title": "UnderlyingYearGainSummary",
   "description": "Dataclass that contains information about the yearly gain\nor loss for an underlying",
   "type": "object",
   "properties": {
      "year": {
         "title": "Year",
         "type": "integer"
      },
      "account-number": {
         "title": "Account-Number",
         "type": "string"
      },
      "symbol": {
         "title": "Symbol",
         "type": "string"
      },
      "instrument-type": {
         "$ref": "#/$defs/InstrumentType"
      },
      "fees": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$",
               "type": "string"
            }
         ],
         "title": "Fees"
      },
      "commissions": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$",
               "type": "string"
            }
         ],
         "title": "Commissions"
      },
      "yearly-realized-gain": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$",
               "type": "string"
            }
         ],
         "title": "Yearly-Realized-Gain"
      },
      "realized-lot-gain": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "pattern": "^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$",
               "type": "string"
            }
         ],
         "title": "Realized-Lot-Gain"
      }
   },
   "$defs": {
      "InstrumentType": {
         "description": "Contains the valid types of instruments and their representation in the API.",
         "enum": [
            "Bond",
            "Cryptocurrency",
            "Currency Pair",
            "Equity",
            "Equity Offering",
            "Equity Option",
            "Fixed Income Security",
            "Future",
            "Future Option",
            "Index",
            "Liquidity Pool",
            "Unknown",
            "Warrant"
         ],
         "title": "InstrumentType",
         "type": "string"
      }
   },
   "required": [
      "year",
      "account-number",
      "symbol",
      "instrument-type",
      "fees",
      "commissions",
      "yearly-realized-gain",
      "realized-lot-gain"
   ]
}

Fields:
Validators:
field account_number : str [Required] (alias 'account-number')
Validated by:
field commissions : Decimal [Required]
Validated by:
field fees : Decimal [Required]
Validated by:
field instrument_type : InstrumentType [Required] (alias 'instrument-type')
Validated by:
field realized_lot_gain : Decimal [Required] (alias 'realized-lot-gain')
Validated by:
field symbol : str [Required]
Validated by:
field year : int [Required]
Validated by:
field yearly_realized_gain : Decimal [Required] (alias 'yearly-realized-gain')
Validated by:
validator validate_price_effects  »  all fields