ostium-rust-sdk 0.1.0

Rust SDK for interacting with the Ostium trading platform on Arbitrum
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# 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.