Hey guys I am getting 401 when trying to create a limit order here is my script:
require('dotenv').config({ path: './api_key.env' });
const { sign } = require('jsonwebtoken');
const axios = require('axios');
const crypto = require('crypto');
const { json } = require('express/lib/response');
const key_name = process.env.COINBASE_TRADING_API_KEY;
const key_secret = process.env.COINBASE_PRIVATE_KEY.replace(/\\n/g, '\n');
const service_name = "retail_rest_api_proxy";
const algorithm = 'ES256';
function generateToken(request_path) {
const url = 'api.coinbase.com'; // Base URL for Coinbase API
const uri = 'GET ' + url + request_path; // Concatenate request method, URL, and path
const token = sign({
aud: [service_name],
iss: 'coinbase-cloud',
nbf: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 120, // Token expiration time (2 minutes from now)
sub: key_name,
uri,
}, key_secret, {
algorithm,
header: {
kid: key_name,
nonce: crypto.randomBytes(16).toString('hex'), // Generate a nonce value
},
});
return token;
}
async function createOrder(orderDetails) {
const requestPath = '/api/v3/brokerage/orders';
const token = generateToken(requestPath); // Generate token for this specific request
let body = {
client_order_id: orderDetails.client_order_id,
product_id: orderDetails.product_id,
side: orderDetails.side,
order_configuration: orderDetails.order_configuration // Use the provided order configuration directly
};
console.log(body);
let config = {
method: 'post',
url: `https://api.coinbase.com${requestPath}`,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
data: JSON.stringify(body), // Ensure proper serialization
};
try {
const response = await axios(config);
console.log(`Order created successfully:`, response.data);
return response.data;
} catch (error) {
// Improved error handling
console.error(`Error creating order:`, error.response ? error.response.data : error.message);
return null;
}
}
const orderDetails = {
client_order_id: `buy-${currency}-${Date.now()}`,
product_id: `USD-${currency}`,
//product_id: `${currency}-USD`, <--- also tried that
order_configuration: {
"limit_limit_gtc": {
"base_size": lastInvestment.amount.toString(),
"limit_price": currentPrice.toString(),
//"post_only": true
}
},
side: "BUY",
};
await createOrder(orderDetails);
When trying to access open orders, or check for best_bid_ask all working as expected.