Skip to content
Merged

rf #4

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
218 changes: 195 additions & 23 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -1,37 +1,209 @@
# hyperqit

A rust-based hyperliquid integration ot build strategies (interact with core and hypevm both)
A Rust SDK for Hyperliquid.

## Features
## Installation

- **Strategy Engine:**
```bash
cargo add hyperqit
```

- Periodically evaluates market and funding conditions.
- Dynamically manages positions in spot and perpetual markets.
- Supports configurable leverage, slippage, and liquidation risk thresholds.
## Quick Start

- **Health and Risk Monitoring:**
### Placing Orders

- Monitors funding rates and proximity to liquidation.
- Automatically exits or maintains positions based on real-time risk assessment.
```rust
use hyperqit::*;
use alloy::primitives::Address;

- **Position Management:**
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Setup signer
let private_key = "your_private_key_here";
let signer = LocalWallet::signer(private_key.to_string());
let user_address = signer.address();

- Programmatic entry and exit of positions.
- Unified handling of spot and perp assets.
- Automated rebalancing and state tracking.
// Create client
let client = HyperliquidClient::new(
Network::Testnet,
Box::new(signer),
user_address,
);

- **Hyperliquid Integration:**
- Direct interaction with Hyperliquid APIs for order placement, funding history, leverage updates, and asset transfers.
- Secure signing and wallet management.
// Place an order
let order = BulkOrder {
orders: vec![OrderRequest {
asset: 0, // BTC perpetual
is_buy: true,
limit_px: "50000.0".to_string(),
sz: "0.001".to_string(),
reduce_only: false,
order_type: OrderType::Limit(Limit { tif: "Ioc".into() }),
cloid: None,
}],
grouping: "na".to_string(),
};

## Strategy Logic
let result = client.create_position_raw(order).await?;
println!("Order placed: {:?}", result);

- **Risk-Aware Execution:**
- Enters positions according to user configuration.
- Exits positions if funding turns negative or liquidation risk exceeds threshold.
- Maintains positions when conditions are favorable, with continuous monitoring.
Ok(())
}
```

## Configuration
### Multi Sig Operations

- All operational parameters (keys, asset, thresholds) are set via environment variables.
```rust
use hyperqit::*;
use alloy::primitives::Address;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Setup primary signer
let primary_signer = LocalWallet::signer("primary_key".to_string());
let primary_address = primary_signer.address();

// Setup other signers
let other_signers = vec![
Box::new(LocalWallet::signer("signer2_key".to_string())),
Box::new(LocalWallet::signer("signer3_key".to_string())),
];

let client = HyperliquidClient::new(
Network::Testnet,
Box::new(primary_signer),
primary_address,
);

// Multi-sig USD transfer
let multi_sig_address: Address = "0x1234...".parse()?;
client.multi_sig_usd_class_transfer(
1000, // amount
true, // to_perp
"0xa4b1".to_string(), // chain ID
other_signers, // other signers
multi_sig_address, // multi-sig address
).await?;

println!("Multi-sig transfer completed");
Ok(())
}
```

## Asset IDs & Market Data

Get asset IDs and market information:

```rust
use hyperqit::market_info::*;

// Get unified market data
let perp_info = client.get_perp_info(None).await?;
let spot_info = client.get_spot_info(None).await?;
let unified = create_unified_market_info(perp_info, spot_info);

// Find asset by name and get ID
if let Some(market) = find_market_by_name(&unified, "BTC") {
let btc_perp_id = market.perp.as_ref().map(|p| p.asset_id);
let btc_spot_id = market.spot.as_ref().map(|s| s.asset_id);

println!("BTC Perp ID: {:?}", btc_perp_id);
println!("BTC Spot ID: {:?}", btc_spot_id);
}

// Get current prices
let btc_perp_price = get_current_price(&unified, "BTC", true, true); // perp, use_mid
let btc_spot_price = get_current_price(&unified, "BTC", false, true); // spot, use_mid
```

## Examples

The binary tools demonstrate SDK usage:

- `dex` - DEX operations, order management, and market data
- `multisig` - Multi-signature operations and conversions
- `transfer` - USD transfers between spot and perp accounts
- `strat` - **Delta neutral funding rate farming strategy** with web interface
- `deployer` - **HIP-3 builder-deployed perpetuals** deployment and management

Run examples with:

```bash
cargo run --bin dex
cargo run --bin multisig
cargo run --bin transfer
cargo run --bin strat
cargo run --bin deployer
```

### Delta Neutral Strategy (`strat`)

Delta neutral funding rate farming strategy that goes long spot + short perp when funding is positive.

**Configuration:**

```bash
PRIVATE_KEY=your_private_key
USER_ADDRESS=0x1234...
BOT_URL=https://your-webhook-url.com
CHECK_EVERY=60
BIND_ADDR=0.0.0.0:3000
```

### HIP-3 Builder-Deployed Perpetuals (`deployer`)

The `deployer` binary demonstrates HIP-3 perpetual deployment using the SDK:

**SDK Support:**

- `PerpDeployAction` enum for all deployment actions
- `RegisterAsset` - Deploy new perpetual markets
- `SetOracle` - Update oracle and mark prices
- `SetFundingMultipliers` - Configure funding rates
- `HaltTrading` - Control market trading

**Example Usage:**

```rust
// Deploy new perpetual market
let deploy_action = PerpDeployAction::RegisterAsset(RegisterAsset {
max_gas: Some(1000000),
asset_request: RegisterAssetRequest {
coin: "NEWCOIN".to_string(),
sz_decimals: 6,
oracle_px: "100.0".to_string(),
margin_table_id: 0,
only_isolated: false,
},
dex: "dex".to_string(),
schema: Some(PerpDexSchemaInput {
full_name: "New Coin Perpetual".to_string(),
collateral_token: 0,
oracle_updater: None,
}),
});

client.perp_deploy_action(deploy_action).await?;
```

## Signing

The SDK supports multiple signing methods through the `Signer` trait:

```rust
#[async_trait]
pub trait Signer {
async fn sign_order(&self, to_sign: FixedBytes<32>) -> Result<SignedMessage>;
}
```

**Built-in Signers:**

- `LocalWallet` - Local private key signing

**Extending Signers:**
Implement the `Signer` trait for custom signing backends like hardware wallets, remote signers, or multi-party computation systems.

## License

MIT License
56 changes: 56 additions & 0 deletions src/bin/dn_strat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Delta Neutral Strategy

A delta neutral funding rate farming strategy for Hyperliquid.

## Strategy Overview

**Long Spot + Short Perp** when funding rate is positive to capture funding payments while maintaining delta neutrality.

## Configuration

Set environment variables:

```bash
PRIVATE_KEY=your_private_key
USER_ADDRESS=0x1234...
BOT_URL=https://your-webhook-url.com
CHECK_EVERY=60 # seconds
BIND_ADDR=0.0.0.0:3000
```

## Running

```bash
cargo run --bin strat
```

## Strategy Logic

1. **Entry**: Long spot + Short perp when funding rate > 0
2. **Monitoring**: Continuous health checks every `CHECK_EVERY` seconds
3. **Exit Conditions**:
- Funding rate turns negative
- Price approaches liquidation threshold (70% of liquidation price)
4. **Notifications**: Webhook alerts for strategy events

## API Endpoints

The strategy exposes HTTP endpoints for manual control:

- `POST /v1/strategy/open` - Enter position
- `POST /v1/strategy/close` - Exit position
- `GET /v1/strategy/position` - Get current position status

## Risk Management

- **Liquidation Risk**: Monitors price vs liquidation price
- **Funding Risk**: Exits when funding turns negative
- **Dust Threshold**: Ignores positions below 0.1 USD
- **Slippage**: 0.5% slippage tolerance

## Strategy Parameters

- **Leverage**: 1x (configurable)
- **Slippage**: 0.5%
- **Dust Threshold**: 0.1 USD
- **Liquidation Threshold**: 70% of liquidation price
3 changes: 0 additions & 3 deletions src/bin/dn_strat/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ pub struct Config {
#[envconfig(from = "PRIVATE_KEY")]
pub private_key: String,

#[envconfig(from = "RUST_LOG")]
pub log_level: String,

#[envconfig(from = "USER_ADDRESS")]
pub user_address: String,

Expand Down
4 changes: 2 additions & 2 deletions src/bin/dn_strat/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ async fn main() {
)
.init();
let config = Config::init_from_env().unwrap();
let signer = Signers::Local(hyperqit::LocalWallet::signer(config.private_key));
let signer = hyperqit::LocalWallet::signer(config.private_key);

let user_address: Address = config.user_address.parse().unwrap();

let executor = crate::HyperliquidClient::new(Network::Testnet, signer, user_address);
let executor = crate::HyperliquidClient::new(Network::Testnet, Box::new(signer), user_address);
let asset = Asset::CommonAsset("HYPE".to_owned());
let notifier = NotifierService::new(config.bot_url, user_address.to_string());
let strategy = Arc::new(Strategy::new(
Expand Down
Loading