tektii


Nametektii JSON
Version 1.3.0 PyPI version JSON
download
home_pageNone
SummaryBuild trading strategies that run anywhere - Write Once. Trade Everywhere.
upload_time2025-08-13 11:31:35
maintainerNone
docs_urlNone
authorNone
requires_python>=3.11
licenseApache-2.0
keywords trading algorithmic-trading algo-trading quantitative-finance finance fintech strategy backtesting grpc trading-bot trading-strategies market-data portfolio-management
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Tektii Python SDK

[![PyPI Version](https://img.shields.io/pypi/v/tektii)](https://pypi.org/project/tektii/)
[![Python Version](https://img.shields.io/pypi/pyversions/tektii)](https://pypi.org/project/tektii/)
[![License](https://img.shields.io/pypi/l/tektii)](https://github.com/tektii/tektii-sdk-python/blob/main/LICENSE)
[![Documentation](https://img.shields.io/badge/docs-latest-blue)](https://docs.tektii.com/sdk)

**Build trading strategies that run anywhere - Write Once. Trade Everywhere.**

The Tektii Python SDK provides a powerful, type-safe framework for building algorithmic trading strategies. Built with a dual-service architecture separating broker operations from strategy logic, the SDK features protocol-based proto conversions, comprehensive type safety, and financial-grade decimal precision. Whether you're backtesting historical data or deploying to production, Tektii's event-driven architecture and comprehensive tooling help you focus on strategy development.

## ⚑ Quick Start

```bash
# Install the SDK
pip install tektii

# Create a new strategy from template
tektii new my-awesome-strategy
cd my-awesome-strategy

# Test your strategy with mock broker
tektii serve --mock-broker

# Deploy to Tektii platform
tektii push
```

## πŸš€ Features

- **🏯 Dual-Service Architecture** - Clear separation between broker operations and strategy logic
- **πŸ”„ Protocol-Based Proto Conversion** - Type-safe `ProtoConvertible[T]` protocol for seamless proto ↔ Python model mapping
- **βœ… Enhanced Type Safety** - Pydantic models with generic protocols, custom validators, and full mypy/pyright support
- **πŸ’° Financial Precision** - `PreciseDecimal` with 6-decimal precision for all monetary calculations
- **🎯 Advanced Enums** - Business logic-aware enums with proto conversion and string parsing
- **πŸ“‘ Event-Driven Architecture** - Comprehensive event routing for market data, orders, positions, and account updates
- **πŸ”§ Robust gRPC Server** - Exponential backoff retry, health checks, and graceful error handling
- **☁️ Production Ready** - Deploy directly to Tektii's cloud infrastructure with built-in validation

## πŸ“¦ Installation

### Requirements

- Python 3.11 or higher
- pip or poetry

### Install from PyPI

```bash
pip install tektii
```

### Install with Proto Dependencies

The SDK uses pre-built protobuf packages from buf.build:

```bash
pip install tektii --extra-index-url https://buf.build/gen/python
```

### Install for Development

```bash
# Clone the repository
git clone https://github.com/tektii/tektii-sdk-python.git
cd tektii-sdk-python

# Quick setup (creates venv, installs deps, proto packages)
make setup

# Or manual setup:
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -e ".[dev]" --extra-index-url https://buf.build/gen/python
```

## 🎯 Getting Started

### Step 1: Set Up Your Development Environment

```bash
# Create a new directory for your strategy
mkdir my-trading-strategy
cd my-trading-strategy

# Create a Python virtual environment
python -m venv venv

# Activate the virtual environment
# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\Scripts\activate

# Create a requirements.txt file
echo "tektii" > requirements.txt

# Install the Tektii SDK
pip install -r requirements.txt
```

### Step 2: Create Your Strategy from Template

```bash
# Use the Tektii CLI to create a new strategy
tektii new my-strategy

# This creates:
# - strategy.py: Your strategy implementation
# - requirements.txt: Python dependencies
# - config.yaml: Strategy configuration
# - tests/: Unit tests for your strategy
# - Dockerfile: For containerized deployment
# - README.md: Strategy documentation
```

### Step 3: Explore the Generated Strategy

```bash
# Navigate to your new strategy
cd my-strategy

# Open strategy.py in your favorite editor
# You'll see a template strategy ready for customization
```

### Step 4: Customize Your Strategy

Edit `strategy.py` to implement your trading logic:

```python
from decimal import Decimal
from typing import Optional

from tektii import TektiiStrategy
from tektii.models.strategy.events import TickData, CandleData
from tektii.models.broker.handlers import PlaceOrderRequest
from tektii.models.strategy.types import MarketOrder, OrderSide


class MyStrategy(TektiiStrategy):
    """A simple moving average crossover strategy."""

    def __init__(self):
        super().__init__()
        self.position_size = Decimal("100")

    def on_initialize(self, config: dict[str, str], symbols: list[str]) -> None:
        """Initialize strategy with configuration."""
        self.log_info(f"Initializing strategy with symbols: {symbols}")
        if "position_size" in config:
            self.position_size = Decimal(config["position_size"])

    def on_market_data(
        self,
        tick_data: Optional[TickData] = None,
        candle_data: Optional[CandleData] = None
    ) -> None:
        """React to incoming market data."""
        if candle_data and candle_data.close > Decimal("150.00"):
            # Create a market order using the model directly
            order = MarketOrder(
                symbol=candle_data.symbol,
                side=OrderSide.BUY,
                quantity=self.position_size
            )

            # Submit through broker service
            request = PlaceOrderRequest(order=order)
            response = self.place_order(request)

            if response.success:
                self.log_info(f"Order placed: {response.order_id}")
```

### Step 5: Test Your Strategy

```bash
# Validate your strategy implementation
tektii validate

# Run tests with the mock broker
tektii serve --mock-broker

# Or use pytest directly for custom tests
pytest tests/ -xvs
```

Write custom tests using the mock broker:

```python
from tektii.testing import StrategyTestHarness
from tektii.testing.fixtures import create_candle_data


def test_my_strategy():
    # Create test harness
    harness = StrategyTestHarness(MyStrategy)

    # Send test market data
    test_candle = create_candle_data(
        symbol="AAPL",
        close=Decimal("151.00")  # Above our threshold
    )
    harness.process_candle_data(test_candle)

    # Verify order was created
    orders = harness.get_orders()
    assert len(orders) == 1
    assert orders[0].side == OrderSide.BUY
```

### Step 6: Run Your Strategy Locally

```bash
# Validate your strategy code
tektii validate

# Run strategy as a gRPC service
tektii serve --port 50051

# Your strategy is now ready to receive market data!
```

### Step 7: Deploy to Tektii Platform

```bash
# Deploy your strategy to the cloud
tektii push

# View deployment logs
tektii logs

# Check deployment status
tektii status
```

## πŸ“– Examples

### Moving Average Crossover Strategy

Check out our complete example in [`examples/basic_ma_crossover.py`](examples/basic_ma_crossover.py) that demonstrates:

- Price history management with collections.deque
- Moving average calculation and crossover detection
- Order placement using the dual-service model architecture
- Comprehensive event handling (market data, order updates, positions)
- Proper logging and error handling

```python
# Run the example locally with mock broker
tektii serve --strategy examples.basic_ma_crossover:MovingAverageCrossoverStrategy --mock-broker

# Or run directly
python examples/basic_ma_crossover.py
```

### More Examples Coming Soon

- **Mean Reversion Strategy** - Statistical arbitrage with z-score calculations
- **Pairs Trading** - Market-neutral strategy with cointegration
- **Options Strategy** - Delta-neutral options trading with Greeks
- **Portfolio Optimization** - Multi-asset allocation with risk parity

## πŸ“š Core Concepts

### Dual-Service Architecture

The SDK separates broker operations from strategy logic for clean, maintainable code:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     Your Strategy                                   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ on_market_data() | on_order_update() | on_position_update() β”‚  β”‚
β”‚  └────────────────────────────↓─────────────────────↑───────────└  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β†“β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β†‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                             ↓                           ↑
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β†“β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β†‘β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Strategy Service          ↔   gRPC   ↔   Broker Service              β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ Events: Market Data    β”‚                         β”‚ Handlers: Orders     β”‚  β”‚
β”‚  β”‚ Types: Order Models    β”‚                         β”‚ Types: Positions     β”‚  β”‚
β”‚  β”‚ Proto: Conversions     β”‚                         β”‚ Proto: Conversions   β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

#### Broker Service Models (`tektii.models.broker`)
- Handles communication with trading brokers
- Request/response models for order placement, cancellation, state queries
- Core types: `Order`, `Account`, `Position`, `Fill`

#### Strategy Service Models (`tektii.models.strategy`)
- Handles strategy-specific events and processing
- Event models for market data, order updates, position changes
- Strategy-specific types with business logic

#### Proto Conversion Protocol

All models implement the `ProtoConvertible[T]` protocol for seamless proto conversion:

```python
from tektii.models.base import ProtoConvertible
from tektii.models.strategy.types import MarketOrder

# All models have bidirectional proto conversion
order = MarketOrder(
    symbol="AAPL",
    side=OrderSide.BUY,
    quantity=Decimal("100")
)

# Convert to proto for gRPC transmission
proto_msg = order.to_proto()

# Reconstruct from proto with full type safety
reconstructed = MarketOrder.from_proto(proto_msg)
assert order == reconstructed
```

### Strategy Development

Your strategy should inherit from `TektiiStrategy` and implement the event handlers:

```python
from typing import Optional
from decimal import Decimal

from tektii import TektiiStrategy
from tektii.models.strategy.events import (
    TickData, CandleData, OrderUpdateEvent,
    PositionUpdateEvent, AccountUpdateEvent
)
from tektii.models.broker.handlers import PlaceOrderRequest
from tektii.models.strategy.types import MarketOrder, OrderSide

class MyStrategy(TektiiStrategy):
    def on_initialize(self, config: dict[str, str], symbols: list[str]) -> None:
        """Initialize strategy with configuration."""
        self.symbols = symbols
        self.position_size = Decimal(config.get("position_size", "100"))
        self.log_info(f"Strategy initialized for {len(symbols)} symbols")

    def on_market_data(
        self,
        tick_data: Optional[TickData] = None,
        candle_data: Optional[CandleData] = None
    ) -> None:
        """Handle incoming market data."""
        if candle_data:
            # Your trading logic here
            if self.should_buy(candle_data):
                order = MarketOrder(
                    symbol=candle_data.symbol,
                    side=OrderSide.BUY,
                    quantity=self.position_size
                )
                request = PlaceOrderRequest(order=order)
                response = self.place_order(request)

    def on_order_update(self, order_update: OrderUpdateEvent) -> None:
        """Handle order status updates."""
        if order_update.status.is_terminal():
            self.log_info(f"Order {order_update.order_id} completed: {order_update.status}")

    def on_position_update(self, position_update: PositionUpdateEvent) -> None:
        """Handle position changes."""
        self.log_info(f"Position updated: {position_update.symbol} qty={position_update.quantity}")

    def on_account_update(self, account_update: AccountUpdateEvent) -> None:
        """Handle account updates."""
        self.log_info(f"Account balance: {account_update.balance}")

    def on_shutdown(self) -> None:
        """Clean up resources."""
        self.log_info("Strategy shutting down gracefully")
```

### Order Management

The SDK provides multiple ways to create and manage orders:

#### 1. Direct Model Creation (Recommended)

```python
from decimal import Decimal
from tektii.models.broker.handlers import PlaceOrderRequest
from tektii.models.strategy.types import (
    MarketOrder, LimitOrder, StopOrder, StopLimitOrder,
    OrderSide, TimeInForce
)

# Market order - executes immediately at current price
market_order = MarketOrder(
    symbol="AAPL",
    side=OrderSide.BUY,
    quantity=Decimal("100")
)

# Limit order - executes at specified price or better
limit_order = LimitOrder(
    symbol="GOOGL",
    side=OrderSide.SELL,
    quantity=Decimal("50"),
    limit_price=Decimal("2500.00"),
    time_in_force=TimeInForce.GTC  # Good Till Cancelled
)

# Stop order - becomes market order when stop price is reached
stop_order = StopOrder(
    symbol="MSFT",
    side=OrderSide.SELL,
    quantity=Decimal("200"),
    stop_price=Decimal("380.00")
)

# Stop-limit order - becomes limit order when stop price is reached
stop_limit = StopLimitOrder(
    symbol="TSLA",
    side=OrderSide.BUY,
    quantity=Decimal("10"),
    stop_price=Decimal("700.00"),
    limit_price=Decimal("705.00")
)
```

#### 2. Submit Orders Through Broker Service

```python
# Create request and submit to broker
request = PlaceOrderRequest(order=market_order)
response = self.place_order(request)

if response.success:
    self.log_info(f"Order placed: {response.order_id}")
    # Track order for later management
    self.active_orders[response.order_id] = market_order
else:
    self.log_error(f"Order failed: {response.message}")
```

#### 3. Order Lifecycle Management

```python
from tektii.models.broker.handlers import (
    CancelOrderRequest,
    ModifyOrderRequest,
    GetOrderStatusRequest
)

# Cancel an order
cancel_request = CancelOrderRequest(order_id="order_123")
cancel_response = self.cancel_order(cancel_request)

# Modify an existing order
modify_request = ModifyOrderRequest(
    order_id="order_123",
    new_quantity=Decimal("150"),
    new_limit_price=Decimal("155.50")
)
modify_response = self.modify_order(modify_request)

# Check order status
status_request = GetOrderStatusRequest(order_id="order_123")
status_response = self.get_order_status(status_request)

if status_response.order.status.is_terminal():
    self.log_info("Order completed")
```

### Error Handling & Validation

The SDK provides comprehensive error handling with Pydantic validation:

```python
from pydantic import ValidationError
from tektii.models.strategy.types import OrderStatus, OrderSide
from tektii.models.base import PreciseDecimal

try:
    # Pydantic validation
    order = MarketOrder(
        symbol="AAPL",
        side="INVALID",  # Will raise ValidationError
        quantity=Decimal("100")
    )
except ValidationError as e:
    self.log_error(f"Order validation failed: {e}")

# Business logic methods on enums
status = OrderStatus.FILLED
if status.is_terminal():  # FILLED, CANCELLED, REJECTED, EXPIRED
    self.log_info("Order completed")

# Financial precision handling
price = PreciseDecimal("123.456789")  # Automatically rounds to 6 decimals
assert price == Decimal("123.456789")

# Proto conversion with type safety
proto_order = order.to_proto()  # Type-safe conversion
reconstructed = MarketOrder.from_proto(proto_order)
assert order == reconstructed
```

## πŸ§ͺ Testing

The SDK includes comprehensive testing utilities:

```bash
# Run all quality checks
make check  # Runs lint, type-check, and tests

# Individual test commands
make test           # Run all tests with coverage
make test-fast      # Skip slow tests
make test-security  # Run security tests with bandit

# Run specific test file
pytest tests/test_.py -xvs

# Development workflow
make format         # Auto-format code
make lint          # Check code style
make type-check    # Verify type annotations
```

### Writing Tests

```python
import pytest
from decimal import Decimal
from tektii.testing import MockBrokerService
from tektii.models.strategy.events import CandleData


class TestMyStrategy:
    def test_strategy_initialization(self):
        # Initialize with mock broker
        mock_broker = MockBrokerService()
        strategy = MyStrategy()
        strategy.broker = mock_broker

        # Test initialization
        config = {"position_size": "100"}
        symbols = ["AAPL", "GOOGL"]
        strategy.on_initialize(config, symbols)

        assert strategy.position_size == Decimal("100")

    def test_order_creation_on_signal(self):
        mock_broker = MockBrokerService()
        strategy = MyStrategy()
        strategy.broker = mock_broker

        # Create test candle data
        candle = CandleData(
            symbol="AAPL",
            timestamp=datetime.now(),
            open=Decimal("150.00"),
            high=Decimal("156.00"),
            low=Decimal("149.00"),
            close=Decimal("155.00"),
            volume=1000000
        )

        # Process market data
        strategy.on_market_data(candle_data=candle)

        # Verify order was placed
        orders = mock_broker.get_orders()
        assert len(orders) == 1
        assert orders[0].symbol == "AAPL"
```

## πŸ”§ CLI Commands

The Tektii CLI provides commands for the complete development lifecycle:

| Command             | Aliases       | Description                         |
| ------------------- | ------------- | ----------------------------------- |
| `tektii new <name>` | `n`, `create` | Create a new strategy from template |
| `tektii serve`      | `s`, `run`    | Run strategy as gRPC service        |
| `tektii validate`   | `v`, `check`  | Validate strategy implementation    |
| `tektii push`       | `p`, `deploy` | Deploy to Tektii platform           |
| `tektii backtest`   | `bt`          | Run strategy backtest on platform   |
| `tektii analyze`    | `a`           | Analyze backtest results            |

### Development Mode

```bash
# Run with mock broker for development
tektii serve --mock-broker

# Specify custom port
tektii serve --port 50051

# Validate without deploying
tektii push --dry-run
```

## πŸ—οΈ SDK Architecture

```
tektii/
β”œβ”€β”€ __init__.py              # Public API exports
β”œβ”€β”€ strategy.py              # TektiiStrategy base class & gRPC server
β”œβ”€β”€ cli.py                   # CLI entry point with command routing
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ base.py             # ProtoConvertible[T] protocol & PreciseDecimal
β”‚   β”œβ”€β”€ broker/             # Broker service models (orders, positions, fills)
β”‚   β”‚   β”œβ”€β”€ handlers/       # Request/response models for broker ops
β”‚   β”‚   β”‚   β”œβ”€β”€ place_order.py      # PlaceOrderRequest/Response
β”‚   β”‚   β”‚   β”œβ”€β”€ cancel_order.py     # CancelOrderRequest/Response
β”‚   β”‚   β”‚   β”œβ”€β”€ get_state.py        # GetStateRequest/Response
β”‚   β”‚   β”‚   └── ...                 # Other broker operations
β”‚   β”‚   └── types/          # Core broker types with proto conversion
β”‚   └── strategy/           # Strategy service models
β”‚       β”œβ”€β”€ events/         # Market data and update events
β”‚       β”‚   β”œβ”€β”€ tick_data.py        # Tick-level market data
β”‚       β”‚   β”œβ”€β”€ candle_data.py      # OHLCV candle data
β”‚       β”‚   └── order_update.py     # Order status updates
β”‚       β”œβ”€β”€ handlers/       # Strategy service handlers
β”‚       └── types/          # Strategy types with business logic
β”œβ”€β”€ testing/                # Testing utilities
β”‚   └── mock_broker.py      # MockBrokerService for development
└── commands/               # CLI command implementations
    β”œβ”€β”€ new.py             # Strategy template generation
    β”œβ”€β”€ serve.py           # gRPC server with retry logic
    β”œβ”€β”€ validator.py       # Strategy validation
    β”œβ”€β”€ push.py            # Deploy to Tektii platform
    └── backtest.py        # Run backtests on platform
```

## πŸ—οΈ Strategy Project Structure

When you run `tektii new my-strategy`, it creates:

```
my-strategy/
β”œβ”€β”€ strategy.py          # Your strategy implementation
β”œβ”€β”€ requirements.txt     # Python dependencies (includes tektii)
β”œβ”€β”€ config.yaml         # Strategy configuration
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ test_strategy.py  # Unit tests for your strategy
β”‚   └── fixtures.py       # Test fixtures and helpers
β”œβ”€β”€ Dockerfile          # Container for cloud deployment
β”œβ”€β”€ .dockerignore       # Docker build exclusions
└── README.md          # Strategy documentation
```

### Configuration (config.yaml)

```yaml
name: my-strategy
version: 1.0.0
description: My trading strategy
author: Your Name

# Strategy parameters
parameters:
  position_size: "100"
  max_positions: "5"
  stop_loss_percent: "2.0"

# Trading symbols
symbols:
  - AAPL
  - GOOGL
  - MSFT

# Risk management
risk:
  max_drawdown: "10.0"
  position_sizing: "fixed"
```

## 🀝 Contributing

We welcome contributions! Here's how to get started:

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes and add tests
4. Run quality checks (`make check`)
5. Commit your changes (`git commit -m 'Add amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. Open a Pull Request

### Development Workflow

```bash
# Complete first-time setup
make setup

# Before committing changes
make check  # Runs all quality checks

# Auto-fix issues
make format  # Format with black and isort

# Clean up
make clean  # Remove caches and build artifacts

# Build distribution
make build  # Create wheel and sdist packages
```

## πŸ“„ License

This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.

## πŸ”— Resources

- **πŸ“– Documentation:** [docs.tektii.com/sdk](https://docs.tektii.com/sdk)
- **πŸ”§ API Reference:** [docs.tektii.com/sdk/api](https://docs.tektii.com/sdk/api)
- **πŸ’‘ Examples:** [examples/](https://github.com/tektii/tektii-sdk-python/tree/main/examples) - Working strategy implementations
- **πŸ“¦ PyPI Package:** [pypi.org/project/tektii](https://pypi.org/project/tektii/)
- **πŸ—ΊοΈ Roadmap:** [GitHub Projects](https://github.com/tektii/tektii-sdk-python/projects/1)

## πŸ’¬ Support

- **Issues & Bugs:** [GitHub Issues](https://github.com/tektii/tektii-sdk-python/issues)
- **Discussions:** [GitHub Discussions](https://github.com/tektii/tektii-sdk-python/discussions)
- **Community:** [Discord Server](https://discord.gg/tektii)
- **Questions:** [Stack Overflow](https://stackoverflow.com/questions/tagged/tektii)
- **Email:** support@tektii.com

## πŸ† Acknowledgments

Built with ❀️ by the Tektii team. Special thanks to all our contributors and the open-source community.

### Key Technologies

- **[gRPC](https://grpc.io/)** - High-performance RPC framework
- **[Pydantic](https://pydantic.dev/)** - Data validation using Python type annotations
- **[Protobuf](https://protobuf.dev/)** - Protocol buffers for serialization
- **[buf.build](https://buf.build/)** - Modern protobuf toolchain

---

<div align="center">
  <b>Ready to build your trading strategy?</b><br>
  <a href="https://docs.tektii.com/sdk/quickstart">Get Started with Tutorials β†’</a> |
  <a href="https://github.com/tektii/tektii-sdk-python/tree/main/examples">View Examples β†’</a> |
  <a href="https://discord.gg/tektii">Join Discord β†’</a>
</div>

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "tektii",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": "Tektii Team <support@tektii.com>",
    "keywords": "trading, algorithmic-trading, algo-trading, quantitative-finance, finance, fintech, strategy, backtesting, grpc, trading-bot, trading-strategies, market-data, portfolio-management",
    "author": null,
    "author_email": "Tektii <support@tektii.com>",
    "download_url": "https://files.pythonhosted.org/packages/92/b2/519c93d328d9e86bee2e654cb0fe846ad8d152efd0f201f3731605253e7b/tektii-1.3.0.tar.gz",
    "platform": null,
    "description": "# Tektii Python SDK\n\n[![PyPI Version](https://img.shields.io/pypi/v/tektii)](https://pypi.org/project/tektii/)\n[![Python Version](https://img.shields.io/pypi/pyversions/tektii)](https://pypi.org/project/tektii/)\n[![License](https://img.shields.io/pypi/l/tektii)](https://github.com/tektii/tektii-sdk-python/blob/main/LICENSE)\n[![Documentation](https://img.shields.io/badge/docs-latest-blue)](https://docs.tektii.com/sdk)\n\n**Build trading strategies that run anywhere - Write Once. Trade Everywhere.**\n\nThe Tektii Python SDK provides a powerful, type-safe framework for building algorithmic trading strategies. Built with a dual-service architecture separating broker operations from strategy logic, the SDK features protocol-based proto conversions, comprehensive type safety, and financial-grade decimal precision. Whether you're backtesting historical data or deploying to production, Tektii's event-driven architecture and comprehensive tooling help you focus on strategy development.\n\n## \u26a1 Quick Start\n\n```bash\n# Install the SDK\npip install tektii\n\n# Create a new strategy from template\ntektii new my-awesome-strategy\ncd my-awesome-strategy\n\n# Test your strategy with mock broker\ntektii serve --mock-broker\n\n# Deploy to Tektii platform\ntektii push\n```\n\n## \ud83d\ude80 Features\n\n- **\ud83c\udfef Dual-Service Architecture** - Clear separation between broker operations and strategy logic\n- **\ud83d\udd04 Protocol-Based Proto Conversion** - Type-safe `ProtoConvertible[T]` protocol for seamless proto \u2194 Python model mapping\n- **\u2705 Enhanced Type Safety** - Pydantic models with generic protocols, custom validators, and full mypy/pyright support\n- **\ud83d\udcb0 Financial Precision** - `PreciseDecimal` with 6-decimal precision for all monetary calculations\n- **\ud83c\udfaf Advanced Enums** - Business logic-aware enums with proto conversion and string parsing\n- **\ud83d\udce1 Event-Driven Architecture** - Comprehensive event routing for market data, orders, positions, and account updates\n- **\ud83d\udd27 Robust gRPC Server** - Exponential backoff retry, health checks, and graceful error handling\n- **\u2601\ufe0f Production Ready** - Deploy directly to Tektii's cloud infrastructure with built-in validation\n\n## \ud83d\udce6 Installation\n\n### Requirements\n\n- Python 3.11 or higher\n- pip or poetry\n\n### Install from PyPI\n\n```bash\npip install tektii\n```\n\n### Install with Proto Dependencies\n\nThe SDK uses pre-built protobuf packages from buf.build:\n\n```bash\npip install tektii --extra-index-url https://buf.build/gen/python\n```\n\n### Install for Development\n\n```bash\n# Clone the repository\ngit clone https://github.com/tektii/tektii-sdk-python.git\ncd tektii-sdk-python\n\n# Quick setup (creates venv, installs deps, proto packages)\nmake setup\n\n# Or manual setup:\npython -m venv .venv\nsource .venv/bin/activate  # On Windows: .venv\\Scripts\\activate\npip install -e \".[dev]\" --extra-index-url https://buf.build/gen/python\n```\n\n## \ud83c\udfaf Getting Started\n\n### Step 1: Set Up Your Development Environment\n\n```bash\n# Create a new directory for your strategy\nmkdir my-trading-strategy\ncd my-trading-strategy\n\n# Create a Python virtual environment\npython -m venv venv\n\n# Activate the virtual environment\n# On macOS/Linux:\nsource venv/bin/activate\n# On Windows:\nvenv\\Scripts\\activate\n\n# Create a requirements.txt file\necho \"tektii\" > requirements.txt\n\n# Install the Tektii SDK\npip install -r requirements.txt\n```\n\n### Step 2: Create Your Strategy from Template\n\n```bash\n# Use the Tektii CLI to create a new strategy\ntektii new my-strategy\n\n# This creates:\n# - strategy.py: Your strategy implementation\n# - requirements.txt: Python dependencies\n# - config.yaml: Strategy configuration\n# - tests/: Unit tests for your strategy\n# - Dockerfile: For containerized deployment\n# - README.md: Strategy documentation\n```\n\n### Step 3: Explore the Generated Strategy\n\n```bash\n# Navigate to your new strategy\ncd my-strategy\n\n# Open strategy.py in your favorite editor\n# You'll see a template strategy ready for customization\n```\n\n### Step 4: Customize Your Strategy\n\nEdit `strategy.py` to implement your trading logic:\n\n```python\nfrom decimal import Decimal\nfrom typing import Optional\n\nfrom tektii import TektiiStrategy\nfrom tektii.models.strategy.events import TickData, CandleData\nfrom tektii.models.broker.handlers import PlaceOrderRequest\nfrom tektii.models.strategy.types import MarketOrder, OrderSide\n\n\nclass MyStrategy(TektiiStrategy):\n    \"\"\"A simple moving average crossover strategy.\"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.position_size = Decimal(\"100\")\n\n    def on_initialize(self, config: dict[str, str], symbols: list[str]) -> None:\n        \"\"\"Initialize strategy with configuration.\"\"\"\n        self.log_info(f\"Initializing strategy with symbols: {symbols}\")\n        if \"position_size\" in config:\n            self.position_size = Decimal(config[\"position_size\"])\n\n    def on_market_data(\n        self,\n        tick_data: Optional[TickData] = None,\n        candle_data: Optional[CandleData] = None\n    ) -> None:\n        \"\"\"React to incoming market data.\"\"\"\n        if candle_data and candle_data.close > Decimal(\"150.00\"):\n            # Create a market order using the model directly\n            order = MarketOrder(\n                symbol=candle_data.symbol,\n                side=OrderSide.BUY,\n                quantity=self.position_size\n            )\n\n            # Submit through broker service\n            request = PlaceOrderRequest(order=order)\n            response = self.place_order(request)\n\n            if response.success:\n                self.log_info(f\"Order placed: {response.order_id}\")\n```\n\n### Step 5: Test Your Strategy\n\n```bash\n# Validate your strategy implementation\ntektii validate\n\n# Run tests with the mock broker\ntektii serve --mock-broker\n\n# Or use pytest directly for custom tests\npytest tests/ -xvs\n```\n\nWrite custom tests using the mock broker:\n\n```python\nfrom tektii.testing import StrategyTestHarness\nfrom tektii.testing.fixtures import create_candle_data\n\n\ndef test_my_strategy():\n    # Create test harness\n    harness = StrategyTestHarness(MyStrategy)\n\n    # Send test market data\n    test_candle = create_candle_data(\n        symbol=\"AAPL\",\n        close=Decimal(\"151.00\")  # Above our threshold\n    )\n    harness.process_candle_data(test_candle)\n\n    # Verify order was created\n    orders = harness.get_orders()\n    assert len(orders) == 1\n    assert orders[0].side == OrderSide.BUY\n```\n\n### Step 6: Run Your Strategy Locally\n\n```bash\n# Validate your strategy code\ntektii validate\n\n# Run strategy as a gRPC service\ntektii serve --port 50051\n\n# Your strategy is now ready to receive market data!\n```\n\n### Step 7: Deploy to Tektii Platform\n\n```bash\n# Deploy your strategy to the cloud\ntektii push\n\n# View deployment logs\ntektii logs\n\n# Check deployment status\ntektii status\n```\n\n## \ud83d\udcd6 Examples\n\n### Moving Average Crossover Strategy\n\nCheck out our complete example in [`examples/basic_ma_crossover.py`](examples/basic_ma_crossover.py) that demonstrates:\n\n- Price history management with collections.deque\n- Moving average calculation and crossover detection\n- Order placement using the dual-service model architecture\n- Comprehensive event handling (market data, order updates, positions)\n- Proper logging and error handling\n\n```python\n# Run the example locally with mock broker\ntektii serve --strategy examples.basic_ma_crossover:MovingAverageCrossoverStrategy --mock-broker\n\n# Or run directly\npython examples/basic_ma_crossover.py\n```\n\n### More Examples Coming Soon\n\n- **Mean Reversion Strategy** - Statistical arbitrage with z-score calculations\n- **Pairs Trading** - Market-neutral strategy with cointegration\n- **Options Strategy** - Delta-neutral options trading with Greeks\n- **Portfolio Optimization** - Multi-asset allocation with risk parity\n\n## \ud83d\udcda Core Concepts\n\n### Dual-Service Architecture\n\nThe SDK separates broker operations from strategy logic for clean, maintainable code:\n\n```\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502                     Your Strategy                                   \u2502\n\u2502  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502\n\u2502  \u2502 on_market_data() | on_order_update() | on_position_update() \u2502  \u2502\n\u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2193\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2191\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2514  \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2193\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2191\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                             \u2193                           \u2191\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2193\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2191\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502              Strategy Service          \u2194   gRPC   \u2194   Broker Service              \u2502\n\u2502  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510                         \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510  \u2502\n\u2502  \u2502 Events: Market Data    \u2502                         \u2502 Handlers: Orders     \u2502  \u2502\n\u2502  \u2502 Types: Order Models    \u2502                         \u2502 Types: Positions     \u2502  \u2502\n\u2502  \u2502 Proto: Conversions     \u2502                         \u2502 Proto: Conversions   \u2502  \u2502\n\u2502  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518                         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518  \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\n\n#### Broker Service Models (`tektii.models.broker`)\n- Handles communication with trading brokers\n- Request/response models for order placement, cancellation, state queries\n- Core types: `Order`, `Account`, `Position`, `Fill`\n\n#### Strategy Service Models (`tektii.models.strategy`)\n- Handles strategy-specific events and processing\n- Event models for market data, order updates, position changes\n- Strategy-specific types with business logic\n\n#### Proto Conversion Protocol\n\nAll models implement the `ProtoConvertible[T]` protocol for seamless proto conversion:\n\n```python\nfrom tektii.models.base import ProtoConvertible\nfrom tektii.models.strategy.types import MarketOrder\n\n# All models have bidirectional proto conversion\norder = MarketOrder(\n    symbol=\"AAPL\",\n    side=OrderSide.BUY,\n    quantity=Decimal(\"100\")\n)\n\n# Convert to proto for gRPC transmission\nproto_msg = order.to_proto()\n\n# Reconstruct from proto with full type safety\nreconstructed = MarketOrder.from_proto(proto_msg)\nassert order == reconstructed\n```\n\n### Strategy Development\n\nYour strategy should inherit from `TektiiStrategy` and implement the event handlers:\n\n```python\nfrom typing import Optional\nfrom decimal import Decimal\n\nfrom tektii import TektiiStrategy\nfrom tektii.models.strategy.events import (\n    TickData, CandleData, OrderUpdateEvent,\n    PositionUpdateEvent, AccountUpdateEvent\n)\nfrom tektii.models.broker.handlers import PlaceOrderRequest\nfrom tektii.models.strategy.types import MarketOrder, OrderSide\n\nclass MyStrategy(TektiiStrategy):\n    def on_initialize(self, config: dict[str, str], symbols: list[str]) -> None:\n        \"\"\"Initialize strategy with configuration.\"\"\"\n        self.symbols = symbols\n        self.position_size = Decimal(config.get(\"position_size\", \"100\"))\n        self.log_info(f\"Strategy initialized for {len(symbols)} symbols\")\n\n    def on_market_data(\n        self,\n        tick_data: Optional[TickData] = None,\n        candle_data: Optional[CandleData] = None\n    ) -> None:\n        \"\"\"Handle incoming market data.\"\"\"\n        if candle_data:\n            # Your trading logic here\n            if self.should_buy(candle_data):\n                order = MarketOrder(\n                    symbol=candle_data.symbol,\n                    side=OrderSide.BUY,\n                    quantity=self.position_size\n                )\n                request = PlaceOrderRequest(order=order)\n                response = self.place_order(request)\n\n    def on_order_update(self, order_update: OrderUpdateEvent) -> None:\n        \"\"\"Handle order status updates.\"\"\"\n        if order_update.status.is_terminal():\n            self.log_info(f\"Order {order_update.order_id} completed: {order_update.status}\")\n\n    def on_position_update(self, position_update: PositionUpdateEvent) -> None:\n        \"\"\"Handle position changes.\"\"\"\n        self.log_info(f\"Position updated: {position_update.symbol} qty={position_update.quantity}\")\n\n    def on_account_update(self, account_update: AccountUpdateEvent) -> None:\n        \"\"\"Handle account updates.\"\"\"\n        self.log_info(f\"Account balance: {account_update.balance}\")\n\n    def on_shutdown(self) -> None:\n        \"\"\"Clean up resources.\"\"\"\n        self.log_info(\"Strategy shutting down gracefully\")\n```\n\n### Order Management\n\nThe SDK provides multiple ways to create and manage orders:\n\n#### 1. Direct Model Creation (Recommended)\n\n```python\nfrom decimal import Decimal\nfrom tektii.models.broker.handlers import PlaceOrderRequest\nfrom tektii.models.strategy.types import (\n    MarketOrder, LimitOrder, StopOrder, StopLimitOrder,\n    OrderSide, TimeInForce\n)\n\n# Market order - executes immediately at current price\nmarket_order = MarketOrder(\n    symbol=\"AAPL\",\n    side=OrderSide.BUY,\n    quantity=Decimal(\"100\")\n)\n\n# Limit order - executes at specified price or better\nlimit_order = LimitOrder(\n    symbol=\"GOOGL\",\n    side=OrderSide.SELL,\n    quantity=Decimal(\"50\"),\n    limit_price=Decimal(\"2500.00\"),\n    time_in_force=TimeInForce.GTC  # Good Till Cancelled\n)\n\n# Stop order - becomes market order when stop price is reached\nstop_order = StopOrder(\n    symbol=\"MSFT\",\n    side=OrderSide.SELL,\n    quantity=Decimal(\"200\"),\n    stop_price=Decimal(\"380.00\")\n)\n\n# Stop-limit order - becomes limit order when stop price is reached\nstop_limit = StopLimitOrder(\n    symbol=\"TSLA\",\n    side=OrderSide.BUY,\n    quantity=Decimal(\"10\"),\n    stop_price=Decimal(\"700.00\"),\n    limit_price=Decimal(\"705.00\")\n)\n```\n\n#### 2. Submit Orders Through Broker Service\n\n```python\n# Create request and submit to broker\nrequest = PlaceOrderRequest(order=market_order)\nresponse = self.place_order(request)\n\nif response.success:\n    self.log_info(f\"Order placed: {response.order_id}\")\n    # Track order for later management\n    self.active_orders[response.order_id] = market_order\nelse:\n    self.log_error(f\"Order failed: {response.message}\")\n```\n\n#### 3. Order Lifecycle Management\n\n```python\nfrom tektii.models.broker.handlers import (\n    CancelOrderRequest,\n    ModifyOrderRequest,\n    GetOrderStatusRequest\n)\n\n# Cancel an order\ncancel_request = CancelOrderRequest(order_id=\"order_123\")\ncancel_response = self.cancel_order(cancel_request)\n\n# Modify an existing order\nmodify_request = ModifyOrderRequest(\n    order_id=\"order_123\",\n    new_quantity=Decimal(\"150\"),\n    new_limit_price=Decimal(\"155.50\")\n)\nmodify_response = self.modify_order(modify_request)\n\n# Check order status\nstatus_request = GetOrderStatusRequest(order_id=\"order_123\")\nstatus_response = self.get_order_status(status_request)\n\nif status_response.order.status.is_terminal():\n    self.log_info(\"Order completed\")\n```\n\n### Error Handling & Validation\n\nThe SDK provides comprehensive error handling with Pydantic validation:\n\n```python\nfrom pydantic import ValidationError\nfrom tektii.models.strategy.types import OrderStatus, OrderSide\nfrom tektii.models.base import PreciseDecimal\n\ntry:\n    # Pydantic validation\n    order = MarketOrder(\n        symbol=\"AAPL\",\n        side=\"INVALID\",  # Will raise ValidationError\n        quantity=Decimal(\"100\")\n    )\nexcept ValidationError as e:\n    self.log_error(f\"Order validation failed: {e}\")\n\n# Business logic methods on enums\nstatus = OrderStatus.FILLED\nif status.is_terminal():  # FILLED, CANCELLED, REJECTED, EXPIRED\n    self.log_info(\"Order completed\")\n\n# Financial precision handling\nprice = PreciseDecimal(\"123.456789\")  # Automatically rounds to 6 decimals\nassert price == Decimal(\"123.456789\")\n\n# Proto conversion with type safety\nproto_order = order.to_proto()  # Type-safe conversion\nreconstructed = MarketOrder.from_proto(proto_order)\nassert order == reconstructed\n```\n\n## \ud83e\uddea Testing\n\nThe SDK includes comprehensive testing utilities:\n\n```bash\n# Run all quality checks\nmake check  # Runs lint, type-check, and tests\n\n# Individual test commands\nmake test           # Run all tests with coverage\nmake test-fast      # Skip slow tests\nmake test-security  # Run security tests with bandit\n\n# Run specific test file\npytest tests/test_.py -xvs\n\n# Development workflow\nmake format         # Auto-format code\nmake lint          # Check code style\nmake type-check    # Verify type annotations\n```\n\n### Writing Tests\n\n```python\nimport pytest\nfrom decimal import Decimal\nfrom tektii.testing import MockBrokerService\nfrom tektii.models.strategy.events import CandleData\n\n\nclass TestMyStrategy:\n    def test_strategy_initialization(self):\n        # Initialize with mock broker\n        mock_broker = MockBrokerService()\n        strategy = MyStrategy()\n        strategy.broker = mock_broker\n\n        # Test initialization\n        config = {\"position_size\": \"100\"}\n        symbols = [\"AAPL\", \"GOOGL\"]\n        strategy.on_initialize(config, symbols)\n\n        assert strategy.position_size == Decimal(\"100\")\n\n    def test_order_creation_on_signal(self):\n        mock_broker = MockBrokerService()\n        strategy = MyStrategy()\n        strategy.broker = mock_broker\n\n        # Create test candle data\n        candle = CandleData(\n            symbol=\"AAPL\",\n            timestamp=datetime.now(),\n            open=Decimal(\"150.00\"),\n            high=Decimal(\"156.00\"),\n            low=Decimal(\"149.00\"),\n            close=Decimal(\"155.00\"),\n            volume=1000000\n        )\n\n        # Process market data\n        strategy.on_market_data(candle_data=candle)\n\n        # Verify order was placed\n        orders = mock_broker.get_orders()\n        assert len(orders) == 1\n        assert orders[0].symbol == \"AAPL\"\n```\n\n## \ud83d\udd27 CLI Commands\n\nThe Tektii CLI provides commands for the complete development lifecycle:\n\n| Command             | Aliases       | Description                         |\n| ------------------- | ------------- | ----------------------------------- |\n| `tektii new <name>` | `n`, `create` | Create a new strategy from template |\n| `tektii serve`      | `s`, `run`    | Run strategy as gRPC service        |\n| `tektii validate`   | `v`, `check`  | Validate strategy implementation    |\n| `tektii push`       | `p`, `deploy` | Deploy to Tektii platform           |\n| `tektii backtest`   | `bt`          | Run strategy backtest on platform   |\n| `tektii analyze`    | `a`           | Analyze backtest results            |\n\n### Development Mode\n\n```bash\n# Run with mock broker for development\ntektii serve --mock-broker\n\n# Specify custom port\ntektii serve --port 50051\n\n# Validate without deploying\ntektii push --dry-run\n```\n\n## \ud83c\udfd7\ufe0f SDK Architecture\n\n```\ntektii/\n\u251c\u2500\u2500 __init__.py              # Public API exports\n\u251c\u2500\u2500 strategy.py              # TektiiStrategy base class & gRPC server\n\u251c\u2500\u2500 cli.py                   # CLI entry point with command routing\n\u251c\u2500\u2500 models/\n\u2502   \u251c\u2500\u2500 base.py             # ProtoConvertible[T] protocol & PreciseDecimal\n\u2502   \u251c\u2500\u2500 broker/             # Broker service models (orders, positions, fills)\n\u2502   \u2502   \u251c\u2500\u2500 handlers/       # Request/response models for broker ops\n\u2502   \u2502   \u2502   \u251c\u2500\u2500 place_order.py      # PlaceOrderRequest/Response\n\u2502   \u2502   \u2502   \u251c\u2500\u2500 cancel_order.py     # CancelOrderRequest/Response\n\u2502   \u2502   \u2502   \u251c\u2500\u2500 get_state.py        # GetStateRequest/Response\n\u2502   \u2502   \u2502   \u2514\u2500\u2500 ...                 # Other broker operations\n\u2502   \u2502   \u2514\u2500\u2500 types/          # Core broker types with proto conversion\n\u2502   \u2514\u2500\u2500 strategy/           # Strategy service models\n\u2502       \u251c\u2500\u2500 events/         # Market data and update events\n\u2502       \u2502   \u251c\u2500\u2500 tick_data.py        # Tick-level market data\n\u2502       \u2502   \u251c\u2500\u2500 candle_data.py      # OHLCV candle data\n\u2502       \u2502   \u2514\u2500\u2500 order_update.py     # Order status updates\n\u2502       \u251c\u2500\u2500 handlers/       # Strategy service handlers\n\u2502       \u2514\u2500\u2500 types/          # Strategy types with business logic\n\u251c\u2500\u2500 testing/                # Testing utilities\n\u2502   \u2514\u2500\u2500 mock_broker.py      # MockBrokerService for development\n\u2514\u2500\u2500 commands/               # CLI command implementations\n    \u251c\u2500\u2500 new.py             # Strategy template generation\n    \u251c\u2500\u2500 serve.py           # gRPC server with retry logic\n    \u251c\u2500\u2500 validator.py       # Strategy validation\n    \u251c\u2500\u2500 push.py            # Deploy to Tektii platform\n    \u2514\u2500\u2500 backtest.py        # Run backtests on platform\n```\n\n## \ud83c\udfd7\ufe0f Strategy Project Structure\n\nWhen you run `tektii new my-strategy`, it creates:\n\n```\nmy-strategy/\n\u251c\u2500\u2500 strategy.py          # Your strategy implementation\n\u251c\u2500\u2500 requirements.txt     # Python dependencies (includes tektii)\n\u251c\u2500\u2500 config.yaml         # Strategy configuration\n\u251c\u2500\u2500 tests/\n\u2502   \u251c\u2500\u2500 __init__.py\n\u2502   \u251c\u2500\u2500 test_strategy.py  # Unit tests for your strategy\n\u2502   \u2514\u2500\u2500 fixtures.py       # Test fixtures and helpers\n\u251c\u2500\u2500 Dockerfile          # Container for cloud deployment\n\u251c\u2500\u2500 .dockerignore       # Docker build exclusions\n\u2514\u2500\u2500 README.md          # Strategy documentation\n```\n\n### Configuration (config.yaml)\n\n```yaml\nname: my-strategy\nversion: 1.0.0\ndescription: My trading strategy\nauthor: Your Name\n\n# Strategy parameters\nparameters:\n  position_size: \"100\"\n  max_positions: \"5\"\n  stop_loss_percent: \"2.0\"\n\n# Trading symbols\nsymbols:\n  - AAPL\n  - GOOGL\n  - MSFT\n\n# Risk management\nrisk:\n  max_drawdown: \"10.0\"\n  position_sizing: \"fixed\"\n```\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Here's how to get started:\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes and add tests\n4. Run quality checks (`make check`)\n5. Commit your changes (`git commit -m 'Add amazing feature'`)\n6. Push to the branch (`git push origin feature/amazing-feature`)\n7. Open a Pull Request\n\n### Development Workflow\n\n```bash\n# Complete first-time setup\nmake setup\n\n# Before committing changes\nmake check  # Runs all quality checks\n\n# Auto-fix issues\nmake format  # Format with black and isort\n\n# Clean up\nmake clean  # Remove caches and build artifacts\n\n# Build distribution\nmake build  # Create wheel and sdist packages\n```\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.\n\n## \ud83d\udd17 Resources\n\n- **\ud83d\udcd6 Documentation:** [docs.tektii.com/sdk](https://docs.tektii.com/sdk)\n- **\ud83d\udd27 API Reference:** [docs.tektii.com/sdk/api](https://docs.tektii.com/sdk/api)\n- **\ud83d\udca1 Examples:** [examples/](https://github.com/tektii/tektii-sdk-python/tree/main/examples) - Working strategy implementations\n- **\ud83d\udce6 PyPI Package:** [pypi.org/project/tektii](https://pypi.org/project/tektii/)\n- **\ud83d\uddfa\ufe0f Roadmap:** [GitHub Projects](https://github.com/tektii/tektii-sdk-python/projects/1)\n\n## \ud83d\udcac Support\n\n- **Issues & Bugs:** [GitHub Issues](https://github.com/tektii/tektii-sdk-python/issues)\n- **Discussions:** [GitHub Discussions](https://github.com/tektii/tektii-sdk-python/discussions)\n- **Community:** [Discord Server](https://discord.gg/tektii)\n- **Questions:** [Stack Overflow](https://stackoverflow.com/questions/tagged/tektii)\n- **Email:** support@tektii.com\n\n## \ud83c\udfc6 Acknowledgments\n\nBuilt with \u2764\ufe0f by the Tektii team. Special thanks to all our contributors and the open-source community.\n\n### Key Technologies\n\n- **[gRPC](https://grpc.io/)** - High-performance RPC framework\n- **[Pydantic](https://pydantic.dev/)** - Data validation using Python type annotations\n- **[Protobuf](https://protobuf.dev/)** - Protocol buffers for serialization\n- **[buf.build](https://buf.build/)** - Modern protobuf toolchain\n\n---\n\n<div align=\"center\">\n  <b>Ready to build your trading strategy?</b><br>\n  <a href=\"https://docs.tektii.com/sdk/quickstart\">Get Started with Tutorials \u2192</a> |\n  <a href=\"https://github.com/tektii/tektii-sdk-python/tree/main/examples\">View Examples \u2192</a> |\n  <a href=\"https://discord.gg/tektii\">Join Discord \u2192</a>\n</div>\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Build trading strategies that run anywhere - Write Once. Trade Everywhere.",
    "version": "1.3.0",
    "project_urls": {
        "Changelog": "https://github.com/tektii/tektii-sdk-python/blob/main/CHANGELOG.md",
        "Documentation": "https://docs.tektii.com/sdk",
        "Homepage": "https://tektii.com",
        "Issues": "https://github.com/tektii/tektii-sdk-python/issues",
        "Repository": "https://github.com/tektii/tektii-sdk-python"
    },
    "split_keywords": [
        "trading",
        " algorithmic-trading",
        " algo-trading",
        " quantitative-finance",
        " finance",
        " fintech",
        " strategy",
        " backtesting",
        " grpc",
        " trading-bot",
        " trading-strategies",
        " market-data",
        " portfolio-management"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e6c1d955ced19638f74429c48dabace827b5151ff9c930cf16925894270c3d6b",
                "md5": "69022075b517e46722e2ad6cd4ef3c65",
                "sha256": "fd09271d101f39e3a5adf8637a5967b599d407d91464482416e7a18175e77515"
            },
            "downloads": -1,
            "filename": "tektii-1.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "69022075b517e46722e2ad6cd4ef3c65",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 100741,
            "upload_time": "2025-08-13T11:31:33",
            "upload_time_iso_8601": "2025-08-13T11:31:33.631763Z",
            "url": "https://files.pythonhosted.org/packages/e6/c1/d955ced19638f74429c48dabace827b5151ff9c930cf16925894270c3d6b/tektii-1.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "92b2519c93d328d9e86bee2e654cb0fe846ad8d152efd0f201f3731605253e7b",
                "md5": "c5af572029e0dae555b4ac091ecfa35d",
                "sha256": "7fa86fb62941d2694541e7ed0adc8637450d5f357cbdbbf2dd217b2e68c2c6fa"
            },
            "downloads": -1,
            "filename": "tektii-1.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "c5af572029e0dae555b4ac091ecfa35d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 91755,
            "upload_time": "2025-08-13T11:31:35",
            "upload_time_iso_8601": "2025-08-13T11:31:35.367878Z",
            "url": "https://files.pythonhosted.org/packages/92/b2/519c93d328d9e86bee2e654cb0fe846ad8d152efd0f201f3731605253e7b/tektii-1.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-13 11:31:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "tektii",
    "github_project": "tektii-sdk-python",
    "github_not_found": true,
    "lcname": "tektii"
}
        
Elapsed time: 0.75164s