Skip to content

Commit

Permalink
add twap feature
Browse files Browse the repository at this point in the history
  • Loading branch information
dennohpeter committed Mar 10, 2024
1 parent 856b9e9 commit 56814ff
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 12 deletions.
19 changes: 16 additions & 3 deletions examples/cancel-order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use hyperliquid::{
types::{
exchange::{
request::{CancelByCloidRequest, CancelRequest, Limit, OrderRequest, OrderType, Tif},
response::{Response, Status},
response::{Response, Status, StatusType},
},
Chain,
},
Expand Down Expand Up @@ -49,7 +49,14 @@ async fn main() {
Response::Err(error) => panic!("Failed to place order: {:?}", error),
};

let status = &response.data.unwrap().statuses[0];
let status_type = &response.data.unwrap();

let status = match status_type {
StatusType::Statuses(statuses) => &statuses[0],
_ => {
panic!("Failed to place order: {:?}", status_type);
}
};

let oid = match status {
Status::Filled(order) => order.oid,
Expand Down Expand Up @@ -105,7 +112,13 @@ async fn main() {
Response::Err(error) => panic!("Failed to place order: {:?}", error),
};

let status = &response.data.unwrap().statuses[0];
let data = &response.data.unwrap();
let status = match data {
StatusType::Statuses(statuses) => &statuses[0],
_ => {
panic!("Failed to place order: {:?}", data);
}
};

let oid = match status {
Status::Filled(order) => order.oid,
Expand Down
11 changes: 9 additions & 2 deletions examples/modify-order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use hyperliquid::{
types::{
exchange::{
request::{Limit, ModifyRequest, OrderRequest, OrderType, Tif},
response::{Response, Status},
response::{Response, Status, StatusType},
},
Chain,
},
Expand Down Expand Up @@ -50,7 +50,14 @@ async fn main() {
Response::Err(error) => panic!("Failed to place order: {:?}", error),
};

let status = &response.data.unwrap().statuses[0];
let status_type = &response.data.unwrap();

let status = match status_type {
StatusType::Statuses(statuses) => &statuses[0],
_ => {
panic!("Failed to place order: {:?}", status_type);
}
};

let oid = match status {
Status::Filled(order) => order.oid,
Expand Down
11 changes: 9 additions & 2 deletions examples/order-status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use hyperliquid::{
types::{
exchange::{
request::{Limit, OrderRequest, OrderType, Tif},
response::{Response, Status},
response::{Response, Status, StatusType},
},
Chain, Oid,
},
Expand Down Expand Up @@ -55,7 +55,14 @@ async fn main() {

println!("Response: {:?}", response.data);

let status = &response.data.unwrap().statuses[0];
let status_type = &response.data.unwrap();

let status = match status_type {
StatusType::Statuses(statuses) => &statuses[0],
_ => {
panic!("Failed to place order: {:?}", status_type);
}
};

let oid = match status {
Status::Filled(order) => order.oid,
Expand Down
42 changes: 42 additions & 0 deletions examples/twap-order.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use std::sync::Arc;

use ethers::signers::LocalWallet;
use hyperliquid::{
types::{exchange::request::TwapRequest, Chain},
utils::parse_size,
Exchange, Hyperliquid,
};

#[tokio::main]
async fn main() {
// Key was randomly generated for testing and shouldn't be used with any real funds
let wallet: Arc<LocalWallet> = Arc::new(
"e908f86dbb4d55ac876378565aafeabc187f6690f046459397b17d9b9a19688e"
.parse()
.unwrap(),
);

let exchange: Exchange = Hyperliquid::new(Chain::Dev);

let asset = 0;
let sz_decimals = 2;

let twap = TwapRequest {
asset,
is_buy: true,
reduce_only: false,
minutes: 10,
sz: parse_size(13.85, sz_decimals),
randomize: true,
};

let vault_address = None;

println!("Placing a TWAP order...");
let response = exchange
.twap_order(wallet.clone(), twap, vault_address)
.await
.expect("Failed to place twap order");

println!("Response: {:?}", response);
}
32 changes: 31 additions & 1 deletion src/exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::{
exchange::{
request::{
Action, Agent, CancelByCloidRequest, CancelRequest, Grouping, ModifyRequest,
OrderRequest, Request, TransferRequest, WithdrawalRequest,
OrderRequest, Request, TransferRequest, TwapRequest, WithdrawalRequest,
},
response::Response,
},
Expand Down Expand Up @@ -270,6 +270,36 @@ impl Exchange {
self.client.post(&API::Exchange, &request).await
}

/// Place a TWAP order
/// # Arguments
/// * `wallet` - The wallet to sign the order with
/// * `twap` - The twap order to place
/// * `vault_address` - If trading on behalf of a vault, its onchain address in 42-character hexadecimal format
/// e.g. `0x0000000000000000000000000000000000000000`
pub async fn twap_order(
&self,
wallet: Arc<LocalWallet>,
twap: TwapRequest,
vault_address: Option<Address>,
) -> Result<Response> {
let nonce = self.nonce()?;

let action = Action::TwapOrder { twap };

let connection_id = action.connection_id(vault_address, nonce)?;

let signature = self.sign(wallet, connection_id).await?;

let request = Request {
action,
nonce,
signature,
vault_address,
};

self.client.post(&API::Exchange, &request).await
}

/// Send usd to another address. This transfer does not touch the EVM bridge. The signature
/// format is human readable for wallet interfaces.
///
Expand Down
39 changes: 35 additions & 4 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,26 @@ pub mod exchange {
pub order: OrderRequest,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TwapRequest {
#[serde(rename = "a", alias = "asset")]
pub asset: u32,
#[serde(rename = "b", alias = "isBuy")]
pub is_buy: bool,
#[serde(rename = "s", alias = "sz")]
pub sz: String,
#[serde(rename = "r", alias = "reduceOnly", default)]
pub reduce_only: bool,
/// Running Time (5m - 24h)
#[serde(rename = "m", alias = "minutes")]
pub minutes: u64,
/// if set to true, the size of each sub-trade will be automatically adjusted
/// within a certain range, typically upto to 20% higher or lower than the original trade size
#[serde(rename = "t", alias = "randomize")]
pub randomize: bool,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferRequest {
Expand Down Expand Up @@ -655,7 +675,9 @@ pub mod exchange {
BatchModify {
modifies: Vec<ModifyRequest>,
},

TwapOrder {
twap: TwapRequest,
},
UsdTransfer {
chain: Chain,
payload: TransferRequest,
Expand Down Expand Up @@ -755,6 +777,12 @@ pub mod exchange {
pub avg_px: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TwapId {
pub twap_id: u64,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Status {
Expand All @@ -764,18 +792,21 @@ pub mod exchange {
Success,
WaitingForFill,
WaitingForTrigger,
Running(TwapId),
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Statuses {
pub statuses: Vec<Status>,
#[serde(rename_all = "camelCase")]
pub enum StatusType {
Statuses(Vec<Status>),
Status(Status),
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Data {
#[serde(rename = "type")]
pub type_: String,
pub data: Option<Statuses>,
pub data: Option<StatusType>,
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down

0 comments on commit 56814ff

Please sign in to comment.