Skip to main content

QuantScript Docs

Key Concepts

  • Indicators as pure functions: All technical indicators accept candle data as input and return calculated series

  • Series indexing: Series use reverse indexing where [0] is the most recent value, [1] is previous, etc.

  • Cross helpers: Use TA.CrossAbove() and TA.CrossBelow() to detect crossovers between series or values

  • Tuple unpacking: Multi-value indicators like MACD return tuples that can be unpacked


Market

Market data and price information.

Market.Ticker

Returns full ticker data including bid, ask, last, volume.

Parameters:

  • symbol (string): Trading pair symbol

Returns: Ticker object with attributes:

  • symbol (string)

  • bid (Decimal)

  • ask (Decimal)

  • last (Decimal)

  • quote_volume (Decimal)

Example:

ticker = Market.Ticker(symbol="BTC/USDT") 
spread = ticker.ask - ticker.bid


Market.Candles

Returns historical candlestick data.

Parameters:

  • timeframe (string): Timeframe - 1m, 5m, 15m, 30m, 1h, 4h, 1d

  • symbol (string): Trading pair symbol

  • limit (int, optional): Number of candles (default: 100, max: 1000)

Returns: CandleSeries object with series attributes:

  • opens (DecimalSeries)

  • highs (DecimalSeries)

  • lows (DecimalSeries)

  • closes (DecimalSeries)

All series use reverse indexing: [0] = most recent, [1] = previous, etc.

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT")  

# Access current candle
current_close = candles.closes[0]
previous_close = candles.closes[1]

# Use with indicators
rsi = TA.RSI(candles, length=14)


Orders

Order placement and management.

Orders.Buy

Places a buy order on the exchange.

Parameters:

  • symbol (string): Trading pair symbol (e.g., "BTC/USDT")

  • quantity (Decimal): Order quantity in base currency

  • type (string): Order type - "MARKET" or "LIMIT"

  • price (Decimal, optional): Limit price (required for LIMIT orders, ignored for MARKET)

  • time_in_force (string, optional): Time in force policy - "GTC" (Good Till Cancel), "IOC" (Immediate or Cancel), "FOK" (Fill or Kill). Default: "GTC"

  • post_only (bool, optional): For LIMIT orders only - if True, ensures the order will only be placed if it doesn't immediately match (post to order book). If the order would immediately match, it will be rejected instead. Default: False

Returns: Order object (see Data Types section for all attributes)

Example:

# Market buy order 
order = Orders.Buy(
symbol="BTC/USDT",
quantity=Decimal("0.1"),
type="MARKET"
)

# Limit buy order with custom TIF
order = Orders.Buy(
symbol="BTC/USDT",
quantity=Decimal("0.1"),
type="LIMIT",
price=Decimal("50000.00"),
time_in_force="GTC"
)

# Post-only limit order (rejected if would immediately match)
order = Orders.Buy(
symbol="BTC/USDT",
quantity=Decimal("0.1"),
type="LIMIT",
price=Decimal("50000.00"),
post_only=True
)

# Save order ID to state for later tracking
State["last_buy_order_id"] = order.id


Orders.Sell

Places a sell order on the exchange.

Parameters:

  • symbol (string): Trading pair symbol (e.g., "BTC/USDT")

  • quantity (Decimal): Order quantity in base currency

  • type (string): Order type - "MARKET" or "LIMIT"

  • price (Decimal, optional): Limit price (required for LIMIT orders, ignored for MARKET)

  • time_in_force (string, optional): Time in force policy - "GTC", "IOC", "FOK". Default: "GTC"

  • post_only (bool, optional): For LIMIT orders only - if True, ensures the order will only be placed if it doesn't immediately match (post to order book). If the order would immediately match, it will be rejected instead. Default: False

Returns: Order object (see Data Types section for all attributes)

Example:

# Market sell order 
order = Orders.Sell(
symbol="BTC/USDT",
quantity=Decimal("0.1"),
type="MARKET"
)

# Limit sell order
order = Orders.Sell(
symbol="BTC/USDT",
quantity=Decimal("0.1"),
type="LIMIT",
price=Decimal("52000.00")
)

# Check order status immediately
if order.status == "PLACED":
State["active_sell_order"] = order.id


Orders.Cancel

Cancels a single order by ID.

Parameters:

  • order_id (string): Order identifier to cancel

Returns: Order object with updated status (typically "CANCELED")

Example:

# Cancel a tracked order 
if State["stop_loss_order_id"] != None:
canceled_order = Orders.Cancel(State["stop_loss_order_id"])
State["stop_loss_order_id"] = None


Orders.CancelAll

Cancels all open orders created by this strategy, optionally filtered by symbol.

Parameters:

  • symbol (string, optional): Trading pair symbol to filter by. If None, cancels all open orders created by this strategy across all symbols. Default: None

Returns: List of Order objects representing canceled orders

Example:

# Stop loss - cancel all pending orders before emergency exit 
if stop_loss_triggered:
Orders.CancelAll(symbol="BTC/USDT")
Orders.Sell(symbol="BTC/USDT", quantity=position_size, type="MARKET")


Orders.Get

Retrieves a single order by ID.

Parameters:

  • order_id (string): Internal order identifier

Returns: Order object

Example:

# Retrieve order to check current status 
order_id = State["pending_order_id"]
order = Orders.Get(order_id)

if order.status == "FILLED":
profit = (order.avg_price - State["entry_price"]) * order.executed_quantity
State["pending_order_id"] = None


Orders.GetAllOpen

Retrieves all open orders (NEW, PLACED, PARTIALLY_FILLED) created by this strategy, optionally filtered by symbol.

Parameters:

  • symbol (string, optional): Trading pair symbol to filter by. If None, returns all open orders created by this strategy across all symbols. Default: None

Returns: List of Order objects, sorted by created_at descending (most recently created first)

Example:

# Get all open orders for a symbol open_orders = Orders.GetAllOpen(symbol="BTC/USDT")  

# Check if we have any pending orders before placing new ones
if len(open_orders) == 0:
# No open orders, safe to place new order
order = Orders.Buy(
symbol="BTC/USDT",
quantity=Decimal("0.1"),
type="LIMIT",
price=Decimal("50000.00")
)

# Cancel partially filled orders
for order in open_orders:
if order.status == "PARTIALLY_FILLED":
Orders.Cancel(order.id)


Orders.GetAllFinished

Retrieves all finished orders (FILLED, CANCELED, REJECTED, EXPIRED) created by this strategy, optionally filtered by symbol.

Important: Returns maximum 500 most recent finished orders.

Parameters:

  • symbol (string, optional): Trading pair symbol to filter by. If None, returns all finished orders created by this strategy across all symbols. Default: None

Returns: List of Order objects, sorted by finished_at descending (most recently finished first). Maximum 500 orders.

Example:

# Get all finished orders for analysis 
finished_orders = Orders.GetAllFinished(symbol="BTC/USDT")

# Calculate total executed volume
total_volume = Decimal("0")
for order in finished_orders:
if order.status == "FILLED":
total_volume = total_volume + order.executed_volume

# Count rejected orders
rejected_count = 0
for order in finished_orders:
if order.status == "REJECTED":
rejected_count = rejected_count + 1


TA (Technical Analysis)

Technical indicators for market analysis. All indicators accept candle data as the first parameter and return DecimalSeries (or tuples of series for multi-value indicators).

TA.SMA

Simple Moving Average - arithmetic mean of prices over a period.

Parameters:

  • candles (CandleSeries): Candlestick data

  • length (int): Period length

Returns: DecimalSeries - SMA values

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
sma_50 = TA.SMA(candles, length=50)
sma_200 = TA.SMA(candles, length=200)

# Golden cross detection
if TA.CrossAbove(sma_50, sma_200):
# Buy signal
pass


TA.EMA

Exponential Moving Average - trend-following indicator giving more weight to recent prices.

Parameters:

  • candles (CandleSeries): Candlestick data

  • length (int): Period length (e.g., 12, 26, 50, 200)

Returns: DecimalSeries - EMA values

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
ema_fast = TA.EMA(candles, length=12)
ema_slow = TA.EMA(candles, length=26)

if TA.CrossAbove(ema_fast, ema_slow):
# Bullish EMA cross
pass

if TA.CrossBelow(ema_fast, ema_slow):
# Bearish EMA cross
pass


TA.RSI

Relative Strength Index - measures momentum and identifies overbought/oversold conditions.

Parameters:

  • candles (CandleSeries): Candlestick data

  • length (int): Period length (default: 14)

Returns: DecimalSeries - RSI values (0-100)

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
rsi = TA.RSI(candles, length=14)

oversold = Decimal("30")
overbought = Decimal("70")

if rsi[0] < oversold:
# RSI oversold
pass

if TA.CrossAbove(rsi, oversold):
# RSI crossed above 30 - potential buy signal
pass


TA.MACD

Moving Average Convergence Divergence - shows relationship between two moving averages.

Parameters:

  • candles (CandleSeries): Candlestick data

  • fast (int, optional): Fast EMA period (default: 12)

  • slow (int, optional): Slow EMA period (default: 26)

  • signal (int, optional): Signal line period (default: 9)

Returns: Tuple of three DecimalSeries:

  • macd_line - MACD line (fast EMA - slow EMA)

  • signal_line - Signal line (EMA of MACD line)

  • histogram - Histogram (MACD - Signal)

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
macd_line, signal, histogram = TA.MACD(candles, fast=12, slow=26, signal=9)

zero = Decimal("0")

if TA.CrossAbove(macd_line, signal):
# MACD bullish cross
pass

if TA.CrossAbove(histogram, zero):
# Histogram turned positive
pass


TA.ATR

Average True Range - measures market volatility.

Parameters:

  • candles (CandleSeries): Candlestick data

  • length (int): Period length (default: 14)

Returns: DecimalSeries - ATR values

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
atr = TA.ATR(candles, length=14)

# Use ATR for stop-loss calculation
stop_distance = atr[0] * Decimal("2")


TA.ADX

Average Directional Index - measures trend strength.

Parameters:

  • candles (CandleSeries): Candlestick data

  • length (int): Period length (default: 14)

Returns: DecimalSeries - ADX values (0-100 scale, higher = stronger trend)

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
adx = TA.ADX(candles, length=14)

strong_trend = Decimal("25")

if adx[0] > strong_trend:
# Strong trend detected
pass


TA.BollingerBands

Bollinger Bands - volatility bands around a moving average.

Parameters:

  • candles (CandleSeries): Candlestick data

  • length (int): Period length (default: 20)

  • stddev (float, optional): Standard deviation multiplier (default: 2.0)

Returns: Tuple of three DecimalSeries:

  • lower - Lower band

  • middle - Middle band (SMA)

  • upper - Upper band

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
lower, middle, upper = TA.BollingerBands(candles, length=20, stddev=2.0)

# Check if price touches lower band
if candles.closes[0] <= lower[0]:
# Price at lower band - potential bounce
pass


TA.Stochastic

Stochastic Oscillator - momentum indicator comparing closing price to price range.

Parameters:

  • candles (CandleSeries): Candlestick data

  • k_period (int): %K period

  • k_smoothing (int, optional): %K smoothing period (default: 1).

  • d_period (int, optional): %D period (SMA of %K). Default: 1.

Returns: Tuple of two DecimalSeries - (%K, %D)

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
stoch_k, stoch_d = TA.Stochastic(candles, k_period=14, k_smoothing=3, d_period=3)

oversold = Decimal("20")
overbought = Decimal("80")

if stoch_k[0] < oversold and TA.CrossAbove(stoch_k, stoch_d):
# Bullish crossover in oversold zone
pass


TA.VWAP

Volume Weighted Average Price - average price weighted by volume.

Parameters:

  • candles (CandleSeries): Candlestick data

Returns: DecimalSeries - VWAP values

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
vwap = TA.VWAP(candles)

if candles.closes[0] > vwap[0]:
# Price above VWAP - bullish
pass


TA.SAR

Parabolic SAR (Stop and Reverse) - identifies potential reversal points.

Parameters:

  • candles (CandleSeries): Candlestick data

  • acceleration (float, optional): Acceleration factor (default: 0.02)

  • maximum (float, optional): Maximum acceleration (default: 0.2)

Returns: DecimalSeries - SAR values

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
sar = TA.SAR(candles, acceleration=0.02, maximum=0.2)

# SAR below price = uptrend, SAR above price = downtrend
if candles.closes[0] > sar[0]:
# Uptrend
pass

if TA.CrossAbove(candles.closes, sar):
# Bullish reversal
pass

if TA.CrossBelow(candles.closes, sar):
# Bearish reversal
pass


TA.CrossAbove

Helper function to detect when a series crosses above another series or value.

Parameters:

  • series (DecimalSeries): The series to check

  • target (DecimalSeries | Decimal | int | float): Value or series to compare against

Returns: bool - True if series[1] <= target[1] and series[0] > target[0]

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
rsi = TA.RSI(candles, length=14)
ema_fast = TA.EMA(candles, length=12)
ema_slow = TA.EMA(candles, length=26)

# Cross above constant value
if TA.CrossAbove(rsi, Decimal("30")):
# RSI crossed above 30
pass

# Cross between two series
if TA.CrossAbove(ema_fast, ema_slow):
# Fast EMA crossed above slow EMA
pass

# Price crosses indicator
if TA.CrossAbove(candles.closes, ema_slow):
# Price broke above EMA
pass


TA.CrossBelow

Helper function to detect when a series crosses below another series or value.

Parameters:

  • series (DecimalSeries): The series to check

  • target (DecimalSeries | Decimal | int | float): Value or series to compare against

Returns: bool - True if series[1] >= target[1] and series[0] < target[0]

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
rsi = TA.RSI(candles, length=14)

if TA.CrossBelow(rsi, Decimal("70")):
# RSI crossed below 70
pass

if TA.CrossBelow(candles.closes, TA.EMA(candles, length=50)):
# Price broke below EMA
pass


State

Persistent mutable dictionary that persists between Run() executions. Use it to maintain strategy state like position tracking, counters, or previous values.

Behavior:

  • Reading non-existent key returns None

  • Setting key to None deletes the key

  • Maximum 1000 keys

Example:

# Initialize state on first run 
if State["position"] == None:
State["position"] = 0
State["entry_price"] = Decimal("0")
State["run_count"] = 0

State["run_count"] = State["run_count"] + 1

# Store position entry
if buy_signal:
State["position"] = 1
State["entry_price"] = current_price

# Check state
if State["position"] == 1:
profit = (current_price - State["entry_price"]) / State["entry_price"]

# Delete a key State["entry_price"] = None

# Clear all state when needed
State.Clear()


Data Types

Order

Order object returned by order placement and management functions.

Attributes:

  • id (string) - Internal order identifier

  • symbol (string) - Trading pair symbol (e.g., "BTC/USDT")

  • side (string) - Order side: "BUY" or "SELL"

  • status (string) - Order status: "NEW", "PLACED", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED", "EXPIRED"

  • type (string) - Order type: "MARKET" or "LIMIT"

  • time_in_force (string) - Time in force: "GTC", "IOC", "FOK"

  • post_only (bool) - For LIMIT orders - whether this order is post-only (rejected if would immediately match)

  • order_price (Decimal) - Limit price for the order

  • quantity (Decimal) - Order quantity in base currency

  • volume (Decimal) - Order volume in quote currency

  • executed_quantity (Decimal) - Executed quantity in base currency

  • executed_volume (Decimal) - Executed volume in quote currency

  • avg_price (Decimal) - Average execution price

  • fees (list[Fee]) - Trading fees charged for this order

  • error_code (string) - Error code if order was rejected or failed

  • error_message (string) - Error message if order was rejected or failed

  • created_at (datetime) - Order creation timestamp

  • updated_at (datetime) - Order last update timestamp

  • finished_at (datetime) - Order completion timestamp (filled, canceled, rejected, or expired)

Example:

order = Orders.Buy(     
symbol="BTC/USDT",
quantity=Decimal("0.1"),
type="LIMIT",
price=Decimal("50000.00") )

# Access order attributes
if order.status == "PLACED":
State["order_id"] = order.id
State["order_price"] = order.order_price

# Check execution
later_order = Orders.Get(order.id)
if later_order.status == "FILLED":
fill_price = later_order.avg_price
total_fees = Decimal("0")
for fee in later_order.fees:
total_fees = total_fees + fee.amount


Fee

Fee object representing trading fees charged.

Attributes:

  • currency (string) - Currency in which the fee was charged (e.g., "USDT")

  • amount (Decimal) - Fee amount

Example:

order = Orders.Get(order_id) 
for fee in order.fees:
# Process each fee
if fee.currency == "USDT":
State["total_usdt_fees"] = State["total_usdt_fees"] + fee.amount


Decimal

High-precision decimal type for financial calculations. Avoids floating-point errors.

Constructor:

Decimal(value)  # value can be string, int, or float

Methods:

  • d.String() - Convert to string

  • d.Float() - Convert to float

  • d.Int() - Get integer part

  • d.Abs() - Absolute value

  • d.Round(places) - Round to N decimal places

  • d.Truncate(places) - Truncate to N decimal places

Operations:

  • Arithmetic: +, -, *, /, %, // (floor division)

  • Comparison: ==, !=, <, <=, >, >=

  • Unary: -d (negation)

Example:

price = Decimal("104500.50") 
quantity = Decimal("0.001")
total = price * quantity

# Round to 2 decimal places
total_rounded = total.Round(2)


Ticker

Ticker object returned by Market.Ticker().

Attributes:

  • symbol (string) - Trading pair symbol

  • bid (Decimal) - Best bid price

  • ask (Decimal) - Best ask price

  • last (Decimal) - Last trade price

  • quote_volume (Decimal) - 24h quote volume


Candle

Single candlestick object. Usually accessed through CandleSeries indexing.

Attributes:

  • symbol (string) - Trading pair symbol

  • timestamp (int) - Unix timestamp in milliseconds

  • open (Decimal) - Open price

  • high (Decimal) - High price

  • low (Decimal) - Low price

  • close (Decimal) - Close price

  • volume (Decimal) - Volume

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT") 
current_candle = candles[0]


CandleSeries

Series of candlesticks returned by Market.Candles(). Supports indexing and provides price series attributes.

Indexing:

  • candles[0] - Most recent Candle object

  • candles[1] - Previous Candle object

Attributes:

  • opens (DecimalSeries) - Open prices series

  • highs (DecimalSeries) - High prices series

  • lows (DecimalSeries) - Low prices series

  • closes (DecimalSeries) - Close prices series

Example:

candles = Market.Candles(timeframe="1h", symbol="BTC/USDT")  

# Access via attributes (recommended)
current_close = candles.closes[0]
previous_close = candles.closes[1]

# Access via indexing
current_candle = candles[0]
candle_close = current_candle.close


DecimalSeries

Series of Decimal values returned by technical indicators and candle attributes. Supports reverse indexing.

Indexing:

  • series[0] - Most recent value (Decimal)

  • series[1] - Previous value (Decimal)

  • series[n] - Value at index n

Example:

rsi = TA.RSI(candles, length=14) 
current_rsi = rsi[0]
previous_rsi = rsi[1]

if current_rsi > previous_rsi:
# RSI rising
pass
Did this answer your question?