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
167 changes: 167 additions & 0 deletions .github/.copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# Python Kraken SDK - Copilot Instructions

## Project Overview

This is the **python-kraken-sdk** - a high-performance REST and WebSocket API
client for Kraken Crypto Asset Exchange supporting both Spot and Futures
trading. The SDK prioritizes performance, maintainability, reliability,
modularization, and code reuse.

## Core Principles

### Code Quality Standards

- **Performance First**: Optimize for speed and memory efficiency
- **Maintainability**: Write clean, readable, self-documenting code
- **Reliability**: Implement robust error handling and comprehensive testing
- **Modularization**: Favor composition over inheritance, create reusable
components
- **DRY Principle**: Eliminate code duplication through shared utilities and
base classes

### Comment Philosophy

- **Minimal Comments**: Code should be self-explanatory through clear naming and
structure
- **Only When Necessary**: Add comments only for non-obvious business logic,
complex algorithms, or API-specific quirks
- **No Obvious Comments**: Avoid stating what the code clearly does
- **Focus on Why**: When commenting, explain the reasoning, not the mechanics

## Project Structure

```
src/kraken/
├── __init__.py # Main package exports
├── cli.py # Command-line interface
├── base_api/ # Core base classes and utilities
│ └── __init__.py # SpotClient, FuturesClient, SpotAsyncClient, FuturesAsyncClient
├── exceptions/ # Custom exception classes
│ └── __init__.py # KrakenException hierarchy
├── utils/ # Shared utilities and helpers
├── spot/ # Spot trading API
│ ├── __init__.py # Spot client exports
│ ├── market.py # Market data client
│ ├── trade.py # Trading operations client
│ ├── user.py # User account client
│ ├── funding.py # Funding operations client
│ ├── earn.py # Earn/staking client
│ ├── orderbook.py # Order book client
│ ├── ws_client.py # WebSocket client implementation
│ └── websocket/ # WebSocket infrastructure
│ ├── __init__.py # SpotWSClientBase
│ └── connectors.py # Connection management
└── futures/ # Futures trading API
├── __init__.py # Futures client exports
├── market.py # Futures market data
├── trade.py # Futures trading
├── user.py # Futures user account
├── funding.py # Futures funding
├── ws_client.py # Futures WebSocket client
└── websocket/ # Futures WebSocket infrastructure
```

## Architecture Patterns

### Client Hierarchy

- **Base Classes**: `SpotClient`, `FuturesClient` (REST), `SpotAsyncClient`,
`FuturesAsyncClient` (async REST)
- **Specialized Clients**: Market, Trade, User, Funding, Earn (inherit from
base)
- **WebSocket Clients**: `SpotWSClient`, `FuturesWSClient` (extend async base
classes)

### Key Design Patterns

- **Composition over Inheritance**: Favor utility functions and mixins
- **Async/Await**: All WebSocket and async operations use proper async patterns
- **Context Managers**: Support `async with` for resource management
- **Type Hints**: Comprehensive typing with `typing` and `TYPE_CHECKING`
- **Error Handling**: Custom exception hierarchy with specific error types

## Development Guidelines

### Code Style

- **Python 3.11+**: Use modern Python features and syntax
- **Type Annotations**: All functions must have complete type hints
- **Docstrings**: Use Google-style docstrings for public APIs
- **Naming**: Clear, descriptive names that eliminate need for comments

### Performance Optimization

- **Async Operations**: Use async/await for I/O operations
- **Connection Pooling**: Reuse HTTP connections where possible
- **Memory Efficiency**: Avoid unnecessary object creation in hot paths
- **Caching**: Use `@lru_cache` for expensive computations
- **Lazy Loading**: Initialize resources only when needed

### Error Handling

- **Custom Exceptions**: Use specific exception types from `kraken.exceptions`
- **Graceful Degradation**: Handle network failures and API errors robustly
- **Retry Logic**: Implement exponential backoff for transient failures
- **Logging**: Use structured logging with appropriate levels

### Testing Standards

- **Comprehensive Coverage**: Aim for high test coverage
- **Unit Tests**: Test individual components in isolation
- **Integration Tests**: Test API interactions (with mocking when needed)
- **Class-Based Organization**: Use pytest classes with shared fixtures and
constants
- **Helper Methods**: Create reusable assertion helpers to eliminate duplication

### WebSocket Patterns

- **Connection Management**: Proper connection lifecycle handling
- **Subscription Management**: Track active subscriptions
- **Message Routing**: Efficient message dispatch to handlers
- **Reconnection Logic**: Automatic reconnection with backoff

## Code Generation Guidelines

### When Creating New Features

1. **Extend Existing Patterns**: Follow established client patterns
2. **Reuse Base Classes**: Inherit from appropriate base classes
3. **Share Common Logic**: Extract reusable components
4. **Maintain API Consistency**: Follow existing parameter and return patterns
5. **Add Comprehensive Tests**: Include unit and integration tests

### When Refactoring

1. **Preserve Public APIs**: Maintain backward compatibility
2. **Improve Performance**: Look for optimization opportunities
3. **Reduce Complexity**: Simplify complex methods through decomposition
4. **Enhance Type Safety**: Add or improve type annotations
5. **Update Tests**: Ensure tests reflect changes

### Specific Preferences

- **Constants**: Use UPPER_CASE for module-level constants
- **Private Methods**: Use single underscore prefix for internal methods
- **Property Methods**: Use `@property` for computed attributes
- **Context Managers**: Implement `__enter__`/`__exit__` or
`__aenter__`/`__aexit__` when managing resources

## API Design Philosophy

- **Pythonic Interface**: Feel natural to Python developers
- **Sensible Defaults**: Minimize required parameters
- **Flexibility**: Support both high-level convenience and low-level control
- **Performance**: Optimize for common use cases
- **Documentation**: Self-documenting through clear parameter names and types

## Testing Philosophy

- **Fast Feedback**: Tests should run quickly
- **Reliable**: Tests should not be flaky
- **Isolated**: Each test should be independent
- **Realistic**: Test real scenarios, not just edge cases
- **Maintainable**: Tests should be easy to understand and modify

Remember: The goal is to create a professional, high-performance SDK that
developers love to use. Prioritize clarity, performance, and reliability in all
code contributions.
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,8 @@ task-tags = ["todo", "TODO", "fixme", "FIXME"]
"S311", # pseudo-random-generator
"SLF001", # private member access
"TID252", # ban relative imports
"PLR0904", # too many public methods
"ANN401", # Use of typing.Any
]

[tool.ruff.lint.flake8-copyright]
Expand Down
28 changes: 14 additions & 14 deletions tests/futures/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,19 @@
FUTURES_EXTENDED_TIMEOUT: int = 30


@pytest.fixture
@pytest.fixture(scope="session")
def futures_api_key() -> str:
"""Returns the Futures API key"""
return FUTURES_API_KEY


@pytest.fixture
@pytest.fixture(scope="session")
def futures_secret_key() -> str:
"""Returns the Futures API secret key"""
return FUTURES_SECRET_KEY


@pytest.fixture
@pytest.fixture(scope="session")
def futures_market() -> Market:
"""
Fixture providing an unauthenticated Futures Market client
Expand All @@ -40,7 +40,7 @@ def futures_market() -> Market:
return market


@pytest.fixture
@pytest.fixture(scope="session")
def futures_auth_market() -> Market:
"""
Fixture providing an authenticated Futures Market client.
Expand All @@ -50,7 +50,7 @@ def futures_auth_market() -> Market:
return market


@pytest.fixture
@pytest.fixture(scope="session")
def futures_demo_market() -> Market:
"""
Fixture providing an authenticated Futures Market client that
Expand All @@ -65,7 +65,7 @@ def futures_demo_market() -> Market:
return market


@pytest.fixture
@pytest.fixture(scope="session")
def futures_user() -> User:
"""
Fixture providing an unauthenticated Futures User client.
Expand All @@ -75,7 +75,7 @@ def futures_user() -> User:
return user


@pytest.fixture
@pytest.fixture(scope="session")
def futures_auth_user() -> User:
"""
Fixture providing an authenticated Futures User client.
Expand All @@ -85,7 +85,7 @@ def futures_auth_user() -> User:
return user


@pytest.fixture
@pytest.fixture(scope="session")
def futures_demo_user() -> User:
"""
Fixture providing an authenticated Futures User client that
Expand All @@ -100,7 +100,7 @@ def futures_demo_user() -> User:
return user


@pytest.fixture
@pytest.fixture(scope="session")
def futures_trade() -> Trade:
"""
Fixture providing an unauthenticated Futures Trade client.
Expand All @@ -110,7 +110,7 @@ def futures_trade() -> Trade:
return trade


@pytest.fixture
@pytest.fixture(scope="session")
def futures_auth_trade() -> Trade:
"""
Fixture providing an authenticated Futures Trade client.
Expand All @@ -120,7 +120,7 @@ def futures_auth_trade() -> Trade:
return trade


@pytest.fixture
@pytest.fixture(scope="session")
def futures_demo_trade() -> Trade:
"""
Fixture providing an authenticated Futures Trade client that
Expand All @@ -135,7 +135,7 @@ def futures_demo_trade() -> Trade:
return trade


@pytest.fixture
@pytest.fixture(scope="session")
def futures_funding() -> Funding:
"""
Fixture providing an unauthenticated Futures Funding client.
Expand All @@ -145,7 +145,7 @@ def futures_funding() -> Funding:
return funding


@pytest.fixture
@pytest.fixture(scope="session")
def futures_auth_funding() -> Funding:
"""
Fixture providing an authenticated Futures Funding client.
Expand All @@ -155,7 +155,7 @@ def futures_auth_funding() -> Funding:
return funding


@pytest.fixture
@pytest.fixture(scope="session")
def futures_demo_funding() -> Funding:
"""
Fixture providing an authenticated Futures Funding client that
Expand Down
Loading
Loading