Skip to content
Back to App

Python API Reference

This page documents every function available to your Python strategy code in the Algo Playground. These functions are defined in the auto-generated script header and are available in all templates and custom strategies.

api()

The generic API caller. All other functions use this internally. You can call any TopStep API endpoint directly.

def api(path, body=None)

Parameters:

ParameterTypeRequiredDescription
pathstrYesAPI endpoint path (e.g., "Order/place", "Account/search")
bodydict or NoneNoRequest body as a Python dictionary. Automatically serialized to JSON.

Returns: A Python dictionary parsed from the JSON response.

Error handling: On HTTP errors, returns {"success": False, "errorCode": <http_status>, "errorMessage": "<body>"}. On connection errors, returns {"success": False, "errorCode": -1, "errorMessage": "<error>"}. Errors are also printed to stderr with the [ERROR] prefix.

Examples:

# Search for active accounts
result = api("Account/search", {"onlyActiveAccounts": True})
accounts = result.get("accounts", [])
# Get trade history
trades = api("Trade/search", {
"accountId": ACCOUNT_ID,
"startDate": "2025-01-15"
})
# End a replay session
result = api("Replay/end", {"accountId": ACCOUNT_ID})

place_order()

Places a trading order. Supports market, limit, and stop orders.

def place_order(account_id, contract_id, side, size, order_type=2, limit_price=None, stop_price=None)

Parameters:

ParameterTypeRequiredDefaultDescription
account_idintYesThe account ID (use ACCOUNT_ID from session setup)
contract_idstrYesThe contract ID (use CONTRACT_ID from session setup)
sideintYes0 = Buy, 1 = Sell
sizeintYesNumber of contracts
order_typeintNo21 = Limit, 2 = Market, 4 = Stop
limit_pricefloat or NoneNoNoneRequired for limit orders (type 1)
stop_pricefloat or NoneNoNoneRequired for stop orders (type 4)

Returns: The API response dictionary from the Order/place endpoint.

Examples:

# Market buy 1 contract
place_order(ACCOUNT_ID, CONTRACT_ID, 0, 1)
# Market sell 2 contracts (e.g., close long + open short)
place_order(ACCOUNT_ID, CONTRACT_ID, 1, 2)
# Limit buy at 21500.00
place_order(ACCOUNT_ID, CONTRACT_ID, 0, 1, order_type=1, limit_price=21500.00)
# Stop sell at 21480.00 (stop-loss)
place_order(ACCOUNT_ID, CONTRACT_ID, 1, 1, order_type=4, stop_price=21480.00)

Side values

ValueMeaning
0Buy (go long or close short)
1Sell (go short or close long)

Order type values

ValueMeaningRequired price params
1Limit orderlimit_price
2Market orderNone
4Stop orderstop_price

get_positions()

Returns a list of currently open positions for the account.

def get_positions(account_id)

Parameters:

ParameterTypeRequiredDescription
account_idintYesThe account ID

Returns: A list of position dictionaries. Each position has:

FieldTypeDescription
typeint1 = Long, 2 = Short
sizeintNumber of contracts
averagePricefloatAverage entry price
contractIdstrContract identifier

Returns an empty list [] if there are no open positions.

Example:

positions = get_positions(ACCOUNT_ID)
for pos in positions:
direction = "LONG" if pos["type"] == 1 else "SHORT"
print(f"[INFO] Position: {direction} {pos['size']} @ {pos['averagePrice']}")
# Check if currently in a position
if len(get_positions(ACCOUNT_ID)) > 0:
print("[INFO] Have open positions")

close_all_positions()

Closes all open positions for the account by placing opposite-side market orders. Also known as “flattening.”

def close_all_positions(account_id, contract_id)

Parameters:

ParameterTypeRequiredDescription
account_idintYesThe account ID
contract_idstrYesThe contract ID

Returns: Nothing (implicitly returns None).

Behavior: Queries all open positions, then for each position places a market order on the opposite side with the same size. If there are no open positions, does nothing.

Example:

# Flatten before end of session
close_all_positions(ACCOUNT_ID, CONTRACT_ID)
print("[INFO] All positions closed")
# Use as an emergency exit
if some_risk_condition:
close_all_positions(ACCOUNT_ID, CONTRACT_ID)
position = None
print("[INFO] Emergency flatten — risk limit hit")

get_account()

Returns account information including balance and equity.

def get_account(account_id=None)

Parameters:

ParameterTypeRequiredDefaultDescription
account_idint or NoneNoNoneSpecific account ID to look up. If None, returns the first active account.

Returns: An account dictionary with fields including:

FieldTypeDescription
idintAccount ID
balancefloatCurrent account balance
namestrAccount name

Returns None if no matching account is found.

Example:

# Get current account info
account = get_account(ACCOUNT_ID)
if account:
balance = account.get("balance", 0)
print(f"[INFO] Current balance: ${balance:,.2f}")
# Check balance before placing a trade
account = get_account(ACCOUNT_ID)
if account and account.get("balance", 0) < 48000:
print("[INFO] Balance below $48,000 — stopping strategy")
break

read_speed()

Reads the current playback speed from the Playground UI. This allows the user to change the backtest speed while it is running.

def read_speed()

Parameters: None.

Returns: The current STEP_DELAY value (a float representing the delay in seconds between bars).

Behavior: Reads the speed value from a file on disk (specified by the SPEED_FILE environment variable). Updates the global STEP_DELAY variable. If the file does not exist or cannot be read, the current STEP_DELAY is left unchanged.

Example:

# Standard usage — call on every bar
for i in range(MAX_BARS):
bar = get_next_bar()
if bar is None:
break
read_speed() # Update STEP_DELAY from UI
if STEP_DELAY > 0:
time.sleep(STEP_DELAY) # Pause between bars
# ... strategy logic ...

get_next_bar()

Returns the next OHLCV bar from the replay session. This is how your strategy receives market data.

def get_next_bar()

Parameters: None.

Returns: A bar dictionary (see Bar Data Format), or None if there are no more bars available or the end date has been reached.

Behavior: Calls the Replay/step API endpoint to advance the replay by one bar. If the end date is set and the bar’s timestamp exceeds it, returns None.

Example:

bar = get_next_bar()
if bar is None:
print("[INFO] No more bars available")
break
# Access bar fields
timestamp = bar["t"] # "2025-01-15T14:30:00Z"
open_price = bar["o"] # 21500.25
high_price = bar["h"] # 21505.50
low_price = bar["l"] # 21498.75
close_price = bar["c"] # 21503.00
volume = bar["v"] # 150

Function reference summary

FunctionPurposeReturns
api(path, body)Call any API endpointResponse dict
place_order(acct, contract, side, size, ...)Place a tradeResponse dict
get_positions(acct)Get open positionsList of position dicts
close_all_positions(acct, contract)Flatten all positionsNone
get_account(acct)Get account infoAccount dict or None
read_speed()Read UI speed settingCurrent STEP_DELAY float
get_next_bar()Get next market data barBar dict or None

Global variables available

In addition to the functions above, your strategy has access to these global variables set up by the auto-generated sections:

VariableTypeDescription
API_URLstrBase URL for API calls
TOKENstrAuthentication token
INSTRUMENTstrInstrument symbol (e.g., "NQ")
START_DATEstrBacktest start date
END_DATEstrBacktest end date
TIMEFRAMEstrBar timeframe (e.g., "1m")
STEP_DELAYfloatCurrent delay between bars (updated by read_speed())
ACCOUNT_IDintActive account ID
CONTRACT_IDstrActive contract ID
TOTAL_BARSintTotal bars in the session
MAX_BARSintMaximum bars to process (set by your strategy)