|
| 1 | +use anyhow::{bail, Context, Result}; |
| 2 | +use hmac::{Hmac, Mac}; |
| 3 | +use reqwest::Client; |
| 4 | +use serde_json::json; |
| 5 | +use sha2::Sha256; |
| 6 | +use std::time::{SystemTime, UNIX_EPOCH}; |
| 7 | + |
| 8 | +type HmacSha256 = Hmac<Sha256>; |
| 9 | + |
| 10 | +const BASE_URL: &str = "https://api.coinbase.com"; |
| 11 | + |
| 12 | +/// Sign a request with HMAC-SHA256 |
| 13 | +/// timestamp + method + requestPath + body |
| 14 | +pub fn sign_request(secret: &str, timestamp: &str, method: &str, path: &str, body: &str) -> String { |
| 15 | + let message = format!("{}{}{}{}", timestamp, method, path, body); |
| 16 | + let mut mac = |
| 17 | + HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC can take key of any size"); |
| 18 | + mac.update(message.as_bytes()); |
| 19 | + let result = mac.finalize(); |
| 20 | + hex::encode(result.into_bytes()) |
| 21 | +} |
| 22 | + |
| 23 | +/// Get current timestamp in seconds |
| 24 | +fn timestamp() -> String { |
| 25 | + SystemTime::now() |
| 26 | + .duration_since(UNIX_EPOCH) |
| 27 | + .unwrap() |
| 28 | + .as_secs() |
| 29 | + .to_string() |
| 30 | +} |
| 31 | + |
| 32 | +/// Place a spot limit order on Coinbase |
| 33 | +#[allow(clippy::too_many_arguments)] |
| 34 | +pub async fn spot_order( |
| 35 | + client: &Client, |
| 36 | + api_key: &str, |
| 37 | + api_secret: &str, |
| 38 | + symbol: &str, |
| 39 | + side: &str, // "BUY" or "SELL" |
| 40 | + size: f64, |
| 41 | + price: f64, |
| 42 | + json_output: bool, |
| 43 | +) -> Result<()> { |
| 44 | + let ts = timestamp(); |
| 45 | + let path = "/api/v3/brokerage/orders"; |
| 46 | + |
| 47 | + // Generate client_order_id |
| 48 | + let client_order_id = uuid::Uuid::new_v4().to_string(); |
| 49 | + |
| 50 | + // Coinbase uses BTC-USD format (not BTCUSDT) |
| 51 | + let product_id = format!("{}-USD", symbol.to_uppercase()); |
| 52 | + |
| 53 | + let body = json!({ |
| 54 | + "client_order_id": client_order_id, |
| 55 | + "product_id": product_id, |
| 56 | + "side": side, |
| 57 | + "order_configuration": { |
| 58 | + "limit_limit_gtc": { |
| 59 | + "base_size": format!("{:.8}", size), |
| 60 | + "limit_price": format!("{:.2}", price), |
| 61 | + } |
| 62 | + } |
| 63 | + }); |
| 64 | + |
| 65 | + let body_str = serde_json::to_string(&body)?; |
| 66 | + let signature = sign_request(api_secret, &ts, "POST", path, &body_str); |
| 67 | + |
| 68 | + let url = format!("{}{}", BASE_URL, path); |
| 69 | + |
| 70 | + let response = client |
| 71 | + .post(&url) |
| 72 | + .header("CB-ACCESS-KEY", api_key) |
| 73 | + .header("CB-ACCESS-SIGN", signature) |
| 74 | + .header("CB-ACCESS-TIMESTAMP", ts) |
| 75 | + .header("Content-Type", "application/json") |
| 76 | + .body(body_str) |
| 77 | + .send() |
| 78 | + .await |
| 79 | + .context("Failed to send Coinbase spot order")?; |
| 80 | + |
| 81 | + let status = response.status(); |
| 82 | + let response_body: serde_json::Value = |
| 83 | + response.json().await.context("Failed to parse response")?; |
| 84 | + |
| 85 | + if !status.is_success() { |
| 86 | + let error_msg = if let Some(msg) = response_body.get("message") { |
| 87 | + format!("Coinbase API error: {}", msg) |
| 88 | + } else if let Some(msg) = response_body.get("error") { |
| 89 | + format!("Coinbase API error: {}", msg) |
| 90 | + } else { |
| 91 | + format!("Coinbase API error: {:?}", response_body) |
| 92 | + }; |
| 93 | + bail!(error_msg); |
| 94 | + } |
| 95 | + |
| 96 | + let result = json!({ |
| 97 | + "exchange": "coinbase", |
| 98 | + "market": "spot", |
| 99 | + "action": side.to_lowercase(), |
| 100 | + "symbol": product_id, |
| 101 | + "quantity": size, |
| 102 | + "price": price, |
| 103 | + "response": response_body, |
| 104 | + }); |
| 105 | + |
| 106 | + if json_output { |
| 107 | + println!("{}", serde_json::to_string_pretty(&result)?); |
| 108 | + } else { |
| 109 | + println!("\n ✅ Coinbase spot {} order placed!", side.to_lowercase()); |
| 110 | + println!( |
| 111 | + " Order ID: {}", |
| 112 | + response_body.get("order_id").unwrap_or(&json!(null)) |
| 113 | + ); |
| 114 | + println!(" Product: {}", product_id); |
| 115 | + println!(" Quantity: {:.8}", size); |
| 116 | + println!(" Price: ${:.2}\n", price); |
| 117 | + } |
| 118 | + |
| 119 | + Ok(()) |
| 120 | +} |
| 121 | + |
| 122 | +/// Get account balances |
| 123 | +pub async fn get_accounts( |
| 124 | + client: &Client, |
| 125 | + api_key: &str, |
| 126 | + api_secret: &str, |
| 127 | + json_output: bool, |
| 128 | +) -> Result<()> { |
| 129 | + let ts = timestamp(); |
| 130 | + let path = "/api/v3/brokerage/accounts"; |
| 131 | + let signature = sign_request(api_secret, &ts, "GET", path, ""); |
| 132 | + |
| 133 | + let url = format!("{}{}", BASE_URL, path); |
| 134 | + |
| 135 | + let response = client |
| 136 | + .get(&url) |
| 137 | + .header("CB-ACCESS-KEY", api_key) |
| 138 | + .header("CB-ACCESS-SIGN", signature) |
| 139 | + .header("CB-ACCESS-TIMESTAMP", ts) |
| 140 | + .send() |
| 141 | + .await |
| 142 | + .context("Failed to fetch Coinbase accounts")?; |
| 143 | + |
| 144 | + let status = response.status(); |
| 145 | + let body: serde_json::Value = response.json().await.context("Failed to parse response")?; |
| 146 | + |
| 147 | + if !status.is_success() { |
| 148 | + let error_msg = if let Some(msg) = body.get("message") { |
| 149 | + format!("Coinbase API error: {}", msg) |
| 150 | + } else { |
| 151 | + format!("Coinbase API error: {:?}", body) |
| 152 | + }; |
| 153 | + bail!(error_msg); |
| 154 | + } |
| 155 | + |
| 156 | + if json_output { |
| 157 | + println!( |
| 158 | + "{}", |
| 159 | + serde_json::to_string_pretty(&json!({ |
| 160 | + "exchange": "coinbase", |
| 161 | + "accounts": body, |
| 162 | + }))? |
| 163 | + ); |
| 164 | + return Ok(()); |
| 165 | + } |
| 166 | + |
| 167 | + println!("\n 💰 Coinbase Account Balance\n"); |
| 168 | + |
| 169 | + if let Some(accounts) = body.get("accounts").and_then(|v| v.as_array()) { |
| 170 | + for account in accounts { |
| 171 | + let currency = account |
| 172 | + .get("currency") |
| 173 | + .and_then(|v| v.as_str()) |
| 174 | + .unwrap_or(""); |
| 175 | + let available_balance: f64 = account |
| 176 | + .get("available_balance") |
| 177 | + .and_then(|v| v.get("value")) |
| 178 | + .and_then(|v| v.as_str()) |
| 179 | + .and_then(|s| s.parse().ok()) |
| 180 | + .unwrap_or(0.0); |
| 181 | + let hold: f64 = account |
| 182 | + .get("hold") |
| 183 | + .and_then(|v| v.get("value")) |
| 184 | + .and_then(|v| v.as_str()) |
| 185 | + .and_then(|s| s.parse().ok()) |
| 186 | + .unwrap_or(0.0); |
| 187 | + |
| 188 | + if available_balance > 0.0 || hold > 0.0 { |
| 189 | + use colored::Colorize; |
| 190 | + println!( |
| 191 | + " {}: {} (available: {}, hold: {})", |
| 192 | + currency.cyan(), |
| 193 | + available_balance + hold, |
| 194 | + available_balance, |
| 195 | + hold |
| 196 | + ); |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + println!(); |
| 202 | + Ok(()) |
| 203 | +} |
| 204 | + |
| 205 | +/// Get open orders |
| 206 | +pub async fn get_orders( |
| 207 | + client: &Client, |
| 208 | + api_key: &str, |
| 209 | + api_secret: &str, |
| 210 | + symbol: Option<&str>, |
| 211 | + _json_output: bool, |
| 212 | +) -> Result<serde_json::Value> { |
| 213 | + let ts = timestamp(); |
| 214 | + let mut path = "/api/v3/brokerage/orders/historical/batch?order_status=OPEN".to_string(); |
| 215 | + |
| 216 | + if let Some(sym) = symbol { |
| 217 | + let product_id = format!("{}-USD", sym.to_uppercase()); |
| 218 | + path.push_str(&format!("&product_id={}", product_id)); |
| 219 | + } |
| 220 | + |
| 221 | + let signature = sign_request(api_secret, &ts, "GET", &path, ""); |
| 222 | + |
| 223 | + let url = format!("{}{}", BASE_URL, path); |
| 224 | + |
| 225 | + let response = client |
| 226 | + .get(&url) |
| 227 | + .header("CB-ACCESS-KEY", api_key) |
| 228 | + .header("CB-ACCESS-SIGN", signature) |
| 229 | + .header("CB-ACCESS-TIMESTAMP", ts) |
| 230 | + .send() |
| 231 | + .await |
| 232 | + .context("Failed to fetch Coinbase orders")?; |
| 233 | + |
| 234 | + let status = response.status(); |
| 235 | + let body: serde_json::Value = response.json().await.context("Failed to parse response")?; |
| 236 | + |
| 237 | + if !status.is_success() { |
| 238 | + let error_msg = if let Some(msg) = body.get("message") { |
| 239 | + format!("Coinbase API error: {}", msg) |
| 240 | + } else { |
| 241 | + format!("Coinbase API error: {:?}", body) |
| 242 | + }; |
| 243 | + bail!(error_msg); |
| 244 | + } |
| 245 | + |
| 246 | + Ok(body) |
| 247 | +} |
| 248 | + |
| 249 | +/// Cancel an order |
| 250 | +pub async fn cancel_order( |
| 251 | + client: &Client, |
| 252 | + api_key: &str, |
| 253 | + api_secret: &str, |
| 254 | + order_id: &str, |
| 255 | + json_output: bool, |
| 256 | +) -> Result<()> { |
| 257 | + let ts = timestamp(); |
| 258 | + let path = "/api/v3/brokerage/orders/batch_cancel"; |
| 259 | + |
| 260 | + let body = json!({ |
| 261 | + "order_ids": [order_id] |
| 262 | + }); |
| 263 | + |
| 264 | + let body_str = serde_json::to_string(&body)?; |
| 265 | + let signature = sign_request(api_secret, &ts, "POST", path, &body_str); |
| 266 | + |
| 267 | + let url = format!("{}{}", BASE_URL, path); |
| 268 | + |
| 269 | + let response = client |
| 270 | + .post(&url) |
| 271 | + .header("CB-ACCESS-KEY", api_key) |
| 272 | + .header("CB-ACCESS-SIGN", signature) |
| 273 | + .header("CB-ACCESS-TIMESTAMP", ts) |
| 274 | + .header("Content-Type", "application/json") |
| 275 | + .body(body_str) |
| 276 | + .send() |
| 277 | + .await |
| 278 | + .context("Failed to cancel Coinbase order")?; |
| 279 | + |
| 280 | + let status = response.status(); |
| 281 | + let response_body: serde_json::Value = |
| 282 | + response.json().await.context("Failed to parse response")?; |
| 283 | + |
| 284 | + if !status.is_success() { |
| 285 | + let error_msg = if let Some(msg) = response_body.get("message") { |
| 286 | + format!("Coinbase API error: {}", msg) |
| 287 | + } else { |
| 288 | + format!("Coinbase API error: {:?}", response_body) |
| 289 | + }; |
| 290 | + bail!(error_msg); |
| 291 | + } |
| 292 | + |
| 293 | + if json_output { |
| 294 | + println!( |
| 295 | + "{}", |
| 296 | + serde_json::to_string_pretty(&json!({ |
| 297 | + "exchange": "coinbase", |
| 298 | + "order_id": order_id, |
| 299 | + "result": response_body, |
| 300 | + }))? |
| 301 | + ); |
| 302 | + } else { |
| 303 | + use colored::Colorize; |
| 304 | + println!("\n ✅ Coinbase order cancelled!"); |
| 305 | + println!(" Order ID: {}\n", order_id.cyan()); |
| 306 | + } |
| 307 | + |
| 308 | + Ok(()) |
| 309 | +} |
0 commit comments