Skip to main content

stockapis-bot

Python SDK for building trading bots with StockAPIs platform.

Features

  • Pydantic v2 typed settings with JSON Schema (auto-sent to Django)
  • Deterministic bot_id from name (UUID5 - same name = same ID everywhere)
  • Built-in environment configs (DEV/PROD) - no infrastructure setup needed
  • gRPC streaming for real-time signals from Django
  • Binance Futures testnet/live trading
  • Redis pub/sub for event handling

Install

pip install stockapis-bot

Environment

Only credentials needed - infrastructure config (hosts, ports) is built into the package:

# Binance TESTNET
BINANCE__API_KEY=your_testnet_api_key
BINANCE__API_SECRET=your_testnet_api_secret
BINANCE__TESTNET=true

# gRPC API Key (host/port built-in per environment)
GRPC__API_KEY=your-api-key

# Redis (host/port built-in per environment)
REDIS__PASSWORD=
REDIS__CHANNEL=trading_signals

Quick Start

from decimal import Decimal
from pydantic import Field
from stockapis_bot import (
    BotClient, BotSettings, ClientConfig, Environment,
    TradingBot, TradingSignal, SignalDecision,
)

# 1. Define settings schema (sent to Django for dynamic form generation)
class ScalperSettings(BotSettings):
    min_confidence: float = Field(default=0.7, ge=0, le=1, description="Min confidence")
    position_size: Decimal = Field(default=Decimal("100"), description="Position USDT")

# 2. Create bot with settings schema
class MyBot(TradingBot):
    settings_schema = ScalperSettings  # Schema sent to Django on registration

    async def on_signal(self, signal: TradingSignal) -> SignalDecision:
        # Access typed settings (updated from Django)
        if signal.confidence < self.settings.min_confidence:
            return SignalDecision.skip("Low confidence")

        qty = str(self.settings.position_size)
        if signal.is_buy_signal:
            return SignalDecision.buy(qty, "High confidence buy")
        elif signal.is_sell_signal:
            return SignalDecision.sell(qty, "High confidence sell")

        return SignalDecision.skip("Unknown signal")

    async def on_start(self) -> None:
        print(f"Bot {self.name} ({self.bot_id}) started")
        print(f"Settings: {self.settings}")

    async def on_stop(self, reason: str) -> None:
        print(f"Bot stopped: {reason}")

# 3. Run - bot_id auto-generated from name (deterministic UUID5)
async def main():
    bot = MyBot(name="my-scalper")
    config = ClientConfig.from_settings(
        bot_id=bot.bot_id,
        bot_name=bot.name,
        env=Environment.DEV,    # or Environment.PROD
        include_exchange=True,  # Binance from .env
        include_redis=True,     # Redis listener
    )
    client = BotClient.create(bot, config)  # Schema sent to Django here
    await client.run()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Environments

Built-in infrastructure configs - just select DEV or PROD:

# Development (localhost)
config = ClientConfig.from_settings(bot_id, bot_name, env=Environment.DEV)

# Production (StockAPIs cloud)
config = ClientConfig.from_settings(bot_id, bot_name, env=Environment.PROD)

Bot Methods

# Trading
await self.buy(symbol, quantity)
await self.sell(symbol, quantity, reduce_only=True)

# Market data
ticker = await self.get_ticker("BTCUSDT")  # ticker.price
balance = await self.get_balance()          # balance.available_usdt

# Utils
qty = await self.calculate_quantity(symbol, usdt_amount=100, leverage=10)
await self.set_leverage(symbol, leverage=20)

# State
self.is_running    # bool
self.is_active     # bool (running + config.active)
self.config        # BotConfig from Django (enabled, active, etc.)
self.settings      # Typed settings (ScalperSettings) - updated from Django

License

MIT

Metadata

Release files for stockapis-bot 0.3.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for stockapis-bot 0.3.3
File Size Uploaded
stockapis_bot-0.3.3.tar.gz 76.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for stockapis-bot 0.3.3
File Interpreter ABI Platform
stockapis_bot-0.3.3-py3-none-any.whl Python 3 none any Details

Total release size: 144.7 kB

Release files / stockapis_bot-0.3.3.tar.gz

Download URL stockapis_bot-0.3.3.tar.gz
Size 76.5 kB
Tags Source
SHA-256 checksum
How to use checksums
f0d68ac1cfc4e4083a16aabe2c9026b03e22aa6f3ef04d114489e4e25a0122e6
BLAKE2b-256 checksum
How to use checksums
dd99ed16d6045d89881e5d1b8c7c2a51460004cd04868002660bee45e57165a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.18

Release files / stockapis_bot-0.3.3-py3-none-any.whl

Download URL stockapis_bot-0.3.3-py3-none-any.whl
Size 68.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cdc0742da0ad4c84b9caa454f8be645565a9f952c86ca024a9973e76bbac1b5c
BLAKE2b-256 checksum
How to use checksums
bb29ead942fb30e6bcc1319d0d63ce68628e22f7537afaa715a8b9d776d451ca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.18

Release history Release notifications | RSS feed

This release

0.3.3 This release

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page