This commit is contained in:
discountry
2025-10-03 15:28:16 +08:00
parent d5c4b04746
commit fcb83bd16b
925 changed files with 165721 additions and 4 deletions
@@ -0,0 +1,74 @@
'use strict';
import ccxt from '../../../js/ccxt.js';
// your version must be 0.7+
console.log ('CCXT Version:', ccxt.version)
function handle (exchange, symbol, ticker) {
console.log (new Date (), exchange.id, symbol, ticker)
}
async function loop (exchange, symbol) {
while (true) {
try {
const ticker = await exchange.watchMyTrades ()
handle (exchange, symbol, ticker)
sleep( 10000 )
} catch (e) {
console.log (symbol, e)
// do nothing and retry on next loop iteration
// throw e // uncomment to break all loops in case of an error in any one of them
// break // you can also break just this one loop if it fails
}
}
}
async function main () {
const exchange = new ccxt.pro.apex ({
'apiKey': 'your api Key',
'secret': 'your api secret',
'walletAddress': 'your eth address',
'options': {
'accountId': 'your account id',
'passphrase': 'your api passphrase',
'seeds': 'your zklink omni seed',
'brokerId': '',
},
}) // usd(s)-margined contracts
exchange.setSandboxMode(true)
//
// or
//
// const exchange = new ccxt.pro.binance () // spot markets
//
// WARNING: when using the spot markets mind subscription limits!
// don't attempt to subscribe to all of them
// the exchanges will not allow that in general
// instead, specify a shorter list of symbols to subscribe to
//
// or
//
// const exchange = new ccxt.pro.binancecoinm () // coin-margined contracts
if (exchange.has['watchTicker']) {
await exchange.loadMarkets ()
// many symbols
//await Promise.all (exchange.symbols.map (symbol => loop (exchange, symbol)))
//
// or
//
// const symbols = [ 'BTC/USDT', 'ETH/USDT' ] // specific symbols
// await Promise.all (symbols.map (symbol => loop (exchange, symbol)))
//
// or
//
await loop (exchange, ['BTC-USDT','ETH-USDT']) // one symbol
} else {
console.log (exchange.id, 'does not support watchTicker yet')
}
}
main ()
@@ -0,0 +1,55 @@
'use strict';
const ccxt = require ('../../../ccxt')
console.log ('CCXT Version:', ccxt.version)
// This example will run silent and will return your balance only when the balance is updated.
//
// 1. launch the example with your keys and keep it running
// 2. go to the trading section on the website
// 3. place a order on a spot market
// 4. see your balance updated in the example
//
// Warning! This example might produce a lot of output to your screen
async function watchBalance (exchange) {
let balance = await exchange.fetchBalance ()
console.log ('---------------------------------------------------------')
console.log (exchange.iso8601 (exchange.milliseconds ()))
console.log (balance, '\n')
while (true) {
try {
const update = await exchange.watchBalance ()
balance = exchange.deep_extend (balance, update)
// it will print the balance update when the balance changes
// if the balance remains unchanged the exchange will not send it
console.log ('---------------------------------------------------------')
console.log (exchange.iso8601 (exchange.milliseconds ()))
console.log (balance, '\n')
} catch (e) {
console.log (e.constructor.name, e.message)
break
}
}
}
async function main() {
const exchange = new ccxt.pro.binance ({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
await exchange.loadMarkets ()
// exchange.verbose = true // uncomment for debugging purposes if necessary
await watchBalance (exchange)
await exchange.close ()
}
main ()
@@ -0,0 +1,48 @@
'use strict';
const ccxt = require ('../../../ccxt')
console.log ('CCXT Version:', ccxt.version)
let HttpsProxyAgent = undefined
try {
HttpsProxyAgent = require ('https-proxy-agent')
} catch (e) {
console.log (e.constructor.name, e.message)
console.log ("\nCould not load the HTTPS proxy agent")
console.log ("\nPlease, run this command to make sure it's properly installed:")
console.log ("\nnpm install https-proxy-agent\n")
process.exit ()
}
async function main () {
console.log ('Using proxy server', httpsProxyUrl);
// adjust for your HTTPS proxy URL
const httpsProxyUrl = process.env.https_proxy || 'https://username:password@your-proxy.com'
, httpsAgent = new HttpsProxyAgent (httpsProxyUrl)
, exchange = new ccxt.binance ({
httpsAgent: httpsAgent, // ←--------------------- httpsAgent here
options: {
'ws': {
'options': { agent: httpsAgent }, // ←--- httpsAgent here
},
},
})
const symbol = 'BTC/USDT'
await exchange.loadMarkets ()
console.log ('Markets loaded')
while (true) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
console.log (exchange.iso8601 (exchange.milliseconds()), symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
}
main ()
@@ -0,0 +1,38 @@
"use strict";
const ccxt = require ('ccxt')
const ohlcvsBySymbol = {}
function handleAllOHLCVs (exchange, ohlcvs, symbol, timeframe) {
const now = exchange.iso8601 (exchange.milliseconds ())
const lastCandle = exchange.safeValue (ohlcvs, ohlcvs.length - 1)
const datetime = exchange.iso8601 (lastCandle[0])
console.log (now, datetime, symbol, timeframe, lastCandle.slice (1))
}
async function pollOHLCV (exchange, symbol, timeframe) {
await exchange.throttle (1000) // 1000ms delay between subscriptions
while (true) {
try {
const response = await exchange.watchOHLCV (symbol, timeframe)
ohlcvsBySymbol[symbol] = response
handleAllOHLCVs(exchange, response, symbol, timeframe)
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
}
async function main () {
const exchange = new ccxt.pro.binance()
const markets = await exchange.loadMarkets ()
const timeframe = '5m'
const firstOneHundredSymbols = exchange.symbols.slice (0, 100)
await Promise.all (firstOneHundredSymbols.map (symbol => pollOHLCV (exchange, symbol, timeframe)))
}
main ()
@@ -0,0 +1,64 @@
'use strict';
const ccxt = require ('ccxt');
// your version must be 0.7+
console.log ('CCXT Version:', ccxt.version)
function handle (exchange, symbol, timeframe, candles) {
const lastCandle = candles[candles.length - 1]
const lastClosingPrice = lastCandle[4]
console.log (new Date (), exchange.id, timeframe, symbol, '\t', lastClosingPrice)
}
async function loop (exchange, symbol, timeframe) {
while (true) {
try {
const candles = await exchange.watchOHLCV (symbol, timeframe)
handle (exchange, symbol, timeframe, candles)
} catch (e) {
console.log (symbol, e)
// do nothing and retry on next loop iteration
// throw e // uncomment to break all loops in case of an error in any one of them
// break // you can also break just this one loop if it fails
}
}
}
async function main () {
const exchange = new ccxt.pro.binanceusdm () // usd(s)-margined contracts
//
// or
//
// const exchange = new ccxt.pro.binance () // spot markets
//
// WARNING: when using the spot markets mind subscription limits!
// don't attempt to subscribe to all of them
// the exchanges will not allow that in general
// instead, specify a shorter list of symbols to subscribe to
//
// or
//
// const exchange = new ccxt.pro.binancecoinm () // coin-margined contracts
if (exchange.has['watchOHLCV']) {
await exchange.loadMarkets ()
const timeframe = '15m'
// many symbols
await Promise.all (exchange.symbols.map (symbol => loop (exchange, symbol, timeframe)))
//
// or
//
// const symbols = [ 'BTC/USDT', 'ETH/USDT' ] // specific symbols
// await Promise.all (symbols.map (symbol => loop (exchange, symbol, timeframe)))
//
// or
//
// await loop (exchange, 'BTC/USDT', timeframe) // one symbol
} else {
console.log (exchange.id, 'does not support watchOHLCV yet')
}
}
main ()
@@ -0,0 +1,62 @@
'use strict';
const ccxt = require ('ccxt');
// your version must be 0.7+
console.log ('CCXT Version:', ccxt.version)
function handle (exchange, symbol, ticker) {
console.log (new Date (), exchange.id, symbol, ticker['last'])
}
async function loop (exchange, symbol) {
while (true) {
try {
const ticker = await exchange.watchTicker (symbol)
handle (exchange, symbol, ticker)
} catch (e) {
console.log (symbol, e)
// do nothing and retry on next loop iteration
// throw e // uncomment to break all loops in case of an error in any one of them
// break // you can also break just this one loop if it fails
}
}
}
async function main () {
const exchange = new ccxt.pro.binanceusdm () // usd(s)-margined contracts
//
// or
//
// const exchange = new ccxt.pro.binance () // spot markets
//
// WARNING: when using the spot markets mind subscription limits!
// don't attempt to subscribe to all of them
// the exchanges will not allow that in general
// instead, specify a shorter list of symbols to subscribe to
//
// or
//
// const exchange = new ccxt.pro.binancecoinm () // coin-margined contracts
if (exchange.has['watchTicker']) {
await exchange.loadMarkets ()
// many symbols
await Promise.all (exchange.symbols.map (symbol => loop (exchange, symbol)))
//
// or
//
// const symbols = [ 'BTC/USDT', 'ETH/USDT' ] // specific symbols
// await Promise.all (symbols.map (symbol => loop (exchange, symbol)))
//
// or
//
// await loop (exchange, 'BTC/USDT') // one symbol
} else {
console.log (exchange.id, 'does not support watchTicker yet')
}
}
main ()
@@ -0,0 +1,68 @@
'use strict';
const ccxt = require ('ccxt');
const asTable = require ('as-table').configure ({ delimiter: ' | ' })
console.log ('CCXT Version:', ccxt.version)
async function loop (exchange, symbol, timeframe, completeCandlesOnly = false) {
const durationInSeconds = exchange.parseTimeframe (timeframe)
const durationInMs = durationInSeconds * 1000
while (true) {
try {
const trades = await exchange.watchTrades (symbol)
if (trades.length > 0) {
const currentMinute = parseInt (exchange.milliseconds () / durationInMs)
let ohlcvc = exchange.buildOHLCVC (trades, timeframe)
if (completeCandlesOnly) {
ohlcvc = ohlcvc.filter (candle => parseInt (candle[0] / durationInMs) < currentMinute)
}
if (ohlcvc.length > 0) {
console.log("Symbol:", symbol, "timeframe:", timeframe);
console.log ('-----------------------------------------------------------')
console.log (asTable (ohlcvc))
console.log ('-----------------------------------------------------------')
}
}
} catch (e) {
console.log (symbol, e)
// do nothing and retry on next loop iteration
// throw e // uncomment to break all loops in case of an error in any one of them
// break // you can also break just this one loop if it fails
}
}
}
async function main () {
// select the exchange
const exchange = new ccxt.pro.ftx ()
if (exchange.has['watchTrades']) {
await exchange.loadMarkets ()
// Change this value accordingly
const timeframe = '1m'
const allSymbols = exchange.symbols;
// arbitrary n symbols
const limit = 5;
// const selectedSymbols = allSymbols.slice(0, limit);
// you can also specify the symbols manually
// example:
// const selectedSymbols = ['BTC/USDT', 'LTC/USDT']
console.log(selectedSymbols);
// Use this variable to choose if only complete candles
// should be considered
const completeCandlesOnly = true
await Promise.all (selectedSymbols.map (symbol => loop (exchange, symbol, timeframe, completeCandlesOnly)))
} else {
console.log (exchange.id, 'does not support watchTrades yet')
}
}
main ()
@@ -0,0 +1,82 @@
'use strict';
const ccxt = require ('../../../ccxt');
console.log ('CCXT Version:', ccxt.version)
let ohlcvs = {}
async function log (exchange, symbol, timeframe) {
const market = exchange.market (symbol)
const duration = exchange.parseTimeframe (timeframe) * 1000
console.log (exchange.iso8601 (exchange.milliseconds ()), 'Warming up, waiting for at least one trade...')
while (!Object.keys (ohlcvs).length) {
await exchange.throttle (1)
}
let now = exchange.milliseconds ()
const start = (parseInt (now / duration) + 1) * duration
console.log (exchange.iso8601 (exchange.milliseconds ()), 'Trades started arriving, waiting till', exchange.iso8601 (start))
await exchange.sleep (start - now)
console.log (exchange.iso8601 (exchange.milliseconds ()), 'Done warming up')
for (let i = 0;; i++) {
now = exchange.milliseconds ()
let candle = Object.values (ohlcvs)[0]
console.log ('')
console.log (exchange.iso8601 (now), '------------------------------------------------------')
console.log ('Datetime ', 'Timestamp ', ... [ 'Open', 'High', 'Low', 'Close', market['base'], market['quote'] ].map (x => x.toString ().padEnd (10, ' ')))
for (let j = start; j < now; j += duration) {
if (!(j in ohlcvs)) {
ohlcvs[j] = [ j, candle[4], candle[4], candle[4], candle[4], 0, 0 ]
}
candle = exchange.safeValue (ohlcvs, j);
console.log (exchange.iso8601 (j), ... candle.map (x => x.toString ().padEnd (10, ' ')))
}
ohlcvs = exchange.indexBy (Object.values (ohlcvs).slice (-1000), 0)
await exchange.sleep(1000)
}
}
async function watch (exchange, symbol, timeframe) {
console.log ('Starting', exchange.id, symbol)
const duration = exchange.parseTimeframe (timeframe) * 1000
while (true) {
try {
const trades = await exchange.watchTrades(symbol)
for (const trade of trades) {
const timestamp = parseInt(trade['timestamp'] / duration) * duration
let candle = exchange.safe_value(ohlcvs, timestamp)
if (candle) {
candle[2] = Math.max(trade['price'], candle[2])
candle[3] = Math.min(trade['price'], candle[3])
candle[4] = trade['price']
candle[5] = exchange.parseNumber(exchange.amountToPrecision(symbol, trade['amount'] + candle[5]))
candle[6] = exchange.parseNumber(exchange.costToPrecision(symbol, trade['cost'] + candle[6]))
} else {
candle = [
timestamp,
trade['price'],
trade['price'],
trade['price'],
trade['price'],
exchange.parseNumber(exchange.amountToPrecision(symbol, trade['amount'])),
exchange.parseNumber(exchange.costToPrecision(symbol, trade['cost'])),
]
}
ohlcvs[timestamp] = candle
}
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
}
async function main() {
const symbol = 'BTC/USDT'
const exchange = new ccxt.pro.binance ({ 'newUpdates': true })
await exchange.loadMarkets ()
const timeframe = '1m'
await Promise.all ([ watch (exchange, symbol, timeframe), log (exchange, symbol, timeframe) ])
await exchange.close ()
}
main()
@@ -0,0 +1,59 @@
'use strict';
const ccxt = require ('../../../ccxt');
console.log ('CCXT Version:', ccxt.version)
async function main() {
let ohlcvs = {}
const symbol = 'BTC/USDT'
const exchange = new ccxt.pro.binance ({ 'newUpdates': true })
await exchange.loadMarkets ()
const market = exchange.market (symbol)
const timeframe = '1m'
const duration = exchange.parseTimeframe (timeframe) * 1000
console.log ('Starting', exchange.id, symbol)
while (true) {
try {
const trades = await exchange.watchTrades(symbol)
for (const trade of trades) {
const timestamp = parseInt(trade['timestamp'] / duration) * duration
let candle = exchange.safe_value(ohlcvs, timestamp)
if (candle) {
candle[2] = Math.max(trade['price'], candle[2])
candle[3] = Math.min(trade['price'], candle[3])
candle[4] = trade['price']
candle[5] = exchange.parseNumber(exchange.amountToPrecision(symbol, trade['amount'] + candle[5]))
candle[6] = exchange.parseNumber(exchange.costToPrecision(symbol, trade['cost'] + candle[6]))
} else {
candle = [
timestamp,
trade['price'],
trade['price'],
trade['price'],
trade['price'],
exchange.parseNumber(exchange.amountToPrecision(symbol, trade['amount'])),
exchange.parseNumber(exchange.costToPrecision(symbol, trade['cost'])),
]
}
ohlcvs[timestamp] = candle
}
console.log ('')
console.log (exchange.iso8601 (exchange.milliseconds ()), '------------------------------------------------------')
const values = Object.values (ohlcvs).slice (-1000)
ohlcvs = exchange.indexBy (values, 0)
console.log ('Datetime ', 'Timestamp ', ... [ 'Open', 'High', 'Low', 'Close', market['base'], market['quote'] ].map (x => x.toString ().padEnd (10, ' ')))
for (let i = 0; i < values.length; i++) {
const candle = values[i]
console.log (exchange.iso8601 (candle[0]), ... candle.map (x => x.toString ().padEnd (10, ' ')))
}
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
await exchange.close ()
}
main()
@@ -0,0 +1,72 @@
"use strict";
/* ------------------------------------------------------------------------ */
const ccxt = require ('../../../ccxt.js').pro
, asTable = require ('as-table') // .configure ({ print: require ('string.ify').noPretty })
, log = require ('ololog').noLocate
, ansi = require ('ansicolor').nice
;(async function test () {
let total = 0
let missing = 0
let implemented = 0
let emulated = 0
const exchanges = ccxt.exchanges
.map (id => new ccxt[id]())
.filter (exchange => exchange.has.ws)
log (
asTable (
exchanges
.map (exchange => {
let result = {};
[
'ws',
'watchOrderBook',
'watchTicker',
'watchTrades',
'watchOHLCV',
'watchBalance',
'watchOrders',
'watchMyTrades',
].forEach (key => {
total += 1
let capability = (key in exchange.has) ?
exchange.has[key].toString () :
'undefined'
if (!exchange.has[key]) {
capability = exchange.id.red.dim
missing += 1
} else if (exchange.has[key] === 'emulated') {
capability = exchange.id.yellow
emulated += 1
} else {
capability = exchange.id.green
implemented += 1
}
result[key] = capability
})
return result
})
)
)
log ('Summary:',
exchanges.length.toString ().green, 'exchanges,',
implemented.toString ().green, 'methods implemented,',
emulated.toString ().yellow, 'emulated,',
missing.toString ().red, 'missing,',
total.toString (), 'total')
}) ()
@@ -0,0 +1,46 @@
'use strict';
const ccxt = require ('../../../ccxt')
console.log ("CCXT Pro Version:", ccxt.version)
const orderbooks = {}
let run = true
async function watchOrderBook (exchange, symbol) {
while (run) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
orderbooks[symbol] = orderbook
console.log (exchange.iso8601 (exchange.milliseconds ()), orderbook['datetime'], orderbook['nonce'], symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
}
async function stop (exchange) {
await exchange.sleep (10000)
run = false
await exchange.close ()
}
async function main () {
const exchange = new ccxt.pro.binance ()
await exchange.loadMarkets ()
exchange.verbose = true
const symbols = [
'BTC/USDT',
'ETH/USDT',
]
stop (exchange).then (() => {})
await Promise.all (symbols.map (symbol => watchOrderBook (exchange, symbol)))
console.log ('Sleeping for a moment...')
await exchange.sleep (10000)
console.log ('Done')
}
main ()
@@ -0,0 +1,30 @@
'use strict';
const ccxt = require ('ccxt')
console.log ("CCXT Pro Version:", ccxt.version)
async function loop (exchange, method, symbol) {
while (true) {
try {
const orderbook = await exchange[method] (symbol)
console.log (exchange.iso8601 (exchange.milliseconds ()), orderbook['datetime'], orderbook['nonce'], symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
}
async function main () {
const exchange = new ccxt.pro.gateio ({
'options': {'defaultType':'swap'}
})
await exchange.loadMarkets ()
// exchange.verbose = true // uncomment for debugging purposes if necessary
const symbols = [
'ANC/USDT:USDT',
]
await Promise.all (symbols.map (symbol => loop (exchange, 'fetchOrderBook', symbol)))
}
main ()
@@ -0,0 +1,23 @@
const ccxt = require ('../../../ccxt')
console.log ('CCXT Pro version:', ccxt.version)
async function main () {
const exchange = new ccxt.pro.gateio ({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
})
await exchange.loadMarkets ()
exchange.verbose = true
while (true) {
try {
const response = await exchange.watchBalance ()
console.log (new Date (), response)
} catch (e) {
console.log (e.constructor.name, e.message)
await exchange.sleep (1000)
}
}
}
main ()
@@ -0,0 +1,71 @@
'use strict';
const ccxt = require ('ccxt')
console.log ("CCXT Pro Version:", ccxt.version)
const orderbooks = {}
async function watchAllSymbols (exchange, symbols) {
while (true) {
const keys = Object.keys (orderbooks);
if (symbols.length === keys.length) {
console.log ('\n\n\n\n\n')
console.log ('----------------------------------------------------')
console.log ('All orderbooks received at least one update:');
for (let i = 0; i < symbols.length; i++) {
const symbol = symbols[i]
const orderbook = orderbooks[symbol]
console.log (exchange.iso8601 (exchange.milliseconds ()), orderbook['datetime'], orderbook['nonce'], symbol, orderbook['asks'][0], orderbook['bids'][0])
}
console.log ('----------------------------------------------------')
console.log ('\n\n\n\n\n')
// process.exit () // stop here if you want
break
} else {
await exchange.sleep (1000);
}
}
}
async function watchOrderBook (exchange, symbol) {
while (true) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
orderbooks[symbol] = orderbook
console.log (exchange.iso8601 (exchange.milliseconds ()), orderbook['datetime'], orderbook['nonce'], symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
}
async function main () {
const exchange = new ccxt.pro.gateio ({
'options': {
'defaultType': 'swap',
},
})
await exchange.loadMarkets ()
// exchange.verbose = true // uncomment for debugging purposes if necessary
const symbols = [
// 'SOS/USDT:USDT',
// 'JASMY/USDT:USDT',
// 'SLP/USDT:USDT',
'ACH/USDT:USDT',
'MKISHU/USDT:USDT',
// 'GMT/USDT:USDT',
// 'ASTR/USDT:USDT',
'RAMP/USDT:USDT',
'RSR/USDT:USDT',
// 'RACA/USDT:USDT',
// 'ROOK/USDT:USDT',
// 'ROSE/USDT:USDT',
]
await Promise.all ([
watchAllSymbols (exchange, symbols),
... symbols.map (symbol => watchOrderBook (exchange, symbol))
])
}
main ()
@@ -0,0 +1,43 @@
'use strict';
const ccxt = require ('../../../ccxt');
let stop = false
async function shutdown (milliseconds) {
await ccxt.sleep (10000)
stop = true
}
async function watchOrderBook (exchangeId, symbol) {
const exchange = new ccxt.pro[exchangeId] ()
await exchange.loadMarkets ()
// exchange.verbose = true
while (!stop) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
console.log (new Date (), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (symbol, e)
stop = true
break
}
}
await exchange.close ()
}
async function main () {
const streams = {
'binance': 'BTC/USDT',
'ftx': 'BTC/USDT',
};
await Promise.all ([
shutdown (10000),
... Object.entries (streams).map (([ exchangeId, symbol ]) => watchOrderBook (exchangeId, symbol))
])
}
main()
@@ -0,0 +1,37 @@
'use strict';
const ccxt = require ('../../../ccxt');
(async () => {
const streams = {
'binance': 'BTC/USDT',
'bittrex': 'BTC/USDT',
'poloniex': 'BTC/USDT',
'bitfinex': 'BTC/USDT',
'hitbtc': 'BTC/USDT',
'upbit': 'BTC/USDT',
'coinbasepro': 'BTC/USD',
'ftx': 'BTC/USDT',
'okex': 'BTC/USDT',
'gateio': 'BTC/USDT',
};
await Promise.all (Object.keys (streams).map (exchangeId =>
(async () => {
const exchange = new ccxt.pro[exchangeId] ({ enableRateLimit: true })
const symbol = streams[exchangeId]
while (true) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
console.log (new Date (), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (symbol, e)
}
}
}) ())
)
}) ()
@@ -0,0 +1,48 @@
'use strict';
const ccxt = require ('ccxt')
, exchange = new ccxt.okex ({
apiKey: 'YOUR_API_KEY',
secret: 'YOUR_API_SECRET',
password: 'YOUR_API_PASSWORD',
enableRateLimit: true,
options: { defaultType: 'futures' },
})
, symbol = 'BTC/USDT:USDT-201225'
, amount = 1 // how may contracts
, price = undefined // or your limit price
, side = 'buy' // or 'sell'
, type = '1' // 1 open long, 2 open short, 3 close long, 4 close short for futures
, order_type = '4' // 0 = limit order, 4 = market order
console.log ('CCXT Pro Version: ', ccxt.version)
async function main () {
try {
await exchange.loadMarkets ()
// exchange.verbose = true // uncomment for debugging
// open long market price order
const order = await exchange.createOrder(symbol, 'market', side, amount, price, { type });
// --------------------------------------------------------------------
// open long market price order
// const order = await exchange.createOrder(symbol, type, side, amount, price, { order_type });
// --------------------------------------------------------------------
// close short market price order
// const order = await exchange.createOrder(symbol, 'market', side, amount, price, { type, order_type });
// --------------------------------------------------------------------
// close short market price order
// const order = await exchange.createOrder(symbol, '4', side, amount, price, { order_type });
// ...
console.log (order)
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
main ()
@@ -0,0 +1,54 @@
const ccxt = require ('ccxt')
console.log ('Node.js:', process.version)
console.log ('CCXT Pro v' + ccxt.version)
const exchange = new ccxt.pro.okex ({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_API_SECRET',
'password': 'YOUR_API_PASWORD'
})
async function watchBalance (code) {
while (true) {
const balance = await exchange.watchBalance ({
'code': code,
})
console.log ('New', code, 'balance is: ', balance[code])
}
}
async function createOrder (symbol, type, side, amount, price = undefined, params = {}) {
console.log ('Creating', symbol, type, 'order')
const order = await exchange.createOrder (symbol, type, side, amount, price, params);
console.log (symbol, type, side, 'order created')
console.log (order)
}
;(async () => {
await exchange.loadMarkets ()
console.log (exchange.id, 'markets loaded')
const symbol = 'ETH/USDT'
const market = exchange.market (symbol)
const quote = market['quote']
// run in parallel without await
console.log ('Watching', quote, 'balance')
watchBalance (quote)
// wait a bit to allow it to subscribe
await exchange.sleep (3000)
const ticker = await exchange.watchTicker (symbol)
const type = 'market'
const side = 'buy'
const amount = 0.1
const price = ticker['bid']
await createOrder (symbol, type, side, amount, price)
}) ()
@@ -0,0 +1,31 @@
import ccxt from '../../../js/ccxt.js';
async function main() {
const exchange = new ccxt.pro.okx()
await exchange.loadMarkets()
// exchange.verbose = true
while (true) {
try {
// don't do this, specify a list of symbols to watch for watchTickers
// or a very large subscription message will crash your WS connection
// const tickers = await exchange.watchTickers ()
// do this instead
const symbols = [
'ETH/BTC',
'BTC/USDT',
'ETH/USDT',
// ...
]
const tickers = await exchange.watchTickers (symbols)
symbols = Object.keys(tickers)
console.log (new Date(), 'received', symbols.length, 'symbols', ... symbols.slice(0,5).join(', '), '...')
} catch (e) {
console.log (new Date(), e.constructor.name, e.message)
break
}
}
}
main()
@@ -0,0 +1,46 @@
'use strict';
const ccxt = require ('ccxt')
console.log ('CCXT Version:', ccxt.version)
async function watchOrders(exchange) {
while (true) {
try {
const orders = await exchange.watchOrders() // await here
console.log(orders)
} catch (e) {
console.log(e)
}
}
}
async function watchBalance(exchange) {
while (true) {
try {
const balance = await exchange.watchBalance() // await here
console.log(balance)
} catch (e) {
console.log(e)
}
}
}
async function main() {
const exchange = new ccxt.pro.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_SECRET',
'password': 'IF NECESSARY',
// etc...
})
await exchange.loadMarkets () // await here
// exchange.verbose = true // uncomment for debugging purposes if necessary
watchOrders(exchange) // no await
watchBalance(exchange) // no await
await exchange.close()
}
main()
@@ -0,0 +1,26 @@
'use strict';
const ccxt = require ('ccxt');
(async () => {
const exchange = new ccxt.pro.binance ({ enableRateLimit: true })
const symbols = [ 'BTC/USDT', 'ETH/BTC', 'ETH/USDT' ]
const loop = async (symbol) => {
while (true) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
console.log (new Date (), symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (symbol, e)
// do nothing and retry on next loop iteration
// throw e // uncomment to break all loops in case of an error in any one of them
// break // you can also break just this one loop if it fails
}
}
}
await Promise.all (symbols.map (symbol => loop (symbol)))
}) ()
@@ -0,0 +1,28 @@
'use strict';
const ccxt = require ('ccxt');
(async () => {
const exchange = new ccxt.pro.binance ({ enableRateLimit: true })
const symbols = [ 'BTC/USDT', 'ETH/BTC', 'ETH/USDT' ]
await Promise.all (symbols.map (symbol =>
(async () => {
while (true) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
console.log (new Date (), symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (symbol, e)
// do nothing and retry on next loop iteration
// throw e // uncomment to break all loops in case of an error in any one of them
// break // you can also break just this one loop if it fails
}
}
}) ())
)
}) ()
@@ -0,0 +1,30 @@
'use strict';
const ccxt = require ('ccxt')
, SocksProxyAgent = require ('socks-proxy-agent')
, socks = 'socks://127.0.0.1:7000'
, socksAgent = new SocksProxyAgent (socks)
, exchange = new ccxt.binance ({
enableRatLimit: true,
httpsAgent: socksAgent, // ←--------------------- socksAgent here
options: {
'ws': {
'options': { agent: socksAgent }, // ←--- socksAgent here
},
},
})
;(async () => {
console.log (socks)
const symbol = 'BTC/USDT'
await exchange.loadMarkets ()
console.log ('Markets loaded')
while (true) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
console.log (exchange.iso8601 (exchange.milliseconds()), symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (e.constructor.name, e.message)
}
}
}) ()
@@ -0,0 +1,40 @@
'use strict';
const ccxt = require ('../../../ccxt');
async function watchOrderBook (exchange, symbol) {
while (true) {
try {
const method = exchange.has.watchOrderBook ? 'watchOrderBook' : 'fetchOrderBook'
const orderbook = await exchange[method](symbol)
console.log (new Date (), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (symbol, e)
process.exit ()
}
}
}
async function watchExchange (exchangeId, symbols) {
const exchange = new ccxt.pro[exchangeId] ()
await exchange.loadMarkets ()
await Promise.all (symbols.map (symbol => watchOrderBook (exchange, symbol)))
}
async function main () {
const streams = {
'ftx': [
'BTC/USDT',
'ETH/BTC',
],
'coinex': [
'BTC/USDT',
'ETH/BTC',
],
};
const entries = Object.entries (streams)
await Promise.all (entries.map (([ exchangeId, symbols ]) => watchExchange (exchangeId, symbols)))
}
main()
@@ -0,0 +1,38 @@
'use strict';
const ccxt = require ('../../../ccxt');
async function watchOrderBook (exchange, symbol) {
while (true) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
console.log (new Date (), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (symbol, e)
}
}
}
async function watchExchange (exchangeId, symbols) {
const exchange = new ccxt.pro[exchangeId] ()
await exchange.loadMarkets ()
await Promise.all (symbols.map (symbol => watchOrderBook (exchange, symbol)))
}
async function main () {
const streams = {
'binance': [
'BTC/USDT',
'ETH/BTC',
],
'ftx': [
'BTC/USDT',
'ETH/BTC',
],
};
const entries = Object.entries (streams)
await Promise.all (entries.map (([ exchangeId, symbols ]) => watchExchange (exchangeId, symbols)))
}
main()
@@ -0,0 +1,40 @@
'use strict';
const ccxt = require ('../../../ccxt');
console.log ('CCXT Version:', ccxt.version)
async function watchTickerLoop (exchange, symbol) {
// exchange.verbose = true // uncomment for debugging purposes if necessary
while (true) {
try {
const ticker = await exchange.watchTicker (symbol)
console.log (new Date (), exchange.id, symbol, ticker['last'])
} catch (e) {
console.log (symbol, e)
// do nothing and retry on next loop iteration
// throw e // uncomment to break all loops in case of an error in any one of them
// break // you can also break just this one loop if it fails
}
}
}
async function exchangeLoop (exchangeId, symbols) {
const exchange = new ccxt.pro[exchangeId]()
await exchange.loadMarkets ()
const loops = symbols.map (symbol => watchTickerLoop (exchange, symbol))
await Promise.all (loops)
await exchange.close ()
}
async function main () {
const exchanges = {
'binance': [ 'BTC/USDT', 'ETH/USDT' ],
'ftx': [ 'BTC/USD', 'ETH/USD' ],
}
const loops = Object.entries (exchanges).map (([ exchangeId, symbols ]) => exchangeLoop (exchangeId, symbols))
await Promise.all (loops)
}
main ()
@@ -0,0 +1,27 @@
'use strict';
const ccxt = require ('ccxt');
async function watchOrderBook (exchangeId, symbol) {
const exchange = new ccxt.pro[exchangeId] ()
while (true) {
try {
const orderbook = await exchange.watchOrderBook (symbol)
console.log (new Date (), exchange.id, symbol, orderbook['asks'][0], orderbook['bids'][0])
} catch (e) {
console.log (symbol, e)
}
}
}
async function main () {
const streams = {
'binance': 'BTC/USDT',
'ftx': 'BTC/USDT',
};
await Promise.all (Object.entries (streams).map (([ exchangeId, symbol ]) => watchOrderBook (exchangeId, symbol)))
}
main()
@@ -0,0 +1,43 @@
'use strict';
const ccxt = require ('../../../ccxt');
console.log ('CCXT Version:', ccxt.version);
async function watchExchange (exchangeId, symbol) {
const exchange = new ccxt.pro[exchangeId] ({
newUpdates: true,
})
await exchange.loadMarkets ();
// exchange.verbose = true // uncomment for debugging purposes if necessary
while (true) {
try {
const trades = await exchange.watchTrades (symbol)
for (let i = 0; i < trades.length; i++) {
const trade = trades[i]
console.log (exchange.iso8601 (exchange.milliseconds ()), exchange.id, trade['symbol'], trade['id'], trade['datetime'], trade['price'], trade['amount'])
}
} catch (e) {
console.log (symbol, e)
}
}
}
async function main () {
const streams = {
'binance': 'BTC/USDT',
'okex': 'BTC/USDT',
'kraken': 'BTC/USD',
};
const values = Object.entries (streams)
const promises = values.map (([ exchangeId, symbol ]) => watchExchange (exchangeId, symbol))
await Promise.all (promises)
}
main ()
@@ -0,0 +1,42 @@
'use strict';
const ccxt = require ('../../../ccxt');
(async () => {
const streams = {
'binance': 'BTC/USDT',
'okex': 'BTC/USDT'
};
await Promise.all (Object.keys (streams).map (exchangeId =>
(async () => {
const exchange = new ccxt.pro[exchangeId] ({
enableRateLimit: true,
options: {
tradesLimit: 100, // lower = better, 1000 by default
},
})
const symbol = streams[exchangeId]
let lastId = ''
while (true) {
console.log ('---')
try {
const trades = await exchange.watchTrades (symbol)
for (let i = 0; i < trades.length; i++) {
const trade = trades[i]
if (trade['id'] > lastId) {
console.log (exchange.iso8601 (exchange.milliseconds ()), exchange.id, trade['symbol'], trade['id'], trade['datetime'], trade['price'], trade['amount'])
lastId = trade['id']
}
}
} catch (e) {
console.log (symbol, e)
}
}
}) ())
)
}) ()
@@ -0,0 +1,29 @@
'use strict';
const ccxt = require ('ccxt');
console.log ('CCXT Version:', ccxt.version)
async function watchTrades (exchange, symbol) {
while (true) {
try {
const trades = await exchange.watchTrades (symbol)
console.log (new Date (), exchange.id, symbol, trades.length, 'trades')
} catch (e) {
console.log (symbol, e)
}
}
}
async function main () {
const symbols = [ 'USDT/THB', 'BTC/THB', 'ETH/THB' ]
const exchange = new ccxt.pro.zipmex({
'newUpdates': true
})
const markets = await exchange.loadMarkets ()
exchange.verbose = true
await Promise.all (symbols.map ((symbol) => watchTrades (exchange, symbol)))
}
main()
@@ -0,0 +1,29 @@
// see this issue for details
// https://github.com/ccxt/ccxt/issues/6659
const ccxt = require ('ccxt')
const exchange = new ccxt.pro.kraken ()
function yellow (s) {
return '\x1b[33m' + s + '\x1b[0m'
}
async function runWs () {
while (1) {
const book = await exchange.watchOrderBook ('ETH/BTC')
console.log (new Date (), 'WS ', book['datetime'], book['bids'][0][0], book['asks'][0][0])
}
}
async function runRest () {
while (1) {
const book = await exchange.fetchOrderBook ('ETH/BTC')
const timestamp = new Date (exchange.last_response_headers['Date']).getTime ()
const datetime = exchange.iso8601 (timestamp)
console.log (new Date (), 'REST', yellow (datetime), book['bids'][0][0], book['asks'][0][0])
}
}
runWs ()
runRest ()