Provides context and instructions for working with the Finam (Финам) broker Trade API: algorithmic trading strategies, order placement, real-time quotes via gRPC/WebSocket, OHLCV candles, backtesting on Russian equities, and portfolio analysis.
Ships in finam. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
To execute Trade API requests, the skill needs one credential:
TRADE_API_SECRET — API token. Get it at api.finam.ru/docs/tokensYou can use this skill without it — to design strategies, explore docs, or write scripts.
The secret comes from the environment if the user exported it, otherwise from a .env file in the project root (your working directory). Most users only paste the token into .env — they don't need to know any shell.
Every shell call starts a fresh shell, and the JWT expires after 15 minutes, so start every shell call that talks to the API with this auth prefix and append your command after the last && \:
export TRADE_API_SECRET="${TRADE_API_SECRET:-$(sed -n 's/^TRADE_API_SECRET=//p' .env 2>/dev/null | tr -d "\r\"' ")}" ACCOUNT_ID="${ACCOUNT_ID:-$(sed -n 's/^ACCOUNT_ID=//p' .env 2>/dev/null | tr -d "\r\"' ")}" && \
{ [ -n "$TRADE_API_SECRET" ] || { echo "❌ TRADE_API_SECRET is not set"; false; }; } && \
TOKEN=$(curl -sL "https://api.finam.ru/v1/sessions" \
--header "Content-Type: application/json" \
--data '{"secret": "'"$TRADE_API_SECRET"'"}' | jq -r '.token') && \
curl -sL "https://api.finam.ru/v1/..." --header "Authorization: $TOKEN" | jq
What it does:
TRADE_API_SECRET and ACCOUNT_ID from ./.env. The file is parsed, not executed (unlike source), and nothing is printed, so the value never shows up in the conversation. export lets Python scripts and SDK snippets started in the same call see it.$TOKEN.Shell examples in this skill are POSIX (bash/zsh). On Windows, run them via Git Bash or WSL; if your shell is PowerShell, call bash -c '...' or translate the command — a PowerShell error here doesn't mean the secret is missing.
The examples below show only the part that goes after the prefix.
Scripts and SDK code — bundled scripts/*.py, code you write, official strategies — read TRADE_API_SECRET only from the environment. Run them after the first two lines of the prefix (load and check); the SDK gets the JWT on its own. The scripts/... paths in the examples are relative to the skill directory (where this SKILL.md lives) — run them from the project root by full path, e.g. python3 "<skill dir>/scripts/scanner.py" ru 10, so the prefix finds the project's ./.env. Don't cd into the skill directory.
When you hand the user a command to run a script themselves, include loading .env in it: uv run --env-file .env python main.py ... for uv projects (all official strategies), otherwise set -a && source .env && set +a && python3 script.py. Don't ask them to export the token by hand.
Set up .env for the user rather than asking them to type shell commands:
./.env doesn't exist, copy the template that ships with this skill (.env.example next to this SKILL.md): cp "<skill dir>/.env.example" .env. If you can't locate the skill directory, create .env with the same content yourself — a comment with the tokens page link, an empty TRADE_API_SECRET= line and a commented-out # ACCOUNT_ID=. Never write a real token into it..env is ignored so the token never gets committed:
git rev-parse --is-inside-work-tree >/dev/null 2>&1 && { grep -qxF '.env' .gitignore 2>/dev/null || echo '.env' >> .gitignore; }
.env, ask them to open it in any text editor, paste the token right after TRADE_API_SECRET= (no quotes or spaces), save, and let you know. Mention where to get a token (tokens page) and that a 2-week demo account is available there.If .env already exists but the prefix still reports ❌, skip to step 3 — the key is probably empty or misspelled.
Users who prefer not to keep a file can export the variable in their own terminal before launching the agent (export TRADE_API_SECRET=...), or in Claude Code put it into .claude/settings.local.json as { "env": { "TRADE_API_SECRET": "..." } }. An exported value takes priority over .env.
Handling the secret — the token gives full trading access to the user's account, and anything that appears in the conversation is stored in the session history:
export TRADE_API_SECRET=... with the value on their behalf.echo $TRADE_API_SECRET, env, printenv, no cat/Read of .env or .claude/settings.local.json. Get the value only through the auth prefix.Account-scoped requests (portfolio, orders, account-specific asset fields) need an ACCOUNT_ID. Resolve it once per session — the token itself knows which accounts it can access. After the auth prefix:
DETAILS=$(curl -sL "https://api.finam.ru/v1/sessions/details" \
--header "Content-Type: application/json" \
--data '{"token": "'"$TOKEN"'"}') && \
ACCOUNT_ID="${ACCOUNT_ID:-$(echo "$DETAILS" | jq -r 'if (.account_ids | length) == 1 then .account_ids[0] else empty end')}" && \
echo "ACCOUNT_ID=${ACCOUNT_ID:-❌ could not resolve automatically}"
ACCOUNT_ID is already set in the environment or in .env (picked up by the auth prefix), it wins — treat it as an explicit override (useful when the token exposes several accounts and the user always wants the same one). Most users never need to set it.ACCOUNT_ID resolves automatically from /v1/sessions/details — no setup step required.printf '%s\n' "$DETAILS" | jq -r '.account_ids' and ask the user which account to use for this session before making any account-scoped request — don't guess which one.$ACCOUNT_ID in every request below. Like $TOKEN, it lives only within one shell call — once resolved, put the value into later calls yourself (ACCOUNT_ID=... && ... after the prefix).Demo account: Can be opened at the tokens page. Valid for 2 weeks; works identically to a real account.
Rate limits: 200 requests/min per method by default (some methods are lower) — see Rate Limits.
Maintenance window: 05:00–06:15 MSK daily — API may be unavailable.
Quotas are counted per method, per user, in a 1-minute window. Defaults:
| Method | Limit |
|---|---|
Every method (including gRPC streams and /v1/usage itself) | 200 requests/min |
ReportsService.createAccountReport | 3 requests/min |
Defaults can change and may be raised for a specific user — the live numbers come from GET /v1/usage, so check it rather than relying on this table when it matters.
curl -sL "https://api.finam.ru/v1/usage" --header "Authorization: $TOKEN" \
| jq -r '.quotas | sort_by(.name)[] | [.name, .limit, .remaining, (.reset_time // "-")] | @tsv' | column -t
Each entry in quotas:
name — Service.method, e.g. MarketDataService.bars, OrdersService.placeOrderlimit — quota size for the window (int64, serialized as a string in REST JSON)remaining — requests left in the current windowreset_time — when the current window resets (RFC 3339, UTC). Present only for methods already called in the current window; absent means the full limit is available.Python SDK: client.metrics.GetUsageMetrics(GetUsageMetricsRequest()) (from finam_trade_api.metrics import GetUsageMetricsRequest).
429 / gRPC RESOURCE_EXHAUSTED (RateLimitError in the SDK). Don't retry in a tight loop — wait until reset_time for that method. The SDK does not auto-retry 429 unless the server sends a retry pushback.MarketDataService.bars hardest: throttle to under 200 calls/min (e.g. time.sleep(0.3) between calls) or check remaining before a large batch.subscribeQuote, subscribeOrderBook, …) over polling lastQuote / orderBook — opening a stream is one call that keeps delivering updates, while every poll spends quota.Limits can't be changed through the API. If the user needs more (e.g. a bot regularly hits 429), point them to the request form: open api.finam.ru/docs/rest/#introduction, click «Увеличить лимиты API» and fill in the form. The user submits it themselves — don't fill it in on their behalf.
Raised limits are bound to an application ID, not to the secret alone. The ID (source_app_id) is issued to the user once the request is approved — the user can't make one up, so if they don't have it yet, the request is still pending. Every token request must carry source_app_id, otherwise the session gets the default quotas. Keep the ID in an env var (e.g. SOURCE_APP_ID) and pass it when exchanging the secret for a JWT — use this instead of the TOKEN= step of the auth prefix:
TOKEN=$(curl -sL "https://api.finam.ru/v1/sessions" \
--header "Content-Type: application/json" \
--data "$(jq -n --arg s "$TRADE_API_SECRET" --arg a "$SOURCE_APP_ID" '{secret: $s, source_app_id: $a}')" \
| jq -r '.token')
The same field exists on gRPC AuthRequest and SubscribeJwtRenewalRequest. FinamClient / AsyncFinamClient currently send only secret, so a script that needs the raised limits must obtain the token via REST (as above) or call AuthService.Auth itself with source_app_id set.
After approval, fetch a token with source_app_id and verify the new numbers with GET /v1/usage.
Symbol Format: All symbols must be in ticker@mic format (e.g., SBER@MISX)
Base MIC Codes:
MISX - Moscow Exchange (all markets)RTSX - Moscow Exchange, Derivatives Market (futures & options)XNYS - New York Stock ExchangeARCX - NYSE Arca (ETFs)XNGS - NASDAQ/NGS (Global Select Market)XNMS - NASDAQ/NNS (Global Market)XNCM - NASDAQ Capital MarketView all supported exchanges with their MIC codes:
curl -sL "https://api.finam.ru/v1/exchanges" --header "Authorization: $TOKEN" | \
jq -r '.exchanges[] | "\(.mic) - \(.name)"'
Fetch detailed specification for a specific instrument (lot size, price step, decimals, trading schedule, etc.):
SYMBOL="SBER@MISX"
curl -sL "https://api.finam.ru/v1/assets/$SYMBOL?account_id=$ACCOUNT_ID" \
--header "Authorization: $TOKEN" | jq
account_id is optional but recommended — returns account-specific fields (margin, available quantity, etc.).
Search instruments by ticker glob pattern and/or name substring:
# By ticker glob
python3 scripts/asset_search.py 'SBER*'
# By name (case-insensitive substring)
python3 scripts/asset_search.py --name 'apple'
# By ticker glob + type + exchange filter
python3 scripts/asset_search.py 'NG*' --type FUTURES --mic RTSX
# Search expired/archived instruments (e.g. expired futures contracts)
python3 scripts/asset_search.py 'NGF6' --type FUTURES --mic RTSX --archived
# By name + exchange + archived
python3 scripts/asset_search.py --name 'NG-' --type FUTURES --mic RTSX --archived
Available types: EQUITIES, FUTURES, BONDS, FUNDS, SPREADS, OTHER, CURRENCIES, OPTIONS, SWAPS, INDICES
--mic MIC filters by exchange (e.g. RTSX, MISX). --archived fetches expired/delisted instruments via GET /v1/assets/all?only_disabled=true. --max=N sets the pagination cap (default: 200 000).
Fetch current index components — IMOEX for RU market, NDX for US market:
# Table output (default)
python3 scripts/top_stocks.py ru
python3 scripts/top_stocks.py us
# First N entries
python3 scripts/top_stocks.py ru --n 10
# JSON output (for piping to other tools)
python3 scripts/top_stocks.py ru --json
Retrieve portfolio information including positions, balances, and P&L:
curl -sL "https://api.finam.ru/v1/accounts/$ACCOUNT_ID" \
--header "Authorization: $TOKEN" | jq
Retrieve current bid/ask prices and last trade:
SYMBOL="SBER@MISX"
curl -sL "https://api.finam.ru/v1/instruments/$SYMBOL/quotes/latest" \
--header "Authorization: $TOKEN" | jq
View current market depth with bid/ask levels:
SYMBOL="SBER@MISX"
curl -sL "https://api.finam.ru/v1/instruments/$SYMBOL/orderbook" \
--header "Authorization: $TOKEN" | jq
List the most recent executed trades:
SYMBOL="SBER@MISX"
curl -sL "https://api.finam.ru/v1/instruments/$SYMBOL/trades/latest" \
--header "Authorization: $TOKEN" | jq
Retrieve historical price data with specified timeframe:
SYMBOL="SBER@MISX"
TIMEFRAME="TIME_FRAME_D"
START_TIME="2024-01-01T00:00:00Z"
END_TIME="2024-04-01T00:00:00Z"
curl -sL "https://api.finam.ru/v1/instruments/$SYMBOL/bars?timeframe=$TIMEFRAME&interval.start_time=$START_TIME&interval.end_time=$END_TIME" \
--header "Authorization: $TOKEN" | jq
Available Timeframes:
| Timeframe | Description | Max data depth (end_time - start_time) |
|---|---|---|
TIME_FRAME_UNSPECIFIED | Not specified | — |
TIME_FRAME_M1 | 1 minute | 7 days |
TIME_FRAME_M5 | 5 minutes | 30 days |
TIME_FRAME_M15 | 15 minutes | 30 days |
TIME_FRAME_M30 | 30 minutes | 30 days |
TIME_FRAME_H1 | 1 hour | 30 days |
TIME_FRAME_H2 | 2 hours | 30 days |
TIME_FRAME_H4 | 4 hours | 30 days |
TIME_FRAME_H8 | 8 hours | 30 days |
TIME_FRAME_D | Day | 365 days |
TIME_FRAME_W | Week | ~5 years |
TIME_FRAME_MN | Month | ~5 years |
TIME_FRAME_QR | Quarter | ~5 years |
Note: The max data depth is the maximum allowed range for
end_time - start_time. If the range exceeds the limit, the API returns empty data.
Date Format (RFC 3339):
YYYY-MM-DDTHH:MM:SSZ or YYYY-MM-DDTHH:MM:SS+HH:MMstart_time - Inclusive (interval start, included in results)end_time - Exclusive (interval end, NOT included in results)2024-01-15T10:30:00Z (UTC)2024-01-15T10:30:00+03:00 (Moscow time, UTC+3)News is served by the Trade API NewsService (proto/grpc/tradeapi/v1/news/) and
needs the same JWT as every other call. Do not scrape RSS feeds or web pages for
news. In the Python SDK use client.news with message types from
finam_trade_api.news; in Node use api.news with types from
@finam/trade-api/news.
| RPC | REST | Purpose |
|---|---|---|
GetNewsHistory | GET /v1/news/history | Page of news in a time range (time_range is required; page_size 1..100, 0 = default 50; paginate with cursor/next_cursor) |
GetNews | GET /v1/news/{news_id} | One news item by its public id |
GetNewsSources | GET /v1/news/sources | Available news sources |
SubscribeNews | gRPC stream only | Live stream of new and updated items, filtered by symbols / sources |
import os
from datetime import datetime, timedelta, timezone
from finam_trade_api import FinamClient
from finam_trade_api.news import GetNewsHistoryRequest, NewsFilter
with FinamClient(secret=os.environ["TRADE_API_SECRET"]) as client:
end = datetime.now(timezone.utc)
req = GetNewsHistoryRequest(filter=NewsFilter(symbols=["SBER@MISX"]), page_size=20)
req.time_range.to.FromDatetime(end)
getattr(req.time_range, "from").FromDatetime(end - timedelta(days=1))
for item in client.news.GetNewsHistory(req).items:
print(f"{item.published_at.ToDatetime():%Y-%m-%d %H:%M} [{item.source}] {item.title}")
news.* requires finam-sdk / @finam/trade-api newer than 2.24.0. With older
SDKs call the REST endpoints above with the JWT.
IMPORTANT: Before placing or cancelling any order, you MUST explicitly confirm the details with the user and receive their approval. State the full order parameters (symbol, side, quantity, type, price) and wait for confirmation before executing.
Order Types:
ORDER_TYPE_MARKET - Market order (executes immediately, no limit_price required)ORDER_TYPE_LIMIT - Limit order (requires limit_price)curl -sL "https://api.finam.ru/v1/accounts/$ACCOUNT_ID/orders" \
--header "Authorization: $TOKEN" \
--header "Content-Type: application/json" \
--data "$(jq -n \
--arg symbol "SBER@MISX" \
--arg quantity "10" \
--arg side "SIDE_BUY" \
--arg type "ORDER_TYPE_LIMIT" \
--arg price "310.50" \
'{symbol: $symbol, quantity: {value: $quantity}, side: $side, type: $type, limit_price: {value: $price}}')" \
| jq
Parameters:
symbol - Instrument (e.g., SBER@MISX)quantity.value - Number of shares/contractsside - SIDE_BUY or SIDE_SELLtype - ORDER_TYPE_MARKET or ORDER_TYPE_LIMITlimit_price - Only for ORDER_TYPE_LIMIT (omit for market orders)Check the status of a specific order:
ORDER_ID="12345678"
curl -sL "https://api.finam.ru/v1/accounts/$ACCOUNT_ID/orders/$ORDER_ID" \
--header "Authorization: $TOKEN" | jq
Cancel a pending order:
ORDER_ID="12345678"
curl -sL --request DELETE "https://api.finam.ru/v1/accounts/$ACCOUNT_ID/orders/$ORDER_ID" \
--header "Authorization: $TOKEN" | jq
Every algo strategy follows the same loop:
For one-off runs use FinamClient (sync). For continuous bots, use AsyncFinamClient with a reconnection loop (see Python SDK section).
Buy if the stock grew over the last N days and you hold no position; sell only an existing long position when it fell. Like the strategies in examples/strategies/, the template is a dry run unless TRADE_API_EXECUTE=1, and it never sells what the account does not hold (a SELL without a position would open a short):
import os
from datetime import datetime, timedelta, timezone
from google.type.decimal_pb2 import Decimal
from decimal import Decimal as D
from uuid import uuid4
from finam_trade_api import FinamClient
from finam_trade_api.accounts import GetAccountRequest
from finam_trade_api.auth_messages import TokenDetailsRequest
from finam_trade_api.market_data import BarsRequest, TimeFrame
from finam_trade_api.orders import Order, OrderType, Side, TimeInForce
SYMBOLS = ["SBER@MISX", "GAZP@MISX", "LKOH@MISX"]
LOOKBACK_DAYS = 30
QUANTITY = D("1")
EXECUTE = os.environ.get("TRADE_API_EXECUTE") == "1" # confirm with the user first
def get_growth(client, symbol, days):
end = datetime.now(timezone.utc)
start = end - timedelta(days=days)
req = BarsRequest(symbol=symbol, timeframe=TimeFrame.TIME_FRAME_D)
req.interval.start_time.FromDatetime(start)
req.interval.end_time.FromDatetime(end)
bars = list(client.market_data.Bars(req).bars)
if len(bars) < 2:
return None
first, last = float(bars[0].close.value), float(bars[-1].close.value)
return (last - first) / first * 100
def held_quantity(client, account_id, symbol) -> D:
account = client.accounts.GetAccount(GetAccountRequest(account_id=account_id))
match = next((p for p in account.positions if p.symbol == symbol), None)
return D(match.quantity.value) if match else D(0)
def resolve_account_id(client) -> str:
if account_id := os.environ.get("ACCOUNT_ID"):
return account_id
details = client.auth.TokenDetails(TokenDetailsRequest(token=client.get_token()))
if len(details.account_ids) == 1:
return details.account_ids[0]
raise RuntimeError(
f"Token exposes {len(details.account_ids)} accounts {list(details.account_ids)}; "
"ask the user which one to use, or set ACCOUNT_ID to pin one"
)
with FinamClient(secret=os.environ["TRADE_API_SECRET"]) as client:
account_id = resolve_account_id(client)
for symbol in SYMBOLS:
growth = get_growth(client, symbol, LOOKBACK_DAYS)
if growth is None:
print(f"{symbol}: not enough data, skipping")
continue
held = held_quantity(client, account_id, symbol)
if growth > 0 and held == 0:
side, qty = Side.SIDE_BUY, QUANTITY
elif growth <= 0 and held > 0:
side, qty = Side.SIDE_SELL, min(held, QUANTITY) # only close a long
else:
print(f"{symbol}: growth={growth:+.1f}%, held={held} → no action")
continue
label = "BUY" if side == Side.SIDE_BUY else "SELL"
print(f"{symbol}: growth={growth:+.1f}%, held={held} → {label} {qty}")
if not EXECUTE:
print(" DRY RUN: set TRADE_API_EXECUTE=1 after the user confirms")
continue
state = client.orders.PlaceOrder(Order(
account_id=account_id,
symbol=symbol,
quantity=Decimal(value=format(qty, "f")),
side=side,
type=OrderType.ORDER_TYPE_MARKET,
time_in_force=TimeInForce.TIME_IN_FORCE_DAY,
client_order_id=uuid4().hex[:20],
))
print(f" Order placed: {state.order_id}")
To backtest a strategy on historical data, shift the start/end window in BarsRequest to a past period and replay your signal logic bar by bar. No external framework needed:
# Continues the momentum example above (same imports and `client`)
# Simulate momentum over the second half of 2024 (TIME_FRAME_D allows at most 365 days per request)
backtest_end = datetime(2024, 12, 31, tzinfo=timezone.utc)
backtest_start = datetime(2024, 7, 1, tzinfo=timezone.utc)
req = BarsRequest(symbol="SBER@MISX", timeframe=TimeFrame.TIME_FRAME_D)
req.interval.start_time.FromDatetime(backtest_start)
req.interval.end_time.FromDatetime(backtest_end)
bars = list(client.market_data.Bars(req).bars)
# Walk forward: at each bar, compute signal on the preceding window
window = 30
for i in range(window, len(bars)):
segment = bars[i - window:i]
first = float(segment[0].close.value)
last = float(segment[-1].close.value)
signal = "BUY" if last > first else "SELL"
print(f"{bars[i].time.ToDatetime():%Y-%m-%d} {signal} close={last}")
Max historical depth per request depends on timeframe (e.g.
TIME_FRAME_D→ 365 days). For longer periods, paginate by shifting the window.
Scans top-100 stocks for volatility, growth, and volume. Supports filtering and sorting by any metric.
Usage:
python3 scripts/scanner.py [ru|us] [N] [--sort volatility|growth|volume] [--days N] [--min-growth PCT] [--min-volume VAL]
Examples:
# Top 10 most volatile Russian stocks (last 60 days)
python3 scripts/scanner.py ru 10
# Stocks up >5% this week with avg daily volume >500M rubles
python3 scripts/scanner.py ru --days 5 --sort growth --min-growth 5 --min-volume 500000000
# Top 5 most volatile US stocks
python3 scripts/scanner.py us 5
All scripts support --help for usage details (e.g. python3 scripts/scanner.py --help).
Endpoint: https://api.finam.ru/v1 (HTTP/2 required — HTTP/1 causes method errors)
Use for one-off requests: historical OHLCV data, account info, positions, balances, trade history, instrument search, placing or cancelling orders where 100–200 ms latency is acceptable.
Endpoint: api.finam.ru:443
Use for low-latency and streaming scenarios: real-time quotes, order book, trade feed, live bar data for signal generation, monitoring own orders/trades via subscription, long-running trading bots with persistent auto-reconnecting connections.
Note: Streams disconnect once per day (~86400s from subscription start) — implement reconnection logic in long-running bots.
Endpoint: wss://api.finam.ru/ws (the only channel address in specs/asyncapi/asyncapi-v1.0.0.yaml). Subscription types: ORDERS, TRADES, QUOTES, ORDER_BOOK, BARS, INSTRUMENT_TRADES, ACCOUNT.
Use when you need a browser-compatible or firewall-friendly alternative to gRPC for real-time data: streaming quotes, order book updates, and trade events over a standard WebSocket connection.
Always fetch live docs — never rely on local cached copies. Use the WebFetch tool to load documentation on demand.
Fetch the index for the relevant protocol to discover available docs:
| Protocol | Index URL |
|---|---|
| REST | https://api.finam.ru/docs/rest/llms.txt |
| gRPC | https://api.finam.ru/docs/grpc/llms.txt |
| WebSocket / AsyncAPI | https://api.finam.ru/docs/async-api/llms.txt |
Fetch the specific endpoint doc linked from the index. URL patterns:
https://api.finam.ru/docs/rest/<servicename_methodname>.md (e.g. ordersservice_placeorder.md)https://api.finam.ru/docs/grpc/<methodname>.md (e.g. placeorder.md)https://api.finam.ru/docs/async-api/<topicname>.mdFetch only the docs you actually need for the current task.
Use the Finam SDK (pip install finam-sdk) for any Python scripts that interact with the API — both for one-off queries and streaming/trading bots. It handles JWT issuance and refresh automatically, provides typed exceptions, and exposes the full gRPC surface via a single FinamClient / AsyncFinamClient entry point.
Before running any script that imports finam_trade_api, make sure the package is installed — run python3 -c "import finam_trade_api" and, if it fails, install with pip install finam-sdk before executing the script.
Full reference: fetch live from https://raw.githubusercontent.com/FinamWeb/finam-trade-api/main/sdk/python/README.md (source: https://github.com/FinamWeb/finam-trade-api/tree/main/sdk/python)
Most account-scoped calls need an account_id. The JWT token itself knows which accounts it can access — fetch that via TokenDetails instead of hardcoding an account. Reuse this helper in every example below:
import os
from finam_trade_api.auth_messages import TokenDetailsRequest
def resolve_account_id(client) -> str:
if account_id := os.environ.get("ACCOUNT_ID"):
return account_id # explicit override — pins a specific account
details = client.auth.TokenDetails(TokenDetailsRequest(token=client.get_token()))
if len(details.account_ids) == 1:
return details.account_ids[0]
raise RuntimeError(
f"Token exposes {len(details.account_ids)} accounts {list(details.account_ids)}; "
"ask the user which one to use, or set ACCOUNT_ID to pin one"
)
If resolve_account_id raises because of multiple accounts, don't guess — ask the user which account to use, or have them set ACCOUNT_ID (or pass it directly).
import os
from finam_trade_api import FinamClient
from finam_trade_api.accounts import GetAccountRequest
with FinamClient(secret=os.environ["TRADE_API_SECRET"]) as client:
account = client.accounts.GetAccount(
GetAccountRequest(account_id=resolve_account_id(client))
)
print(account)
This places a real order that can fill before it is cancelled. Mirror
examples/sdk/python/place_limit_order.py: require an explicit opt-in flag and an
explicit price (never a hard-coded "far from market" guess), and give every order a
unique client_order_id. Confirm all parameters with the user first.
import os
from uuid import uuid4
from google.type.decimal_pb2 import Decimal
from finam_trade_api import FinamClient
from finam_trade_api.orders import (
CancelOrderRequest, Order, OrderType, Side, TimeInForce,
)
if os.environ.get("TRADE_API_EXECUTE") != "1":
raise RuntimeError("set TRADE_API_EXECUTE=1 to acknowledge that this places a real order")
try:
limit_price = os.environ["TRADE_API_LIMIT_PRICE"]
except KeyError as exc:
raise RuntimeError("set TRADE_API_LIMIT_PRICE to the intended limit price") from exc
with FinamClient(secret=os.environ["TRADE_API_SECRET"]) as client:
account_id = resolve_account_id(client)
state = client.orders.PlaceOrder(Order(
account_id=account_id,
symbol="SBER@MISX",
quantity=Decimal(value="1"),
side=Side.SIDE_BUY,
type=OrderType.ORDER_TYPE_LIMIT,
time_in_force=TimeInForce.TIME_IN_FORCE_DAY,
limit_price=Decimal(value=limit_price),
client_order_id=uuid4().hex[:20], # unique per order
))
print(f"Placed: {state.order_id} status={state.status}")
cancelled = client.orders.CancelOrder(
CancelOrderRequest(account_id=account_id, order_id=state.order_id)
)
print(f"Cancelled: {cancelled.order_id} status={cancelled.status}")
import asyncio, os, sys
from finam_trade_api import AsyncFinamClient
from finam_trade_api.market_data import SubscribeQuoteRequest
async def main(symbols: list[str]) -> None:
async with AsyncFinamClient(secret=os.environ["TRADE_API_SECRET"]) as client:
async for tick in client.market_data.SubscribeQuote(
SubscribeQuoteRequest(symbols=symbols)
):
print(tick, flush=True)
asyncio.run(main(sys.argv[1:] or ["SBER@MISX"]))
Streams are not retried by the SDK. The server closes them after ~86400 s, and transient network errors (UNAVAILABLE) also end them, so recreate the client inside the loop and reconnect with exponential backoff. The SDK renews the JWT in the background; UNAUTHENTICATED or PERMISSION_DENIED therefore means the secret is invalid, revoked, or lacks access — stop and tell the user instead of reconnecting:
import asyncio, os, random, grpc
from finam_trade_api import AsyncFinamClient
from finam_trade_api.market_data import SubscribeQuoteRequest
FATAL = {grpc.StatusCode.UNAUTHENTICATED, grpc.StatusCode.PERMISSION_DENIED}
def process(tick) -> None:
print(tick, flush=True) # replace with your handler
async def stream_with_reconnect(symbols: list[str]) -> None:
delay = 1.0
while True:
try:
async with AsyncFinamClient(secret=os.environ["TRADE_API_SECRET"]) as client:
async for tick in client.market_data.SubscribeQuote(
SubscribeQuoteRequest(symbols=symbols)
):
delay = 1.0 # healthy stream: reset the backoff
process(tick)
except grpc.RpcError as exc:
# A revoked/invalid secret or a missing permission will not fix itself:
# stop instead of hammering the API.
if exc.code() in FATAL:
raise
# Exponential backoff with jitter, capped at 60 s.
await asyncio.sleep(delay + random.uniform(0, delay / 4))
delay = min(delay * 2, 60.0)
Ready-to-run strategy implementations built with the Finam SDK.
Index: https://raw.githubusercontent.com/FinamWeb/finam-trade-api/main/examples/strategies/README.md
When the user asks about strategies or wants to copy one:
examples/strategies/<name>/README.md) — it describes the rule, candle handling, safety guards, and configuration../<strategy_name>).https://api.github.com/repos/FinamWeb/finam-trade-api/contents/examples/strategies/<name>
https://api.github.com/repos/FinamWeb/finam-trade-api/contents/examples/strategies/<name>/<lang>
download_url values from the API response:
mkdir -p "<target_dir>/<lang>"
curl -sL "url1" -o "<target_dir>/file1" \
"url2" -o "<target_dir>/file2" ...
Do not copy subdirectories — only top-level files in each directory.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
finam, trade-api, algorithmic-trading, russian-market, moscow-exchange
/finam:trade-apifrom finam
npx claudepluginhub finamweb/finam-trade-api --plugin finamOther plugins' skills for the same job