diff --git a/examples/js/advanced-error-handling.js b/examples/js/advanced-error-handling.js new file mode 100644 index 000000000000..7b75ba33bb5b --- /dev/null +++ b/examples/js/advanced-error-handling.js @@ -0,0 +1,39 @@ +"use strict"; + +const ccxt = require ('../../ccxt.js'); + +// instantiate the exchange +let exchange = new ccxt.coinbasepro ({ + 'apiKey': 'XXXXXXXXXXXXXX', + 'secret': 'YYYYYYYYYYYYYY', +}); + +async function checkOrders(){ + try { + // fetch orders + let orders = await exchange.fetchOrders ('BTC/USDT'); + // output the result + console.log (exchange.id, 'fetched orders', orders); + } catch (e) { + if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) { + console.log ('[DDoS Protection] ' + e.message); + } else if (e instanceof ccxt.RequestTimeout) { + console.log ('[Request Timeout] ' + e.message); + } else if (e instanceof ccxt.AuthenticationError) { + console.log ('[Authentication Error] ' + e.message); + } else if (e instanceof ccxt.ExchangeNotAvailable) { + console.log ('[Exchange Not Available Error] ' + e.message); + } else if (e instanceof ccxt.ExchangeError) { + console.log ('[Exchange Error] ' + e.message); + } else if (e instanceof ccxt.NetworkError) { + console.log ('[Network Error] ' + e.message); + } else { + // you can throw it if you want to stop the execution + // console.log ('[Exception ' + e.constructor.name + '] ' + e.message); + throw e; + } + } +} + +// for demonstrational purposes, we use 1000 ms interval +setInterval(checkOrders, 1000); diff --git a/examples/js/balances.js b/examples/js/balances.js deleted file mode 100644 index 50247b2a89ae..000000000000 --- a/examples/js/balances.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; - -const ccxt = require ('../../ccxt.js') -const asTable = require ('as-table') -const log = require ('ololog').configure ({ locate: false }) - -require ('ansicolor').nice - -let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms)) - -;(async () => { - - // instantiate the exchange - let coinbasepro = new ccxt.coinbasepro ({ // ... or new ccxt.coinbasepro () - 'apiKey': '92560ffae9b8a01d012726c698bcb2f1', // standard - 'secret': '9aHjPmW+EtRRKN/OiZGjXh8OxyThnDL4mMDre4Ghvn8wjMniAr5jdEZJLN/knW6FHeQyiz3dPIL5ytnF0Y6Xwg==', - 'password': '6kszf4aci8r', // Coinbase Pro requires a password! - }) - - // use the testnet for Coinbase Pro - coinbasepro.urls['api'] = coinbasepro.urls['test'] - - let hitbtc = new ccxt.hitbtc ({ - 'apiKey': '18339694544745d9357f9e7c0f7c41bb', - 'secret': '8340a60fb4e9fc73a169c26c7a7926f5', - }) - - try { - - // fetch account balance from the exchange - let coinbaseproBalance = await coinbasepro.fetchBalance () - - // output the result - log (coinbasepro.name.green, 'balance', coinbaseproBalance) - - // fetch another - let hitbtcBalance = await hitbtc.fetchBalance () - - // output it - log (hitbtc.name.green, 'balance', hitbtcBalance) - - } catch (e) { - - if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) { - log.bright.yellow ('[DDoS Protection] ' + e.message) - } else if (e instanceof ccxt.RequestTimeout) { - log.bright.yellow ('[Request Timeout] ' + e.message) - } else if (e instanceof ccxt.AuthenticationError) { - log.bright.yellow ('[Authentication Error] ' + e.message) - } else if (e instanceof ccxt.ExchangeNotAvailable) { - log.bright.yellow ('[Exchange Not Available Error] ' + e.message) - } else if (e instanceof ccxt.ExchangeError) { - log.bright.yellow ('[Exchange Error] ' + e.message) - } else if (e instanceof ccxt.NetworkError) { - log.bright.yellow ('[Network Error] ' + e.message) - } else { - throw e; - } - } - -}) () \ No newline at end of file diff --git a/examples/js/binance-fetch-ohlcv-many-symbols-since.js b/examples/js/binance-fetch-ohlcv-many-symbols-since.js deleted file mode 100644 index 4ae8ca8456b3..000000000000 --- a/examples/js/binance-fetch-ohlcv-many-symbols-since.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; - -const ccxt = require ('../../ccxt.js') - - -async function fetchOHLCVSince (exchange, symbol, timeframe, since) { - let ohlcvs = [] - while (true) { - try { - const response = await exchange.fetchOHLCV (symbol, timeframe, since) - if (response.length) { - const firstCandle = exchange.safeValue (response, 0) - const lastCandle = exchange.safeValue (response, response.length - 1) - const firstTimestamp = exchange.safeInteger (firstCandle, 0) - const lastTimestamp = exchange.safeInteger (lastCandle, 0) - const firstDatetime = exchange.iso8601 (firstTimestamp) - const lastDatetime = exchange.iso8601 (lastTimestamp) - const currentDatetime = exchange.iso8601 (exchange.milliseconds ()) - since = lastTimestamp + 1 - ohlcvs = ohlcvs.concat (response) - console.log (currentDatetime, symbol, timeframe, 'fetched', response.length, 'candles since', firstDatetime, 'till', lastDatetime, 'total', ohlcvs.length) - } else { - break - } - } catch (e) { - console.log (e.constructor.name, e.message) - } - } - return { symbol, ohlcvs } -} - -async function main () { - - const exchange = new ccxt.binance() - const markets = await exchange.loadMarkets () - const timeframe = '5m' - - const firstOneHundredSymbols = exchange.symbols.slice (0, 10) - const now = exchange.milliseconds () - const oneWeek = 60 * 60 * 24 * 7 * 1000 // milliseconds - const since = now - oneWeek - const allCandles = await Promise.all (firstOneHundredSymbols.map (symbol => fetchOHLCVSince (exchange, symbol, timeframe, since))) - const allCandlesBySymbol = exchange.indexBy (allCandles, 'symbol') - - console.log ('Fetched', Object.keys (allCandlesBySymbol)) - console.log ('Done') - -} - -main () \ No newline at end of file diff --git a/examples/js/binance-fetch-ohlcv.js b/examples/js/binance-fetch-ohlcv.js deleted file mode 100644 index 278e7c1770cd..000000000000 --- a/examples/js/binance-fetch-ohlcv.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; - -const ccxt = require ('../../ccxt.js') -const asciichart = require ('asciichart') -const asTable = require ('as-table') -const log = require ('ololog').configure ({ locate: false }) - -require ('ansicolor').nice - -//----------------------------------------------------------------------------- - -;(async function main () { - - const index = 4 // [ timestamp, open, high, low, close, volume ] - - - const ohlcv = await new ccxt.binance ().fetchOHLCV ('BTC/USDT', '1h') - - - const lastPrice = ohlcv[ohlcv.length - 1][index] // closing price - const series = ohlcv.slice (-80).map (x => x[index]) // closing price - const bitcoinRate = ('₿ = $' + lastPrice).green - const chart = asciichart.plot (series, { height: 15, padding: ' ' }) - log.yellow ("\n" + chart, bitcoinRate, "\n") - process.exit () - -}) () \ No newline at end of file diff --git a/examples/js/fetch-balance.js b/examples/js/fetch-balance.js new file mode 100644 index 000000000000..1f14c8ced8b5 --- /dev/null +++ b/examples/js/fetch-balance.js @@ -0,0 +1,28 @@ +"use strict"; + +const ccxt = require ('../../ccxt.js'); + +// instantiate the exchange +let exchange = new ccxt.coinbasepro ({ + 'apiKey': 'XXXXXXXXXXXXXX', + 'secret': 'YYYYYYYYYYYYYY', + 'password': 'ZZZZZZ', // if exchange requires password +}); + + +async function checkMyBalance() { + try { + // fetch account balance from the exchange + let myBalance = await exchange.fetchBalance (); + + // output the result + console.log (exchange.id, 'fetched balance', myBalance); + + } catch (e) { + // fpr advanced error-handling, see the "advanced-error-handling.js" example file + console.log ('[' + e.constructor.name + '] ' + e.message); + throw e; + } +} + +checkMyBalance(); \ No newline at end of file diff --git a/examples/js/fetch-ohlcv-from-to-mark-index-premium.js b/examples/js/fetch-ohlcv-from-to-mark-index-premium.js new file mode 100644 index 000000000000..5a74d5647360 --- /dev/null +++ b/examples/js/fetch-ohlcv-from-to-mark-index-premium.js @@ -0,0 +1,72 @@ +"use strict"; + +const ccxt = require ('../../ccxt') + +const exchange = new ccxt.binance (); + +const symbols = [ 'BTC/USDT', 'ETH/USDT', 'ADA/USDT']; +// start from i.e. 01 february 2022 +// you can use milliseconds integer or also parse uniform datetime string, i.e. exchange.parse8601 ('2020-02-01T00:00:00Z') +const fromTimestamp = 1643659200000; +const tillTimestamp = exchange.milliseconds (); +const timeframe = '1h'; +const itemsLimit = 1000; +const fetchMethod = 'fetchOHLCV'; // if using swap exchanges, you can also use fetchMarkOHLCV, fetchIndexOHLCV, fetchPremiumIndexOHLCV + +async function myDataFetch (symbol) { + + await exchange.loadMarkets (); + + // get the duration of one timeframe period in milliseconds + const duration = exchange.parseTimeframe (timeframe) * 1000; + console.log ('Fetching', symbol, timeframe, 'candles', 'from', exchange.iso8601 (fromTimestamp), 'to', exchange.iso8601 (tillTimestamp), '...'); + + let result = []; + let since = fromTimestamp; + do { + + try { + + const candles = await exchange[fetchMethod] (symbol, timeframe, since, itemsLimit); + + const message = '[' + symbol + '] Fetched ' + candles.length + ' ' + timeframe + ' candles since ' + exchange.iso8601 (since); + + if (candles.length) { + + const first = candles[0]; + const last = candles[candles.length - 1]; + console.log ( message, ' | first', exchange.iso8601 (first[0]), ' | last', exchange.iso8601 (last[0]) ); + + // store your candles to a database or to a file here + // ... + result = result.concat (candles); + since = last[0] + duration // next start from last candle timestamp + duration + + } else { + console.log ( message, ' | moving into next period'); + since = since + duration * itemsLimit; // next start from the current period's end + } + + } catch (e) { + + console.log (symbol, e.constructor.name, e.message, ' Taking small pause...'); + await exchange.sleep (2000); + // retry on next iteration + } + + } while (since + duration <= tillTimestamp) + + console.log (symbol + ' completed !'); + return result; +} + + + +async function checkAllSymbols() { + // download in parallel + await Promise.all (symbols.map (symbol => myDataFetch (symbol))); + // you can also do one by one (but that is not much optimal) + //for (const symbol of symbols) { + // const data = await myDataFetch (symbol); +} +checkAllSymbols(); diff --git a/examples/js/fetch-ohlcv-mark-index-price.js b/examples/js/fetch-ohlcv-mark-index-price.js deleted file mode 100644 index 377498dd6c49..000000000000 --- a/examples/js/fetch-ohlcv-mark-index-price.js +++ /dev/null @@ -1,37 +0,0 @@ -const ccxt = require('../../ccxt') - , asTable = require ('as-table').configure ({ delimiter: ' | ' }) - -console.log ('CCXT Version:', ccxt.version) - -async function main () { - - const exchange = new ccxt.binanceusdm() - , symbol = 'ADA/USDT' - , timeframe = '1h' - , since = undefined - , limit = undefined - - // ------------------------------------------------------------------------ - // method 1 – fetch mark price OHLCVs with a `price` override in `params`: - - const params = { 'price': 'mark' } - const response = await exchange.fetchOHLCV (symbol, timeframe, since, limit, params) - - console.log (asTable (response)) - - // ------------------------------------------------------------------------ - // method 2 – use convenience shorthands - - const mark = await exchange.fetchMarkOHLCV (symbol, timeframe) - - console.log ('-----------------------------------------------------------') - console.log (asTable (mark)) - - const index = await exchange.fetchIndexOHLCV (symbol, timeframe) - - console.log ('-----------------------------------------------------------') - console.log (asTable (index)) - -} - -main () diff --git a/examples/js/hitbtc-fetch-all-ohlcvs.js b/examples/js/hitbtc-fetch-all-ohlcvs.js deleted file mode 100644 index 35aa508c4695..000000000000 --- a/examples/js/hitbtc-fetch-all-ohlcvs.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; - -const ccxt = require ('../../ccxt') - -const exchange = new ccxt.hitbtc () - -;(async () => { - - await exchange.loadMarkets () - - // start from february 2020 - const start = exchange.parse8601 ('2020-02-01T00:00:00Z') - const timeframe = '1m' - // get the duration of one timeframe period in milliseconds - const duration = exchange.parseTimeframe (timeframe) * 1000 - - for (const symbol of exchange.symbols) { - - console.log ('-------------------------------------------------------') - console.log ('Fetching', symbol, timeframe, 'candles') - - let since = start - - do { - - try { - const candles = await exchange.fetchOHLCV (symbol, timeframe, since) - - if (candles.length) { - - const first = candles[0] - const last = candles[candles.length - 1] - - console.log ( - 'Fetched', candles.length, symbol, timeframe, 'candles', - 'from', exchange.iso8601 (first[0]), - 'to', exchange.iso8601 (last[0]) - ) - - // store your candles to a database or to a file here - // ... - - since = last[0] + duration // next start from last candle timestamp + duration - - } else { - - console.log ('Fetched', candles.length, symbol, 'candles') - break - } - - } catch (e) { - - console.log (e.constructor.name, e.constructor.message) - // retry on next iteration - } - - } while (since < exchange.milliseconds ()) - } - -}) () diff --git a/examples/js/oceanex-fetch-ohlcv.js b/examples/js/oceanex-fetch-ohlcv.js deleted file mode 100644 index 44374ffc1078..000000000000 --- a/examples/js/oceanex-fetch-ohlcv.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; - -const ccxt = require ('../../ccxt.js') -const asciichart = require ('asciichart') -const asTable = require ('as-table') -const log = require ('ololog').configure ({ locate: false }) - -require ('ansicolor').nice - -//----------------------------------------------------------------------------- - -;(async function main () { - - const index = 4 // [ timestamp, open, high, low, close, volume ] - - - const ohlcv = await new ccxt.oceanex ().fetchOHLCV ('BTC/USDT', '1h') - - - const lastPrice = ohlcv[ohlcv.length - 1][index] // closing price - const series = ohlcv.slice (-80).map (x => x[index]) // closing price - const bitcoinRate = ('₿ = $' + lastPrice).green - const chart = asciichart.plot (series, { height: 15, padding: ' ' }) - log.yellow ("\n" + chart, bitcoinRate, "\n") - process.exit () - -}) () \ No newline at end of file diff --git a/examples/js/fetch-ohlcv-cex.js b/examples/js/ohlcv-console-chart.js similarity index 65% rename from examples/js/fetch-ohlcv-cex.js rename to examples/js/ohlcv-console-chart.js index 8b11c747d6f8..785b7e5823b9 100644 --- a/examples/js/fetch-ohlcv-cex.js +++ b/examples/js/ohlcv-console-chart.js @@ -14,12 +14,12 @@ require ('ansicolor').nice // experimental, not yet implemented for all exchanges // your contributions are welcome ;) - const index = 4 // [ timestamp, open, high, low, close, volume ] + const indexOfClose = 4 // [ timestamp, open, high, low, close, volume ] const ohlcv = await new ccxt.cex ().fetchOHLCV ('BTC/USD', '1m') - const lastPrice = ohlcv[ohlcv.length - 1][index] // closing price - const series = ohlcv.slice (-80).map (x => x[index]) // closing price + const lastPrice = ohlcv[ohlcv.length - 1][indexOfClose] // closing price + const plotSeriesData = ohlcv.slice (-80).map (x => x[indexOfClose]) // closing price const bitcoinRate = ('₿ = $' + lastPrice).green - const chart = asciichart.plot (series, { height: 15, padding: ' ' }) + const chart = asciichart.plot (plotSeriesData, { height: 15, padding: ' ' }) log.yellow ("\n" + chart, bitcoinRate, "\n") process.exit () diff --git a/examples/js/okex-fetch-ohlcv-since-limit.js b/examples/js/okex-fetch-ohlcv-since-limit.js deleted file mode 100644 index d679f89ad43a..000000000000 --- a/examples/js/okex-fetch-ohlcv-since-limit.js +++ /dev/null @@ -1,37 +0,0 @@ -const ccxt = require ('../../ccxt.js') - , log = require ('ololog') - , ansi = require ('ansicolor').nice - -;(async () => { - - const exchange = new ccxt['okex']() - - let limit = undefined - let symbol = 'BTC/USDT' - let interval = '15m' - - // enable either of the following two lines - exchange.options['warnOnFetchOHLCVLimitArgument'] = false - // limit = 3 - - const dates = [ - '2014-01-01T00:00:00', // okex did not exist then - '2016-02-01T00:00:00', - '2018-02-15T00:00:00', - '2018-02-25T00:00:00', - '2018-02-27T00:00:00', - ] - - const results = await Promise.all (dates.map (async date => { - since = exchange.parse8601 (date) - const ohlcv = await exchange.fetchOHLCV (symbol, interval, since, limit) - const fetchingFrom = date.green - const firstCandleDate = ohlcv.length ? exchange.iso8601 (ohlcv[0][0]).yellow : undefined - const lastCandleDate = ohlcv.length ? exchange.iso8601 (ohlcv[ohlcv.length - 1][0]).yellow : undefined - const count = ohlcv.length.toString ().red - return { fetchingFrom, firstCandleDate, lastCandleDate, count, ohlcv } - })) - - log (results) - -}) ()