# fractrade-hl-simple
A simple Python wrapper for the Hyperliquid DEX API, focusing on perpetual futures trading. This library is yet in idea stage and not all features are available yet. We are using it for our own trading platform on fractrade.xyz and will add features as we need them.
⚠️ **Warning**: This is an early version of the library. Use with caution and test thoroughly before trading with real funds. Not all features are available yet.
## Installation & Updates
Using pip:
```bash
# Install
pip install fractrade-hl-simple
# Update to latest version
pip install --upgrade fractrade-hl-simple
```
Using poetry:
```bash
# Install
poetry add fractrade-hl-simple
# Update to latest version
poetry update fractrade-hl-simple
```
⚠️ **Note**: This library is under active development. We recommend updating regularly to get the latest features and fixes.
## Setup
1. Create a `.env` file in your project root:
```env
HYPERLIQUID_ENV=testnet # or mainnet
HYPERLIQUID_PUBLIC_ADDRESS=your_public_address
HYPERLIQUID_PRIVATE_KEY=your_private_key
```
We recommend creating a seperate API key wallet in the Hyperliquid UI for automated trading. This API wallets have not withdrawal permissions.
2. Initialize the client:
```python
from fractrade_hl_simple import HyperliquidClient
client = HyperliquidClient()
```
## Authentication Modes
The client can operate in three modes:
### 1. Authenticated with Environment Variables (Default)
```python
from fractrade_hl_simple import HyperliquidClient
# Automatically loads credentials from .env
client = HyperliquidClient()
```
### 2. Authenticated with Explicit Account
```python
from fractrade_hl_simple import HyperliquidClient, HyperliquidAccount
account = HyperliquidAccount(
private_key="your_private_key",
env="mainnet",
public_address="your_public_address"
)
client = HyperliquidClient(account=account)
```
### 3. Unauthenticated Mode
If no credentials are available, the client falls back to unauthenticated mode:
```python
# No .env file, no account provided
client = HyperliquidClient() # Works for public endpoints only
```
### Public vs Private Endpoints
Some methods can be used without authentication:
```python
# These work without authentication
prices = client.get_price("BTC")
balance = client.get_perp_balance("0x123...") # Requires address
state = client.get_user_state("0x123...") # Requires address
market_info = client.get_market_info()
```
Methods that require authentication:
```python
# These require authentication
client.buy("BTC", 0.001)
client.sell("BTC", 0.001)
client.cancel_all()
client.get_positions()
balance = client.get_perp_balance() # Without address requires auth
```
The client will automatically warn you when running in unauthenticated mode and help you understand which methods are available.
## Basic Usage
### Get Market Prices
```python
# Get single price
btc_price = client.get_price("BTC")
print(f"BTC price: ${btc_price:,.2f}")
# Get all prices
all_prices = client.get_price()
for symbol, price in all_prices.items():
print(f"{symbol}: ${price:,.2f}")
```
### Check Account Balance
```python
balance = client.get_perp_balance()
print(f"Account balance: ${float(balance):,.2f}")
```
### View Positions
```python
positions = client.get_positions()
for pos in positions:
print(f"Position: {pos.symbol} Size: {float(pos.size):+.3f}")
```
### Place Orders
Market Buy:
```python
order = client.buy("BTC", size=0.001) # Market buy 0.001 BTC
print(f"Order placed: {order.order_id}")
```
Limit Buy:
```python
current_price = client.get_price("BTC")
limit_price = current_price * 0.99 # 1% below market
order = client.buy("BTC", size=0.001, limit_price=limit_price)
print(f"Limit order placed: {order.order_id}")
```
Market Sell:
```python
order = client.sell("BTC", size=0.001) # Market sell 0.001 BTC
print(f"Order placed: {order.order_id}")
```
### Stop Loss and Take Profit
For Long Positions:
```python
# When you have a long position (bought BTC)
current_price = client.get_price("BTC")
# Place stop loss 5% below entry (sell when price drops)
stop_price = current_price * 0.95
sl_order = client.stop_loss("BTC", size=0.001, stop_price=stop_price) # is_buy=False by default for long positions
# Place take profit 10% above entry (sell when price rises)
take_profit_price = current_price * 1.10
tp_order = client.take_profit("BTC", size=0.001, take_profit_price=take_profit_price) # is_buy=False by default for long positions
```
For Short Positions:
```python
# When you have a short position (sold BTC)
current_price = client.get_price("BTC")
# Place stop loss 5% above entry (buy when price rises)
stop_price = current_price * 1.05
sl_order = client.stop_loss("BTC", size=0.001, stop_price=stop_price, is_buy=True) # Must set is_buy=True for short positions
# Place take profit 10% below entry (buy when price drops)
take_profit_price = current_price * 0.90
tp_order = client.take_profit("BTC", size=0.001, take_profit_price=take_profit_price, is_buy=True) # Must set is_buy=True for short positions
```
The `is_buy` parameter determines whether the TP/SL order will buy or sell when triggered:
- For long positions: use `is_buy=False` (default) to sell when triggered
- For short positions: use `is_buy=True` to buy when triggered
### Open Position with TP/SL
Alternatively, you can use the convenience methods that handle both entry and TP/SL orders:
Long Position:
```python
current_price = client.get_price("BTC")
position = client.open_long_position(
symbol="BTC",
size=0.001,
stop_loss_price=current_price * 0.95, # 5% below entry
take_profit_price=current_price * 1.10 # 10% above entry
)
print(f"Entry order: {position['entry'].order_id}")
print(f"Stop loss: {position['stop_loss'].order_id}")
print(f"Take profit: {position['take_profit'].order_id}")
```
Short Position:
```python
current_price = client.get_price("BTC")
position = client.open_short_position(
symbol="BTC",
size=0.001,
stop_loss_price=current_price * 1.05, # 5% above entry
take_profit_price=current_price * 0.90 # 10% below entry
)
```
These methods automatically set the correct `is_buy` parameter for TP/SL orders based on the position direction.
### Close Position
```python
close_order = client.close("BTC")
print(f"Position closed with order: {close_order.order_id}")
```
### Cancel Orders
```python
# Cancel orders for specific symbol
client.cancel_all_orders("BTC")
# Cancel all orders across all symbols
client.cancel_all()
```
## Complete Trading Example
Here's a full example showing a basic trading flow:
```python
from fractrade_hl_simple import HyperliquidClient
import time
def main():
client = HyperliquidClient()
SYMBOL = "BTC"
POSITION_SIZE = 0.001
try:
# Check current price
price = client.get_price(SYMBOL)
print(f"Current {SYMBOL} price: ${price:,.2f}")
# Place limit buy order
limit_price = price * 0.99 # 1% below market
order = client.buy(SYMBOL, POSITION_SIZE, limit_price=limit_price)
print(f"Limit order placed: {order.order_id}")
time.sleep(2)
# Cancel limit order if not filled
client.cancel_all_orders(SYMBOL)
# Open market position
order = client.buy(SYMBOL, POSITION_SIZE)
print(f"Position opened with order: {order.order_id}")
# Check position
positions = client.get_positions()
position = next((p for p in positions if p.symbol == SYMBOL), None)
if position:
print(f"Current position: {float(position.size):+.3f} {position.symbol}")
print(f"Entry price: ${float(position.entry_price):,.2f}")
print(f"Unrealized PnL: ${float(position.unrealized_pnl):,.2f}")
# Close position
close_order = client.close(SYMBOL)
print(f"Position closed with order: {close_order.order_id}")
except Exception as e:
print(f"Error: {str(e)}")
# Cleanup
client.cancel_all_orders(SYMBOL)
client.close(SYMBOL)
if __name__ == "__main__":
main()
```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
MIT
## Disclaimer
This software is for educational purposes only. Use at your own risk. The authors take no responsibility for any financial losses incurred while using this software.
```
Raw data
{
"_id": null,
"home_page": "https://fractrade.xyz",
"name": "fractrade-hl-simple",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.12",
"maintainer_email": null,
"keywords": "hyperliquid, trading, crypto, api, defi",
"author": "crjameson",
"author_email": "93468664+crjameson@users.noreply.github.com",
"download_url": "https://files.pythonhosted.org/packages/0d/2d/1cec9950784723aeb2d3503eae66486e2d7b0998744c7e307b4835207d05/fractrade_hl_simple-0.1.5.tar.gz",
"platform": null,
"description": "# fractrade-hl-simple\n\nA simple Python wrapper for the Hyperliquid DEX API, focusing on perpetual futures trading. This library is yet in idea stage and not all features are available yet. We are using it for our own trading platform on fractrade.xyz and will add features as we need them.\n\n\u26a0\ufe0f **Warning**: This is an early version of the library. Use with caution and test thoroughly before trading with real funds. Not all features are available yet. \n\n## Installation & Updates\n\nUsing pip:\n```bash\n# Install\npip install fractrade-hl-simple\n\n# Update to latest version\npip install --upgrade fractrade-hl-simple\n```\n\nUsing poetry:\n```bash\n# Install\npoetry add fractrade-hl-simple\n\n# Update to latest version\npoetry update fractrade-hl-simple\n```\n\n\u26a0\ufe0f **Note**: This library is under active development. We recommend updating regularly to get the latest features and fixes.\n\n## Setup\n\n1. Create a `.env` file in your project root:\n```env\nHYPERLIQUID_ENV=testnet # or mainnet\nHYPERLIQUID_PUBLIC_ADDRESS=your_public_address\nHYPERLIQUID_PRIVATE_KEY=your_private_key\n```\n\nWe recommend creating a seperate API key wallet in the Hyperliquid UI for automated trading. This API wallets have not withdrawal permissions. \n\n2. Initialize the client:\n```python\nfrom fractrade_hl_simple import HyperliquidClient\n\nclient = HyperliquidClient()\n```\n\n## Authentication Modes\n\nThe client can operate in three modes:\n\n### 1. Authenticated with Environment Variables (Default)\n```python\nfrom fractrade_hl_simple import HyperliquidClient\n\n# Automatically loads credentials from .env\nclient = HyperliquidClient()\n```\n\n### 2. Authenticated with Explicit Account\n```python\nfrom fractrade_hl_simple import HyperliquidClient, HyperliquidAccount\n\naccount = HyperliquidAccount(\n private_key=\"your_private_key\",\n env=\"mainnet\",\n public_address=\"your_public_address\"\n)\nclient = HyperliquidClient(account=account)\n```\n\n### 3. Unauthenticated Mode\nIf no credentials are available, the client falls back to unauthenticated mode:\n```python\n# No .env file, no account provided\nclient = HyperliquidClient() # Works for public endpoints only\n```\n\n### Public vs Private Endpoints\n\nSome methods can be used without authentication:\n```python\n# These work without authentication\nprices = client.get_price(\"BTC\")\nbalance = client.get_perp_balance(\"0x123...\") # Requires address\nstate = client.get_user_state(\"0x123...\") # Requires address\nmarket_info = client.get_market_info()\n```\n\nMethods that require authentication:\n```python\n# These require authentication\nclient.buy(\"BTC\", 0.001)\nclient.sell(\"BTC\", 0.001)\nclient.cancel_all()\nclient.get_positions()\nbalance = client.get_perp_balance() # Without address requires auth\n```\n\nThe client will automatically warn you when running in unauthenticated mode and help you understand which methods are available.\n\n## Basic Usage\n\n### Get Market Prices\n```python\n# Get single price\nbtc_price = client.get_price(\"BTC\")\nprint(f\"BTC price: ${btc_price:,.2f}\")\n\n# Get all prices\nall_prices = client.get_price()\nfor symbol, price in all_prices.items():\n print(f\"{symbol}: ${price:,.2f}\")\n```\n\n### Check Account Balance\n```python\nbalance = client.get_perp_balance()\nprint(f\"Account balance: ${float(balance):,.2f}\")\n```\n\n### View Positions\n```python\npositions = client.get_positions()\nfor pos in positions:\n print(f\"Position: {pos.symbol} Size: {float(pos.size):+.3f}\")\n```\n\n### Place Orders\n\nMarket Buy:\n```python\norder = client.buy(\"BTC\", size=0.001) # Market buy 0.001 BTC\nprint(f\"Order placed: {order.order_id}\")\n```\n\nLimit Buy:\n```python\ncurrent_price = client.get_price(\"BTC\")\nlimit_price = current_price * 0.99 # 1% below market\norder = client.buy(\"BTC\", size=0.001, limit_price=limit_price)\nprint(f\"Limit order placed: {order.order_id}\")\n```\n\nMarket Sell:\n```python\norder = client.sell(\"BTC\", size=0.001) # Market sell 0.001 BTC\nprint(f\"Order placed: {order.order_id}\")\n```\n\n### Stop Loss and Take Profit\n\nFor Long Positions:\n```python\n# When you have a long position (bought BTC)\ncurrent_price = client.get_price(\"BTC\")\n\n# Place stop loss 5% below entry (sell when price drops)\nstop_price = current_price * 0.95\nsl_order = client.stop_loss(\"BTC\", size=0.001, stop_price=stop_price) # is_buy=False by default for long positions\n\n# Place take profit 10% above entry (sell when price rises)\ntake_profit_price = current_price * 1.10\ntp_order = client.take_profit(\"BTC\", size=0.001, take_profit_price=take_profit_price) # is_buy=False by default for long positions\n```\n\nFor Short Positions:\n```python\n# When you have a short position (sold BTC)\ncurrent_price = client.get_price(\"BTC\")\n\n# Place stop loss 5% above entry (buy when price rises)\nstop_price = current_price * 1.05\nsl_order = client.stop_loss(\"BTC\", size=0.001, stop_price=stop_price, is_buy=True) # Must set is_buy=True for short positions\n\n# Place take profit 10% below entry (buy when price drops)\ntake_profit_price = current_price * 0.90\ntp_order = client.take_profit(\"BTC\", size=0.001, take_profit_price=take_profit_price, is_buy=True) # Must set is_buy=True for short positions\n```\n\nThe `is_buy` parameter determines whether the TP/SL order will buy or sell when triggered:\n- For long positions: use `is_buy=False` (default) to sell when triggered\n- For short positions: use `is_buy=True` to buy when triggered\n\n### Open Position with TP/SL\n\nAlternatively, you can use the convenience methods that handle both entry and TP/SL orders:\n\nLong Position:\n```python\ncurrent_price = client.get_price(\"BTC\")\nposition = client.open_long_position(\n symbol=\"BTC\",\n size=0.001,\n stop_loss_price=current_price * 0.95, # 5% below entry\n take_profit_price=current_price * 1.10 # 10% above entry\n)\nprint(f\"Entry order: {position['entry'].order_id}\")\nprint(f\"Stop loss: {position['stop_loss'].order_id}\")\nprint(f\"Take profit: {position['take_profit'].order_id}\")\n```\n\nShort Position:\n```python\ncurrent_price = client.get_price(\"BTC\")\nposition = client.open_short_position(\n symbol=\"BTC\",\n size=0.001,\n stop_loss_price=current_price * 1.05, # 5% above entry\n take_profit_price=current_price * 0.90 # 10% below entry\n)\n```\n\nThese methods automatically set the correct `is_buy` parameter for TP/SL orders based on the position direction.\n\n### Close Position\n```python\nclose_order = client.close(\"BTC\")\nprint(f\"Position closed with order: {close_order.order_id}\")\n```\n\n### Cancel Orders\n```python\n# Cancel orders for specific symbol\nclient.cancel_all_orders(\"BTC\")\n\n# Cancel all orders across all symbols\nclient.cancel_all()\n```\n\n## Complete Trading Example\n\nHere's a full example showing a basic trading flow:\n\n```python\nfrom fractrade_hl_simple import HyperliquidClient\nimport time\n\ndef main():\n client = HyperliquidClient()\n SYMBOL = \"BTC\"\n POSITION_SIZE = 0.001\n \n try:\n # Check current price\n price = client.get_price(SYMBOL)\n print(f\"Current {SYMBOL} price: ${price:,.2f}\")\n \n # Place limit buy order\n limit_price = price * 0.99 # 1% below market\n order = client.buy(SYMBOL, POSITION_SIZE, limit_price=limit_price)\n print(f\"Limit order placed: {order.order_id}\")\n \n time.sleep(2)\n \n # Cancel limit order if not filled\n client.cancel_all_orders(SYMBOL)\n \n # Open market position\n order = client.buy(SYMBOL, POSITION_SIZE)\n print(f\"Position opened with order: {order.order_id}\")\n \n # Check position\n positions = client.get_positions()\n position = next((p for p in positions if p.symbol == SYMBOL), None)\n if position:\n print(f\"Current position: {float(position.size):+.3f} {position.symbol}\")\n print(f\"Entry price: ${float(position.entry_price):,.2f}\")\n print(f\"Unrealized PnL: ${float(position.unrealized_pnl):,.2f}\")\n \n # Close position\n close_order = client.close(SYMBOL)\n print(f\"Position closed with order: {close_order.order_id}\")\n \n except Exception as e:\n print(f\"Error: {str(e)}\")\n # Cleanup\n client.cancel_all_orders(SYMBOL)\n client.close(SYMBOL)\n\nif __name__ == \"__main__\":\n main()\n```\n\n\n## Contributing\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\nMIT\n\n## Disclaimer\nThis software is for educational purposes only. Use at your own risk. The authors take no responsibility for any financial losses incurred while using this software.\n```\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A simple API wrapper for automated trading on Hyperliquid DEX with Python",
"version": "0.1.5",
"project_urls": {
"Documentation": "https://github.com/fractrade-xyz/fractrade-hl-simple",
"Homepage": "https://fractrade.xyz",
"Repository": "https://github.com/fractrade-xyz/fractrade-hl-simple"
},
"split_keywords": [
"hyperliquid",
" trading",
" crypto",
" api",
" defi"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "1d5a7c93feb35e537333859997da82a62aaed5de7ac970faf00b741755dfd98f",
"md5": "eac0f0f152cf7c8efcea8b2580746a71",
"sha256": "18d1ba15329a4bb86319066b1ed47f41cd87b073b888a1bf29672da794e09e27"
},
"downloads": -1,
"filename": "fractrade_hl_simple-0.1.5-py3-none-any.whl",
"has_sig": false,
"md5_digest": "eac0f0f152cf7c8efcea8b2580746a71",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.12",
"size": 15999,
"upload_time": "2025-02-22T16:54:51",
"upload_time_iso_8601": "2025-02-22T16:54:51.513785Z",
"url": "https://files.pythonhosted.org/packages/1d/5a/7c93feb35e537333859997da82a62aaed5de7ac970faf00b741755dfd98f/fractrade_hl_simple-0.1.5-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "0d2d1cec9950784723aeb2d3503eae66486e2d7b0998744c7e307b4835207d05",
"md5": "fddff7a52986777354d705c132b628ba",
"sha256": "d7d38bd40c40d5efd1844cc8c0fd8650683ce3f2627218207d74b1cf4fb7e449"
},
"downloads": -1,
"filename": "fractrade_hl_simple-0.1.5.tar.gz",
"has_sig": false,
"md5_digest": "fddff7a52986777354d705c132b628ba",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.12",
"size": 16534,
"upload_time": "2025-02-22T16:54:53",
"upload_time_iso_8601": "2025-02-22T16:54:53.309711Z",
"url": "https://files.pythonhosted.org/packages/0d/2d/1cec9950784723aeb2d3503eae66486e2d7b0998744c7e307b4835207d05/fractrade_hl_simple-0.1.5.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-02-22 16:54:53",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "fractrade-xyz",
"github_project": "fractrade-hl-simple",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "fractrade-hl-simple"
}