From 114ae58393436e91b363c78a02c4c7c64a0cad5f Mon Sep 17 00:00:00 2001 From: 117 <16513382+117@users.noreply.github.com> Date: Sat, 30 Mar 2024 18:49:27 -0600 Subject: [PATCH] feat: new method pattern --- README.md | 478 ++++++++++++++-- src/api/_shared.ts | 2 + src/api/trade.ts | 1333 ++++++++++++++++++++++---------------------- 3 files changed, 1077 insertions(+), 736 deletions(-) create mode 100644 src/api/_shared.ts diff --git a/README.md b/README.md index 1152236..d8b6c4b 100644 --- a/README.md +++ b/README.md @@ -139,64 +139,426 @@ The methods are named to reflect the structure of their API paths. Since the client is fully-typed 😁, you can use your IDE to explore the available methods and their parameters. They are also documented below. -#### Methods - -These are available on `api` and `paper-api` `baseURL`'s: - -| Path | Method(s) | -| :----------------------------------- | :------------------------------- | -| `v2.account` | `get` | -| `v2.account.portfolio.history` | `get` | -| `v2.account.configurations` | `get`, `patch` | -| `v2.account.activities` | `get` | -| `v2.orders` | `get`, `post`, `patch`, `delete` | -| `v2.positions` | `get`, `delete` | -| `v2.positions.exercise` | `post` | -| `v2.watchlists` | `get`, `post`, `patch`, `delete` | -| `v2.calendar` | `get` | -| `v2.clock` | `get` | -| `v2.assets` | `get` | -| `v2.options.contracts` | `get` | -| `v2.corporate_actions.announcements` | `get` | -| `v2.wallets` | `get` | -| `v2.wallets.whitelists` | `get`, `post`, `delete` | -| `v2.wallets.fees.estimate` | `get` | -| `v2.wallets.transfers` | `get`, `post`, `delete` | - -These are available on the `https://data.alpaca.markets` `baseURL`: - -| Path | Method(s) | -| :------------------------------------- | :-------- | -| `v1beta1.corporate_actions` | `get` | -| `v1beta1.forex.latest.rates` | `get` | -| `v1beta1.forex.rates` | `get` | -| `v1beta1.logos` | `get` | -| `v1beta1.news` | `get` | -| `v1beta1.options.bars` | `get` | -| `v1beta1.options.meta.exchanges` | `get` | -| `v1beta1.options.quotes.latest` | `get` | -| `v1beta1.options.trades.latest` | `get` | -| `v1beta1.options.trades` | `get` | -| `v1beta1.options.snapshots` | `get` | -| `v1beta1.screener.stocks.most_actives` | `get` | -| `v1beta1.screener.movers` | `get` | -| `v1beta3.crypto.bars` | `get` | -| `v1beta3.crypto.latest.bars` | `get` | -| `v1beta3.crypto.latest.orderbooks` | `get` | -| `v1beta3.crypto.latest.quotes` | `get` | -| `v1beta3.crypto.latest.trades` | `get` | -| `v1beta3.crypto.quotes` | `get` | -| `v1beta3.crypto.snapshots` | `get` | -| `v1beta3.crypto.trades` | `get` | -| `v2.stocks.auctions` | `get` | -| `v2.stocks.bars` | `get` | -| `v2.stocks.bars.latest` | `get` | -| `v2.stocks.meta.conditions` | `get` | -| `v2.stocks.meta.exchanges` | `get` | -| `v2.stocks.meta.quotes` | `get` | -| `v2.stocks.snapshots` | `get` | -| `v2.stocks.trades` | `get` | -| `v2.stocks.trades.latest` | `get` | +### Methods + +- [getAccount](#getaccount) +- [createOrder](#createorder) +- [getOrders](#getorders) +- [getOrder](#getorder) +- [replaceOrder](#replaceorder) +- [cancelOrders](#cancelorders) +- [cancelOrder](#cancelorder) +- [getPositions](#getpositions) +- [getPosition](#getposition) +- [closePositions](#closepositions) +- [closePosition](#closeposition) +- [exerciseOption](#exerciseoption) +- [getMarketCalendar](#getmarketcalendar) +- [getMarketClock](#getmarketclock) +- [getAssets](#getassets) +- [getAsset](#getasset) +- [getOptionsContracts](#getoptionscontracts) +- [getOptionsContract](#getoptionscontract) +- [getCorporateActionsAnnouncements](#getcorporateactionsannouncements) +- [getCorporateActionsAnnouncement](#getcorporateactionsannouncement) +- [getWatchlists](#getwatchlists) +- [getWatchlist](#getwatchlist) +- [createWatchlist](#createwatchlist) +- [updateWatchlist](#updatewatchlist) +- [deleteWatchlist](#deletewatchlist) +- [getPortfolioHistory](#getportfoliohistory) +- [getAccountConfigurations](#getaccountconfigurations) +- [updateAccountConfigurations](#updateaccountconfigurations) +- [getAccountActivities](#getaccountactivities) +- [getAccountActivity](#getaccountactivity) +- [getWallets](#getwallets) +- [getWallet](#getwallet) +- [getFeeEstimate](#getfeeestimate) +- [getTransfers](#gettransfers) +- [getTransfer](#gettransfer) +- [createTransfer](#createtransfer) +- [getWhitelists](#getwhitelists) +- [createWhitelist](#createwhitelist) +- [removeWhitelist](#removewhitelist) + +##### Get Account + +```typescript +client.getAccount().then(console.log); +``` + +##### Create Order + +```typescript +const options: CreateOrderOptions = { + symbol: "AAPL", + qty: 1, + side: "buy", + type: "market", + time_in_force: "day", +}; + +client.createOrder(options).then(console.log); +``` + +##### Get Orders + +```typescript +const options: GetOrdersOptions = { + status: "open", + limit: 10, +}; + +client.getOrders(options).then(console.log); +``` + +##### Get Order + +```typescript +const options: GetOrderOptions = { + order_id: "123abc", +}; + +client.getOrder(options).then(console.log); +``` + +##### Replace Order + +```typescript +const options: ReplaceOrderOptions = { + order_id: "123abc", + qty: 2, + limit_price: 150, +}; + +client.replaceOrder(options).then(console.log); +``` + +##### Cancel Orders + +```typescript +client.cancelOrders().then(console.log); +``` + +##### Cancel Order + +```typescript +const options: CancelOrderOptions = { + order_id: "123abc", +}; + +client.cancelOrder(options).then(console.log); +``` + +##### Get Positions + +```typescript +client.getPositions().then(console.log); +``` + +##### Get Position + +```typescript +const options: GetPositionOptions = { + symbol_or_asset_id: "AAPL", +}; + +client.getPosition(options).then(console.log); +``` + +##### Close Positions + +```typescript +client.closePositions().then(console.log); +``` + +##### Close Position + +```typescript +const options: ClosePositionOptions = { + symbol_or_asset_id: "AAPL", +}; + +client.closePosition(options).then(console.log); +``` + +##### Exercise Option + +```typescript +const option: ExerciseOption = { + symbol_or_contract_id: "AAPL230623C00130000", +}; + +client.exerciseOption(option).then(console.log); +``` + +##### Get Market Calendar + +```typescript +const options: GetCalendarOptions = { + start: "2023-01-01", + end: "2023-12-31", +}; + +client.getMarketCalendar(options).then(console.log); +``` + +##### Get Market Clock + +```typescript +client.getMarketClock().then(console.log); +``` + +##### Get Assets + +```typescript +const options: GetAssetsOptions = { + status: "active", + asset_class: "us_equity", +}; + +client.getAssets(options).then(console.log); +``` + +##### Get Asset + +```typescript +const options: GetAssetOptions = { + symbol_or_asset_id: "AAPL", +}; + +client.getAsset(options).then(console.log); +``` + +##### Get Options Contracts + +```typescript +const options: GetOptionsContractsOptions = { + underlying_symbols: "AAPL", + expiration_date_gte: "2023-06-01", + expiration_date_lte: "2023-06-30", +}; + +client.getOptionsContracts(options).then(console.log); +``` + +##### Get Options Contract + +```typescript +const options: GetOptionsContractOptions = { + symbol_or_contract_id: "AAPL230623C00130000", +}; + +client.getOptionsContract(options).then(console.log); +``` + +##### Get Corporate Actions Announcements + +```typescript +const options: GetCorporateActionsAnnouncementsOptions = { + ca_types: "dividend", + since: "2023-01-01", + until: "2023-12-31", +}; + +client.getCorporateActionsAnnouncements(options).then(console.log); +``` + +##### Get Corporate Actions Announcement + +```typescript +const options: GetCorporateActionsAnnouncementOptions = { + id: "123abc", +}; + +client.getCorporateActionsAnnouncement(options).then(console.log); +``` + +##### Get Watchlists + +```typescript +client.getWatchlists().then(console.log); +``` + +##### Get Watchlist + +```typescript +const options: GetWatchlistOptions = { + watchlist_id: "123abc", +}; + +client.getWatchlist(options).then(console.log); +``` + +##### Create Watchlist + +```typescript +const options: CreateWatchlistOptions = { + name: "My Watchlist", + symbols: ["AAPL", "AMZN", "GOOG"], +}; + +client.createWatchlist(options).then(console.log); +``` + +##### Update Watchlist + +```typescript +const options: UpdateWatchlistOptions = { + watchlist_id: "123abc", + name: "Updated Watchlist", + symbols: ["AAPL", "MSFT"], +}; + +client.updateWatchlist(options).then(console.log); +``` + +##### Delete Watchlist + +```typescript +const options: DeleteWatchlistOptions = { + watchlist_id: "123abc", +}; + +client.deleteWatchlist(options).then(console.log); +``` + +##### Get Portfolio History + +```typescript +const options: GetPortfolioHistoryOptions = { + period: "1M", + timeframe: "1D", +}; + +client.getPortfolioHistory(options).then(console.log); +``` + +##### Get Account Configurations + +```typescript +client.getAccountConfigurations().then(console.log); +``` + +##### Update Account Configurations + +```typescript +const options: UpdateAccountConfigurationsOptions = { + dtbp_check: "both", + no_shorting: true, +}; + +client.updateAccountConfigurations(options).then(console.log); +``` + +##### Get Account Activities + +```typescript +client.getAccountActivities().then(console.log); +``` + +##### Get Account Activity + +```typescript +const options: GetAccountActivityOptions = { + activity_type: "FILL", +}; + +client.getAccountActivity(options).then(console.log); +``` + +##### Get Wallets + +```typescript +client.getWallets().then(console.log); +``` + +##### Get Wallet + +```typescript +const options: GetWalletOptions = { + asset: "BTC", +}; + +client.getWallet(options).then(console.log); +``` + +##### Get Fee Estimate + +```typescript +const options: GetFeeEstimateOptions = { + asset: "BTC", + from_address: "abc123", + to_address: "def456", + amount: "0.1", +}; + +client.getFeeEstimate(options).then(console.log); +``` + +##### Get Transfers + +```typescript +const options: GetTransfersOptions = { + asset: "BTC", +}; + +client.getTransfers(options).then(console.log); +``` + +##### Get Transfer + +```typescript +const options: GetTransferOptions = { + transfer_id: "123abc", +}; + +client.getTransfer(options).then(console.log); +``` + +##### Create Transfer + +```typescript +const options: CreateTransferOptions = { + asset: "BTC", + amount: "0.1", + address: "abc123", +}; + +client.createTransfer(options).then(console.log); +``` + +##### Get Whitelists + +```typescript +const options: GetWhitelistsOptions = { + asset: "BTC", + address: "abc123", +}; + +client.getWhitelists(options).then(console.log); +``` + +##### Create Whitelist + +```typescript +const options: CreateWhitelistOptions = { + asset: "BTC", + address: "abc123", +}; + +client.createWhitelist(options).then(console.log); +``` + +##### Remove Whitelist + +```typescript +const options: RemoveWhitelistOptions = { + whitelisted_address_id: "123abc", +}; + +client.removeWhitelist(options).then(console.log); +``` ### WebSocket diff --git a/src/api/_shared.ts b/src/api/_shared.ts new file mode 100644 index 0000000..5edf2d3 --- /dev/null +++ b/src/api/_shared.ts @@ -0,0 +1,2 @@ +// Typically used for fields where the type may change based on the context, such as prices. +export type UnstableNumber = string | number; diff --git a/src/api/trade.ts b/src/api/trade.ts index 8880fd9..a0bd200 100644 --- a/src/api/trade.ts +++ b/src/api/trade.ts @@ -1,16 +1,23 @@ import { ClientContext } from "../factory/createClient.ts"; +import { UnstableNumber } from "./_shared.ts"; + +export type AccountStatus = + | "ONBOARDING" + | "SUBMISSION_FAILED" + | "SUBMITTED" + | "ACCOUNT_UPDATED" + | "APPROVAL_PENDING" + | "ACTIVE" + | "REJECTED"; + +export type OptionsApprovedLevel = 0 | 1 | 2; + +export type OptionsTradingLevel = 0 | 1 | 2; export type Account = { id: string; account_number: string; - status: - | "ONBOARDING" - | "SUBMISSION_FAILED" - | "SUBMITTED" - | "ACCOUNT_UPDATED" - | "APPROVAL_PENDING" - | "ACTIVE" - | "REJECTED"; + status: AccountStatus; currency: string; cash: string; portfolio_value: string; @@ -39,153 +46,16 @@ export type Account = { daytrading_buying_power: string; regt_buying_power: string; options_buying_power: string; - options_approved_level: 0 | 1 | 2; - options_trading_level: 0 | 1 | 2; -}; - -export type CorporateActionAnnouncement = { - id: string; - corporate_actions_id: string; - ca_type: string; - ca_sub_type: string; - initiating_symbol: string; - initiating_original_cusip: string; - target_symbol: string; - target_original_cusip: string; - declaration_date: string; - expiration_date: string; - record_date: string; - payable_date: string; - cash: string; - old_rate: string; - new_rate: string; -}; - -export type CorporateActionDateType = - | "declaration" - | "ex" - | "record" - | "payable"; - -export type CorporateActionsAnnouncementsOptions = { - get: { - ca_types: string; - since: string; - until: string; - symbol?: string; - cusip?: string; - date_type?: CorporateActionDateType; - id: string; - }; -}; - -export type CryptoFundingWallet = { - chain: string; - address: string; - created_at: string; -}; - -export type WalletsWhitelistsOptions = { - get: { - address: string; - asset: string; - }; - delete: { - whitelisted_address_id: string; - }; -}; -export type WhitelistedAddress = { - id: string; - chain: string; - asset: string; - address: string; - status: "ACTIVE" | "PENDING"; - created_at: string; + options_approved_level: OptionsApprovedLevel; + options_trading_level: OptionsTradingLevel; }; -export type CryptoFundingTransfer = { - id: string; - tx_hash: string; - direction: "INCOMING" | "OUTGOING"; - status: "PROCESSING" | "FAILED" | "COMPLETE"; - amount: string; - usd_value: string; - network_fee: string; - fees: string; - chain: string; - asset: string; - from_address: string; - to_address: string; - created_at: string; -}; - -export type CryptoFundingResponse = { - wallets?: CryptoFundingWallet | CryptoFundingWallet[]; - transfers?: CryptoFundingTransfer[]; -}; - -export type WalletsTransfersOptions = { - get: { - asset?: string; - transfer_id: string; - }; - post: { - amount: string; - address: string; - asset: string; - }; -}; - -export type WalletsFeesEstimateOptions = { - get: { - asset: string; - from_address: string; - to_address: string; - amount: string; - }; -}; - -export type Fee = { fee: string }; - -export type OptionsContractsOptions = { - get: { - underlying_symbols?: string; - status?: string; - active?: boolean; - expiration_date?: string; - expiration_date_gte?: string; - expiration_date_lte?: string; - root_symbol?: string; - type?: string; - style?: string; - strike_price_gte?: UnstableNumber; - strike_price_lte?: UnstableNumber; - page_token?: string; - limit?: UnstableNumber; - symbol_or_contract_id: string; - }; -}; - -export type OptionsContract = { - id: string; - symbol: string; - name: string; - status: string; - tradable: boolean; - expiration_date: string; - root_symbol?: string; - underlying_symbol: string; - underlying_asset_id: string; - type: string; - style: string; - strike_price: string; - size: string; - open_interest?: string; - open_interest_date?: string; - close_price?: string; - close_price_date?: string; - next_page_token: UnstableNumber; -}; +export const getAccount = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/account", + }); export type BaseOrder = { id: string; @@ -241,13 +111,225 @@ export type CryptoOrder = BaseOrder & { export type Order = EquityOrder | OptionsOrder | CryptoOrder; -export type MarketClock = { +export type TimeInForce = "day" | "gtc" | "opg" | "cls" | "ioc" | "fok"; + +export type PositionIntent = + | "buy_to_open" + | "buy_to_close" + | "sell_to_open" + | "sell_to_close"; + +export type Type = "market" | "limit" | "stop" | "stop_limit" | "trailing_stop"; + +export type Side = "buy" | "sell"; + +export type OrderClass = "simple" | "oco" | "oto" | "bracket" | ""; + +export type Direction = "long" | "short"; + +export type TakeProfit = { + limit_price?: string; +}; + +export type StopLoss = { + stop_price?: string; + limit_price?: string; +}; + +export type CreateOrderOptions = { + symbol: string; + qty?: UnstableNumber; + notional?: UnstableNumber; + side: Side; + type: Type; + time_in_force: TimeInForce; + limit_price?: UnstableNumber; + stop_price?: UnstableNumber; + trail_price?: UnstableNumber; + trail_percent?: UnstableNumber; + extended_hours?: boolean; + client_order_id?: string; + order_class?: OrderClass; + take_profit?: TakeProfit; + stop_loss?: StopLoss; + position_intent?: PositionIntent; +}; + +export const createOrder = + ({ request }: ClientContext) => + (data: CreateOrderOptions) => + request({ + path: "/v2/orders", + method: "POST", + data, + }); + +export type GetOrdersOptions = { + status?: string; + limit?: UnstableNumber; + after?: string; + until?: string; + direction?: Direction; + nested?: boolean; + symbols?: string; + side?: Side; + order_id: string; +}; + +export const getOrders = + ({ request }: ClientContext) => + (params: GetOrdersOptions) => + request({ + path: "/v2/orders", + method: "GET", + params, + }); + +export type GetOrderOptions = { + order_id: string; +}; + +export const getOrder = + ({ request }: ClientContext) => + ({ order_id }: GetOrderOptions) => + request({ + path: `/v2/orders/${order_id}`, + method: "GET", + }); + +export type ReplaceOrderOptions = { + qty?: UnstableNumber; + time_in_force?: string; + limit_price?: UnstableNumber; + stop_price?: UnstableNumber; + trail?: UnstableNumber; + client_order_id?: string; + order_id: string; +}; + +export const replaceOrder = + ({ request }: ClientContext) => + (data: ReplaceOrderOptions) => + request({ + path: `/v2/orders/${data.order_id}`, + method: "PATCH", + data, + }); + +export const cancelOrders = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/orders", + method: "DELETE", + }); + +export type CancelOrderOptions = { + order_id: string; +}; + +export const cancelOrder = + ({ request }: ClientContext) => + ({ order_id }: CancelOrderOptions) => + request({ + path: `/v2/orders/${order_id}`, + method: "DELETE", + }); + +export const getPositions = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/positions", + method: "GET", + }); + +export type GetPositionOptions = { + symbol_or_asset_id: string; +}; + +export const getPosition = + ({ request }: ClientContext) => + ({ symbol_or_asset_id }: GetPositionOptions) => + request({ + path: `/v2/positions/${symbol_or_asset_id}`, + method: "GET", + }); + +export const closePositions = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/positions", + method: "DELETE", + }); + +export type ClosePositionOptions = { + symbol_or_asset_id: string; +}; + +export const closePosition = + ({ request }: ClientContext) => + ({ symbol_or_asset_id }: ClosePositionOptions) => + request({ + path: `/v2/positions/${symbol_or_asset_id}`, + method: "DELETE", + }); + +export type GetAssetsOptions = { + status?: string; + asset_class?: string; + asset_status?: string; +}; + +export type ExerciseOption = { + symbol_or_contract_id: string; +}; + +export const exerciseOption = + ({ request }: ClientContext) => + ({ symbol_or_contract_id }: ExerciseOption) => + request({ + path: `/v2/positions/${symbol_or_contract_id}/exercise`, + method: "POST", + }); + +export type GetCalendarOptions = { + start?: string; + end?: string; + dateType?: "TRADING" | "SETTLEMENT"; +}; + +export type Calendar = { + date: string; + open: string; + close: string; + settlement_date: string; +}; + +export const getMarketCalendar = + ({ request }: ClientContext) => + (params: GetCalendarOptions = {}) => + request({ + path: "/v2/calendar", + method: "GET", + params, + }); + +export type Clock = { timestamp: string; is_open: boolean; next_open: string; next_close: string; }; +export const getMarketClock = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/clock", + }); + export type Asset = { id: string; class: string; @@ -261,80 +343,283 @@ export type Asset = { easy_to_borrow: boolean; fractionable: boolean; maintenance_margin_requirement: string; - attributes: string[]; + tradability: string; + symbol_with_class: string; + asset_id: string; }; -export type PortfolioHistoryOptions = { - get: { - period?: string; - timeframe?: string; - intraday_reporting?: string; - start?: string; - end?: string; - pnl_reset?: string; +export const getAssets = + ({ request }: ClientContext) => + (params: GetAssetsOptions = {}) => + request({ + path: "/v2/assets", + method: "GET", + params, + }); + +export type GetAssetOptions = { + symbol_or_asset_id: string; +}; + +export const getAsset = + ({ request }: ClientContext) => + ({ symbol_or_asset_id }: GetAssetOptions) => + request({ + path: `/v2/assets/${symbol_or_asset_id}`, + method: "GET", + }); + +export type OptionsContract = { + id: string; + symbol: string; + name: string; + status: string; + tradable: boolean; + tradability: string; + chain_id: string; + type: string; + option_type: string; + expiration_date: string; + strike_price: string; + min_ticks: { + above_tick: string; + below_tick: string; + cutoff_price: string; }; + option_style: string; + created_at: string; + updated_at: string; + last_trade_date: string; + underlying: string; + tradable_chain_id: string; + chain_symbol: string; + description: string; + asset_id: string; }; -export type PortfolioHistory = { - timestamp: number[]; - equity: number[]; - profit_loss: number[]; - profit_loss_pct: number[]; - base_value: number; - base_value_asof: string; - timeframe: string; +export type GetOptionsContractsOptions = { + underlying_symbols?: string; + status?: string; + active?: boolean; + expiration_date?: string; + expiration_date_gte?: string; + expiration_date_lte?: string; + root_symbol?: string; + type?: string; + style?: string; + strike_price_gte?: UnstableNumber; + strike_price_lte?: UnstableNumber; + page_token?: string; + limit?: UnstableNumber; + symbol_or_contract_id: string; +}; + +export const getOptionsContracts = + ({ request }: ClientContext) => + (params: GetOptionsContractsOptions) => + request({ + path: "/v2/options/contracts", + method: "GET", + params, + }); + +export type GetOptionsContractOptions = { + symbol_or_contract_id: string; +}; + +export const getOptionsContract = + ({ request }: ClientContext) => + ({ symbol_or_contract_id }: GetOptionsContractOptions) => + request({ + path: `/v2/options/contracts/${symbol_or_contract_id}`, + method: "GET", + }); + +export type CorporateActionAnnouncement = { + id: string; + corporate_actions_id: string; + ca_type: string; + ca_sub_type: string; + initiating_symbol: string; + initiating_original_cusip: string; + target_symbol: string; + target_original_cusip: string; + declaration_date: string; + expiration_date: string; + record_date: string; + payable_date: string; + cash: string; + old_rate: string; + new_rate: string; }; -export type DTBPCheck = "both" | "entry" | "exit"; +export type GetCorporateActionsAnnouncementsOptions = { + ca_types: string; + since: string; + until: string; + symbol?: string; + cusip?: string; + date_type?: string; + id: string; +}; -export type TradeConfirmEmail = "all" | "none"; +export const getCorporateActionsAnnouncements = + ({ request }: ClientContext) => + (params: GetCorporateActionsAnnouncementsOptions) => + request({ + path: "/v2/corporate_actions/announcements", + method: "GET", + params, + }); -export type MaxMarginMultiplier = "1" | "2"; +export type GetCorporateActionsAnnouncementOptions = { + id: string; +}; -export type PDTCheck = "both" | "entry" | "exit"; +export const getCorporateActionsAnnouncement = + ({ request }: ClientContext) => + ({ id }: GetCorporateActionsAnnouncementOptions) => + request({ + path: `/v2/corporate_actions/announcements/${id}`, + method: "GET", + }); + +export type Watchlist = { + id: string; + account_id: string; + created_at: string; + updated_at: string; + name: string; + assets: Asset[]; +}; -export type MaxOptionsTradingLevel = 0 | 1 | 2; +export const getWatchlists = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/watchlists", + }); -export type AccountConfigurations = { - dtbpCheck: DTBPCheck; - tradeConfirmEmail: TradeConfirmEmail; - suspendTrade: boolean; - noShorting: boolean; - fractionalTrading: boolean; - maxMarginMultiplier: MaxMarginMultiplier; - maxOptionsTradingLevel: MaxOptionsTradingLevel; - pdtCheck: PDTCheck; - ptpNoExceptionEntry: boolean; -}; - -export type AccountConfigurationsOptions = { - patch: { - dtbp_check?: string; - trade_confirm_email?: string; - suspend_trade?: boolean; - no_shorting?: boolean; - fractional_trading?: boolean; - max_margin_multiplier?: string; - max_options_trading_level?: number; - pdt_check?: string; - ptp_no_exception_entry?: boolean; - }; +export type GetWatchlistOptions = { + watchlist_id: string; }; -export type ActivitiesOptions = { - get: { - activity_type: string; - activity_types?: string; - date?: string; - until?: string; - after?: string; - direction?: string; - pageSize?: number; - pageToken?: string; - category?: string; - }; +export const getWatchlist = + ({ request }: ClientContext) => + ({ watchlist_id }: GetWatchlistOptions) => + request({ + path: `/v2/watchlists/${watchlist_id}`, + }); + +export type CreateWatchlistOptions = { + name: string; + symbols: string[] | null; +}; + +export const createWatchlist = + ({ request }: ClientContext) => + (data: CreateWatchlistOptions) => + request({ + path: "/v2/watchlists", + method: "POST", + data, + }); + +export type UpdateWatchlistOptions = { + name: string; + symbols: string[] | null; + watchlist_id: string; }; +export const updateWatchlist = + ({ request }: ClientContext) => + (data: UpdateWatchlistOptions) => + request({ + path: `/v2/watchlists/${data.watchlist_id}`, + method: "PATCH", + data, + }); + +export type DeleteWatchlistOptions = { + watchlist_id: string; +}; + +export const deleteWatchlist = + ({ request }: ClientContext) => + ({ watchlist_id }: DeleteWatchlistOptions) => + request({ + path: `/v2/watchlists/${watchlist_id}`, + method: "DELETE", + }); + +export type PortfolioHistory = { + timestamp: string[]; + equity: string[]; + profit_loss: string[]; + profit_loss_pct: string[]; + base_value: string; + base_value_asof: string; + timeframe: string; +}; + +export type GetPortfolioHistoryOptions = { + period?: string; + timeframe?: string; + intraday_reporting?: string; + start?: string; + end?: string; + pnl_reset?: string; +}; + +export const getPortfolioHistory = + ({ request }: ClientContext) => + (params: GetPortfolioHistoryOptions) => + request({ + path: "/v2/account/portfolio/history", + method: "GET", + params, + }); + +export type AccountConfigurations = { + dtbp_check: string; + trade_confirm_email: string; + suspend_trade: boolean; + no_shorting: boolean; + fractional_trading: boolean; + max_margin_multiplier: string; + max_options_trading_level: number; + pdt_check: string; + ptp_no_exception_entry: boolean; +}; + +export const getAccountConfigurations = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/account/configurations", + }); + +export type UpdateAccountConfigurationsOptions = { + dtbp_check?: string; + trade_confirm_email?: string; + suspend_trade?: boolean; + no_shorting?: boolean; + fractional_trading?: boolean; + max_margin_multiplier?: string; + max_options_trading_level?: number; + pdt_check?: string; + ptp_no_exception_entry?: boolean; +}; + +export const updateAccountConfigurations = + ({ request }: ClientContext) => + (data: UpdateAccountConfigurationsOptions) => + request({ + path: "/v2/account/configurations", + method: "PATCH", + data, + }); + export type AccountTradingActivity = { activity_type: string; id: string; @@ -362,499 +647,191 @@ export type AccountNonTradeActivity = { export type AccountActivity = AccountTradingActivity | AccountNonTradeActivity; -export type DeletedPositionStatus = { - symbol: string; - status: number; - body: Order; -}; +export const getAccountActivities = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/account/activities", + method: "GET", + }); -export type TakeProfit = { - limit_price?: string; +export type GetAccountActivityOptions = { + activity_type: string; + activity_types?: string; + date?: string; + until?: string; + after?: string; + direction?: string; + pageSize?: number; + pageToken?: string; + category?: string; +}; + +export const getAccountActivity = + ({ request }: ClientContext) => + ({ activity_type }: GetAccountActivityOptions) => + request({ + path: `/v2/account/activities/${activity_type}`, + method: "GET", + }); + +export type CryptoWallet = { + id: string; + currency: string; + balance: string; + available: string; + held: string; + profile_id: string; }; -export type StopLoss = { - stop_price?: string; - limit_price?: string; -}; +export const getWallets = + ({ request }: ClientContext) => + () => + request({ + path: "/v2/wallets", + method: "GET", + }); -export type UnstableNumber = string | number; +export type GetWalletOptions = { + asset: string; +}; -export type TimeInForce = "day" | "gtc" | "opg" | "cls" | "ioc" | "fok"; +export const getWallet = + ({ request }: ClientContext) => + ({ asset }: GetWalletOptions) => + request({ + path: `/v2/wallets/${asset}`, + method: "GET", + }); -export type PositionIntent = - | "buy_to_open" - | "buy_to_close" - | "sell_to_open" - | "sell_to_close"; +export type Fee = { + fee: string; + network_fee: string; + estimated_delivery: string; +}; -export type OrderType = - | "market" - | "limit" - | "stop" - | "stop_limit" - | "trailing_stop"; +export type GetFeeEstimateOptions = { + asset: string; + from_address: string; + to_address: string; + amount: string; +}; -export type OrderSide = "buy" | "sell"; +export const getFeeEstimate = + ({ request }: ClientContext) => + (params: GetFeeEstimateOptions) => + request({ + path: "/v2/wallets/fees/estimate", + method: "GET", + params, + }); -export type OrderClass = "simple" | "oco" | "oto" | "bracket" | ""; +export type CryptoTransfer = { + id: string; + tx_hash: string; + direction: "INCOMING" | "OUTGOING"; + status: "PROCESSING" | "FAILED" | "COMPLETE"; + amount: string; + usd_value: string; + network_fee: string; + fees: string; + chain: string; + asset: string; + from_address: string; + to_address: string; + created_at: string; +}; -export type OrderDirection = "long" | "short"; - -export type OrdersOptions = { - post: { - symbol: string; - qty?: UnstableNumber; - notional?: UnstableNumber; - side: OrderSide; - type: OrderType; - time_in_force: TimeInForce; - limit_price?: UnstableNumber; - stop_price?: UnstableNumber; - trail_price?: UnstableNumber; - trail_percent?: UnstableNumber; - extended_hours?: boolean; - client_order_id?: string; - order_class?: OrderClass; - take_profit?: TakeProfit; - stop_loss?: StopLoss; - position_intent?: PositionIntent; - }; - get: { - status?: string; - limit?: UnstableNumber; - after?: string; - until?: string; - direction?: OrderDirection; - nested?: boolean; - symbols?: string; - side?: OrderSide; - order_id: string; - }; - patch: { - qty?: UnstableNumber; - time_in_force?: string; - limit_price?: UnstableNumber; - stop_price?: UnstableNumber; - trail?: UnstableNumber; - client_order_id?: string; - order_id: string; - }; - delete: { - order_id: string; - }; +export type CryptoTransferResponse = { + wallets?: CryptoWallet | CryptoWallet[]; + transfers?: CryptoTransfer[]; }; -export type PositionsExerciseOptions = { - post: { - symbol_or_contract_id: string; - }; +export type GetTransfersOptions = { + asset?: string; }; -export type PositionsOptions = { - get: { - symbol_or_asset_id: string; - }; - delete: { - symbol_or_asset_id?: string; - cancel_orders?: boolean; - qty?: UnstableNumber; - percentage?: UnstableNumber; - }; +export const getTransfers = + ({ request }: ClientContext) => + (params?: GetTransfersOptions) => + request({ + path: "/v2/wallets/transfers", + method: "GET", + params, + }); + +export type GetTransferOptions = { + transfer_id: string; }; -export type Position = { - asset_id: string; - symbol: string; - exchange: string; - asset_class: string; - avg_entry_price: string; - qty: string | number; - qty_available: string; - side: string; - market_value: string; - cost_basis: string; - unrealized_pl: string; - unrealized_plpc: string; - unrealized_intraday_pl: string; - unrealized_intraday_plpc: string; - current_price: string; - lastday_price: string; - change_today: string; - asset_marginable: boolean; +export const getTransfer = + ({ request }: ClientContext) => + ({ transfer_id }: GetTransferOptions) => + request({ + path: `/v2/wallets/transfers/${transfer_id}`, + method: "GET", + }); + +export type CreateTransferOptions = { + amount: string; + address: string; + asset: string; }; -export type Watchlist = { +export const createTransfer = + ({ request }: ClientContext) => + (data: CreateTransferOptions) => + request({ + path: "/v2/wallets/transfers", + method: "POST", + data, + }); + +export type WhitelistedAddress = { id: string; - account_id: string; + chain: string; + asset: string; + address: string; + status: "ACTIVE" | "PENDING"; created_at: string; - updated_at: string; - name: string; - assets: Asset[]; -}; - -export type WatchlistOptions = { - get: { - watchlist_id?: string; - }; - post: { - name: string; - symbols: string[] | null; - }; - patch: { - name: string; - symbols: string[] | null; - watchlist_id: string; - }; - delete: { - watchlist_id: string; - }; }; -export type MarketCalendarOptions = { - start?: string; - end?: string; - dateType?: "TRADING" | "SETTLEMENT"; +export type GetWhitelistsOptions = { + address: string; + asset: string; }; -export type MarketCalendar = { - date: string; - open: string; - close: string; - settlement_date: string; -}; +export const getWhitelists = + ({ request }: ClientContext) => + (params: GetWhitelistsOptions) => + request({ + path: "/v2/wallets/whitelists", + method: "GET", + params, + }); -export type AssetsOptions = { - get: { - symbol_or_asset_id: string; - status?: string; - asset_class?: string; - exchange?: string; - attributes?: string[]; - }; +export type CreateWhitelistOptions = { + address: string; + asset: string; }; -export type WebSocketEvent = "trade_updates" | "listening" | "authorization"; +export const createWhitelist = + ({ request }: ClientContext) => + (data: CreateWhitelistOptions) => + request({ + path: "/v2/wallets/whitelists", + method: "POST", + data, + }); -export type WalletsOptions = { - get: { - asset: string; - }; +export type RemoveWhitelistOptions = { + whitelisted_address_id: string; }; -export default { - rest: ({ request }: ClientContext) => ({ - v2: { - account: { - get: () => - request({ - path: "/v2/account", - }), - portfolio: { - history: { - get: (params?: PortfolioHistoryOptions["get"]) => - request({ - path: "/v2/account/portfolio/history", - method: "GET", - params, - }), - }, - }, - configurations: { - get: () => - request({ - path: "/v2/account/configurations", - }), - patch: (data: AccountConfigurationsOptions["patch"]) => - request({ - path: "/v2/account/configurations", - method: "PATCH", - data, - }), - }, - activities: { - get: ( - params: Pick = {} - ) => - request({ - path: "/v2/account/activities", - method: "GET", - params, - }), - [":activity_type"]: { - get: (options: Omit) => - request({ - path: `/v2/account/activities/${options.activity_type}`, - }), - }, - }, - }, - orders: { - get: (params: Omit) => - request({ - path: "/v2/orders", - method: "GET", - params, - }), - [":order_id"]: { - get: (params: Pick) => - request({ - path: `/v2/orders/${params.order_id}`, - method: "GET", - params, - }), - delete: ({ order_id }: OrdersOptions["delete"]) => - request({ - path: `/v2/orders/${order_id}`, - method: "DELETE", - }), - }, - post: (data: OrdersOptions["post"]) => - request({ - path: "/v2/orders", - method: "POST", - data, - }), - patch: ({ order_id, ...data }: OrdersOptions["patch"]) => - request({ - path: `/v2/orders/${order_id}`, - method: "PATCH", - data, - }), - delete: () => - request({ - path: "/v2/orders", - method: "DELETE", - }), - }, - positions: { - get: () => - request({ - path: "/v2/positions", - }), - [":symbol_or_asset_id"]: { - get: ({ symbol_or_asset_id }: PositionsOptions["get"]) => - request({ - path: `/v2/positions/${symbol_or_asset_id}`, - }), - delete: ({ symbol_or_asset_id }: PositionsOptions["delete"]) => - request({ - path: `/v2/positions/${symbol_or_asset_id}`, - method: "DELETE", - }), - }, - delete: () => - request({ - path: "/v2/positions", - method: "DELETE", - }), - exercise: { - post: ({ symbol_or_contract_id }: PositionsExerciseOptions["post"]) => - request({ - path: `/v2/positions/${symbol_or_contract_id}/exercise`, - method: "POST", - }), - }, - }, - watchlists: { - get: () => - request({ - path: "/v2/watchlists", - }), - [":wachlist_id"]: { - get: ({ watchlist_id }: WatchlistOptions["get"]) => - request({ - path: `/v2/watchlists/${watchlist_id}`, - }), - }, - post: (data: WatchlistOptions["post"]) => - request({ - path: "/v2/watchlists", - method: "POST", - data, - }), - patch: ({ watchlist_id, ...data }: WatchlistOptions["patch"]) => - request({ - path: `/v2/watchlists/${watchlist_id}`, - method: "PATCH", - data, - }), - delete: ({ watchlist_id }: WatchlistOptions["delete"]) => - request({ - path: `/v2/watchlists/${watchlist_id}`, - method: "DELETE", - }), - }, - calendar: { - get: (params: MarketCalendarOptions = {}) => - request({ - path: "/v2/calendar", - method: "GET", - params, - }), - }, - clock: { - get: () => - request({ - path: "/v2/clock", - }), - }, - assets: { - get: (params: Omit = {}) => - request({ - path: "/v2/assets", - method: "GET", - params, - }), - [":symbol_or_asset_id"]: { - get: ({ symbol_or_asset_id, ...params }: AssetsOptions["get"]) => - request({ - path: `/v2/assets/${symbol_or_asset_id}`, - method: "GET", - params, - }), - }, - }, - options: { - contracts: { - get: ( - params: Omit< - OptionsContractsOptions["get"], - "symbol_or_contract_id" - > = {} - ) => - request({ - path: "/v2/options/contracts", - method: "GET", - params, - }), - [":symbol_or_contract_id"]: { - get: ({ - symbol_or_contract_id, - }: Pick) => - request({ - path: `/v2/options/contracts/${symbol_or_contract_id}`, - method: "GET", - }), - }, - }, - }, - corporate_actions: { - announcements: { - get: ( - params: Omit - ) => - request({ - path: "/v2/corporate_actions/announcements", - method: "GET", - params, - }), - [":id"]: { - get: ({ - id, - }: Pick) => - request({ - path: `/v2/corporate_actions/announcements/${id}`, - method: "GET", - }), - }, - }, - }, - wallets: { - get: (params?: WalletsOptions["get"]) => - request< - "asset" extends keyof typeof params - ? CryptoFundingWallet - : CryptoFundingWallet[] - >({ path: "/v2/wallets", method: "GET", params }), - whitelists: { - get: () => - request({ - path: "/v2/wallets/whitelists", - method: "GET", - }), - post: (data: WalletsWhitelistsOptions["get"]) => - request({ - path: "/v2/wallets/whitelists", - method: "POST", - data, - }), - delete: ({ - whitelisted_address_id, - }: WalletsWhitelistsOptions["delete"]) => - request({ - path: `/v2/wallets/whitelists/${whitelisted_address_id}`, - method: "DELETE", - }), - }, - fees: { - estimate: { - get: (params: WalletsFeesEstimateOptions) => - request({ - path: "/v2/wallets/fees/estimate", - method: "GET", - params, - }), - }, - }, - transfers: { - get: (params?: Omit) => - request({ - path: "/v2/wallets/transfers", - method: "GET", - params, - }), - [":transfer_id"]: { - get: ({ - transfer_id, - }: Pick) => - request({ - path: `/v2/wallets/transfers/${transfer_id}`, - method: "GET", - }), - }, - post: (data: WalletsTransfersOptions["post"]) => - request({ - path: "/v2/wallets/transfers", - method: "POST", - data, - }), - }, - }, - }, - }), - // -------------- OK ABOVE THIS LINE -------------- // - websocket: ({ websocket }: ClientContext) => { - return { - on: (event: WebSocketEvent, callback: (data: any) => void) => { - //@ts-ignore - websocket.addEventListener("customMessage", (message) => { - //@ts-ignore - if (message.detail.stream == event) { - // @ts-ignore - callback(message.detail.data); - } - }); - }, - subscribe: (streams: WebSocketEvent[]) => { - const subscribeMessage = { - action: "listen", - data: { - streams, - }, - }; - - websocket.send(JSON.stringify(subscribeMessage)); - }, - unsubscribe: (streams: WebSocketEvent[]) => { - const unsubscribeMessage = { - action: "listen", - data: { - streams, - }, - }; - - websocket.send(JSON.stringify(unsubscribeMessage)); - }, - }; - }, -}; +export const removeWhitelist = + ({ request }: ClientContext) => + ({ whitelisted_address_id }: RemoveWhitelistOptions) => + request({ + path: `/v2/wallets/whitelists/${whitelisted_address_id}`, + method: "DELETE", + });