tastytrade.streamer

class tastytrade.streamer.AlertStreamer(session: ~tastytrade.session.Session, disconnect_args: tuple[~typing.Any, ...] = (), disconnect_fn: ~typing.Callable[[...], ~collections.abc.Coroutine[~typing.Any, ~typing.Any, None]] = <function _do_nothing>, reconnect_args: tuple[~typing.Any, ...] = (), reconnect_fn: ~typing.Callable[[...], ~collections.abc.Coroutine[~typing.Any, ~typing.Any, None]] = <function _do_nothing>)

Bases: object

Used to subscribe to account-level updates (balances, orders, positions), public watchlist updates, quote alerts, and user-level messages. It should always be initialized as an async context manager, or by awaiting it, since the object cannot be fully instantiated without async.

Example usage:

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

async with AlertStreamer(session) as streamer:
    accounts = Account.get_accounts(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)

Or:

streamer = await AlertStreamer(session)
base_url : str

The base url for the streamer websocket

async close() None

Closes the websocket connection and cancels the pending tasks.

disconnect_args

Variable number of arguments to pass to the reconnect function

disconnect_fn

An async function to be called upon disconnection. The first argument must be of type AlertStreamer and will be a reference to the streamer object.

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

proxy

The proxy URL, if any, associated with the session

reconnect_args

Variable number of arguments to pass to the reconnect function

reconnect_fn

An async function to be called upon reconnection. The first argument must be of type AlertStreamer and will be a reference to the streamer object.

request_id

Counter used to track the request ID for the streamer

async subscribe_accounts(accounts: list[Account]) None

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

Parameters:
accounts: list[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).

token : str

The active session used to initiate the streamer or make requests

tastytrade.streamer.AlertType : TypeAlias = tastytrade.account.AccountBalance | tastytrade.streamer.ExternalTransaction | tastytrade.order.PlacedComplexOrder | tastytrade.order.PlacedOrder | tastytrade.order.OrderChain | 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: ~tastytrade.session.Session, disconnect_args: tuple[~typing.Any, ...] = (), disconnect_fn: ~typing.Callable[[...], ~collections.abc.Coroutine[~typing.Any, ~typing.Any, None]] = <function _do_nothing>, reconnect_args: tuple[~typing.Any, ...] = (), reconnect_fn: ~typing.Callable[[...], ~collections.abc.Coroutine[~typing.Any, ~typing.Any, None]] = <function _do_nothing>, ssl_context: ~ssl.SSLContext = <ssl.SSLContext object>)

Bases: object

A DXLinkStreamer object is used to fetch quotes or greeks for a given symbol or list of symbols. It should always be initialized as an async context manager, or by awaiting it, since the object cannot be fully instantiated without async.

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)

Or:

streamer = await DXLinkStreamer(session)
async close() None

Closes the websocket connection and cancels the heartbeat task.

disconnect_args

Variable number of arguments to pass to the disconnect function

disconnect_fn

An async function to be called upon disconnection. The first argument must be of type DXLinkStreamer and will be a reference to the streamer object.

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

proxy

The proxy URL, if any, associated with the session

reconnect_args

Variable number of arguments to pass to the reconnect function

reconnect_fn

An async function to be called upon reconnection. The first argument must be of type DXLinkStreamer and will be a reference to the streamer object.

async subscribe(event_class: type[Candle | Greeks | Profile | Quote | Summary | TheoPrice | TimeAndSale | Trade | Underlying], symbols: list[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[Candle | Greeks | Profile | Quote | Summary | TheoPrice | TimeAndSale | Trade | Underlying]

type of subscription to add, should be of EventType

symbols: list[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: list[str], interval: str, start_time: datetime, extended_trading_hours: bool = False, refresh_interval: float = 0.1) None

Subscribes to candle data for the given list of symbols.

Parameters:
symbols: list[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

starting time for the data range

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[Candle | Greeks | Profile | Quote | Summary | TheoPrice | TimeAndSale | Trade | Underlying], symbols: list[str]) None

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

Parameters:
event_class: type[Candle | Greeks | Profile | Quote | Summary | TheoPrice | TimeAndSale | Trade | Underlying]

type of subscription to remove

symbols: list[str]

list of symbols to unsubscribe from

async unsubscribe_all(event_class: type[Candle | Greeks | Profile | Quote | Summary | TheoPrice | TimeAndSale | Trade | Underlying]) None

Unsubscribes to all events of the given event type.

Parameters:
event_class: type[Candle | Greeks | Profile | Quote | Summary | TheoPrice | TimeAndSale | Trade | Underlying]

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

tastytrade.streamer.EventType : TypeAlias = tastytrade.dxfeed.candle.Candle | tastytrade.dxfeed.greeks.Greeks | tastytrade.dxfeed.profile.Profile | tastytrade.dxfeed.quote.Quote | tastytrade.dxfeed.summary.Summary | tastytrade.dxfeed.theoprice.TheoPrice | tastytrade.dxfeed.timeandsale.TimeAndSale | tastytrade.dxfeed.trade.Trade | tastytrade.dxfeed.underlying.Underlying

List of all possible types to stream with the data streamer

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"
            },
            {
               "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:
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"
            },
            {
               "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:
enum tastytrade.streamer.SubscriptionType(value)

Bases: str, Enum

This is an Enum that contains the subscription types for the alert streamer.

Member Type:

str

Valid values are as follows:

ACCOUNT = <SubscriptionType.ACCOUNT: 'connect'>
HEARTBEAT = <SubscriptionType.HEARTBEAT: 'heartbeat'>
PUBLIC_WATCHLISTS = <SubscriptionType.PUBLIC_WATCHLISTS: 'public-watchlists-subscribe'>
QUOTE_ALERTS = <SubscriptionType.QUOTE_ALERTS: 'quote-alerts-subscribe'>
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"
            },
            {
               "type": "string"
            }
         ],
         "title": "Fees"
      },
      "commissions": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "type": "string"
            }
         ],
         "title": "Commissions"
      },
      "yearly-realized-gain": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "type": "string"
            }
         ],
         "title": "Yearly-Realized-Gain"
      },
      "realized-lot-gain": {
         "anyOf": [
            {
               "type": "number"
            },
            {
               "type": "string"
            }
         ],
         "title": "Realized-Lot-Gain"
      }
   },
   "$defs": {
      "InstrumentType": {
         "description": "This is an :class:`~enum.Enum` that contains the valid types of instruments\nand 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:
  • validate_price_effects » all fields