Skip to main content

Trading Bot SDK for StockAPIs - Build custom trading bots with ease

Project description

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)
  • gRPC streaming for real-time signals from Django
  • Binance Futures testnet/live trading
  • Redis pub/sub for event handling
  • Telegram channel signal extraction

Install

pip install stockapis-bot

Environment

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

# Django gRPC
GRPC__HOST=localhost
GRPC__PORT=50051
GRPC__API_KEY=dev-key

# Redis
REDIS__HOST=localhost
REDIS__PORT=6379
REDIS__CHANNEL=trading_signals

# Telegram Spy
TELEGRAM__API_ID=123456
TELEGRAM__API_HASH=your_api_hash
TELEGRAM__SESSION=1BQA...          # from `telegram-spy auth`
TELEGRAM__CHANNELS=channel1,channel2

Quick Start

from decimal import Decimal
from pydantic import Field
from stockapis_bot import (
    BotClient, BotSettings, ClientConfig, 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)
bot = MyBot(name="my-scalper")
config = ClientConfig.from_settings(
    bot_id=bot.bot_id,
    bot_name=bot.name,
    include_exchange=True,  # Binance from .env
    include_redis=True,     # Redis listener from .env
)
client = BotClient.create(bot, config)  # Schema sent to Django here
await client.run()

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

CLI

Command Description Args
telegram-spy auth Generate session string -i API_ID -h API_HASH
telegram-spy test Test session validity -i API_ID -h API_HASH -s SESSION
telegram-spy channels List your channels -i API_ID -h API_HASH -s SESSION
telegram-spy run Run spy → Redis reads from env
telegram-spy send Send test signal BOT__TOKEN env

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

stockapis_bot-0.3.1.tar.gz (100.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

stockapis_bot-0.3.1-py3-none-any.whl (100.8 kB view details)

Uploaded Python 3

File details

Details for the file stockapis_bot-0.3.1.tar.gz.

File metadata

  • Download URL: stockapis_bot-0.3.1.tar.gz
  • Upload date:
  • Size: 100.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.8

File hashes

Hashes for stockapis_bot-0.3.1.tar.gz
Algorithm Hash digest
SHA256 a93fc816e7a292e44a1e3e548fa37d47d606d902dce805bf08aa9798b8c4c7e9
MD5 698bb16c949d53b1a487e77c5013c474
BLAKE2b-256 f10bdf9cf648f5c876f2816dc230c0f43c40885654bc09b2ee4c603f932337ef

See more details on using hashes here.

File details

Details for the file stockapis_bot-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: stockapis_bot-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 100.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.8

File hashes

Hashes for stockapis_bot-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c371de7ca165270e5d7532bed6122f52883d4f98b03da689c209ba8d2392bfd8
MD5 17af3f805409bcec05e9a854d727b8c0
BLAKE2b-256 8583113d922e227232cd1e27bc983b243ce1da68a2dcf91f9b422d5ee7f1b5bf

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page