Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .bumpversion.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[bumpversion]
current_version = 0.3.0
current_version = 0.4.0
commit = True
tag = True
tag_name = v{new_version}
Expand Down
174 changes: 174 additions & 0 deletions examples/08_docker_deployment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
"""
Example: Deploy a Trading Bot with Docker

This example demonstrates how to use the Neural SDK deployment module
to deploy trading bots in Docker containers.

⚠️ EXPERIMENTAL: The deployment module is experimental in v0.4.0.

Requirements:
- Docker installed and running
- neural-sdk[deployment] installed
- Kalshi API credentials (optional for paper trading)

Usage:
python examples/08_docker_deployment.py
"""

import asyncio
import os

from neural.deployment import (
DeploymentConfig,
DockerDeploymentProvider,
deploy,
)


async def basic_deployment_example():
"""Basic deployment example using Docker provider."""
print("=" * 60)
print("Neural SDK Deployment Module - Basic Example")
print("=" * 60)
print()

# Create deployment configuration
config = DeploymentConfig(
bot_name="NFL-MeanReversion-Bot",
strategy_type="NFL",
environment="paper", # Use paper trading mode
algorithm_config={
"algorithm_type": "mean_reversion",
"poll_interval": 30.0,
"market_limit": 12,
},
risk_config={
"max_position_size": 100,
"max_total_exposure": 1000,
},
database_enabled=False, # Disable database for this example
websocket_enabled=True,
monitoring_enabled=True,
)

print(f"📋 Configuration:")
print(f" Bot Name: {config.bot_name}")
print(f" Strategy: {config.strategy_type}")
print(f" Environment: {config.environment}")
print()

# Create Docker deployment provider
provider = DockerDeploymentProvider()

# Deploy with context manager (auto-cleanup)
print("🚀 Deploying trading bot...")
async with deploy(provider, config) as deployment:
print(f"✅ Deployed successfully!")
print(f" Deployment ID: {deployment.deployment_id}")
print(f" Container ID: {deployment.container_id[:12]}...")
print(f" Container Name: {deployment.container_name}")
print()

# Wait a moment for container to start
await asyncio.sleep(3)

# Check status
print("📊 Checking deployment status...")
status = await provider.status(deployment.deployment_id)
print(f" Status: {status.status}")
print(f" Uptime: {status.uptime_seconds:.1f} seconds")
if status.metrics:
print(f" CPU: {status.metrics.get('cpu_percent', 0):.1f}%")
print(f" Memory: {status.metrics.get('memory_usage_mb', 0):.1f} MB")
print()

# Get logs
print("📜 Recent logs (last 10 lines):")
logs = await provider.logs(deployment.deployment_id, tail=10)
for log in logs[-10:]:
print(f" {log}")
print()

# Keep running for 30 seconds
print("⏳ Bot running for 30 seconds...")
await asyncio.sleep(30)

print("🛑 Deployment stopped (auto-cleanup on context exit)")
print()


async def manual_deployment_example():
"""Manual deployment example without context manager."""
print("=" * 60)
print("Manual Deployment Example (No Auto-Cleanup)")
print("=" * 60)
print()

config = DeploymentConfig(
bot_name="Manual-Test-Bot",
strategy_type="NFL",
environment="sandbox",
)

provider = DockerDeploymentProvider()

# Deploy manually
print("🚀 Deploying...")
result = await provider.deploy(config)
print(f"✅ Deployed: {result.deployment_id}")
print()

try:
# List all deployments
print("📋 Active deployments:")
deployments = await provider.list_deployments()
for dep in deployments:
print(f" - {dep.bot_name} ({dep.status})")
print()

# Wait a bit
await asyncio.sleep(5)

finally:
# Manual cleanup
print("🛑 Stopping deployment...")
await provider.stop(result.deployment_id)
print("✅ Stopped successfully")
print()


async def main():
"""Run all examples."""
print("\n🤖 Neural SDK Deployment Module Examples\n")

# Check if Docker is available
try:
provider = DockerDeploymentProvider()
print("✅ Docker is available\n")
except Exception as e:
print(f"❌ Docker is not available: {e}")
print(" Please make sure Docker is installed and running.")
return

# Run examples
try:
# Example 1: Basic deployment with context manager
await basic_deployment_example()

# Example 2: Manual deployment
await manual_deployment_example()

print("=" * 60)
print("✨ All examples completed successfully!")
print("=" * 60)

except Exception as e:
print(f"\n❌ Error: {e}")
import traceback

traceback.print_exc()


if __name__ == "__main__":
# Run examples
asyncio.run(main())
5 changes: 3 additions & 2 deletions neural/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
modules (sentiment analysis, FIX streaming) are experimental.
"""

__version__ = "0.3.1"
__version__ = "0.4.0"
__author__ = "Neural Contributors"
__license__ = "MIT"

import warnings
from typing import Set # noqa: UP035

from neural import analysis, auth, data_collection, trading
from neural import analysis, auth, data_collection, deployment, trading

# Track which experimental features have been used
_experimental_features_used: set[str] = set()
Expand Down Expand Up @@ -65,5 +65,6 @@ def _warn_beta() -> None:
"data_collection",
"analysis",
"trading",
"deployment", # v0.4.0: Docker deployment module (experimental)
"_warn_experimental", # For internal use by modules
]
4 changes: 3 additions & 1 deletion neural/data_collection/kalshi.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
_BASE_URL = "https://api.elections.kalshi.com/trade-api/v2"
_SPORT_SERIES_MAP = {
"NFL": "KXNFLGAME",
"NBA": "KXNBA",
"NBA": "KXNBAGAME",
"NBA_CHAMPIONSHIP": "KXNBA",
"WNBA": "KXWNBAGAME",
"MLB": "KXMLB",
"NHL": "KXNHL",
"NCAAF": "KXNCAAFGAME",
Expand Down
135 changes: 135 additions & 0 deletions neural/deployment/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""
Neural SDK Deployment Module (Experimental)

Provides Docker-based deployment infrastructure for trading bots with
database persistence, monitoring, and multi-environment support.

 EXPERIMENTAL: This module is experimental in Neural SDK Beta v0.4.0.
Use with caution in production environments.

Example:
```python
from neural.deployment import DockerDeploymentProvider, DeploymentConfig, deploy

# Configure deployment
config = DeploymentConfig(
bot_name="MyNFLBot",
strategy_type="NFL",
environment="paper",
algorithm_config={"algorithm_type": "mean_reversion"}
)

# Deploy with context manager
provider = DockerDeploymentProvider()
async with deploy(provider, config) as deployment:
print(f"Deployed: {deployment.deployment_id}")

# Get status
status = await provider.status(deployment.deployment_id)
print(f"Status: {status.status}")
# Deployment is automatically stopped when exiting context
```
"""

# Core abstractions
from neural.deployment.base import DeploymentContext, DeploymentProvider

# Configuration models
from neural.deployment.config import (
DatabaseConfig,
DeploymentConfig,
DeploymentInfo,
DeploymentResult,
DeploymentStatus,
DockerConfig,
MonitoringConfig,
)

# Docker provider
from neural.deployment.docker import (
DockerDeploymentProvider,
render_compose_file,
render_dockerfile,
render_dockerignore,
write_compose_file,
)

# Exceptions
from neural.deployment.exceptions import (
ConfigurationError,
ContainerNotFoundError,
DatabaseError,
DeploymentError,
DeploymentTimeoutError,
ImageBuildError,
MonitoringError,
NetworkError,
ProviderNotFoundError,
ResourceLimitExceededError,
)

__all__ = [
# Core abstractions
"DeploymentProvider",
"DeploymentContext",
"deploy",
# Configuration
"DeploymentConfig",
"DockerConfig",
"DatabaseConfig",
"MonitoringConfig",
"DeploymentResult",
"DeploymentStatus",
"DeploymentInfo",
# Providers
"DockerDeploymentProvider",
# Docker utilities
"render_dockerfile",
"render_dockerignore",
"render_compose_file",
"write_compose_file",
# Exceptions
"DeploymentError",
"ProviderNotFoundError",
"ContainerNotFoundError",
"ResourceLimitExceededError",
"DeploymentTimeoutError",
"ConfigurationError",
"ImageBuildError",
"NetworkError",
"DatabaseError",
"MonitoringError",
]


# Convenience function for deploying with context manager
def deploy(
provider: DeploymentProvider,
config: DeploymentConfig,
auto_stop: bool = True,
) -> DeploymentContext:
"""Deploy a trading bot using a deployment provider with automatic cleanup.

This is a convenience function that creates a DeploymentContext for use
with Python's async context manager protocol.

Args:
provider: Deployment provider to use (e.g., DockerDeploymentProvider)
config: Deployment configuration
auto_stop: Whether to automatically stop deployment on context exit (default: True)

Returns:
DeploymentContext that can be used with 'async with'

Example:
```python
provider = DockerDeploymentProvider()
config = DeploymentConfig(bot_name="MyBot", strategy_type="NFL")

async with deploy(provider, config) as deployment:
status = await provider.status(deployment.deployment_id)
print(f"Bot is {status.status}")
# Deployment automatically stopped here
```
"""
return DeploymentContext(provider, config, auto_stop=auto_stop)
Loading
Loading