Coder Social home page Coder Social logo

Comments (6)

skuvv avatar skuvv commented on July 21, 2024

Code:

public async void Run()
{
    Console.WriteLine("CCXT Version:" + ccxt.Exchange.ccxtVersion);

    var exchange = new ccxt.pro.Bitget();

    exchange.apiKey = "xxx";
    exchange.secret = "xxx";
    exchange.password = "xxx";
    exchange.verbose = true;
    exchange.enableRateLimit = true;

    Task.Run(async () => await exchange.LoadMarkets()).Wait();

    Console.WriteLine($"{exchange.symbols.Count} loaded");

    _ = Task.Run(async () =>
    {
        try
        {
            Dictionary<string, object> _ordersParams = new Dictionary<string, object>();
            _ordersParams.Clear();
            _ordersParams.Add("type", "spot");

            while (true)
            {
                var ordersResponse = await exchange.WatchOrders("XRP/USDT", parameters: _ordersParams);

                foreach (var order in ordersResponse)
                    Console.WriteLine($"Spot Order[{order.clientOrderId}] exchangeOrderId: '{order.id}', status: '{order.status}', price: '{order.price}', size: '{order.amount}', average: '{order.average}', filled: '{order.filled}', remain: '{order.remaining}'");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    });

    _ = Task.Run(async () =>
    {
        try
        {
            Dictionary<string, object> _ordersParams = new Dictionary<string, object>();
            _ordersParams.Clear();
            _ordersParams.Add("type", "margin");
            _ordersParams.Add("marginMode", "cross");

            while (true)
            {
                var ordersResponse = await exchange.WatchOrders("XRP/USDT", parameters: _ordersParams);

                foreach (var order in ordersResponse)
                    Console.WriteLine($"Cross Order[{order.clientOrderId}] exchangeOrderId: '{order.id}', status: '{order.status}', price: '{order.price}', size: '{order.amount}', average: '{order.average}', filled: '{order.filled}', remain: '{order.remaining}'");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    });


    _ = Task.Run(async () =>
    {
        try
        {
            Dictionary<string, object> _ordersParams = new Dictionary<string, object>();
            _ordersParams.Clear();
            _ordersParams.Add("type", "margin");
            _ordersParams.Add("marginMode", "isolated");

            while (true)
            {
                var ordersResponse = await exchange.WatchOrders("XRP/USDT", parameters: _ordersParams);

                foreach (var order in ordersResponse)
                    Console.WriteLine($"Isolated Order[{order.clientOrderId}] exchangeOrderId: '{order.id}', status: '{order.status}', price: '{order.price}', size: '{order.amount}', average: '{order.average}', filled: '{order.filled}', remain: '{order.remaining}'");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    });

    await Task.Delay(2500);
    Console.WriteLine("Sending spot order");

    try
    {
        var respSpot = await exchange.CreateOrder("XRP/USDT", "market", "buy", 10, parameters: new Dictionary<string, object>() { { "type", "spot" }, { "createMarketBuyOrderRequiresPrice", false } });
    }
    catch (Exception ex)
    {
        Console.WriteLine("Spot order error: " + ex);
    }

    await Task.Delay(5000);
    Console.WriteLine("Sending cross order");

    try
    {
        var respCross = await exchange.CreateOrder("XRP/USDT", "market", "buy", 10, parameters: new Dictionary<string, object>() { { "marginMode", "cross" }, { "createMarketBuyOrderRequiresPrice", false } });
    }
    catch(Exception ex)
    {
        Console.WriteLine("Cross order error: " + ex);
    }
}

Logs:

1196 loaded
waiting
WebSocket connected to wss://ws.bitget.com/v2/ws/private
Sending message: {"op":"login","args":[{"apiKey":"xxx","passphrase":"xxx","timestamp":"1718637525","sign":"xxx"}]}
On message: {"event":"login","code":0}
Sending message: {"op":"subscribe","args":[{"instType":"SPOT","channel":"orders","instId":"XRPUSDT"}]}
Sending message: {"op":"subscribe","args":[{"instType":"MARGIN","channel":"orders-isolated","instId":"XRPUSDT"}]}
On message: {"event":"subscribe","arg":{"instType":"SPOT","channel":"orders","instId":"XRPUSDT"}}
On message: {"event":"subscribe","arg":{"instType":"MARGIN","channel":"orders-isolated","instId":"XRPUSDT"}}
Sending spot order
fetch Request:
bitget POST https://api.bitget.com/api/v2/spot/trade/place-order
RequestHeaders:
ACCESS-KEY, xxx
ACCESS-SIGN, xxx
ACCESS-TIMESTAMP, 1718637527150
ACCESS-PASSPHRASE, xxx
X-CHANNEL-API-CODE, p4sve
Content-Type, application/json

RequestBody:
"{\"symbol\":\"XRPUSDT\",\"orderType\":\"market\",\"force\":\"GTC\",\"side\":\"buy\",\"size\":\"10\"}"

On message: {"action":"snapshot","arg":{"instType":"SPOT","channel":"orders","instId":"XRPUSDT"},"data":[{"instId":"XRPUSDT","orderId":"1186617283289227267","clientOid":"f3f2206b-d41c-4cc8-b067-d0b7a659ee12","size":"10.0000","newSize":"10.0000","notional":"10.000000","orderType":"market","force":"gtc","side":"buy","accBaseVolume":"0.0000","priceAvg":"0.00000","status":"live","cTime":"1718637527296","uTime":"1718637527296","feeDetail":[],"enterPointSource":"API"}],"ts":1718637527301}
handleRestResponse:
bitget POST https://api.bitget.com/api/v2/spot/trade/place-order 200 OK
ResponseHeaders:

ResponseBody:
{"code":"00000","msg":"success","requestTime":1718637527292,"data":{"orderId":"1186617283289227267","clientOid":"f3f2206b-d41c-4cc8-b067-d0b7a659ee12"}}

Spot Order[f3f2206b-d41c-4cc8-b067-d0b7a659ee12] exchangeOrderId: '1186617283289227267', status: 'open', price: '', size: '', average: '', filled: '0', remain: ''
On message: {"action":"snapshot","arg":{"instType":"SPOT","channel":"orders","instId":"XRPUSDT"},"data":[{"instId":"XRPUSDT","orderId":"1186617283289227267","clientOid":"f3f2206b-d41c-4cc8-b067-d0b7a659ee12","size":"10.0000","newSize":"10.0000","notional":"10.000000","orderType":"market","force":"gtc","side":"buy","fillPrice":"0.51769","tradeId":"1186617283557400578","baseVolume":"19.3165","fillTime":"1718637527360","fillFee":"-0.0193165","fillFeeCoin":"XRP","tradeScope":"T","accBaseVolume":"19.3165","priceAvg":"0.51769","status":"partially_filled","cTime":"1718637527296","uTime":"1718637527412","feeDetail":[{"feeCoin":"XRP","fee":"-0.0193165"}],"enterPointSource":"API"}],"ts":1718637527418}
Spot Order[f3f2206b-d41c-4cc8-b067-d0b7a659ee12] exchangeOrderId: '1186617283289227267', status: 'open', price: '0,51769', size: '19,3165', average: '0,51769', filled: '19,3165', remain: '0'
On message: {"action":"snapshot","arg":{"instType":"SPOT","channel":"orders","instId":"XRPUSDT"},"data":[{"instId":"XRPUSDT","orderId":"1186617283289227267","clientOid":"f3f2206b-d41c-4cc8-b067-d0b7a659ee12","size":"10.0000","newSize":"10.0000","notional":"10.000000","orderType":"market","force":"gtc","side":"buy","accBaseVolume":"19.3165","priceAvg":"0.51769","status":"filled","cTime":"1718637527296","uTime":"1718637527412","feeDetail":[{"feeCoin":"XRP","fee":"-0.0193165"}],"enterPointSource":"API"}],"ts":1718637527418}
Spot Order[f3f2206b-d41c-4cc8-b067-d0b7a659ee12] exchangeOrderId: '1186617283289227267', status: 'closed', price: '0,51769', size: '19,3165', average: '0,51769', filled: '19,3165', remain: '0'

Sending cross order
fetch Request:
bitget POST https://api.bitget.com/api/v2/margin/crossed/place-order
RequestHeaders:
ACCESS-KEY, xxx
ACCESS-SIGN, xxx
ACCESS-TIMESTAMP, 1718637621900
ACCESS-PASSPHRASE, xxx
X-CHANNEL-API-CODE, p4sve
Content-Type, application/json

RequestBody:
"{\"symbol\":\"XRPUSDT\",\"orderType\":\"market\",\"force\":\"GTC\",\"side\":\"buy\",\"loanType\":\"normal\",\"baseSize\":\"10\"}"

handleRestResponse:
bitget POST https://api.bitget.com/api/v2/margin/crossed/place-order 400 Bad Request
ResponseHeaders:

ResponseBody:
{"code":"40019","msg":"Parameter quoteSize cannot be empty","requestTime":1718637622014,"data":null}

Cross order error: ccxt.ExchangeError: bitget {"code":"40019","msg":"Parameter quoteSize cannot be empty","requestTime":1718637622014,"data":null}
   в ccxt.bitget.handleErrors(Object code, Object reason, Object url, Object method, Object headers, Object body, Object response, Object requestHeaders, Object requestBody)
   в ccxt.Exchange.<fetch>d__467.MoveNext()

from ccxt.

carlosmiei avatar carlosmiei commented on July 21, 2024

Hello @skuvv, this is not a bug, it's the expected behavior

https://docs.ccxt.com/#/README?id=market-buys

A lot of exchanges, including bitget, require the amount to be in the quote currency (they don't accept the base amount) when placing spot-market-buy orders.
Example: If you wanted to buy BTC/USDT with a market buy-order you would need to provide amount = 5 USDT instead of 0.000X. We have a check to prevent errors that explicitly require the price because users we will usually provide the amount in the base currency.

So by default if you do, create_order(symbol, 'market', 'buy', 10) will throw an error.
If you do create_order(symbol, 'market', 'buy', 0.001, 20000) ccxt will calculate the cost by doing 0.01*20000 and send that value to the exchange

If you want to provide the cost directly in the amount argument, you can do exchange.options['createMarketBuyOrderRequiresPrice'] = False (you acknowledge that the amount will be the cost for market-buy) and then you can do create_order(symbol, 'market', 'buy', 10)

As I said earlier, price is not required by the exchange, it is only used by ccxt to calculate the cost.
This is basically to avoid a user doing this: create_order('SHIB/USDT', market, buy, 1000000) and the user thinks he's trying to buy 1kk of shib but in reality he's buying 1kk USDT worth of SHIB. For that reason, by default ccxt always accepts the base currency in the amount parameter. But as you said if the exchange requires the cost and the user provided the base amount, we need to request an extra parameter price and multiply them to get the cost . If you're aware of this behavior you can simply disable createMarketBuyOrderRequiresPrice and pass the cost in the amount parameter, but by disabling it does not mean you can place the order using the base amount instead of the quote.

from ccxt.

skuvv avatar skuvv commented on July 21, 2024

Thanks for the details of the first part (Spot).
What about the second part (Margin)?

from ccxt.

carlosmiei avatar carlosmiei commented on July 21, 2024

@skuvv sorry missed that part let me check it

from ccxt.

carlosmiei avatar carlosmiei commented on July 21, 2024

@skuvv can you please update your ccxt version and try again? should be working now

from ccxt.

skuvv avatar skuvv commented on July 21, 2024

@skuvv can you please update your ccxt version and try again? should be working now

fixed, thanks!

from ccxt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.