# Advanced Order Types API Reference
This document provides complete reference documentation for advanced order types in the Ostium Rust SDK, including limit orders, stop orders, and order management.
## Overview
The advanced order types API enables sophisticated trading strategies with:
- **Limit Orders**: Execute only at specified price or better
- **Stop Orders**: Trigger when price crosses a threshold
- **Order Management**: Update, cancel, and validate orders
- **Price Validation**: Ensure order prices are reasonable
All advanced order operations require an authenticated client with a configured private key.
## Order Types
### Limit Orders
Limit orders execute only when the market price reaches your specified price or better.
#### Use Cases
- **Buy Limit**: Place below current price to buy on dips
- **Sell Limit**: Place above current price to sell on rallies
- **Better Entry**: Avoid slippage and get better prices
- **Patience Trading**: Wait for favorable market conditions
#### `place_limit_order`
Places a limit order that executes when price reaches the specified level.
```rust
pub async fn place_limit_order(&self, params: LimitOrderParams) -> Result<TxHash>
```
**Parameters:**
```rust
pub struct LimitOrderParams {
pub symbol: String, // Trading pair (e.g., "BTC/USD")
pub side: PositionSide, // Long or Short
pub size: Decimal, // Position size
pub leverage: Decimal, // Leverage multiplier
pub limit_price: Decimal, // Price to execute at
pub take_profit: Option<Decimal>, // Optional TP price
pub stop_loss: Option<Decimal>, // Optional SL price
}
```
**Example:**
```rust
use ostium_rust_sdk::{LimitOrderParams, PositionSide};
use rust_decimal_macros::dec;
let limit_params = LimitOrderParams {
symbol: "BTC/USD".to_string(),
side: PositionSide::Long,
size: dec!(0.01), // 0.01 BTC
leverage: dec!(5.0), // 5x leverage
limit_price: dec!(48000), // Execute at $48,000
take_profit: Some(dec!(55000)), // TP at $55,000
stop_loss: Some(dec!(45000)), // SL at $45,000
};
let tx_hash = client.place_limit_order(limit_params).await?;
```
### Stop Orders
Stop orders trigger when price crosses a threshold and execute as market orders.
#### Use Cases
- **Breakout Trading**: Enter positions on price momentum
- **Stop Loss**: Limit losses on existing positions
- **Momentum Following**: Trade in direction of strong moves
- **Risk Management**: Automatic position protection
#### `place_stop_order`
Places a stop order that triggers when price crosses the stop level.
```rust
pub async fn place_stop_order(&self, params: StopOrderParams) -> Result<TxHash>
```
**Parameters:**
```rust
pub struct StopOrderParams {
pub symbol: String, // Trading pair
pub side: PositionSide, // Long or Short
pub size: Decimal, // Position size
pub leverage: Decimal, // Leverage multiplier
pub stop_price: Decimal, // Price that triggers the order
pub take_profit: Option<Decimal>, // Optional TP price
pub stop_loss: Option<Decimal>, // Optional SL price
}
```
**Example:**
```rust
let stop_params = StopOrderParams {
symbol: "ETH/USD".to_string(),
side: PositionSide::Long,
size: dec!(0.5), // 0.5 ETH
leverage: dec!(3.0), // 3x leverage
stop_price: dec!(2100), // Trigger at $2,100
take_profit: Some(dec!(2300)), // TP at $2,300
stop_loss: Some(dec!(1950)), // SL at $1,950
};
let tx_hash = client.place_stop_order(stop_params).await?;
```
## Advanced Order Placement
### `place_advanced_order`
Unified interface for placing any order type with full control over parameters.
```rust
pub async fn place_advanced_order(&self, params: AdvancedOrderParams) -> Result<TxHash>
```
**Parameters:**
```rust
pub struct AdvancedOrderParams {
pub symbol: String,
pub side: PositionSide,
pub size: Decimal,
pub leverage: Decimal,
pub order_type: OrderExecutionType, // Market, Limit, or Stop
pub price: Option<Decimal>, // Required for Limit/Stop
pub take_profit: Option<Decimal>,
pub stop_loss: Option<Decimal>,
pub slippage_tolerance: Decimal, // Slippage tolerance
}
pub enum OrderExecutionType {
Market, // Execute immediately
Limit, // Execute at specified price or better
Stop, // Execute when price crosses threshold
}
```
**Example:**
```rust
let advanced_params = AdvancedOrderParams {
symbol: "BTC/USD".to_string(),
side: PositionSide::Short,
size: dec!(0.005),
leverage: dec!(10.0),
order_type: OrderExecutionType::Limit,
price: Some(dec!(52000)), // Limit price
take_profit: Some(dec!(48000)), // TP for short position
stop_loss: Some(dec!(54000)), // SL for short position
slippage_tolerance: dec!(0.01), // 1% slippage
};
let tx_hash = client.place_advanced_order(advanced_params).await?;
```
## Order Management
### Updating Orders
#### `update_limit_order`
Updates an existing limit order's price, take profit, or stop loss.
```rust
pub async fn update_limit_order(&self, params: UpdateLimitOrderParams) -> Result<TxHash>
```
**Parameters:**
```rust
pub struct UpdateLimitOrderParams {
pub order_id: String, // Order ID to update
pub limit_price: Option<Decimal>, // New limit price
pub take_profit: Option<Decimal>, // New TP price
pub stop_loss: Option<Decimal>, // New SL price
}
```
**Example:**
```rust
let update_params = UpdateLimitOrderParams {
order_id: "0x123...abc:0:1".to_string(),
limit_price: Some(dec!(49000)), // Update limit price
take_profit: Some(dec!(56000)), // Update TP
stop_loss: None, // Keep current SL
};
let tx_hash = client.update_limit_order(update_params).await?;
```
### Canceling Orders
#### `cancel_order`
Cancels an open limit or stop order.
```rust
pub async fn cancel_order(&self, params: CancelOrderParams) -> Result<TxHash>
```
**Parameters:**
```rust
pub struct CancelOrderParams {
pub order_id: String, // Order ID to cancel
}
```
**Example:**
```rust
let cancel_params = CancelOrderParams {
order_id: "0x123...abc:0:1".to_string(),
};
let tx_hash = client.cancel_order(cancel_params).await?;
```
## Order Validation
### `validate_order_price`
Validates if an order price is reasonable compared to current market conditions.
```rust
pub async fn validate_order_price(
&self,
symbol: &str,
order_type: OrderExecutionType,
price: Decimal,
) -> Result<bool>
```
**Example:**
```rust
let is_valid = client.validate_order_price(
"BTC/USD",
OrderExecutionType::Limit,
dec!(47000)
).await?;
if is_valid {
// Proceed with order placement
} else {
// Price is too far from market, adjust or warn user
}
```
## Order ID Format
Order IDs follow the format: `trader_address:pair_index:order_index`
Example: `0x742d35Cc6634C0532925a3b8D4C9db96590e4CAF:0:1`
- `trader_address`: Ethereum address of the trader
- `pair_index`: Index of the trading pair (0 for BTC/USD, 1 for ETH/USD, etc.)
- `order_index`: Sequential index of the order for this trader and pair
## Best Practices
### Order Placement Strategy
```rust
// 1. Get current market price
let current_price = client.get_price("BTC/USD").await?.mark_price;
// 2. Calculate reasonable order prices
let limit_buy_price = current_price * dec!(0.98); // 2% below market
let stop_sell_price = current_price * dec!(1.05); // 5% above market
// 3. Validate prices before placing
let is_limit_valid = client.validate_order_price(
"BTC/USD",
OrderExecutionType::Limit,
limit_buy_price
).await?;
if is_limit_valid {
// Place the order
let limit_params = LimitOrderParams {
symbol: "BTC/USD".to_string(),
side: PositionSide::Long,
size: dec!(0.01),
leverage: dec!(5.0),
limit_price: limit_buy_price,
take_profit: Some(current_price * dec!(1.10)),
stop_loss: Some(current_price * dec!(0.95)),
};
client.place_limit_order(limit_params).await?;
}
```
### Risk Management
```rust
// Always set appropriate take profit and stop loss
let risk_reward_ratio = dec!(2.0); // 2:1 risk/reward
let risk_percentage = dec!(0.02); // 2% risk per trade
let entry_price = dec!(50000);
let stop_loss = entry_price * (dec!(1.0) - risk_percentage);
let take_profit = entry_price + (entry_price - stop_loss) * risk_reward_ratio;
let params = LimitOrderParams {
symbol: "BTC/USD".to_string(),
side: PositionSide::Long,
size: dec!(0.01),
leverage: dec!(5.0),
limit_price: entry_price,
take_profit: Some(take_profit),
stop_loss: Some(stop_loss),
};
```
### Order Monitoring
```rust
// Check order status periodically
let orders = client.get_orders(None).await?;
for order in orders {
match order.status {
OrderStatus::Pending => {
println!("Order {} is still pending", order.id);
}
OrderStatus::Filled => {
println!("Order {} was filled at ${}", order.id,
order.avg_fill_price.unwrap_or_default());
}
OrderStatus::Cancelled => {
println!("Order {} was cancelled", order.id);
}
_ => {}
}
}
```
## Error Handling
Common error scenarios and how to handle them:
```rust
match client.place_limit_order(params).await {
Ok(tx_hash) => {
println!("Order placed: {}", tx_hash);
}
Err(OstiumError::Validation(msg)) => {
println!("Invalid order parameters: {}", msg);
// Fix parameters and retry
}
Err(OstiumError::Wallet(msg)) => {
println!("Wallet error: {}", msg);
// Check signer configuration
}
Err(OstiumError::Contract(msg)) => {
println!("Contract error: {}", msg);
// Check network connectivity and gas
}
Err(e) => {
println!("Unexpected error: {}", e);
}
}
```
## Integration Examples
### Complete Trading Bot Example
```rust
use ostium_rust_sdk::*;
use rust_decimal_macros::dec;
async fn trading_bot_example() -> Result<()> {
let client = OstiumClient::builder(Network::Testnet)
.with_private_key("your_private_key")?
.build()
.await?;
// Get current price
let price = client.get_price("BTC/USD").await?;
let current_price = price.mark_price;
// Place a limit buy order 2% below market
let buy_limit = LimitOrderParams {
symbol: "BTC/USD".to_string(),
side: PositionSide::Long,
size: dec!(0.01),
leverage: dec!(5.0),
limit_price: current_price * dec!(0.98),
take_profit: Some(current_price * dec!(1.10)),
stop_loss: Some(current_price * dec!(0.95)),
};
let buy_order_tx = client.place_limit_order(buy_limit).await?;
println!("Buy order placed: {}", buy_order_tx);
// Place a stop sell order 5% above market
let sell_stop = StopOrderParams {
symbol: "BTC/USD".to_string(),
side: PositionSide::Short,
size: dec!(0.01),
leverage: dec!(3.0),
stop_price: current_price * dec!(1.05),
take_profit: Some(current_price * dec!(0.90)),
stop_loss: Some(current_price * dec!(1.08)),
};
let sell_order_tx = client.place_stop_order(sell_stop).await?;
println!("Sell order placed: {}", sell_order_tx);
Ok(())
}
```
This comprehensive API enables sophisticated trading strategies while maintaining safety through validation and proper error handling.