Skip to main content

Python library for HaasOnline API - Free for individual traders and research institutions. Commercial licensing available for hedge funds and financial institutions.

Project description

pyHaasAPI

A comprehensive Python library for interacting with the HaasOnline Trading Bot API.

๐Ÿš€ Quick Start

from pyHaasAPI import api
from pyHaasAPI.model import CreateLabRequest

# Authenticate
executor = api.RequestsExecutor(host="127.0.0.1", port=8090, state=api.Guest())
auth_executor = executor.authenticate(email="your_email", password="your_password")

# Create a lab with proper market and account assignment
from pyHaasAPI.model import CloudMarket
market = CloudMarket(category="SPOT", price_source="BINANCE", primary="BTC", secondary="USDT")

req = CreateLabRequest.with_generated_name(
    script_id="your_script_id",
    account_id="your_account_id", 
    market=market,
    exchange_code="BINANCE",
    interval=1,
    default_price_data_style="CandleStick"
)

lab = api.create_lab(auth_executor, req)
print(f"Lab created: {lab.lab_id}")

๐Ÿ“š Documentation

๐Ÿ”ง Recent Fixes

Market and Account Assignment Fix โœ…

Issue: Labs were being created with incorrect or empty market tags and account IDs, causing them to be queued with wrong market information.

Solution: Fixed HTTP method and data format issues in the API layer, ensuring proper market and account assignment.

Key Changes:

  • Fixed POST request handling for lab updates
  • Added proper JSON encoding for complex objects
  • Fixed indentation and syntax errors
  • Enhanced parameter handling for both dict and object types

Verification: The examples/lab_full_rundown.py script now successfully creates labs with correct market tags and account IDs.

๐ŸŽฏ Key Features

  • Lab Management: Create, update, clone, and delete labs (see Lab Workflows Guide)
  • Market Operations: Fetch markets, prices, and order books
  • Account Management: Manage trading accounts and balances
  • Script Management: Upload, edit, and manage trading scripts
  • Backtesting: Run comprehensive backtests with parameter optimization
  • Bot Management: Create and manage live trading bots
  • Order Management: Place and manage trading orders

๐Ÿ“ฆ Installation

pip install pyHaasAPI

๐Ÿ”‘ Authentication

from pyHaasAPI import api

# Create executor
executor = api.RequestsExecutor(
    host="127.0.0.1",  # HaasOnline API host
    port=8090,         # HaasOnline API port
    state=api.Guest()
)

# Authenticate
auth_executor = executor.authenticate(
    email="your_email@example.com",
    password="your_password"
)

๐Ÿงช Examples

Basic Lab Creation

from pyHaasAPI import api
from pyHaasAPI.model import CreateLabRequest, CloudMarket

# Setup market and account
market = CloudMarket(category="SPOT", price_source="BINANCE", primary="BTC", secondary="USDT")
account_id = "your_account_id"
script_id = "your_script_id"

# Create lab with proper market assignment
req = CreateLabRequest.with_generated_name(
    script_id=script_id,
    account_id=account_id,
    market=market,
    exchange_code="BINANCE",
    interval=1,
    default_price_data_style="CandleStick"
)

lab = api.create_lab(auth_executor, req)
print(f"Lab created with market: {lab.settings.market_tag}")

Running a Backtest

from pyHaasAPI import lab
from pyHaasAPI.domain import BacktestPeriod

# Run a 30-day backtest
period = BacktestPeriod(period_type=BacktestPeriod.Type.DAY, count=30)
results = lab.backtest(auth_executor, lab.lab_id, period)

print(f"Backtest completed with {len(results.items)} configurations")

Bulk Lab Creation

from pyHaasAPI.market_manager import MarketManager

# Create labs for multiple trading pairs
market_manager = MarketManager(auth_executor)
trading_pairs = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT']

for pair in trading_pairs:
    validation = market_manager.validate_market_setup("BINANCE", pair.split('/')[0], pair.split('/')[1])
    if validation["ready"]:
        # Create lab using the working pattern
        req = CreateLabRequest.with_generated_name(
            script_id=script_id,
            account_id=validation["account"].account_id,
            market=validation["market"],
            exchange_code="BINANCE",
            interval=1,
            default_price_data_style="CandleStick"
        )
        lab = api.create_lab(auth_executor, req)
        print(f"Created lab for {pair}: {lab.lab_id}")

๐Ÿ“Š Market History Sync Utility

Before creating a lab or running a backtest, ensure your market is fully synced and has enough historical data:

from pyHaasAPI import api
success = api.ensure_market_history_ready(executor, "BINANCE_BTC_USDT_", months=36)
if success:
    print("Market is ready for lab creation or backtesting!")
else:
    print("Failed to prepare market history.")

Use this to automate and monitor history sync for any market. See docs/api_reference.md for details.

๐Ÿ› ๏ธ Development

Running Tests

# Run the working example
python -m examples.lab_full_rundown

# Run specific tests
python -m pytest tests/

Project Structure

pyHaasAPI/
โ”œโ”€โ”€ pyHaasAPI/           # Core library
โ”‚   โ”œโ”€โ”€ api.py          # API client and functions
โ”‚   โ”œโ”€โ”€ lab.py          # Lab management functions
โ”‚   โ”œโ”€โ”€ model.py        # Data models and types
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ examples/           # Working examples
โ”‚   โ”œโ”€โ”€ lab_full_rundown.py  # Complete workflow example
โ”‚   โ”œโ”€โ”€ bulk_create_labs_for_pairs.py  # Bulk lab creation
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ docs/              # Documentation
โ”‚   โ”œโ”€โ”€ lab_management.md
โ”‚   โ”œโ”€โ”€ MARKET_ACCOUNT_ASSIGNMENT_FIX.md
โ”‚   โ””โ”€โ”€ ...
โ””โ”€โ”€ tests/             # Test suite

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ†˜ Support

  • Documentation: Check the docs directory
  • Examples: See the examples directory
  • Issues: Report bugs and feature requests on GitHub

๐Ÿ”„ Changelog

Latest Changes

  • โœ… Fixed market and account assignment issues
  • โœ… Enhanced lab creation with proper market tag formatting
  • โœ… Improved parameter handling for both dict and object types
  • โœ… Added comprehensive documentation and examples
  • โœ… Fixed HTTP method and data format issues in API layer

For detailed information about recent fixes, see CHANGES_SUMMARY.md.

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

pyhaasapi-0.1.1.tar.gz (111.3 kB view details)

Uploaded Source

Built Distribution

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

pyhaasapi-0.1.1-py3-none-any.whl (52.2 kB view details)

Uploaded Python 3

File details

Details for the file pyhaasapi-0.1.1.tar.gz.

File metadata

  • Download URL: pyhaasapi-0.1.1.tar.gz
  • Upload date:
  • Size: 111.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.11.13 Darwin/24.5.0

File hashes

Hashes for pyhaasapi-0.1.1.tar.gz
Algorithm Hash digest
SHA256 da023ae14d18240c01543db0a20ca933cf9abb6e0622b0b8f266ac30b7dbbb52
MD5 3fd21daee476853c0596b48314fd0d6a
BLAKE2b-256 65b02578b268b0a289f2fd1163a4a8a322379d28dd10d8990cfa255aeb41f57e

See more details on using hashes here.

File details

Details for the file pyhaasapi-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: pyhaasapi-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 52.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.11.13 Darwin/24.5.0

File hashes

Hashes for pyhaasapi-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 7327b44ad56244e7ebc10b22a87cce2f9f2a90d896120d03bf471498a14f39a6
MD5 51d8720feac8b5fecc1016562ed27974
BLAKE2b-256 d9263918464379aa599d1dc766d3c6b6356f4d29302853289b3bbef8d9e03c1f

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