indodax-cli 0.1.21

A command-line interface for the Indodax cryptocurrency exchange
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
use clap::{Parser, Subcommand};
use output::{CommandOutput, OutputFormat};

pub mod auth;
pub mod client;
pub mod commands;
pub mod config;
pub mod errors;
pub mod mcp;
pub mod output;

use client::IndodaxClient;
use errors::IndodaxError;

#[derive(Debug, Parser)]
#[command(
    name = "indodax",
    version,
    about = "Command-line interface for the Indodax cryptocurrency exchange",
    long_about = None
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Command,

    #[arg(short = 'o', long = "output", default_value = "table", help = "Output format: table or json", global = true)]
    pub output: OutputFormat,

    #[arg(long = "api-key", help = "API key (overrides config file and env var)", global = true)]
    pub api_key: Option<String>,

    #[arg(long = "api-secret", help = "API secret (overrides config file and env var)", global = true)]
    pub api_secret: Option<String>,

    #[arg(long = "api-secret-stdin", help = "Read API secret from stdin (more secure than --api-secret)", global = true)]
    pub api_secret_stdin: bool,

    #[arg(short = 'v', long = "verbose", help = "Enable verbose output", global = true)]
    pub verbose: bool,

    #[arg(long = "yes", alias = "force", help = "Skip confirmation prompts for destructive operations", global = true)]
    pub yes: bool,
}

#[derive(Debug, Subcommand)]
pub enum Command {
    // === Legacy Hidden Commands for Backward Compatibility ===
    #[command(hide = true)]
    #[command(subcommand)]
    Market(commands::market::MarketCommand),
    #[command(hide = true)]
    #[command(subcommand)]
    Account(commands::account::AccountCommand),
    #[command(hide = true)]
    #[command(subcommand)]
    Trade(commands::trade::TradeCommand),
    #[command(hide = true)]
    #[command(subcommand)]
    Funding(commands::funding::FundingCommand),

    // === Flat Public Market Commands (originally nested under Market) ===
    /// Get server time
    ServerTime,

    /// List available trading pairs
    Pairs,

    /// Get ticker for a pair
    Ticker {
        #[arg(default_value = "btc_idr")]
        pair: String,
    },

    /// Get tickers for all pairs
    TickerAll,

    /// Get 24h and 7d summaries for all pairs
    Summaries,

    /// Get order book for a pair
    Orderbook {
        #[arg(default_value = "btc_idr")]
        pair: String,
        #[arg(long, default_value = "20", help = "Number of bid/ask levels to show")]
        count: usize,
    },

    /// Get recent trades for a pair
    Trades {
        #[arg(default_value = "btc_idr")]
        pair: String,
    },

    /// Get OHLCV candle data (default --since is 24h ago)
    Ohlc {
        #[arg(short, long, default_value = "btc_idr")]
        pair: String,
        #[arg(long, default_value = "60")]
        interval: String,
        #[arg(short, long, help = "Start timestamp in seconds (default: 24h ago)")]
        since: Option<u64>,
        #[arg(long, help = "End timestamp in seconds (default: now)")]
        to: Option<u64>,
    },

    /// Get price increments (tick sizes)
    PriceIncrements,

    // === Flat Private Account Commands (originally nested under Account) ===
    /// Get current account information (balances, permissions, etc.)
    AccountInfo,

    /// Get non-zero account balances
    Balance,

    /// Get your deposit/withdrawal transactions
    Transactions,

    /// Get your trade history for a specific symbol
    TradesHistory {
        /// Trading pair symbol (e.g., btc_idr)
        pair: String,

        /// Number of trades to return (default: 500)
        #[arg(short, long, default_value = "500")]
        limit: usize,

        /// Start from this trade ID (optional)
        #[arg(long)]
        from_id: Option<u64>,
    },

    // === Flat Trading Command (originally nested under Trade) ===
    /// Place and manage orders
    #[command(subcommand)]
    Order(commands::trade::TradeCommand),

    // === Flat Funding / Withdrawal Commands (originally nested under Funding) ===
    /// Withdraw cryptocurrency
    Withdraw {
        #[arg(short, long)]
        asset: String,
        #[arg(short = 'v', long, help = "Amount to withdraw")]
        volume: f64,
        #[arg(long, help = "Crypto destination address (or Indodax username if --username is set)")]
        address: String,
        #[arg(long, help = "Withdraw to Indodax username instead of blockchain")]
        username: bool,
        #[arg(long, help = "Memo/tag (for currencies that require it)")]
        memo: Option<String>,
        #[arg(long, help = "Blockchain network")]
        network: Option<String>,
        #[arg(long, help = "Callback URL for withdrawal confirmation")]
        callback_url: Option<String>,
    },

    /// Manage withdrawal fees and servers
    #[command(subcommand)]
    Withdrawal(WithdrawalSubcommand),

    // === Flat WebSocket streaming ===
    /// WebSocket streaming
    #[command(subcommand)]
    Ws(commands::websocket::WebSocketCommand),

    // === Flat Paper Trading ===
    /// Paper trading (simulated)
    #[command(subcommand)]
    Paper(commands::paper::PaperCommand),

    // === Flat API Credentials ===
    /// Manage API credentials
    #[command(subcommand)]
    Auth(commands::auth::AuthCommand),

    // === Flat Price Alert Management ===
    /// Price alert management
    #[command(subcommand)]
    Alert(commands::alert::AlertCommand),

    // === Direct Tools ===
    /// Interactive setup wizard
    Setup,

    /// Start interactive REPL
    Shell,

    /// Start MCP stdio server for AI agent integration
    Mcp {
        #[arg(short = 's', long = "groups", default_value = "market,account,paper,auth", help = "Comma-separated service groups: market, account, trade, funding, paper, auth")]
        groups: String,
        #[arg(long, help = "Allow dangerous operations (trade, funding) without acknowledged flag")]
        allow_dangerous: bool,
    },
}

#[derive(Debug, Subcommand)]
pub enum WithdrawalSubcommand {
    /// Check withdrawal fee for a currency
    Fee {
        #[arg(short, long)]
        asset: String,
        #[arg(short, long, help = "Blockchain network (optional)")]
        network: Option<String>,
    },

    /// Start a temporary HTTP server to handle Indodax withdrawal callback
    ServeCallback {
        #[arg(short, long, default_value = "8080")]
        port: u16,
        #[arg(short, long, help = "When true, auto-confirms all callback requests. When false, prompts for each request.", default_value = "false")]
        auto_ok: bool,
        #[arg(long, help = "Listen address (default: 127.0.0.1). Use 0.0.0.0 for network access")]
        listen: Option<String>,
    },
}

pub async fn dispatch(
    cli: Cli,
    client: &IndodaxClient,
    config: &mut config::IndodaxConfig,
) -> Result<CommandOutput, IndodaxError> {
    let output = match cli.command {
        // === Legacy Hidden Commands ===
        Command::Market(ref cmd) => commands::market::execute(client, cmd).await
            .map_err(map_anyhow_error)?,
        Command::Account(ref cmd) => commands::account::execute(client, cmd).await
            .map_err(map_anyhow_error)?,
        Command::Trade(ref cmd) => commands::trade::execute(client, cmd, cli.yes).await
            .map_err(map_anyhow_error)?,
        Command::Funding(ref cmd) => commands::funding::execute(client, config, cmd, cli.output).await
            .map_err(map_anyhow_error)?,

        // === Public Market Commands ===
        Command::ServerTime => commands::market::execute(client, &commands::market::MarketCommand::ServerTime).await
            .map_err(map_anyhow_error)?,
        Command::Pairs => commands::market::execute(client, &commands::market::MarketCommand::Pairs).await
            .map_err(map_anyhow_error)?,
        Command::Ticker { pair } => commands::market::execute(client, &commands::market::MarketCommand::Ticker { pair }).await
            .map_err(map_anyhow_error)?,
        Command::TickerAll => commands::market::execute(client, &commands::market::MarketCommand::TickerAll).await
            .map_err(map_anyhow_error)?,
        Command::Summaries => commands::market::execute(client, &commands::market::MarketCommand::Summaries).await
            .map_err(map_anyhow_error)?,
        Command::Orderbook { pair, count } => commands::market::execute(client, &commands::market::MarketCommand::Orderbook { pair, levels: count }).await
            .map_err(map_anyhow_error)?,
        Command::Trades { pair } => commands::market::execute(client, &commands::market::MarketCommand::Trades { pair }).await
            .map_err(map_anyhow_error)?,
        Command::Ohlc { pair, interval, since, to } => commands::market::execute(client, &commands::market::MarketCommand::Ohlc {
            symbol: pair,
            timeframe: interval,
            from: since,
            to,
        }).await
            .map_err(map_anyhow_error)?,
        Command::PriceIncrements => commands::market::execute(client, &commands::market::MarketCommand::PriceIncrements).await
            .map_err(map_anyhow_error)?,

        // === Account & Balances Commands ===
        Command::AccountInfo => commands::account::execute(client, &commands::account::AccountCommand::Info).await
            .map_err(map_anyhow_error)?,
        Command::Balance => commands::account::execute(client, &commands::account::AccountCommand::Balance).await
            .map_err(map_anyhow_error)?,
        Command::Transactions => commands::account::execute(client, &commands::account::AccountCommand::TransHistory).await
            .map_err(map_anyhow_error)?,
        Command::TradesHistory { pair, limit, from_id: _ } => commands::account::execute(client, &commands::account::AccountCommand::TradeHistory {
            symbol: pair,
            limit: limit as u32,
        }).await
            .map_err(map_anyhow_error)?,

        // === Order Execution ===
        Command::Order(ref cmd) => commands::trade::execute(client, cmd, cli.yes).await
            .map_err(map_anyhow_error)?,

        // === Funding / Withdrawal Operations ===
        Command::Withdraw { asset, volume, address, username, memo, network, callback_url } => {
            let funding_cmd = commands::funding::FundingCommand::Withdraw {
                currency: asset,
                amount: volume,
                address,
                username,
                memo,
                network,
                callback_url,
            };
            commands::funding::execute(client, config, &funding_cmd, cli.output).await
                .map_err(map_anyhow_error)?
        }
        Command::Withdrawal(ref sub) => {
            let funding_cmd = match sub {
                WithdrawalSubcommand::Fee { asset, network } => {
                    commands::funding::FundingCommand::WithdrawFee {
                        currency: asset.clone(),
                        network: network.clone(),
                    }
                }
                WithdrawalSubcommand::ServeCallback { port, auto_ok, listen } => {
                    commands::funding::FundingCommand::ServeCallback {
                        port: *port,
                        auto_ok: *auto_ok,
                        listen: listen.clone(),
                    }
                }
            };
            commands::funding::execute(client, config, &funding_cmd, cli.output).await
                .map_err(map_anyhow_error)?
        }

        // === WS, Paper, Auth, Alert ===
        Command::Ws(ref cmd) => commands::websocket::execute(client, cmd, cli.output).await
            .map_err(map_anyhow_error)?,
        Command::Paper(ref cmd) => commands::paper::execute(client, config, cmd).await
            .map_err(map_anyhow_error)?,
        Command::Auth(ref cmd) => commands::auth::execute(client, config, cmd).await
            .map_err(map_anyhow_error)?,
        Command::Alert(ref cmd) => commands::alert::execute(client, &None, cmd).await
            .map_err(map_anyhow_error)?,

        Command::Setup | Command::Shell | Command::Mcp { .. } => {
            return Err(IndodaxError::Other("This command is handled separately".into()));
        }
    };

    Ok(output.with_format(cli.output))
}

pub fn map_anyhow_error(e: anyhow::Error) -> IndodaxError {
    e.downcast::<IndodaxError>()
        .unwrap_or_else(|e| IndodaxError::Other(e.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cli_parse_ticker() {
        let args = vec!["indodax", "ticker", "btc_idr"];
        let cli = Cli::try_parse_from(args).unwrap();
        match cli.command {
            Command::Ticker { pair: _ } => {
                // Just verify it parsed
            }
            _ => panic!("Expected Ticker command, got {:?}", cli.command),
        }
    }

    #[test]
    fn test_cli_parse_output_json() {
        let args = vec!["indodax", "-o", "json", "ticker"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert_eq!(cli.output, OutputFormat::Json);
    }

    #[test]
    fn test_cli_parse_api_key() {
        let args = vec!["indodax", "--api-key", "mykey", "ticker"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert_eq!(cli.api_key, Some("mykey".into()));
    }

    #[test]
    fn test_cli_parse_api_secret() {
        let args = vec!["indodax", "--api-secret", "mysecret", "ticker"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert_eq!(cli.api_secret, Some("mysecret".into()));
    }

    #[test]
    fn test_cli_parse_verbose() {
        let args = vec!["indodax", "-v", "ticker"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert!(cli.verbose);
    }

    #[test]
    fn test_command_variants() {
        let _cmd1 = Command::ServerTime;
        let _cmd2 = Command::AccountInfo;
        let _cmd3 = Command::Order(crate::commands::trade::TradeCommand::Buy { 
            pair: "btc_idr".into(), 
            idr: 100_000.0, 
            price: None,
            order_type: None,
        });
        let _cmd4 = Command::Withdrawal(WithdrawalSubcommand::Fee { 
            asset: "btc".into(), 
            network: None 
        });
        let _cmd5 = Command::Ws(crate::commands::websocket::WebSocketCommand::Ticker { 
            pair: "btc_idr".into() 
        });
        let _cmd6 = Command::Paper(crate::commands::paper::PaperCommand::Balance);
        let _cmd7 = Command::Auth(crate::commands::auth::AuthCommand::Show);
        let _cmd8 = Command::Setup;
        let _cmd9 = Command::Shell;
        let _cmd10 = Command::Mcp { groups: "market,paper".into(), allow_dangerous: false };
    }

    #[test]
    fn test_output_format_clap() {
        let args = vec!["indodax", "-o", "table", "ticker"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert_eq!(cli.output, OutputFormat::Table);
    }

    #[test]
    fn test_cli_parse_default_output() {
        let args = vec!["indodax", "ticker"];
        let cli = Cli::try_parse_from(args).unwrap();
        assert_eq!(cli.output, OutputFormat::Table);
    }

    #[test]
    fn test_command_display() {
        let cli = Cli::try_parse_from(vec!["indodax", "ticker"]).unwrap();
        let _ = format!("{:?}", cli);
    }
}