//! Open a new BUY order.
//!
//! Usage:
//!   cargo run --example open_order

use ctrader_rs::{proto::common::ProtoOaTradeSide, Client, Config};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenvy::dotenv().ok();

    tracing_subscriber::fmt()
        .with_env_filter("new_order=debug,ctrader_rs=debug")
        .with_line_number(true)
        .init();

    let client_id = std::env::var("CTRADER_CLIENT_ID")?;
    let secret = std::env::var("CTRADER_SECRET")?;
    let token = std::env::var("CTRADER_TOKEN")?;
    let account_id: i64 = std::env::var("CTRADER_ACCOUNT_ID")?.parse()?;

    let config = Config::new(client_id, secret).deadline(Duration::from_secs(5));

    tracing::debug!("Connecting to demo.ctraderapi.com:5035 …");
    let client = Client::start(config).await?;
    tracing::debug!("✓ Connected and application authenticated");

    // Authenticate the account
    let auth_res = client.account_auth(account_id, &token).await?;
    assert_eq!(auth_res.ctid_trader_account_id, account_id);
    tracing::debug!("✓ Account {account_id} authenticated");

    let res = client
        .new_market_order(account_id, 41, ProtoOaTradeSide::Buy, 100000)
        .await?;

    tracing::debug!("{:?}", res);

    // let res = client
    //     .new_limit_order(account_id, 41, ProtoOaTradeSide::Buy, 1000, 4800.00)
    //     .await?;

    // tracing::debug!("{:?}", res);

    // let res = client
    //     .new_stop_loss_take_profit_order(account_id, 41, ProtoOaTradeSide::Buy, 100_000, 500, 1000)
    //     .await?;

    // tracing::debug!("{:?}", res);

    // let res = client
    //     .new_market_range_order(account_id, 41, ProtoOaTradeSide::Buy, 1000)
    //     .await?;

    // tracing::debug!("{:?}", res);

    loop {}
}
