AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(binance): add prices, 24h stats, order book, trades, candles and trading pairs (#16006)
Odai Ahmad3ef7f6fac0aa
diff --git a/bun.lock b/bun.lockindex 952ae027bb5..5a5007a86a5 100644--- a/bun.lock+++ b/bun.lock@@ -1211,7 +1211,7 @@},"packages/pieces/community/binance": {"name": "@activepieces/piece-binance",- "version": "0.4.7",+ "version": "0.5.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -1220,6 +1220,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/bitly": {diff --git a/packages/pieces/community/binance/package.json b/packages/pieces/community/binance/package.jsonindex 65c1cee20e8..1811b4643b0 100644--- a/packages/pieces/community/binance/package.json+++ b/packages/pieces/community/binance/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-binance",- "version": "0.4.7",+ "version": "0.5.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*",@@ -15,6 +16,7 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/binance/src/i18n/translation.json b/packages/pieces/community/binance/src/i18n/translation.jsonindex 5904a48bd92..f5e2082950b 100644--- a/packages/pieces/community/binance/src/i18n/translation.json+++ b/packages/pieces/community/binance/src/i18n/translation.json@@ -1,9 +1,75 @@{- "Fetch the price of a crypto pair from Binance": "Fetch the price of a crypto pair from Binance",+ "Get public Binance spot market data: prices, 24h statistics, order book, recent trades, candles and trading pairs. No API key needed.": "Get public Binance spot market data: prices, 24h statistics, order book, recent trades, candles and trading pairs. No API key needed.","Fetch Pair Price": "Fetch Pair Price",+ "Get Price": "Get Price",+ "Get Multiple Prices": "Get Multiple Prices",+ "Get 24h Ticker Stats": "Get 24h Ticker Stats",+ "Get Price Change (Rolling Window)": "Get Price Change (Rolling Window)",+ "Get Average Price": "Get Average Price",+ "Get Order Book": "Get Order Book",+ "Get Recent Trades": "Get Recent Trades",+ "Get Candles (Klines)": "Get Candles (Klines)",+ "List Trading Pairs": "List Trading Pairs",+ "Get Trading Pair Rules": "Get Trading Pair Rules","Fetch the current price of a pair (e.g. BTC/USDT)": "Fetch the current price of a pair (e.g. BTC/USDT)",+ "Get the latest trade price of one Binance spot trading pair.": "Get the latest trade price of one Binance spot trading pair.",+ "Get the latest trade prices of up to 100 Binance spot trading pairs in one call.": "Get the latest trade prices of up to 100 Binance spot trading pairs in one call.",+ "Get 24-hour price change, high, low, volume and best bid/ask for a Binance spot trading pair.": "Get 24-hour price change, high, low, volume and best bid/ask for a Binance spot trading pair.",+ "Get price change, high, low and volume for a Binance spot trading pair over the last 1 minute to 7 days.": "Get price change, high, low and volume for a Binance spot trading pair over the last 1 minute to 7 days.",+ "Get Binance's current average price of a spot trading pair over its short averaging window (5 minutes).": "Get Binance's current average price of a spot trading pair over its short averaging window (5 minutes).",+ "Get the current best bids and asks (order book depth) of a Binance spot trading pair.": "Get the current best bids and asks (order book depth) of a Binance spot trading pair.",+ "Get the most recent trades of a Binance spot trading pair.": "Get the most recent trades of a Binance spot trading pair.",+ "Get open, high, low, close and volume candles of a Binance spot trading pair at a chosen interval.": "Get open, high, low, close and volume candles of a Binance spot trading pair at a chosen interval.",+ "List the Binance pairs open for spot trading right now (status TRADING and spot trading allowed), optionally filtered by base or quote asset.": "List the Binance pairs open for spot trading right now (status TRADING and spot trading allowed), optionally filtered by base or quote asset.",+ "Get the trading rules of a Binance spot pair: status, tick size, quantity step, minimum and maximum order size and value.": "Get the trading rules of a Binance spot pair: status, tick size, quantity step, minimum and maximum order size and value.","First Coin Symbol": "First Coin Symbol","Second Coin Symbol": "Second Coin Symbol",+ "Symbol": "Symbol",+ "Symbols": "Symbols",+ "Detail Level": "Detail Level",+ "Window Size": "Window Size",+ "Depth": "Depth",+ "Number of Trades": "Number of Trades",+ "Interval": "Interval",+ "Start Time": "Start Time",+ "End Time": "End Time",+ "Time Zone Offset": "Time Zone Offset",+ "Number of Candles": "Number of Candles",+ "Quote Asset": "Quote Asset",+ "Base Asset": "Base Asset",+ "Maximum Pairs": "Maximum Pairs","The currency to fetch the price for (e.g. 'BTC' in 'BTC/USDT')": "The currency to fetch the price for (e.g. 'BTC' in 'BTC/USDT')",- "The currency to fetch the price in (e.g. 'USDT' in 'BTC/USDT')": "The currency to fetch the price in (e.g. 'USDT' in 'BTC/USDT')"+ "The currency to fetch the price in (e.g. 'USDT' in 'BTC/USDT')": "The currency to fetch the price in (e.g. 'USDT' in 'BTC/USDT')",+ "The trading pair: base asset followed by quote asset, for example BTCUSDT or ETHBTC. Spaces and '/' are removed and letters are upper-cased, so 'btc/usdt' also works. Use List Trading Pairs to find a symbol.": "The trading pair: base asset followed by quote asset, for example BTCUSDT or ETHBTC. Spaces and '/' are removed and letters are upper-cased, so 'btc/usdt' also works. Use List Trading Pairs to find a symbol.",+ "Trading pairs to price, for example BTCUSDT and ETHUSDT (base asset followed by quote asset). Up to 100. Spaces and '/' are removed, letters are upper-cased and duplicates are dropped. A comma-separated list in one item also works.": "Trading pairs to price, for example BTCUSDT and ETHUSDT (base asset followed by quote asset). Up to 100. Spaces and '/' are removed, letters are upper-cased and duplicates are dropped. A comma-separated list in one item also works.",+ "Full (default) adds price change and percent, weighted average price, previous close, last quantity and best bid/ask. Mini returns only open, high, low and last price, volumes and trade count.": "Full (default) adds price change and percent, weighted average price, previous close, last quantity and best bid/ask. Mini returns only open, high, low and last price, volumes and trade count.",+ "How far back the window reaches: a number and a unit, 1m to 59m (minutes), 1h to 23h (hours) or 1d to 7d (days), for example 15m, 4h or 7d. Units cannot be combined. Defaults to 1h.": "How far back the window reaches: a number and a unit, 1m to 59m (minutes), 1h to 23h (hours) or 1d to 7d (days), for example 15m, 4h or 7d. Units cannot be combined. Defaults to 1h.",+ "Price levels to return on each side, 1 to 5000. Defaults to 20. Binance rate-limit weight: 5 up to 100 levels, 25 up to 500, 50 up to 1000, 250 above that.": "Price levels to return on each side, 1 to 5000. Defaults to 20. Binance rate-limit weight: 5 up to 100 levels, 25 up to 500, 50 up to 1000, 250 above that.",+ "How many of the most recent trades to return, 1 to 1000. Defaults to 50.": "How many of the most recent trades to return, 1 to 1000. Defaults to 50.",+ "Length of each candle. 1m is one minute and 1M is one month.": "Length of each candle. 1m is one minute and 1M is one month.",+ "Optional. Return candles that open at or after this time (UTC), for example 2026-09-01T00:00:00Z. Leave empty to get the most recent candles.": "Optional. Return candles that open at or after this time (UTC), for example 2026-09-01T00:00:00Z. Leave empty to get the most recent candles.",+ "Optional. Return candles that open at or before this time (UTC). Must not be earlier than the start time.": "Optional. Return candles that open at or before this time (UTC). Must not be earlier than the start time.",+ "Optional. Offset from UTC used to align daily and longer candles, such as 8, -5 or 05:45 (from -12:00 to +14:00). Start and end times are always read as UTC. Defaults to UTC.": "Optional. Offset from UTC used to align daily and longer candles, such as 8, -5 or 05:45 (from -12:00 to +14:00). Start and end times are always read as UTC. Defaults to UTC.",+ "How many candles to return, 1 to 1000. Defaults to 100.": "How many candles to return, 1 to 1000. Defaults to 100.",+ "Optional. Only pairs priced in this asset, for example USDT, BTC or EUR. Not case-sensitive.": "Optional. Only pairs priced in this asset, for example USDT, BTC or EUR. Not case-sensitive.",+ "Optional. Only pairs that trade this asset, for example BTC or ETH. Not case-sensitive.": "Optional. Only pairs that trade this asset, for example BTC or ETH. Not case-sensitive.",+ "Most pairs to return, 1 to 1500. Defaults to 100. The output also says how many pairs matched in total.": "Most pairs to return, 1 to 1500. Defaults to 100. The output also says how many pairs matched in total.",+ "Full": "Full",+ "Mini": "Mini",+ "1 second": "1 second",+ "1 minute": "1 minute",+ "3 minutes": "3 minutes",+ "5 minutes": "5 minutes",+ "15 minutes": "15 minutes",+ "30 minutes": "30 minutes",+ "1 hour": "1 hour",+ "2 hours": "2 hours",+ "4 hours": "4 hours",+ "6 hours": "6 hours",+ "8 hours": "8 hours",+ "12 hours": "12 hours",+ "1 day": "1 day",+ "3 days": "3 days",+ "1 week": "1 week",+ "1 month": "1 month"}\ No newline at end of filediff --git a/packages/pieces/community/binance/src/index.ts b/packages/pieces/community/binance/src/index.tsindex 14b6ed7e001..622b32c7bda 100644--- a/packages/pieces/community/binance/src/index.ts+++ b/packages/pieces/community/binance/src/index.ts@@ -1,14 +1,37 @@import { PieceAuth, createPiece } from '@activepieces/pieces-framework';import { fetchCryptoPairPrice } from './lib/actions/fetch-pair-price';+import { binanceGetPrice } from './lib/actions/get-price';+import { getMultiplePrices } from './lib/actions/get-multiple-prices';+import { get24hTicker } from './lib/actions/get-24h-ticker';+import { getRollingWindowTicker } from './lib/actions/get-rolling-window-ticker';+import { getAveragePrice } from './lib/actions/get-average-price';+import { getOrderBook } from './lib/actions/get-order-book';+import { getRecentTrades } from './lib/actions/get-recent-trades';+import { getCandles } from './lib/actions/get-candles';+import { listTradingPairs } from './lib/actions/list-trading-pairs';+import { getTradingPairRules } from './lib/actions/get-trading-pair-rules';export const binance = createPiece({displayName: 'Binance',- description: 'Fetch the price of a crypto pair from Binance',- minimumSupportedRelease: '0.30.0',+ description:+ 'Get public Binance spot market data: prices, 24h statistics, order book, recent trades, candles and trading pairs. No API key needed.',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/binance.png',categories: [],auth: PieceAuth.None(),- actions: [fetchCryptoPairPrice],+ actions: [+ fetchCryptoPairPrice,+ binanceGetPrice,+ getMultiplePrices,+ get24hTicker,+ getRollingWindowTicker,+ getAveragePrice,+ getOrderBook,+ getRecentTrades,+ getCandles,+ listTradingPairs,+ getTradingPairRules,+ ],authors: ["kishanprmr","khaledmashaly","abuaboud"],triggers: [],});diff --git a/packages/pieces/community/binance/src/lib/actions/fetch-pair-price.ts b/packages/pieces/community/binance/src/lib/actions/fetch-pair-price.tsindex 2f94ef4b51b..9c5ddd4b406 100644--- a/packages/pieces/community/binance/src/lib/actions/fetch-pair-price.ts+++ b/packages/pieces/community/binance/src/lib/actions/fetch-pair-price.ts@@ -1,12 +1,13 @@-import { httpClient, HttpMethod } from '@activepieces/pieces-common';import { createAction, Property } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';export const fetchCryptoPairPrice = createAction({name: 'fetch_crypto_pair_price',classification: 'READ',displayName: 'Fetch Pair Price',description: 'Fetch the current price of a pair (e.g. BTC/USDT)',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Fetches the current spot price of a trading pair from the public Binance market data API by combining two coin symbols (e.g. first coin BTC + second coin USDT). Use to look up the live exchange rate of one crypto asset against another. No authentication required; the symbol must be a pair that exists on Binance or the request fails. Read-only lookup, idempotent.', idempotent: true },props: {first_coin: Property.ShortText({@@ -24,29 +25,22 @@ export const fetchCryptoPairPrice = createAction({},async run(context) {const { first_coin, second_coin } = context.propsValue;- if (first_coin && second_coin)- return await fetchCryptoPairPriceImpl(`${first_coin}${second_coin}`);- throw Error('Missing parameter(s)');+ const first = binanceInput.symbol({ value: first_coin, fieldName: 'First Coin Symbol' });+ const second = binanceInput.symbol({ value: second_coin, fieldName: 'Second Coin Symbol' });+ return await fetchCryptoPairPriceImpl({ symbol: `${first}${second}` });},});-async function fetchCryptoPairPriceImpl(symbol: string): Promise<number> {- const formattedSymbol = symbol- .replace('/', '')- .replace(' ', '')- .toUpperCase();-- const url = `https://api.binance.com/api/v3/ticker/price?symbol=${formattedSymbol}`;-- try {- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url,- });- const data = await response.body;- return Number(data['price']);- } catch (error) {- console.error(`Error fetching price for symbol ${symbol}:`, error);- throw error;+async function fetchCryptoPairPriceImpl({ symbol }: { symbol: string }): Promise<number> {+ const data = await binanceClient.get<{ price?: string }>({+ path: '/ticker/price',+ queryParams: { symbol },+ subject: `the trading pair "${symbol}"`,+ });+ const raw = data?.price;+ const price = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : NaN;+ if (!Number.isFinite(price)) {+ throw new Error(`Binance returned no price for ${symbol}.`);}+ return price;}diff --git a/packages/pieces/community/binance/src/lib/actions/get-24h-ticker.ts b/packages/pieces/community/binance/src/lib/actions/get-24h-ticker.tsnew file mode 100644index 00000000000..93f1c6854d2--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-24h-ticker.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';+import { symbolProp } from '../common/props';+import { get24hTickerOutputSchema } from '../output-schemas';++export const get24hTicker = createAction({+ name: 'get_24h_ticker',+ classification: 'READ',+ displayName: 'Get 24h Ticker Stats',+ description: 'Get 24-hour price change, high, low, volume and best bid/ask for a Binance spot trading pair.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Gets rolling 24-hour statistics for one Binance spot pair such as BTCUSDT. The Full detail level (default) returns price change and percent, weighted average, previous close, best bid/ask, open/high/low/last price, volumes and trade count; Mini returns only open/high/low/last price, volumes and trade count. Use for a daily market summary; use Get Price Change (Rolling Window) for any other window from 1 minute to 7 days. Prices and volumes are exact decimal strings. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ symbol: symbolProp,+ type: Property.StaticDropdown({+ displayName: 'Detail Level',+ description: 'Full (default) adds price change and percent, weighted average price, previous close, last quantity and best bid/ask. Mini returns only open, high, low and last price, volumes and trade count.',+ required: false,+ defaultValue: 'FULL',+ options: {+ disabled: false,+ options: [+ { label: 'Full', value: 'FULL' },+ { label: 'Mini', value: 'MINI' },+ ],+ },+ }),+ },+ outputSchema: get24hTickerOutputSchema,+ async run(context) {+ const symbol = binanceInput.symbol({ value: context.propsValue.symbol });+ const type = context.propsValue.type ?? 'FULL';+ if (type !== 'FULL' && type !== 'MINI') {+ throw new Error('Detail Level must be FULL or MINI.');+ }+ return await binanceClient.get<Record<string, unknown>>({+ path: '/ticker/24hr',+ queryParams: { symbol, type },+ subject: `the trading pair "${symbol}"`,+ });+ },+});diff --git a/packages/pieces/community/binance/src/lib/actions/get-average-price.ts b/packages/pieces/community/binance/src/lib/actions/get-average-price.tsnew file mode 100644index 00000000000..0f8f8f959f9--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-average-price.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';+import { symbolProp } from '../common/props';+import { getAveragePriceOutputSchema } from '../output-schemas';++export const getAveragePrice = createAction({+ name: 'get_average_price',+ classification: 'READ',+ displayName: 'Get Average Price',+ description: "Get Binance's current average price of a spot trading pair over its short averaging window (5 minutes).",+ audience: 'both',+ aiMetadata: {+ description:+ "Gets Binance's current average price for one spot pair such as BTCUSDT, computed over a short window (mins, usually 5 minutes). Use when a smoothed price is better than the last trade, for example for price-based order limits; use Get Price for the latest trade. The price is an exact decimal string. Read-only and idempotent.",+ idempotent: true,+ },+ props: {+ symbol: symbolProp,+ },+ outputSchema: getAveragePriceOutputSchema,+ async run(context) {+ const symbol = binanceInput.symbol({ value: context.propsValue.symbol });+ const data = await binanceClient.get<{ mins: number; price: string; closeTime: number }>({+ path: '/avgPrice',+ queryParams: { symbol },+ subject: `the trading pair "${symbol}"`,+ });+ return { symbol, mins: data.mins, price: data.price, closeTime: data.closeTime };+ },+});diff --git a/packages/pieces/community/binance/src/lib/actions/get-candles.ts b/packages/pieces/community/binance/src/lib/actions/get-candles.tsnew file mode 100644index 00000000000..efc916cc071--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-candles.ts@@ -0,0 +1,120 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';+import { symbolProp } from '../common/props';+import { getCandlesOutputSchema } from '../output-schemas';++const DEFAULT_LIMIT = 100;++const INTERVAL_OPTIONS = [+ { label: '1 second', value: '1s' },+ { label: '1 minute', value: '1m' },+ { label: '3 minutes', value: '3m' },+ { label: '5 minutes', value: '5m' },+ { label: '15 minutes', value: '15m' },+ { label: '30 minutes', value: '30m' },+ { label: '1 hour', value: '1h' },+ { label: '2 hours', value: '2h' },+ { label: '4 hours', value: '4h' },+ { label: '6 hours', value: '6h' },+ { label: '8 hours', value: '8h' },+ { label: '12 hours', value: '12h' },+ { label: '1 day', value: '1d' },+ { label: '3 days', value: '3d' },+ { label: '1 week', value: '1w' },+ { label: '1 month', value: '1M' },+];++export const getCandles = createAction({+ name: 'get_candles',+ classification: 'READ',+ displayName: 'Get Candles (Klines)',+ description: 'Get open, high, low, close and volume candles of a Binance spot trading pair at a chosen interval.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Gets OHLCV candlesticks (klines) for one Binance spot pair at an interval from 1s to 1M, either the most recent ones (optionally ending at an end time) or those from a start time onwards (optionally up to an end time). Use for price history, charts or indicators; use Get Price Change (Rolling Window) when only the change over one period is needed. At most 1000 candles per call; when a start time is given and more candles follow, hasMore is true and nextStartTime is where to continue. Prices and volumes are exact decimal strings. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ symbol: symbolProp,+ interval: Property.StaticDropdown({+ displayName: 'Interval',+ description: 'Length of each candle. 1m is one minute and 1M is one month.',+ required: true,+ defaultValue: '1h',+ options: {+ disabled: false,+ options: INTERVAL_OPTIONS,+ },+ }),+ start_time: Property.DateTime({+ displayName: 'Start Time',+ description:+ 'Optional. Return candles that open at or after this time (UTC), for example 2026-09-01T00:00:00Z. Leave empty to get the most recent candles.',+ required: false,+ }),+ end_time: Property.DateTime({+ displayName: 'End Time',+ description: 'Optional. Return candles that open at or before this time (UTC). Must not be earlier than the start time.',+ required: false,+ }),+ time_zone: Property.ShortText({+ displayName: 'Time Zone Offset',+ description:+ 'Optional. Offset from UTC used to align daily and longer candles, such as 8, -5 or 05:45 (from -12:00 to +14:00). Start and end times are always read as UTC. Defaults to UTC.',+ required: false,+ }),+ limit: Property.Number({+ displayName: 'Number of Candles',+ description: 'How many candles to return, 1 to 1000. Defaults to 100.',+ required: false,+ defaultValue: DEFAULT_LIMIT,+ }),+ },+ outputSchema: getCandlesOutputSchema,+ async run(context) {+ const { propsValue } = context;+ const symbol = binanceInput.symbol({ value: propsValue.symbol });+ const interval = binanceInput.klineInterval({ value: propsValue.interval });+ const startTime = binanceInput.epochMs({ value: propsValue.start_time, fieldName: 'Start Time' });+ const endTime = binanceInput.epochMs({ value: propsValue.end_time, fieldName: 'End Time' });+ const timeZone = binanceInput.timeZone({ value: propsValue.time_zone });+ const limit = binanceInput.limit({ value: propsValue.limit, min: 1, max: 1000, defaultValue: DEFAULT_LIMIT, fieldName: 'Number of Candles' });+ if (startTime !== undefined && endTime !== undefined && startTime > endTime) {+ throw new Error('Start Time must be earlier than End Time.');+ }+ const rows = await binanceClient.get<KlineRow[]>({+ path: '/klines',+ queryParams: {+ symbol,+ interval,+ limit: String(limit),+ ...(startTime === undefined ? {} : { startTime: String(startTime) }),+ ...(endTime === undefined ? {} : { endTime: String(endTime) }),+ ...(timeZone === undefined ? {} : { timeZone }),+ },+ subject: `the trading pair "${symbol}"`,+ timeoutMs: binanceClient.SLOW_TIMEOUT_MS,+ });+ const candles = rows.map((row) => toCandle({ row }));+ const last = candles.at(-1);+ const rangeEnd = endTime ?? Date.now();+ const hasMore = startTime !== undefined && last !== undefined && candles.length === limit && last.closeTime < rangeEnd;+ return {+ symbol,+ interval,+ candles,+ count: candles.length,+ hasMore,+ nextStartTime: hasMore && last !== undefined ? last.closeTime + 1 : null,+ };+ },+});++function toCandle({ row }: { row: KlineRow }) {+ const [openTime, open, high, low, close, volume, closeTime, quoteVolume, tradeCount, takerBuyBaseVolume, takerBuyQuoteVolume] = row;+ return { openTime, open, high, low, close, volume, closeTime, quoteVolume, tradeCount, takerBuyBaseVolume, takerBuyQuoteVolume };+}++type KlineRow = [number, string, string, string, string, string, number, string, number, string, string, string];diff --git a/packages/pieces/community/binance/src/lib/actions/get-multiple-prices.ts b/packages/pieces/community/binance/src/lib/actions/get-multiple-prices.tsnew file mode 100644index 00000000000..9c0507731ef--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-multiple-prices.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';+import { getMultiplePricesOutputSchema } from '../output-schemas';++export const getMultiplePrices = createAction({+ name: 'get_multiple_prices',+ classification: 'READ',+ displayName: 'Get Multiple Prices',+ description: 'Get the latest trade prices of up to 100 Binance spot trading pairs in one call.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Gets the latest Binance spot trade prices for up to 100 trading pair symbols (such as BTCUSDT, ETHUSDT) in one request. Use instead of calling Get Price repeatedly; use Get 24h Ticker Stats for change and volume. Every symbol must be listed on Binance or the whole call fails; listed pairs that are not trading right now are returned in notTrading instead of with a price. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ symbols: Property.Array({+ displayName: 'Symbols',+ description: `Trading pairs to price, for example BTCUSDT and ETHUSDT (base asset followed by quote asset). Up to ${binanceInput.MAX_SYMBOLS_PER_CALL}. Spaces and '/' are removed, letters are upper-cased and duplicates are dropped. A comma-separated list in one item also works.`,+ required: true,+ }),+ },+ outputSchema: getMultiplePricesOutputSchema,+ async run(context) {+ const symbols = binanceInput.symbols({ value: context.propsValue.symbols });+ const rows = await binanceClient.get<{ symbol: string; price: string }[]>({+ path: '/ticker/price',+ queryParams: { symbols: JSON.stringify(symbols), symbolStatus: 'TRADING' },+ subject: `one or more of these symbols (${symbols.join(', ')})`,+ });+ const priceBySymbol = new Map(rows.map((row) => [row.symbol, row.price]));+ const prices: { symbol: string; price: string }[] = [];+ const notTrading: string[] = [];+ for (const symbol of symbols) {+ const price = priceBySymbol.get(symbol);+ if (price === undefined) {+ notTrading.push(symbol);+ } else {+ prices.push({ symbol, price });+ }+ }+ return { prices, count: prices.length, notTrading };+ },+});diff --git a/packages/pieces/community/binance/src/lib/actions/get-order-book.ts b/packages/pieces/community/binance/src/lib/actions/get-order-book.tsnew file mode 100644index 00000000000..763c293577f--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-order-book.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';+import { symbolProp } from '../common/props';+import { getOrderBookOutputSchema } from '../output-schemas';++const DEFAULT_DEPTH = 20;++export const getOrderBook = createAction({+ name: 'get_order_book',+ classification: 'READ',+ displayName: 'Get Order Book',+ description: 'Get the current best bids and asks (order book depth) of a Binance spot trading pair.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Gets the current order book for one Binance spot pair such as BTCUSDT: the best bid and ask price levels with their quantities, best first, up to the requested depth per side (1-5000, default 20). Use to judge liquidity, spread or the price a large order would fill at; use Get Price when only the last trade price is needed. Depths above 100 cost far more rate-limit weight, so keep it small. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ symbol: symbolProp,+ limit: Property.Number({+ displayName: 'Depth',+ description:+ 'Price levels to return on each side, 1 to 5000. Defaults to 20. Binance rate-limit weight: 5 up to 100 levels, 25 up to 500, 50 up to 1000, 250 above that.',+ required: false,+ defaultValue: DEFAULT_DEPTH,+ }),+ },+ outputSchema: getOrderBookOutputSchema,+ async run(context) {+ const symbol = binanceInput.symbol({ value: context.propsValue.symbol });+ const limit = binanceInput.limit({ value: context.propsValue.limit, min: 1, max: 5000, defaultValue: DEFAULT_DEPTH, fieldName: 'Depth' });+ const book = await binanceClient.get<{ lastUpdateId: number; bids: [string, string][]; asks: [string, string][] }>({+ path: '/depth',+ queryParams: { symbol, limit: String(limit) },+ subject: `the trading pair "${symbol}"`,+ });+ return {+ symbol,+ lastUpdateId: book.lastUpdateId,+ bids: book.bids.map(([price, quantity]) => ({ price, quantity })),+ asks: book.asks.map(([price, quantity]) => ({ price, quantity })),+ };+ },+});diff --git a/packages/pieces/community/binance/src/lib/actions/get-price.ts b/packages/pieces/community/binance/src/lib/actions/get-price.tsnew file mode 100644index 00000000000..203e890c014--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-price.ts@@ -0,0 +1,31 @@+import { createAction } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';+import { symbolProp } from '../common/props';+import { getPriceOutputSchema } from '../output-schemas';++export const binanceGetPrice = createAction({+ name: 'binance_get_price',+ classification: 'READ',+ displayName: 'Get Price',+ description: 'Get the latest trade price of one Binance spot trading pair.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Gets the latest Binance spot trade price for one trading pair symbol such as BTCUSDT (base asset followed by quote asset). Use for a single live price; use Get Multiple Prices for up to 100 pairs in one call, or Get 24h Ticker Stats when you also need change and volume. The pair must be listed and currently trading on Binance (find symbols with List Trading Pairs); the price is an exact decimal string. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ symbol: symbolProp,+ },+ outputSchema: getPriceOutputSchema,+ async run(context) {+ const symbol = binanceInput.symbol({ value: context.propsValue.symbol });+ const data = await binanceClient.get<{ symbol: string; price: string }>({+ path: '/ticker/price',+ queryParams: { symbol, symbolStatus: 'TRADING' },+ subject: `the trading pair "${symbol}"`,+ });+ return { symbol: data.symbol, price: data.price };+ },+});diff --git a/packages/pieces/community/binance/src/lib/actions/get-recent-trades.ts b/packages/pieces/community/binance/src/lib/actions/get-recent-trades.tsnew file mode 100644index 00000000000..6e2acff3c8d--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-recent-trades.ts@@ -0,0 +1,50 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';+import { symbolProp } from '../common/props';+import { getRecentTradesOutputSchema } from '../output-schemas';++const DEFAULT_LIMIT = 50;++export const getRecentTrades = createAction({+ name: 'get_recent_trades',+ classification: 'READ',+ displayName: 'Get Recent Trades',+ description: 'Get the most recent trades of a Binance spot trading pair.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Gets the most recent public trades for one Binance spot pair such as BTCUSDT (price, quantity, quote quantity, time, and whether the buyer was the maker), oldest first, up to the requested count (1-1000, default 50). Use to see live trading activity; use Get Candles for aggregated price history over time. Only the latest trades are available, not a time range. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ symbol: symbolProp,+ limit: Property.Number({+ displayName: 'Number of Trades',+ description: 'How many of the most recent trades to return, 1 to 1000. Defaults to 50.',+ required: false,+ defaultValue: DEFAULT_LIMIT,+ }),+ },+ outputSchema: getRecentTradesOutputSchema,+ async run(context) {+ const symbol = binanceInput.symbol({ value: context.propsValue.symbol });+ const limit = binanceInput.limit({ value: context.propsValue.limit, min: 1, max: 1000, defaultValue: DEFAULT_LIMIT, fieldName: 'Number of Trades' });+ const trades = await binanceClient.get<BinanceTrade[]>({+ path: '/trades',+ queryParams: { symbol, limit: String(limit) },+ subject: `the trading pair "${symbol}"`,+ });+ return { symbol, trades, count: trades.length };+ },+});++type BinanceTrade = {+ id: number;+ price: string;+ qty: string;+ quoteQty: string;+ time: number;+ isBuyerMaker: boolean;+ isBestMatch: boolean;+};diff --git a/packages/pieces/community/binance/src/lib/actions/get-rolling-window-ticker.ts b/packages/pieces/community/binance/src/lib/actions/get-rolling-window-ticker.tsnew file mode 100644index 00000000000..865fb46d663--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-rolling-window-ticker.ts@@ -0,0 +1,40 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { binanceInput } from '../common/input';+import { symbolProp } from '../common/props';+import { getRollingWindowTickerOutputSchema } from '../output-schemas';++const DEFAULT_WINDOW = '1h';++export const getRollingWindowTicker = createAction({+ name: 'get_rolling_window_ticker',+ classification: 'READ',+ displayName: 'Get Price Change (Rolling Window)',+ description: 'Get price change, high, low and volume for a Binance spot trading pair over the last 1 minute to 7 days.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Gets price change and percent, open/high/low/last price, volume and trade count for one Binance spot pair over a rolling window ending now, from 1m to 59m, 1h to 23h, or 1d to 7d (default 1h). Use to answer "how much did X move in the last N minutes/hours/days"; use Get 24h Ticker Stats for the 24-hour view with bid/ask, or Get Candles for a time series. Prices and volumes are exact decimal strings. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ symbol: symbolProp,+ window_size: Property.ShortText({+ displayName: 'Window Size',+ description: 'How far back the window reaches: a number and a unit, 1m to 59m (minutes), 1h to 23h (hours) or 1d to 7d (days), for example 15m, 4h or 7d. Units cannot be combined. Defaults to 1h.',+ required: false,+ defaultValue: DEFAULT_WINDOW,+ }),+ },+ outputSchema: getRollingWindowTickerOutputSchema,+ async run(context) {+ const symbol = binanceInput.symbol({ value: context.propsValue.symbol });+ const windowSize = binanceInput.windowSize({ value: context.propsValue.window_size, defaultValue: DEFAULT_WINDOW });+ const stats = await binanceClient.get<Record<string, unknown>>({+ path: '/ticker',+ queryParams: { symbol, windowSize },+ subject: `the trading pair "${symbol}"`,+ });+ return { ...stats, windowSize };+ },+});diff --git a/packages/pieces/community/binance/src/lib/actions/get-trading-pair-rules.ts b/packages/pieces/community/binance/src/lib/actions/get-trading-pair-rules.tsnew file mode 100644index 00000000000..1c5990e8618--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/get-trading-pair-rules.ts@@ -0,0 +1,47 @@+import { createAction } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { exchangeInfo, ExchangeInfoResponse } from '../common/exchange-info';+import { binanceInput } from '../common/input';+import { symbolProp } from '../common/props';+import { getTradingPairRulesOutputSchema } from '../output-schemas';++export const getTradingPairRules = createAction({+ name: 'get_trading_pair_rules',+ classification: 'READ',+ displayName: 'Get Trading Pair Rules',+ description: 'Get the trading rules of a Binance spot pair: status, tick size, quantity step, minimum and maximum order size and value.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Gets the trading rules for one Binance spot pair such as BTCUSDT: status, base and quote asset, precisions, allowed order types, and the price filter (tick size, min/max price), lot size (step size, min/max quantity) and notional limits (min/max order value), plus the raw filter list. Use before computing an order price or quantity; use List Trading Pairs to find pairs. A rule the pair does not define is null. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ symbol: symbolProp,+ },+ outputSchema: getTradingPairRulesOutputSchema,+ async run(context) {+ const symbol = binanceInput.symbol({ value: context.propsValue.symbol });+ const info = await binanceClient.get<ExchangeInfoResponse>({+ path: '/exchangeInfo',+ queryParams: { symbol, showPermissionSets: 'false' },+ subject: `the trading pair "${symbol}"`,+ });+ const pair = info.symbols.find((item) => item.symbol === symbol);+ if (pair === undefined) {+ throw new Error(`Binance returned no trading rules for ${symbol}.`);+ }+ return {+ ...exchangeInfo.toPairSummary({ pair }),+ tickSize: exchangeInfo.filterValue({ pair, filterTypes: ['PRICE_FILTER'], field: 'tickSize' }),+ minPrice: exchangeInfo.filterValue({ pair, filterTypes: ['PRICE_FILTER'], field: 'minPrice' }),+ maxPrice: exchangeInfo.filterValue({ pair, filterTypes: ['PRICE_FILTER'], field: 'maxPrice' }),+ stepSize: exchangeInfo.filterValue({ pair, filterTypes: ['LOT_SIZE'], field: 'stepSize' }),+ minQty: exchangeInfo.filterValue({ pair, filterTypes: ['LOT_SIZE'], field: 'minQty' }),+ maxQty: exchangeInfo.filterValue({ pair, filterTypes: ['LOT_SIZE'], field: 'maxQty' }),+ minNotional: exchangeInfo.filterValue({ pair, filterTypes: ['NOTIONAL', 'MIN_NOTIONAL'], field: 'minNotional' }),+ maxNotional: exchangeInfo.filterValue({ pair, filterTypes: ['NOTIONAL'], field: 'maxNotional' }),+ filters: pair.filters ?? [],+ };+ },+});diff --git a/packages/pieces/community/binance/src/lib/actions/list-trading-pairs.ts b/packages/pieces/community/binance/src/lib/actions/list-trading-pairs.tsnew file mode 100644index 00000000000..a92d39df58a--- /dev/null+++ b/packages/pieces/community/binance/src/lib/actions/list-trading-pairs.ts@@ -0,0 +1,71 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { binanceClient } from '../common/client';+import { exchangeInfo, ExchangeInfoResponse } from '../common/exchange-info';+import { binanceInput } from '../common/input';+import { listTradingPairsOutputSchema } from '../output-schemas';++const DEFAULT_LIMIT = 100;+const MAX_LIMIT = 1500;++export const listTradingPairs = createAction({+ name: 'list_trading_pairs',+ classification: 'SEARCH',+ displayName: 'List Trading Pairs',+ description: 'List the Binance pairs open for spot trading right now (status TRADING and spot trading allowed), optionally filtered by base or quote asset.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Binance pairs that are open for spot trading right now (status TRADING and spot trading allowed; pairs only open for margin are left out), optionally only those with a given quote asset (such as USDT) and/or base asset (such as BTC). Use to find the exact symbol to pass to the price, ticker, order book, trade or candle actions; use Get Trading Pair Rules for one pair\'s tick size and minimum order. Returns at most the requested number of pairs (default 100, max 1500) plus the total match count and a truncated flag; narrow with the asset filters when truncated. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ quote_asset: Property.ShortText({+ displayName: 'Quote Asset',+ description: 'Optional. Only pairs priced in this asset, for example USDT, BTC or EUR. Not case-sensitive.',+ required: false,+ }),+ base_asset: Property.ShortText({+ displayName: 'Base Asset',+ description: 'Optional. Only pairs that trade this asset, for example BTC or ETH. Not case-sensitive.',+ required: false,+ }),+ limit: Property.Number({+ displayName: 'Maximum Pairs',+ description: `Most pairs to return, 1 to ${MAX_LIMIT}. Defaults to ${DEFAULT_LIMIT}. The output also says how many pairs matched in total.`,+ required: false,+ defaultValue: DEFAULT_LIMIT,+ }),+ },+ outputSchema: listTradingPairsOutputSchema,+ async run(context) {+ const { propsValue } = context;+ const quoteAsset = optionalAsset({ value: propsValue.quote_asset, fieldName: 'Quote Asset' });+ const baseAsset = optionalAsset({ value: propsValue.base_asset, fieldName: 'Base Asset' });+ const limit = binanceInput.limit({ value: propsValue.limit, min: 1, max: MAX_LIMIT, defaultValue: DEFAULT_LIMIT, fieldName: 'Maximum Pairs' });+ const info = await binanceClient.get<ExchangeInfoResponse>({+ path: '/exchangeInfo',+ queryParams: { symbolStatus: 'TRADING', showPermissionSets: 'false' },+ timeoutMs: binanceClient.SLOW_TIMEOUT_MS,+ });+ const matches = info.symbols.filter(+ (pair) =>+ exchangeInfo.isOpenForSpotTrading({ pair }) &&+ (quoteAsset === undefined || pair.quoteAsset.toUpperCase() === quoteAsset) &&+ (baseAsset === undefined || pair.baseAsset.toUpperCase() === baseAsset)+ );+ const pairs = matches.slice(0, limit).map((pair) => exchangeInfo.toPairSummary({ pair }));+ return {+ pairs,+ count: pairs.length,+ total: matches.length,+ truncated: matches.length > pairs.length,+ };+ },+});++function optionalAsset({ value, fieldName }: { value: unknown; fieldName: string }): string | undefined {+ if (value === undefined || value === null || (typeof value === 'string' && value.trim() === '')) {+ return undefined;+ }+ return binanceInput.symbol({ value, fieldName });+}diff --git a/packages/pieces/community/binance/src/lib/common/client.ts b/packages/pieces/community/binance/src/lib/common/client.tsnew file mode 100644index 00000000000..ca20873a21e--- /dev/null+++ b/packages/pieces/community/binance/src/lib/common/client.ts@@ -0,0 +1,140 @@+import { httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';++class BinanceApiError extends Error {+ readonly status: number | undefined;+ readonly code: number | undefined;+ readonly responseBody: unknown;++ constructor({ message, status, code, responseBody }: BinanceApiErrorParams) {+ super(message);+ this.name = 'BinanceApiError';+ this.status = status;+ this.code = code;+ this.responseBody = responseBody;+ }+}++async function get<T>({ path, queryParams, subject, timeoutMs = DEFAULT_TIMEOUT_MS }: GetParams): Promise<T> {+ try {+ const response = await httpClient.sendRequest<T>({+ method: HttpMethod.GET,+ url: `${MARKET_DATA_URL}${path}`,+ queryParams,+ timeout: timeoutMs,+ });+ return response.body;+ } catch (error) {+ throw toError({ error, subject, timeoutMs });+ }+}++function toError({ error, subject, timeoutMs }: { error: unknown; subject?: string; timeoutMs: number }): unknown {+ if (error instanceof HttpError) {+ const { status, body } = error.response;+ const { code, msg } = parseBinanceBody(body);+ return new BinanceApiError({+ message: describeFailure({ status, code, msg, subject }),+ status,+ code,+ responseBody: body,+ });+ }+ if (error instanceof Error && error.name === 'AbortError') {+ return new BinanceApiError({+ message: `Binance did not answer within ${timeoutMs / 1000} seconds. This is a read-only request, so it is safe to retry.`,+ });+ }+ return error;+}++function describeFailure({+ status,+ code,+ msg,+ subject,+}: {+ status: number;+ code: number | undefined;+ msg: string | undefined;+ subject: string | undefined;+}): string {+ const target = subject ?? 'the symbol';+ if (status === 451) {+ return 'Binance blocks requests from the region this server runs in (HTTP 451). Binance does not serve this region.';+ }+ if (status === 418) {+ return "Binance has temporarily banned this server's IP address (HTTP 418) after repeated rate-limit errors. Bans last from 2 minutes up to 3 days; wait before running this step again.";+ }+ if (status === 429) {+ return "Binance rate limit reached (HTTP 429): this server's IP address used too much request weight in the last minute. Wait about a minute before retrying; retrying straight away can get the IP banned.";+ }+ if (status === 403) {+ return "Binance's firewall rejected the request (HTTP 403). This usually means this server's IP address is rate limited or blocked; wait a few minutes before retrying.";+ }+ if (code === -1121) {+ return `Binance does not list ${target}. Use the base asset followed by the quote asset with nothing between them (for example BTCUSDT), and check the pair with List Trading Pairs.`;+ }+ if (code === -1220) {+ return `${capitalize(target)} is listed on Binance but is not trading right now (halted or delisted), so it has no live price.`;+ }+ if (status >= 500) {+ return `Binance had a server error (HTTP ${status}). This is a read-only request, so it is safe to retry.`;+ }+ const detail = msg ?? 'no error message';+ return code === undefined+ ? `Binance request failed (HTTP ${status}): ${detail}`+ : `Binance rejected the request (HTTP ${status}, code ${code}): ${detail}`;+}++function parseBinanceBody(body: unknown): { code: number | undefined; msg: string | undefined } {+ const parsed = typeof body === 'string' ? parseJson(body) : body;+ if (typeof parsed === 'string') {+ return { code: undefined, msg: parsed.trim() === '' ? undefined : parsed.slice(0, 300) };+ }+ if (typeof parsed !== 'object' || parsed === null) {+ return { code: undefined, msg: undefined };+ }+ const code: unknown = Reflect.get(parsed, 'code');+ const msg: unknown = Reflect.get(parsed, 'msg');+ return {+ code: typeof code === 'number' ? code : undefined,+ msg: typeof msg === 'string' ? msg : undefined,+ };+}++function parseJson(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ return text;+ }+}++function capitalize(text: string): string {+ return text.charAt(0).toUpperCase() + text.slice(1);+}++const MARKET_DATA_URL = 'https://data-api.binance.vision/api/v3';+const DEFAULT_TIMEOUT_MS = 30_000;+const SLOW_TIMEOUT_MS = 60_000;++export const binanceClient = {+ get,+ MARKET_DATA_URL,+ DEFAULT_TIMEOUT_MS,+ SLOW_TIMEOUT_MS,+};++type GetParams = {+ path: string;+ queryParams?: Record<string, string>;+ subject?: string;+ timeoutMs?: number;+};++type BinanceApiErrorParams = {+ message: string;+ status?: number;+ code?: number;+ responseBody?: unknown;+};diff --git a/packages/pieces/community/binance/src/lib/common/exchange-info.ts b/packages/pieces/community/binance/src/lib/common/exchange-info.tsnew file mode 100644index 00000000000..50adedf9931--- /dev/null+++ b/packages/pieces/community/binance/src/lib/common/exchange-info.ts@@ -0,0 +1,63 @@+function toPairSummary({ pair }: { pair: BinanceSymbolInfo }): PairSummary {+ return {+ symbol: pair.symbol,+ status: pair.status,+ baseAsset: pair.baseAsset,+ quoteAsset: pair.quoteAsset,+ baseAssetPrecision: pair.baseAssetPrecision,+ quoteAssetPrecision: pair.quoteAssetPrecision,+ isSpotTradingAllowed: pair.isSpotTradingAllowed,+ isMarginTradingAllowed: pair.isMarginTradingAllowed,+ orderTypes: Array.isArray(pair.orderTypes) ? pair.orderTypes.join(', ') : '',+ };+}++function filterValue({ pair, filterTypes, field }: { pair: BinanceSymbolInfo; filterTypes: string[]; field: string }): string | null {+ for (const filterType of filterTypes) {+ const filter = (pair.filters ?? []).find((item) => item.filterType === filterType);+ const value: unknown = filter === undefined ? undefined : filter[field];+ if (typeof value === 'string') {+ return value;+ }+ }+ return null;+}++function isOpenForSpotTrading({ pair }: { pair: BinanceSymbolInfo }): boolean {+ return pair.status === 'TRADING' && pair.isSpotTradingAllowed === true;+}++export const exchangeInfo = {+ toPairSummary,+ filterValue,+ isOpenForSpotTrading,+};++export type BinanceSymbolInfo = {+ symbol: string;+ status: string;+ baseAsset: string;+ quoteAsset: string;+ baseAssetPrecision: number;+ quoteAssetPrecision: number;+ isSpotTradingAllowed: boolean;+ isMarginTradingAllowed: boolean;+ orderTypes?: string[];+ filters?: ({ filterType: string } & Record<string, unknown>)[];+};++export type ExchangeInfoResponse = {+ symbols: BinanceSymbolInfo[];+};++type PairSummary = {+ symbol: string;+ status: string;+ baseAsset: string;+ quoteAsset: string;+ baseAssetPrecision: number;+ quoteAssetPrecision: number;+ isSpotTradingAllowed: boolean;+ isMarginTradingAllowed: boolean;+ orderTypes: string;+};diff --git a/packages/pieces/community/binance/src/lib/common/input.ts b/packages/pieces/community/binance/src/lib/common/input.tsnew file mode 100644index 00000000000..492cc816ed4--- /dev/null+++ b/packages/pieces/community/binance/src/lib/common/input.ts@@ -0,0 +1,158 @@+function symbol({ value, fieldName = 'Symbol' }: { value: unknown; fieldName?: string }): string {+ if (typeof value !== 'string' && typeof value !== 'number') {+ throw new Error(`${fieldName} is required, for example BTCUSDT.`);+ }+ const normalized = String(value).replace(/[\s/]+/g, '').toUpperCase();+ if (normalized === '') {+ throw new Error(`${fieldName} is required, for example BTCUSDT.`);+ }+ if (normalized.length > MAX_SYMBOL_LENGTH) {+ throw new Error(+ `${fieldName} "${normalized.slice(0, 60)}" is longer than ${MAX_SYMBOL_LENGTH} characters, so it cannot be a Binance symbol.`+ );+ }+ return normalized;+}++function symbols({ value }: { value: unknown }): string[] {+ const items: unknown[] = Array.isArray(value) ? value : value === undefined || value === null ? [] : [value];+ const parts = items.flatMap((item) => splitSymbolItem({ item }));+ const unique = [...new Set(parts.map((part) => symbol({ value: part })))];+ if (unique.length === 0) {+ throw new Error('Add at least one symbol, for example BTCUSDT.');+ }+ if (unique.length > MAX_SYMBOLS_PER_CALL) {+ throw new Error(+ `This action takes at most ${MAX_SYMBOLS_PER_CALL} symbols per call; ${unique.length} were given. Split the list across several steps.`+ );+ }+ return unique;+}++function limit({ value, min, max, defaultValue, fieldName = 'Limit' }: LimitParams): number {+ if (value === undefined || value === null || value === '') {+ return defaultValue;+ }+ const parsed =+ typeof value === 'number' ? value : typeof value === 'string' && /^\s*-?\d+\s*$/.test(value) ? Number(value) : NaN;+ if (!Number.isInteger(parsed)) {+ throw new Error(`${fieldName} must be a whole number between ${min} and ${max}.`);+ }+ if (parsed < min || parsed > max) {+ throw new Error(`${fieldName} must be between ${min} and ${max}; got ${parsed}.`);+ }+ return parsed;+}++function epochMs({ value, fieldName }: { value: unknown; fieldName: string }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const parsed = parseEpochMs({ value });+ if (parsed === undefined) {+ throw new Error(`${fieldName} must be a date such as 2026-10-01T09:00:00Z, or epoch milliseconds.`);+ }+ if (parsed < MIN_EPOCH_MS) {+ throw new Error(+ `${fieldName} resolves to ${new Date(parsed).toISOString()}, which is before 2001 and earlier than any Binance data. Pass a date such as 2026-10-01T09:00:00Z.`+ );+ }+ return parsed;+}++function windowSize({ value, defaultValue }: { value: unknown; defaultValue: string }): string {+ if (value === undefined || value === null || value === '') {+ return defaultValue;+ }+ const match = typeof value === 'string' ? /^(\d{1,2})([mhd])$/.exec(value.trim()) : null;+ const amount = match ? Number(match[1]) : 0;+ if (!match || amount < 1 || amount > WINDOW_UNIT_MAX[match[2]]) {+ throw new Error(+ `Window size "${String(value)}" is not valid. Use 1m to 59m, 1h to 23h, or 1d to 7d (for example 15m, 4h, 7d).`+ );+ }+ return `${amount}${match[2]}`;+}++function timeZone({ value }: { value: unknown }): string | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';+ const match = /^([+-]?)(\d{1,2})(?::(\d{2}))?$/.exec(text);+ if (match) {+ const sign = match[1] === '-' ? -1 : 1;+ const minutes = match[3] === undefined ? 0 : Number(match[3]);+ const offset = sign * (Number(match[2]) * 60 + minutes);+ if (minutes < 60 && offset >= -12 * 60 && offset <= 14 * 60) {+ return text;+ }+ }+ throw new Error(+ `Time zone "${String(value)}" is not valid. Use an offset from UTC between -12:00 and +14:00, such as 0, 8, -5, 05:45 or -03:30.`+ );+}++function klineInterval({ value }: { value: unknown }): string {+ const text = typeof value === 'string' ? value.trim() : '';+ const match = KLINE_INTERVALS.find((interval) => interval === text);+ if (match === undefined) {+ throw new Error(+ `Interval "${String(value)}" is not valid. Use one of: ${KLINE_INTERVALS.join(', ')} (case-sensitive; 1m is one minute, 1M is one month).`+ );+ }+ return match;+}++function parseEpochMs({ value }: { value: unknown }): number | undefined {+ if (typeof value === 'number') {+ return Number.isInteger(value) ? value : undefined;+ }+ if (typeof value !== 'string') {+ return undefined;+ }+ const trimmed = value.trim();+ if (/^\d+$/.test(trimmed)) {+ return Number(trimmed);+ }+ const parsed = Date.parse(trimmed);+ return Number.isNaN(parsed) ? undefined : parsed;+}++function splitSymbolItem({ item }: { item: unknown }): string[] {+ if (item === undefined || item === null) {+ return [];+ }+ if (typeof item !== 'string' && typeof item !== 'number') {+ throw new Error('Symbols must be text values such as BTCUSDT.');+ }+ return String(item)+ .split(/[,;\n]/)+ .filter((part) => part.trim() !== '');+}++const MAX_SYMBOL_LENGTH = 50;+const MAX_SYMBOLS_PER_CALL = 100;+const MIN_EPOCH_MS = 1_000_000_000_000;+const WINDOW_UNIT_MAX: Record<string, number> = { m: 59, h: 23, d: 7 };+const KLINE_INTERVALS = ['1s', '1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '3d', '1w', '1M'];++export const binanceInput = {+ symbol,+ symbols,+ limit,+ epochMs,+ windowSize,+ timeZone,+ klineInterval,+ MAX_SYMBOLS_PER_CALL,+ KLINE_INTERVALS,+};++type LimitParams = {+ value: unknown;+ min: number;+ max: number;+ defaultValue: number;+ fieldName?: string;+};diff --git a/packages/pieces/community/binance/src/lib/common/props.ts b/packages/pieces/community/binance/src/lib/common/props.tsnew file mode 100644index 00000000000..07be29c8975--- /dev/null+++ b/packages/pieces/community/binance/src/lib/common/props.ts@@ -0,0 +1,8 @@+import { Property } from '@activepieces/pieces-framework';++export const symbolProp = Property.ShortText({+ displayName: 'Symbol',+ description:+ "The trading pair: base asset followed by quote asset, for example BTCUSDT or ETHBTC. Spaces and '/' are removed and letters are upper-cased, so 'btc/usdt' also works. Use List Trading Pairs to find a symbol.",+ required: true,+});diff --git a/packages/pieces/community/binance/src/lib/output-schemas.ts b/packages/pieces/community/binance/src/lib/output-schemas.tsnew file mode 100644index 00000000000..354255bf900--- /dev/null+++ b/packages/pieces/community/binance/src/lib/output-schemas.ts@@ -0,0 +1,173 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const symbolField: OutputSchema['fields'][number] = {+ key: 'symbol',+ label: 'Symbol',+ description: 'Trading pair symbol, base asset followed by quote asset (for example BTCUSDT).',+};++const priceFields: OutputSchema['fields'] = [+ symbolField,+ { key: 'price', label: 'Price', description: 'Latest trade price as an exact decimal string, in the quote asset.' },+];++const changeFields: OutputSchema['fields'] = [+ { key: 'priceChange', label: 'Price Change', description: 'Last price minus open price, exact decimal string.' },+ { key: 'priceChangePercent', label: 'Price Change %', description: 'Price change in percent, exact decimal string.' },+ { key: 'weightedAvgPrice', label: 'Weighted Average Price', description: 'Quote volume divided by volume.' },+];++const marketFields: OutputSchema['fields'] = [+ { key: 'openPrice', label: 'Open Price' },+ { key: 'highPrice', label: 'High Price' },+ { key: 'lowPrice', label: 'Low Price' },+ { key: 'lastPrice', label: 'Last Price' },+ { key: 'volume', label: 'Volume', description: 'Traded amount in the base asset.' },+ { key: 'quoteVolume', label: 'Quote Volume', description: 'Traded amount in the quote asset.' },+ { key: 'openTime', label: 'Open Time', description: 'Window start, epoch milliseconds (UTC).' },+ { key: 'closeTime', label: 'Close Time', description: 'Window end, epoch milliseconds (UTC).' },+ { key: 'firstId', label: 'First Trade ID', description: '-1 when there were no trades.' },+ { key: 'lastId', label: 'Last Trade ID', description: '-1 when there were no trades.' },+ { key: 'count', label: 'Trade Count', format: 'number' },+];++const fullOnlyTickerFields: OutputSchema['fields'] = [+ ...changeFields,+ { key: 'prevClosePrice', label: 'Previous Close Price' },+ { key: 'lastQty', label: 'Last Quantity' },+ { key: 'bidPrice', label: 'Best Bid Price' },+ { key: 'bidQty', label: 'Best Bid Quantity' },+ { key: 'askPrice', label: 'Best Ask Price' },+ { key: 'askQty', label: 'Best Ask Quantity' },+].map((field) => ({ ...field, description: `${field.description ?? ''} Full detail level only.`.trim() }));++const levelFields: OutputSchema['fields'] = [+ { key: 'price', label: 'Price' },+ { key: 'quantity', label: 'Quantity', description: 'Amount in the base asset at this price level.' },+];++const tradeFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Trade ID' },+ { key: 'price', label: 'Price' },+ { key: 'qty', label: 'Quantity', description: 'Amount in the base asset.' },+ { key: 'quoteQty', label: 'Quote Quantity', description: 'Amount in the quote asset.' },+ { key: 'time', label: 'Time', description: 'Trade time, epoch milliseconds (UTC).' },+ { key: 'isBuyerMaker', label: 'Buyer Is Maker', format: 'boolean', description: 'True when the buyer\'s order was resting on the book (a sell hit it).' },+ { key: 'isBestMatch', label: 'Best Price Match', format: 'boolean' },+];++const candleFields: OutputSchema['fields'] = [+ { key: 'openTime', label: 'Open Time', description: 'Candle start, epoch milliseconds (UTC).' },+ { key: 'open', label: 'Open' },+ { key: 'high', label: 'High' },+ { key: 'low', label: 'Low' },+ { key: 'close', label: 'Close' },+ { key: 'volume', label: 'Volume', description: 'Traded amount in the base asset.' },+ { key: 'closeTime', label: 'Close Time', description: 'Candle end, epoch milliseconds (UTC).' },+ { key: 'quoteVolume', label: 'Quote Volume', description: 'Traded amount in the quote asset.' },+ { key: 'tradeCount', label: 'Trade Count', format: 'number' },+ { key: 'takerBuyBaseVolume', label: 'Taker Buy Volume', description: 'Base asset bought by takers.' },+ { key: 'takerBuyQuoteVolume', label: 'Taker Buy Quote Volume', description: 'Quote asset spent by takers buying.' },+];++const pairFields: OutputSchema['fields'] = [+ symbolField,+ { key: 'status', label: 'Status' },+ { key: 'baseAsset', label: 'Base Asset' },+ { key: 'quoteAsset', label: 'Quote Asset' },+ { key: 'baseAssetPrecision', label: 'Base Asset Precision', format: 'number' },+ { key: 'quoteAssetPrecision', label: 'Quote Asset Precision', format: 'number' },+ { key: 'isSpotTradingAllowed', label: 'Spot Trading Allowed', format: 'boolean' },+ { key: 'isMarginTradingAllowed', label: 'Margin Trading Allowed', format: 'boolean' },+ { key: 'orderTypes', label: 'Order Types', description: 'Comma-separated order types the pair accepts.' },+];++export const getPriceOutputSchema: OutputSchema = {+ fields: priceFields,+};++export const getMultiplePricesOutputSchema: OutputSchema = {+ fields: [+ { key: 'prices', label: 'Prices', labelKey: 'symbol', listItems: priceFields },+ { key: 'count', label: 'Count', format: 'number' },+ {+ key: 'notTrading',+ label: 'Not Trading',+ description: 'Requested symbols that are listed but not trading right now, so they have no price.',+ },+ ],+};++export const get24hTickerOutputSchema: OutputSchema = {+ fields: [symbolField, ...fullOnlyTickerFields, ...marketFields],+};++export const getRollingWindowTickerOutputSchema: OutputSchema = {+ fields: [+ symbolField,+ { key: 'windowSize', label: 'Window Size' },+ ...changeFields,+ ...marketFields,+ ],+};++export const getAveragePriceOutputSchema: OutputSchema = {+ fields: [+ symbolField,+ { key: 'price', label: 'Average Price', description: 'Average price over the window, exact decimal string.' },+ { key: 'mins', label: 'Window (Minutes)', format: 'number' },+ { key: 'closeTime', label: 'Last Trade Time', description: 'Epoch milliseconds (UTC).' },+ ],+};++export const getOrderBookOutputSchema: OutputSchema = {+ fields: [+ symbolField,+ { key: 'lastUpdateId', label: 'Last Update ID' },+ { key: 'bids', label: 'Bids', labelKey: 'price', description: 'Buy orders, highest price first.', listItems: levelFields },+ { key: 'asks', label: 'Asks', labelKey: 'price', description: 'Sell orders, lowest price first.', listItems: levelFields },+ ],+};++export const getRecentTradesOutputSchema: OutputSchema = {+ fields: [+ symbolField,+ { key: 'trades', label: 'Trades', labelKey: 'id', description: 'Oldest first.', listItems: tradeFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const getCandlesOutputSchema: OutputSchema = {+ fields: [+ symbolField,+ { key: 'interval', label: 'Interval' },+ { key: 'candles', label: 'Candles', labelKey: 'openTime', description: 'Oldest first.', listItems: candleFields },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when a start time was given and more candles follow the last one.' },+ { key: 'nextStartTime', label: 'Next Start Time', description: 'Start time for the next call when Has More is true, epoch milliseconds; otherwise null.' },+ ],+};++export const listTradingPairsOutputSchema: OutputSchema = {+ fields: [+ { key: 'pairs', label: 'Trading Pairs', labelKey: 'symbol', listItems: pairFields },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'total', label: 'Total Matches', format: 'number' },+ { key: 'truncated', label: 'Truncated', format: 'boolean', description: 'True when more pairs matched than were returned.' },+ ],+};++export const getTradingPairRulesOutputSchema: OutputSchema = {+ fields: [+ ...pairFields,+ { key: 'tickSize', label: 'Tick Size', description: 'Smallest price step (PRICE_FILTER). Null when the pair has no such rule.' },+ { key: 'minPrice', label: 'Minimum Price', description: 'PRICE_FILTER. Null when not defined.' },+ { key: 'maxPrice', label: 'Maximum Price', description: 'PRICE_FILTER. Null when not defined.' },+ { key: 'stepSize', label: 'Quantity Step Size', description: 'Smallest quantity step (LOT_SIZE). Null when not defined.' },+ { key: 'minQty', label: 'Minimum Quantity', description: 'LOT_SIZE. Null when not defined.' },+ { key: 'maxQty', label: 'Maximum Quantity', description: 'LOT_SIZE. Null when not defined.' },+ { key: 'minNotional', label: 'Minimum Order Value', description: 'NOTIONAL filter (or the older MIN_NOTIONAL), in the quote asset. Null when not defined.' },+ { key: 'maxNotional', label: 'Maximum Order Value', description: 'NOTIONAL, in the quote asset. Null when not defined.' },+ { key: 'filters', label: 'All Filters', description: 'Every Binance filter object for the pair, keyed by filterType.' },+ ],+};diff --git a/packages/pieces/community/binance/test/actions.test.ts b/packages/pieces/community/binance/test/actions.test.tsnew file mode 100644index 00000000000..aafeecedc89--- /dev/null+++ b/packages/pieces/community/binance/test/actions.test.ts@@ -0,0 +1,522 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { BASE, errorOf, fail, ok, request, runAction, sendRequest } from './helpers';+import { binance } from '../src';+import { fetchCryptoPairPrice } from '../src/lib/actions/fetch-pair-price';+import { binanceGetPrice } from '../src/lib/actions/get-price';+import { getMultiplePrices } from '../src/lib/actions/get-multiple-prices';+import { get24hTicker } from '../src/lib/actions/get-24h-ticker';+import { getRollingWindowTicker } from '../src/lib/actions/get-rolling-window-ticker';+import { getAveragePrice } from '../src/lib/actions/get-average-price';+import { getOrderBook } from '../src/lib/actions/get-order-book';+import { getRecentTrades } from '../src/lib/actions/get-recent-trades';+import { getCandles } from '../src/lib/actions/get-candles';+import { listTradingPairs } from '../src/lib/actions/list-trading-pairs';+import { getTradingPairRules } from '../src/lib/actions/get-trading-pair-rules';++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },+ };+});++beforeEach(() => {+ sendRequest.mockReset();+});++afterEach(() => {+ vi.useRealTimers();+});++const KLINE = [1790827200000, '83754.01000000', '84207.53000000', '83720.40000000', '84110.01000000', '514.62822000', 1790830799999, '43188989.25964940', 97798, '294.70729000', '24735482.67867050', '0'];++function kline({ openTime, closeTime }: { openTime: number; closeTime: number }) {+ return [openTime, '1.0', '2.0', '0.5', '1.5', '10.0', closeTime, '15.0', 3, '4.0', '6.0', '0'];+}++function pair({+ symbol,+ baseAsset,+ quoteAsset,+ filters = [],+ status = 'TRADING',+ isSpotTradingAllowed = true,+ isMarginTradingAllowed = false,+}: {+ symbol: string;+ baseAsset: string;+ quoteAsset: string;+ filters?: unknown[];+ status?: string;+ isSpotTradingAllowed?: boolean;+ isMarginTradingAllowed?: boolean;+}) {+ return {+ symbol,+ status,+ baseAsset,+ quoteAsset,+ baseAssetPrecision: 8,+ quoteAssetPrecision: 8,+ isSpotTradingAllowed,+ isMarginTradingAllowed,+ orderTypes: ['LIMIT', 'MARKET'],+ filters,+ permissionSets: [],+ };+}++describe('piece wiring', () => {+ it('registers all 11 actions with the expected audience and metadata', () => {+ const actions = binance.actions();+ expect(Object.keys(actions)).toHaveLength(11);+ for (const action of Object.values(actions)) {+ expect(action.aiMetadata?.description).toBeTruthy();+ expect(action.aiMetadata?.idempotent).toBe(true);+ expect(['READ', 'SEARCH']).toContain(action.classification);+ }+ expect(actions['fetch_crypto_pair_price'].audience).toBe('human');+ expect(actions['binance_get_price'].audience).toBe('ai');+ const others = Object.values(actions).filter((a) => a.name !== 'fetch_crypto_pair_price' && a.name !== 'binance_get_price');+ expect(others.every((a) => a.audience === 'both')).toBe(true);+ expect(Object.values(actions).filter((a) => a.outputSchema !== undefined)).toHaveLength(10);+ expect(actions['fetch_crypto_pair_price'].outputSchema).toBeUndefined();+ expect(binance.minimumSupportedRelease).toBe('0.88.2');+ });+});++describe('fetch_crypto_pair_price (existing action)', () => {+ it('calls the market-data host with the symbol as a query param and returns a number', async () => {+ ok({ body: { symbol: 'BTCUSDT', price: '84182.69000000' } });+ const result = await runAction({ action: fetchCryptoPairPrice, props: { first_coin: ' btc/ ', second_coin: ' usdt\n' } });+ expect(result).toBe(84182.69);+ expect(typeof result).toBe('number');+ expect(request()).toEqual({+ method: HttpMethod.GET,+ url: `${BASE}/ticker/price`,+ queryParams: { symbol: 'BTCUSDT' },+ timeout: 30000,+ });+ });++ it('keeps non-ASCII symbols intact for the client to encode', async () => {+ ok({ body: { symbol: '币安人生USDT', price: '0.50490000' } });+ expect(await runAction({ action: fetchCryptoPairPrice, props: { first_coin: '币安人生', second_coin: 'USDT' } })).toBe(0.5049);+ expect(request().queryParams).toEqual({ symbol: '币安人生USDT' });+ });++ it('fails before any request when a coin is blank', async () => {+ const error = await errorOf(runAction({ action: fetchCryptoPairPrice, props: { first_coin: ' ', second_coin: 'USDT' } }));+ expect(error.message).toBe('First Coin Symbol is required, for example BTCUSDT.');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('throws instead of returning NaN when the body has no price', async () => {+ ok({ body: { symbol: 'BTCUSDT' } });+ const error = await errorOf(runAction({ action: fetchCryptoPairPrice, props: { first_coin: 'BTC', second_coin: 'USDT' } }));+ expect(error.message).toBe('Binance returned no price for BTCUSDT.');+ });++ it('maps an unknown pair to a readable error', async () => {+ fail({ status: 400, body: { code: -1121, msg: 'Invalid symbol.' } });+ const error = await errorOf(runAction({ action: fetchCryptoPairPrice, props: { first_coin: 'FOO', second_coin: 'BAR' } }));+ expect(error.message).toContain('Binance does not list the trading pair "FOOBAR"');+ });+});++describe('request building per action', () => {+ it('binance_get_price asks only for trading pairs and returns the exact string', async () => {+ ok({ body: { symbol: 'BTCUSDT', price: '84184.05000000' } });+ expect(await runAction({ action: binanceGetPrice, props: { symbol: 'btc/usdt' } })).toEqual({ symbol: 'BTCUSDT', price: '84184.05000000' });+ expect(request()).toEqual({+ method: HttpMethod.GET,+ url: `${BASE}/ticker/price`,+ queryParams: { symbol: 'BTCUSDT', symbolStatus: 'TRADING' },+ timeout: 30000,+ });+ });++ it('get_multiple_prices sends a JSON array, keeps input order and reports non-trading pairs', async () => {+ ok({ body: [{ symbol: 'ETHUSDT', price: '2714.63000000' }, { symbol: 'BTCUSDT', price: '84184.05000000' }] });+ const result = await runAction({ action: getMultiplePrices, props: { symbols: ['btcusdt', 'ETH/USDT', 'BCCBTC', 'BTC USDT'] } });+ expect(request().queryParams).toEqual({ symbols: '["BTCUSDT","ETHUSDT","BCCBTC"]', symbolStatus: 'TRADING' });+ expect(result).toEqual({+ prices: [+ { symbol: 'BTCUSDT', price: '84184.05000000' },+ { symbol: 'ETHUSDT', price: '2714.63000000' },+ ],+ count: 2,+ notTrading: ['BCCBTC'],+ });+ });++ it('get_multiple_prices rejects 101 symbols before any request', async () => {+ const symbols = Array.from({ length: 101 }, (_, i) => `S${i}USDT`);+ const error = await errorOf(runAction({ action: getMultiplePrices, props: { symbols } }));+ expect(error.message).toContain('at most 100 symbols');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('get_24h_ticker defaults to FULL and passes MINI through', async () => {+ ok({ body: { symbol: 'BTCUSDT', lastPrice: '1' } });+ await runAction({ action: get24hTicker, props: { symbol: 'BTCUSDT' } });+ expect(request(0)).toEqual({ method: HttpMethod.GET, url: `${BASE}/ticker/24hr`, queryParams: { symbol: 'BTCUSDT', type: 'FULL' }, timeout: 30000 });+ ok({ body: { symbol: 'BTCUSDT', lastPrice: '1' } });+ await runAction({ action: get24hTicker, props: { symbol: 'BTCUSDT', type: 'MINI' } });+ expect(request(1).queryParams).toEqual({ symbol: 'BTCUSDT', type: 'MINI' });+ });++ it('get_24h_ticker rejects an unknown detail level', async () => {+ const error = await errorOf(runAction({ action: get24hTicker, props: { symbol: 'BTCUSDT', type: 'HUGE' } }));+ expect(error.message).toBe('Detail Level must be FULL or MINI.');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('get_rolling_window_ticker defaults to 1h, normalises 01h and adds windowSize to the output', async () => {+ ok({ body: { symbol: 'BTCUSDT', priceChange: '1.0' } });+ expect(await runAction({ action: getRollingWindowTicker, props: { symbol: 'BTCUSDT' } })).toEqual({ symbol: 'BTCUSDT', priceChange: '1.0', windowSize: '1h' });+ expect(request(0)).toEqual({ method: HttpMethod.GET, url: `${BASE}/ticker`, queryParams: { symbol: 'BTCUSDT', windowSize: '1h' }, timeout: 30000 });+ ok({ body: { symbol: 'BTCUSDT' } });+ await runAction({ action: getRollingWindowTicker, props: { symbol: 'BTCUSDT', window_size: '01h' } });+ expect(request(1).queryParams.windowSize).toBe('1h');+ });++ it('get_rolling_window_ticker rejects 9d before any request', async () => {+ const error = await errorOf(runAction({ action: getRollingWindowTicker, props: { symbol: 'BTCUSDT', window_size: '9d' } }));+ expect(error.message).toContain('Window size "9d" is not valid');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('get_average_price adds the symbol', async () => {+ ok({ body: { mins: 5, price: '84275.08798119', closeTime: 1790836396722 } });+ expect(await runAction({ action: getAveragePrice, props: { symbol: 'BTCUSDT' } })).toEqual({ symbol: 'BTCUSDT', mins: 5, price: '84275.08798119', closeTime: 1790836396722 });+ expect(request()).toEqual({ method: HttpMethod.GET, url: `${BASE}/avgPrice`, queryParams: { symbol: 'BTCUSDT' }, timeout: 30000 });+ });++ it('get_order_book defaults to depth 20, accepts a numeric string and maps tuples', async () => {+ ok({ body: { lastUpdateId: 7, bids: [['84184.04000000', '0.10457000']], asks: [['84184.05000000', '1.00000000']] } });+ expect(await runAction({ action: getOrderBook, props: { symbol: 'BTCUSDT' } })).toEqual({+ symbol: 'BTCUSDT',+ lastUpdateId: 7,+ bids: [{ price: '84184.04000000', quantity: '0.10457000' }],+ asks: [{ price: '84184.05000000', quantity: '1.00000000' }],+ });+ expect(request(0)).toEqual({ method: HttpMethod.GET, url: `${BASE}/depth`, queryParams: { symbol: 'BTCUSDT', limit: '20' }, timeout: 30000 });+ ok({ body: { lastUpdateId: 7, bids: [], asks: [] } });+ await runAction({ action: getOrderBook, props: { symbol: 'BTCUSDT', limit: '5000' } });+ expect(request(1).queryParams.limit).toBe('5000');+ });++ it.each([0, 5001, 2.5])('get_order_book rejects depth %j before any request', async (limit) => {+ await errorOf(runAction({ action: getOrderBook, props: { symbol: 'BTCUSDT', limit } }));+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('get_recent_trades defaults to 50 and returns the trades with a count', async () => {+ const trade = { id: 1, price: '1', qty: '2', quoteQty: '2', time: 3, isBuyerMaker: true, isBestMatch: true };+ ok({ body: [trade] });+ expect(await runAction({ action: getRecentTrades, props: { symbol: 'BTCUSDT' } })).toEqual({ symbol: 'BTCUSDT', trades: [trade], count: 1 });+ expect(request()).toEqual({ method: HttpMethod.GET, url: `${BASE}/trades`, queryParams: { symbol: 'BTCUSDT', limit: '50' }, timeout: 30000 });+ });++ it.each([0, 1001])('get_recent_trades rejects %j before any request', async (limit) => {+ await errorOf(runAction({ action: getRecentTrades, props: { symbol: 'BTCUSDT', limit } }));+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('get_candles', () => {+ it('sends only the params that are set, with a longer timeout, and names the tuple fields', async () => {+ ok({ body: [KLINE] });+ const result = await runAction({ action: getCandles, props: { symbol: 'BTCUSDT', interval: '1h' } });+ expect(request()).toEqual({+ method: HttpMethod.GET,+ url: `${BASE}/klines`,+ queryParams: { symbol: 'BTCUSDT', interval: '1h', limit: '100' },+ timeout: 60000,+ });+ expect(result).toEqual({+ symbol: 'BTCUSDT',+ interval: '1h',+ candles: [+ {+ openTime: 1790827200000,+ open: '83754.01000000',+ high: '84207.53000000',+ low: '83720.40000000',+ close: '84110.01000000',+ volume: '514.62822000',+ closeTime: 1790830799999,+ quoteVolume: '43188989.25964940',+ tradeCount: 97798,+ takerBuyBaseVolume: '294.70729000',+ takerBuyQuoteVolume: '24735482.67867050',+ },+ ],+ count: 1,+ hasMore: false,+ nextStartTime: null,+ });+ });++ it('passes the range and time zone through', async () => {+ ok({ body: [] });+ await runAction({+ action: getCandles,+ props: { symbol: 'BTCUSDT', interval: '1M', start_time: '2026-09-20T00:00:00.000Z', end_time: '2026-09-22T00:00:00.000Z', time_zone: '05:45', limit: 10 },+ });+ expect(request().queryParams).toEqual({+ symbol: 'BTCUSDT',+ interval: '1M',+ limit: '10',+ startTime: String(Date.UTC(2026, 8, 20)),+ endTime: String(Date.UTC(2026, 8, 22)),+ timeZone: '05:45',+ });+ });++ it('reports hasMore and the next start time when a full page ends before the range end', async () => {+ const hour = 3600000;+ const start = Date.UTC(2026, 8, 20);+ ok({ body: [kline({ openTime: start, closeTime: start + hour - 1 }), kline({ openTime: start + hour, closeTime: start + 2 * hour - 1 })] });+ const result = await runAction({+ action: getCandles,+ props: { symbol: 'BTCUSDT', interval: '1h', start_time: start, end_time: start + 48 * hour, limit: 2 },+ });+ expect(result).toMatchObject({ count: 2, hasMore: true, nextStartTime: start + 2 * hour });+ });++ it('says no more when the page is short or reaches the range end', async () => {+ const hour = 3600000;+ const start = Date.UTC(2026, 8, 20);+ ok({ body: [kline({ openTime: start, closeTime: start + hour - 1 })] });+ expect(await runAction({ action: getCandles, props: { symbol: 'BTCUSDT', interval: '1h', start_time: start, limit: 2 } })).toMatchObject({ hasMore: false, nextStartTime: null });+ ok({ body: [kline({ openTime: start, closeTime: start + hour - 1 })] });+ expect(+ await runAction({ action: getCandles, props: { symbol: 'BTCUSDT', interval: '1h', start_time: start, end_time: start + hour - 1, limit: 1 } })+ ).toMatchObject({ hasMore: false });+ });++ it('never claims more for the most-recent mode (no start time)', async () => {+ ok({ body: [KLINE] });+ expect(await runAction({ action: getCandles, props: { symbol: 'BTCUSDT', interval: '1h', limit: 1 } })).toMatchObject({ hasMore: false, nextStartTime: null });+ });++ it.each([+ [{ interval: '1H' }, 'Interval "1H" is not valid'],+ [{ interval: '1h', start_time: '2026-09-22T00:00:00Z', end_time: '2026-09-20T00:00:00Z' }, 'Start Time must be earlier than End Time.'],+ [{ interval: '1h', time_zone: '14:30' }, 'Time zone "14:30" is not valid'],+ [{ interval: '1h', limit: 1001 }, 'Number of Candles must be between 1 and 1000'],+ [{ interval: '1h', start_time: 'soon' }, 'Start Time must be a date'],+ ])('rejects %j before any request', async (props, message) => {+ const error = await errorOf(runAction({ action: getCandles, props: { symbol: 'BTCUSDT', ...props } }));+ expect(error.message).toContain(message);+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('list_trading_pairs', () => {+ const symbols = [+ pair({ symbol: 'BTCUSDT', baseAsset: 'BTC', quoteAsset: 'USDT' }),+ pair({ symbol: 'ETHUSDT', baseAsset: 'ETH', quoteAsset: 'USDT' }),+ pair({ symbol: 'ETHBTC', baseAsset: 'ETH', quoteAsset: 'BTC' }),+ pair({ symbol: 'BNBUSDT', baseAsset: 'BNB', quoteAsset: 'USDT' }),+ ];++ it('requests TRADING pairs without permission sets and returns slim rows', async () => {+ ok({ body: { symbols } });+ const result = await runAction({ action: listTradingPairs, props: {} });+ expect(request()).toEqual({+ method: HttpMethod.GET,+ url: `${BASE}/exchangeInfo`,+ queryParams: { symbolStatus: 'TRADING', showPermissionSets: 'false' },+ timeout: 60000,+ });+ expect(result).toMatchObject({ count: 4, total: 4, truncated: false });+ expect(result).toMatchObject({+ pairs: [+ {+ symbol: 'BTCUSDT',+ status: 'TRADING',+ baseAsset: 'BTC',+ quoteAsset: 'USDT',+ baseAssetPrecision: 8,+ quoteAssetPrecision: 8,+ isSpotTradingAllowed: true,+ isMarginTradingAllowed: false,+ orderTypes: 'LIMIT, MARKET',+ },+ { symbol: 'ETHUSDT' },+ { symbol: 'ETHBTC' },+ { symbol: 'BNBUSDT' },+ ],+ });+ expect(JSON.stringify(result)).not.toContain('filters');+ expect(JSON.stringify(result)).not.toContain('permissionSets');+ });++ it('filters by quote and base asset case-insensitively', async () => {+ ok({ body: { symbols } });+ const result = await runAction({ action: listTradingPairs, props: { quote_asset: ' usdt ', base_asset: 'eth' } });+ expect(result).toMatchObject({ count: 1, total: 1, truncated: false, pairs: [{ symbol: 'ETHUSDT' }] });+ });++ it('caps the rows and says so', async () => {+ ok({ body: { symbols } });+ expect(await runAction({ action: listTradingPairs, props: { quote_asset: 'USDT', limit: 2 } })).toMatchObject({ count: 2, total: 3, truncated: true });+ });++ it('leaves out pairs that are not open for spot trading and keeps the total in step', async () => {+ ok({+ body: {+ symbols: [+ pair({ symbol: 'BTCUSDT', baseAsset: 'BTC', quoteAsset: 'USDT' }),+ pair({ symbol: 'MARGINUSDT', baseAsset: 'MARGIN', quoteAsset: 'USDT', isSpotTradingAllowed: false, isMarginTradingAllowed: true }),+ pair({ symbol: 'HALTUSDT', baseAsset: 'HALT', quoteAsset: 'USDT', status: 'BREAK' }),+ pair({ symbol: 'ETHUSDT', baseAsset: 'ETH', quoteAsset: 'USDT' }),+ ],+ },+ });+ const result = await runAction({ action: listTradingPairs, props: { quote_asset: 'USDT', limit: 1 } });+ expect(result).toMatchObject({ count: 1, total: 2, truncated: true, pairs: [{ symbol: 'BTCUSDT' }] });+ expect(JSON.stringify(result)).not.toContain('MARGINUSDT');+ expect(JSON.stringify(result)).not.toContain('HALTUSDT');+ });++ it.each([0, 1501])('rejects limit %j before any request', async (limit) => {+ await errorOf(runAction({ action: listTradingPairs, props: { limit } }));+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('get_trading_pair_rules', () => {+ it('flattens the price, lot size and notional filters', async () => {+ const filters = [+ { filterType: 'PRICE_FILTER', minPrice: '0.01000000', maxPrice: '1000000.00000000', tickSize: '0.01000000' },+ { filterType: 'LOT_SIZE', minQty: '0.00001000', maxQty: '9000.00000000', stepSize: '0.00001000' },+ { filterType: 'NOTIONAL', minNotional: '5.00000000', maxNotional: '9000000.00000000' },+ ];+ ok({ body: { symbols: [pair({ symbol: 'BTCUSDT', baseAsset: 'BTC', quoteAsset: 'USDT', filters })] } });+ const result = await runAction({ action: getTradingPairRules, props: { symbol: 'btcusdt' } });+ expect(request()).toEqual({+ method: HttpMethod.GET,+ url: `${BASE}/exchangeInfo`,+ queryParams: { symbol: 'BTCUSDT', showPermissionSets: 'false' },+ timeout: 30000,+ });+ expect(result).toMatchObject({+ symbol: 'BTCUSDT',+ tickSize: '0.01000000',+ minPrice: '0.01000000',+ maxPrice: '1000000.00000000',+ stepSize: '0.00001000',+ minQty: '0.00001000',+ maxQty: '9000.00000000',+ minNotional: '5.00000000',+ maxNotional: '9000000.00000000',+ filters,+ });+ });++ it('reads the minimum order value from the older MIN_NOTIONAL filter when NOTIONAL is absent', async () => {+ const filters = [{ filterType: 'MIN_NOTIONAL', minNotional: '10.00000000', applyToMarket: true, avgPriceMins: 5 }];+ ok({ body: { symbols: [pair({ symbol: 'OLDUSDT', baseAsset: 'OLD', quoteAsset: 'USDT', filters })] } });+ expect(await runAction({ action: getTradingPairRules, props: { symbol: 'OLDUSDT' } })).toMatchObject({ minNotional: '10.00000000', maxNotional: null, filters });+ });++ it('prefers NOTIONAL over MIN_NOTIONAL when both are present', async () => {+ const filters = [+ { filterType: 'MIN_NOTIONAL', minNotional: '10.00000000', applyToMarket: true, avgPriceMins: 5 },+ { filterType: 'NOTIONAL', minNotional: '5.00000000', applyMinToMarket: true, maxNotional: '9000000.00000000', applyMaxToMarket: false, avgPriceMins: 5 },+ ];+ ok({ body: { symbols: [pair({ symbol: 'BTCUSDT', baseAsset: 'BTC', quoteAsset: 'USDT', filters })] } });+ expect(await runAction({ action: getTradingPairRules, props: { symbol: 'BTCUSDT' } })).toMatchObject({ minNotional: '5.00000000', maxNotional: '9000000.00000000' });+ });++ it('returns null for rules the pair does not define', async () => {+ ok({ body: { symbols: [pair({ symbol: 'XUSDT', baseAsset: 'X', quoteAsset: 'USDT' })] } });+ expect(await runAction({ action: getTradingPairRules, props: { symbol: 'XUSDT' } })).toMatchObject({ tickSize: null, stepSize: null, minNotional: null, filters: [] });+ });++ it('fails when Binance returns no matching symbol', async () => {+ ok({ body: { symbols: [] } });+ const error = await errorOf(runAction({ action: getTradingPairRules, props: { symbol: 'XUSDT' } }));+ expect(error.message).toBe('Binance returned no trading rules for XUSDT.');+ });+});++describe('error mapping', () => {+ async function failWith({ status, body }: { status: number; body?: unknown }) {+ fail({ status, body });+ return errorOf(runAction({ action: binanceGetPrice, props: { symbol: 'BTCUSDT' } }));+ }++ it('400 -1121 names the pair and points to List Trading Pairs', async () => {+ const error = await failWith({ status: 400, body: { code: -1121, msg: 'Invalid symbol.' } });+ expect(error.message).toContain('Binance does not list the trading pair "BTCUSDT"');+ expect(error.message).toContain('List Trading Pairs');+ expect(error).toMatchObject({ name: 'BinanceApiError', status: 400, code: -1121, responseBody: { code: -1121, msg: 'Invalid symbol.' } });+ expect(Object.keys(error)).not.toContain('body');+ });++ it('400 -1121 on the multi-price call lists the symbols', async () => {+ fail({ status: 400, body: { code: -1121, msg: 'Invalid symbol.' } });+ const error = await errorOf(runAction({ action: getMultiplePrices, props: { symbols: ['BTCUSDT', 'FOOBAR'] } }));+ expect(error.message).toContain('one or more of these symbols (BTCUSDT, FOOBAR)');+ });++ it('400 -1220 says the pair is not trading', async () => {+ const error = await failWith({ status: 400, body: { code: -1220, msg: "The symbol's status does not match the requested symbolStatus" } });+ expect(error.message).toBe('The trading pair "BTCUSDT" is listed on Binance but is not trading right now (halted or delisted), so it has no live price.');+ });++ it('other Binance codes keep the code and message', async () => {+ const error = await failWith({ status: 400, body: { code: -1100, msg: "Illegal characters found in parameter 'symbol'" } });+ expect(error.message).toBe("Binance rejected the request (HTTP 400, code -1100): Illegal characters found in parameter 'symbol'");+ });++ it('a JSON string body is parsed', async () => {+ const error = await failWith({ status: 400, body: '{"code":-1121,"msg":"Invalid symbol."}' });+ expect(error.message).toContain('does not list');+ });++ it.each([+ [429, 'rate limit reached (HTTP 429)'],+ [418, 'temporarily banned this server\'s IP address (HTTP 418)'],+ [451, 'blocks requests from the region this server runs in (HTTP 451)'],+ [403, "firewall rejected the request (HTTP 403)"],+ [502, 'server error (HTTP 502). This is a read-only request, so it is safe to retry.'],+ ])('HTTP %i is explained', async (status, text) => {+ const error = await failWith({ status, body: status === 429 ? { code: -1003, msg: 'Too much request weight used' } : '' });+ expect(error.message).toContain(text);+ expect(error).toMatchObject({ status });+ });++ it('an unexpected body still produces a readable message', async () => {+ const error = await failWith({ status: 404, body: '<html>Not Found</html>' });+ expect(error.message).toBe('Binance request failed (HTTP 404): <html>Not Found</html>');+ });++ it('a timeout is reported as such', async () => {+ const abort = new Error('This operation was aborted');+ abort.name = 'AbortError';+ sendRequest.mockRejectedValueOnce(abort);+ const error = await errorOf(runAction({ action: binanceGetPrice, props: { symbol: 'BTCUSDT' } }));+ expect(error.message).toBe('Binance did not answer within 30 seconds. This is a read-only request, so it is safe to retry.');+ });++ it('other errors are rethrown unchanged', async () => {+ const boom = new TypeError('fetch failed');+ sendRequest.mockRejectedValueOnce(boom);+ expect(await errorOf(runAction({ action: binanceGetPrice, props: { symbol: 'BTCUSDT' } }))).toBe(boom);+ });++ it('does not retry on its own', async () => {+ fail({ status: 429, body: { code: -1003, msg: 'Too much request weight used' } });+ await errorOf(runAction({ action: binanceGetPrice, props: { symbol: 'BTCUSDT' } }));+ expect(sendRequest).toHaveBeenCalledTimes(1);+ expect(request().retries).toBeUndefined();+ });+});diff --git a/packages/pieces/community/binance/test/helpers.ts b/packages/pieces/community/binance/test/helpers.tsnew file mode 100644index 00000000000..e14e1c2ac64--- /dev/null+++ b/packages/pieces/community/binance/test/helpers.ts@@ -0,0 +1,38 @@+import { HttpError } from '@activepieces/pieces-common';+import { vi } from 'vitest';++export const BASE = 'https://data-api.binance.vision/api/v3';++export const sendRequest = vi.fn();++export function ok({ body }: { body: unknown }) {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+}++export function fail({ status, body = {} }: { status: number; body?: unknown }) {+ sendRequest.mockRejectedValueOnce(new HttpError({}, { status, responseBody: body }));+}++export function request(index = 0) {+ return sendRequest.mock.calls[index][0];+}++export function runAction({ action, props }: { action: { run: unknown }; props: Record<string, unknown> }): Promise<unknown> {+ const run = action.run;+ if (typeof run !== 'function') {+ throw new Error('action has no run');+ }+ return Promise.resolve(Reflect.apply(run, action, [{ propsValue: props }]));+}++export async function errorOf(promise: Promise<unknown>): Promise<Error> {+ try {+ await promise;+ } catch (error) {+ if (error instanceof Error) {+ return error;+ }+ throw new Error(`non-Error thrown: ${String(error)}`);+ }+ throw new Error('expected the action to fail');+}diff --git a/packages/pieces/community/binance/test/input.test.ts b/packages/pieces/community/binance/test/input.test.tsnew file mode 100644index 00000000000..fb9d7a1b916--- /dev/null+++ b/packages/pieces/community/binance/test/input.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from 'vitest';+import { binanceInput } from '../src/lib/common/input';++describe('symbol normalisation', () => {+ it.each([+ ['BTCUSDT', 'BTCUSDT'],+ ['btcusdt', 'BTCUSDT'],+ ['BTC/USDT', 'BTCUSDT'],+ [' btc / usdt ', 'BTCUSDT'],+ ['B T C\tUSDT\n', 'BTCUSDT'],+ ['BTC//USDT', 'BTCUSDT'],+ ['币安人生usdt', '币安人生USDT'],+ ['abc-def_g.h', 'ABC-DEF_G.H'],+ ])('%j -> %s', (input, expected) => {+ expect(binanceInput.symbol({ value: input })).toBe(expected);+ });++ it('rejects empty, whitespace-only and non-text values', () => {+ expect(() => binanceInput.symbol({ value: '' })).toThrow('Symbol is required');+ expect(() => binanceInput.symbol({ value: ' / \n' })).toThrow('Symbol is required');+ expect(() => binanceInput.symbol({ value: undefined })).toThrow('Symbol is required');+ expect(() => binanceInput.symbol({ value: { a: 1 } })).toThrow('Symbol is required');+ expect(() => binanceInput.symbol({ value: '', fieldName: 'First Coin Symbol' })).toThrow('First Coin Symbol is required');+ });++ it('rejects symbols longer than Binance allows', () => {+ expect(() => binanceInput.symbol({ value: 'A'.repeat(51) })).toThrow('longer than 50');+ expect(binanceInput.symbol({ value: 'A'.repeat(50) })).toHaveLength(50);+ });+});++describe('symbol lists', () => {+ it('normalises, splits comma lists and dedupes in order', () => {+ expect(binanceInput.symbols({ value: ['btc usdt', 'ETHUSDT', 'BTC/USDT', 'BNBUSDT, solusdt\nXRPUSDT'] })).toEqual([+ 'BTCUSDT',+ 'ETHUSDT',+ 'BNBUSDT',+ 'SOLUSDT',+ 'XRPUSDT',+ ]);+ });++ it('accepts one comma-separated string', () => {+ expect(binanceInput.symbols({ value: 'BTCUSDT,ETHUSDT' })).toEqual(['BTCUSDT', 'ETHUSDT']);+ });++ it('rejects an empty list and lists over 100 unique symbols', () => {+ expect(() => binanceInput.symbols({ value: [] })).toThrow('at least one symbol');+ expect(() => binanceInput.symbols({ value: ['', ' , '] })).toThrow('at least one symbol');+ const hundred = Array.from({ length: 100 }, (_, i) => `S${i}USDT`);+ expect(binanceInput.symbols({ value: [...hundred, 'S0USDT'] })).toHaveLength(100);+ expect(() => binanceInput.symbols({ value: [...hundred, 'EXTRAUSDT'] })).toThrow('at most 100 symbols');+ });++ it('rejects non-text items', () => {+ expect(() => binanceInput.symbols({ value: [{ symbol: 'BTCUSDT' }] })).toThrow('text values');+ });+});++describe('limits', () => {+ const bounds = { min: 1, max: 1000, defaultValue: 50 };+ it('defaults when empty', () => {+ expect(binanceInput.limit({ value: undefined, ...bounds })).toBe(50);+ expect(binanceInput.limit({ value: null, ...bounds })).toBe(50);+ expect(binanceInput.limit({ value: '', ...bounds })).toBe(50);+ });+ it('accepts integers and numeric strings at the bounds', () => {+ expect(binanceInput.limit({ value: 1, ...bounds })).toBe(1);+ expect(binanceInput.limit({ value: '1000', ...bounds })).toBe(1000);+ expect(binanceInput.limit({ value: ' 20 ', ...bounds })).toBe(20);+ });+ it('rejects out-of-range, fractional and non-numeric values', () => {+ expect(() => binanceInput.limit({ value: 0, ...bounds })).toThrow('between 1 and 1000; got 0');+ expect(() => binanceInput.limit({ value: 1001, ...bounds })).toThrow('got 1001');+ expect(() => binanceInput.limit({ value: 2.5, ...bounds })).toThrow('whole number');+ expect(() => binanceInput.limit({ value: '1e3', ...bounds })).toThrow('whole number');+ expect(() => binanceInput.limit({ value: 'ten', ...bounds, fieldName: 'Depth' })).toThrow('Depth must be a whole number');+ });+});++describe('window size', () => {+ it.each([+ ['1m', '1m'],+ ['59m', '59m'],+ ['01h', '1h'],+ ['23h', '23h'],+ [' 7d ', '7d'],+ ])('%j -> %s', (input, expected) => {+ expect(binanceInput.windowSize({ value: input, defaultValue: '1h' })).toBe(expected);+ });+ it('defaults when empty', () => {+ expect(binanceInput.windowSize({ value: undefined, defaultValue: '1h' })).toBe('1h');+ });+ it.each(['0m', '60m', '24h', '8d', '9d', '1D', '1w', '1d2h', 'abc', '100m'])('rejects %j', (input) => {+ expect(() => binanceInput.windowSize({ value: input, defaultValue: '1h' })).toThrow('is not valid');+ });+});++describe('time zone', () => {+ it.each(['0', '8', '+3', '-5', '05:45', '+05:45', '-03:30', '-12:00', '14:00', '+14'])('accepts %j', (input) => {+ expect(binanceInput.timeZone({ value: input })).toBe(input);+ });+ it('accepts a number and returns undefined when empty', () => {+ expect(binanceInput.timeZone({ value: 8 })).toBe('8');+ expect(binanceInput.timeZone({ value: '' })).toBeUndefined();+ });+ it.each(['14:30', '-12:30', '15', '5:7', '05:60', 'UTC', '+'])('rejects %j', (input) => {+ expect(() => binanceInput.timeZone({ value: input })).toThrow('is not valid');+ });+});++describe('epoch milliseconds', () => {+ it('parses ISO dates, digit strings and numbers', () => {+ expect(binanceInput.epochMs({ value: '2026-09-20T00:00:00.000Z', fieldName: 'Start Time' })).toBe(Date.UTC(2026, 8, 20));+ expect(binanceInput.epochMs({ value: '1789862400000', fieldName: 'Start Time' })).toBe(1789862400000);+ expect(binanceInput.epochMs({ value: 1789862400000, fieldName: 'Start Time' })).toBe(1789862400000);+ expect(binanceInput.epochMs({ value: undefined, fieldName: 'Start Time' })).toBeUndefined();+ });+ it('rejects unparsable values', () => {+ expect(() => binanceInput.epochMs({ value: 'next tuesday', fieldName: 'Start Time' })).toThrow('Start Time must be a date');+ expect(() => binanceInput.epochMs({ value: 1.5, fieldName: 'End Time' })).toThrow('End Time must be a date');+ });+ it('rejects dates before 2001, such as epoch seconds read as milliseconds', () => {+ expect(() => binanceInput.epochMs({ value: 1789862400, fieldName: 'Start Time' })).toThrow('Start Time resolves to 1970-01-21T');+ expect(() => binanceInput.epochMs({ value: '1796-02-24T00:00:00.000Z', fieldName: 'Start Time' })).toThrow('Start Time resolves to 1796-02-24T00:00:00.000Z, which is before 2001');+ expect(() => binanceInput.epochMs({ value: -1, fieldName: 'End Time' })).toThrow('which is before 2001');+ });+});++describe('kline interval', () => {+ it('accepts all 16 documented intervals, case-sensitive', () => {+ for (const interval of binanceInput.KLINE_INTERVALS) {+ expect(binanceInput.klineInterval({ value: interval })).toBe(interval);+ }+ expect(binanceInput.KLINE_INTERVALS).toHaveLength(16);+ });+ it.each(['1H', '2m', '1y', '', undefined])('rejects %j', (input) => {+ expect(() => binanceInput.klineInterval({ value: input })).toThrow('is not valid');+ });+});diff --git a/packages/pieces/community/binance/vitest.config.ts b/packages/pieces/community/binance/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/binance/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})