kandi background
Explore Kits

ccxt | PHP cryptocurrency trading API with support | Cryptocurrency library

 by   ccxt JavaScript Version: Current License: MIT

 by   ccxt JavaScript Version: Current License: MIT

Download this library from

kandi X-RAY | ccxt Summary

ccxt is a JavaScript library typically used in Financial Services, Fintech, Blockchain, Cryptocurrency, Ethereum, Bitcoin applications. ccxt has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can install using 'npm i ccja' or download it from GitHub, npm.
A JavaScript / Python / PHP library for cryptocurrency trading and e-commerce with support for many bitcoin/ether/altcoin exchange markets and merchant APIs. The CCXT library is used to connect and trade with cryptocurrency exchanges and payment processing services worldwide. It provides quick access to market data for storage, analysis, visualization, indicator development, algorithmic trading, strategy backtesting, bot programming, and related software engineering. It is intended to be used by coders, developers, technically-skilled traders, data-scientists and financial analysts for building trading algorithms.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • ccxt has a medium active ecosystem.
  • It has 24082 star(s) with 5938 fork(s). There are 929 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 569 open issues and 6293 have been closed. On average issues are closed in 2 days. There are 186 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of ccxt is current.
ccxt Support
Best in #Cryptocurrency
Average in #Cryptocurrency
ccxt Support
Best in #Cryptocurrency
Average in #Cryptocurrency

quality kandi Quality

  • ccxt has 0 bugs and 0 code smells.
ccxt Quality
Best in #Cryptocurrency
Average in #Cryptocurrency
ccxt Quality
Best in #Cryptocurrency
Average in #Cryptocurrency

securitySecurity

  • ccxt has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • ccxt code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
ccxt Security
Best in #Cryptocurrency
Average in #Cryptocurrency
ccxt Security
Best in #Cryptocurrency
Average in #Cryptocurrency

license License

  • ccxt is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
ccxt License
Best in #Cryptocurrency
Average in #Cryptocurrency
ccxt License
Best in #Cryptocurrency
Average in #Cryptocurrency

buildReuse

  • ccxt releases are not available. You will need to build from source code and install.
  • Deployable package is available in npm.
  • Installation instructions, examples and code snippets are available.
  • ccxt saves you 706702 person hours of effort in developing the same functionality from scratch.
  • It has 346352 lines of code, 13979 functions and 1152 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
ccxt Reuse
Best in #Cryptocurrency
Average in #Cryptocurrency
ccxt Reuse
Best in #Cryptocurrency
Average in #Cryptocurrency
Top functions reviewed by kandi - BETA

kandi has reviewed ccxt and discovered the below as its top functions. This is intended to give you an instant insight into ccxt implemented functionality, and help decide if they suit your requirements.

  • Inf - inflate an output buffer .
  • lint - disable - next - line
  • Deflated state .
  • Fetch remote resource
  • Flattens a block of text into a string .
  • Fills into the window with a random token .
  • Translate a string into an earlier block
  • Recursively format a value into a string .
  • Encode a string into an array of characters
  • Determines the longest pattern of a string .

ccxt Key Features

support for many cryptocurrency exchanges — more coming soon

fully implemented public and private APIs

optional normalized data for cross-exchange analytics and arbitrage

an out of the box unified API that is extremely easy to integrate

works in Node 10.4+, Python 3, PHP 5.4+, and web browsers

Install

copy iconCopydownload iconDownload
git clone https://github.com/ccxt/ccxt.git  # including 1GB of commit history

# or

git clone https://github.com/ccxt/ccxt.git --depth 1  # avoid downloading 1GB of commit history

JavaScript (NPM)

copy iconCopydownload iconDownload
npm install ccxt

JavaScript (for use with the

copy iconCopydownload iconDownload
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/ccxt@1.74.56/dist/ccxt.browser.js"></script>

Python

copy iconCopydownload iconDownload
pip install ccxt

PHP

copy iconCopydownload iconDownload
include "ccxt.php";
var_dump (\ccxt\Exchange::$exchanges); // print a list of all available exchange classes

Docker

copy iconCopydownload iconDownload
docker-compose run --rm ccxt

Intro

copy iconCopydownload iconDownload
// both of these notations work in JavaScript/Python/PHP
exchange.methodName ()  // camelcase pseudocode
exchange.method_name () // underscore pseudocode

JavaScript

copy iconCopydownload iconDownload
'use strict';
const ccxt = require ('ccxt');

(async function () {
    let kraken    = new ccxt.kraken ()
    let bitfinex  = new ccxt.bitfinex ({ verbose: true })
    let huobipro  = new ccxt.huobipro ()
    let okcoinusd = new ccxt.okcoin ({
        apiKey: 'YOUR_PUBLIC_API_KEY',
        secret: 'YOUR_SECRET_PRIVATE_KEY',
    })

    const exchangeId = 'binance'
        , exchangeClass = ccxt[exchangeId]
        , exchange = new exchangeClass ({
            'apiKey': 'YOUR_API_KEY',
            'secret': 'YOUR_SECRET',
        })

    console.log (kraken.id,    await kraken.loadMarkets ())
    console.log (bitfinex.id,  await bitfinex.loadMarkets  ())
    console.log (huobipro.id,  await huobipro.loadMarkets ())

    console.log (kraken.id,    await kraken.fetchOrderBook (kraken.symbols[0]))
    console.log (bitfinex.id,  await bitfinex.fetchTicker ('BTC/USD'))
    console.log (huobipro.id,  await huobipro.fetchTrades ('ETH/USDT'))

    console.log (okcoinusd.id, await okcoinusd.fetchBalance ())

    // sell 1 BTC/USD for market price, sell a bitcoin for dollars immediately
    console.log (okcoinusd.id, await okcoinusd.createMarketSellOrder ('BTC/USD', 1))

    // buy 1 BTC/USD for $2500, you pay $2500 and receive ฿1 when the order is closed
    console.log (okcoinusd.id, await okcoinusd.createLimitBuyOrder ('BTC/USD', 1, 2500.00))

    // pass/redefine custom exchange-specific order params: type, amount, price or whatever
    // use a custom order type
    bitfinex.createLimitSellOrder ('BTC/USD', 1, 10, { 'type': 'trailing-stop' })

}) ();

Python

copy iconCopydownload iconDownload
# coding=utf-8

import ccxt

hitbtc   = ccxt.hitbtc({'verbose': True})
bitmex   = ccxt.bitmex()
huobipro = ccxt.huobipro()
exmo     = ccxt.exmo({
    'apiKey': 'YOUR_PUBLIC_API_KEY',
    'secret': 'YOUR_SECRET_PRIVATE_KEY',
})
kraken = ccxt.kraken({
    'apiKey': 'YOUR_PUBLIC_API_KEY',
    'secret': 'YOUR_SECRET_PRIVATE_KEY',
})

exchange_id = 'binance'
exchange_class = getattr(ccxt, exchange_id)
exchange = exchange_class({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET',
})

hitbtc_markets = hitbtc.load_markets()

print(hitbtc.id, hitbtc_markets)
print(bitmex.id, bitmex.load_markets())
print(huobipro.id, huobipro.load_markets())

print(hitbtc.fetch_order_book(hitbtc.symbols[0]))
print(bitmex.fetch_ticker('BTC/USD'))
print(huobipro.fetch_trades('LTC/USDT'))

print(exmo.fetch_balance())

# sell one ฿ for market price and receive $ right now
print(exmo.id, exmo.create_market_sell_order('BTC/USD', 1))

# limit buy BTC/EUR, you pay €2500 and receive ฿1  when the order is closed
print(exmo.id, exmo.create_limit_buy_order('BTC/EUR', 1, 2500.00))

# pass/redefine custom exchange-specific order params: type, amount, price, flags, etc...
kraken.create_market_buy_order('BTC/USD', 1, {'trading_agreement': 'agree'})

PHP

copy iconCopydownload iconDownload
include 'ccxt.php';

$poloniex = new \ccxt\poloniex ();
$bittrex  = new \ccxt\bittrex  (array ('verbose' => true));
$quoinex  = new \ccxt\quoinex   ();
$zaif     = new \ccxt\zaif     (array (
    'apiKey' => 'YOUR_PUBLIC_API_KEY',
    'secret' => 'YOUR_SECRET_PRIVATE_KEY',
));
$hitbtc   = new \ccxt\hitbtc   (array (
    'apiKey' => 'YOUR_PUBLIC_API_KEY',
    'secret' => 'YOUR_SECRET_PRIVATE_KEY',
));

$exchange_id = 'binance';
$exchange_class = "\\ccxt\\$exchange_id";
$exchange = new $exchange_class (array (
    'apiKey' => 'YOUR_API_KEY',
    'secret' => 'YOUR_SECRET',
));

$poloniex_markets = $poloniex->load_markets ();

var_dump ($poloniex_markets);
var_dump ($bittrex->load_markets ());
var_dump ($quoinex->load_markets ());

var_dump ($poloniex->fetch_order_book ($poloniex->symbols[0]));
var_dump ($bittrex->fetch_trades ('BTC/USD'));
var_dump ($quoinex->fetch_ticker ('ETH/EUR'));
var_dump ($zaif->fetch_ticker ('BTC/JPY'));

var_dump ($zaif->fetch_balance ());

// sell 1 BTC/JPY for market price, you pay ¥ and receive ฿ immediately
var_dump ($zaif->id, $zaif->create_market_sell_order ('BTC/JPY', 1));

// buy BTC/JPY, you receive ฿1 for ¥285000 when the order closes
var_dump ($zaif->id, $zaif->create_limit_buy_order ('BTC/JPY', 1, 285000));

// set a custom user-defined id to your order
$hitbtc->create_order ('BTC/USD', 'limit', 'buy', 1, 3000, array ('clientOrderId' => '123'));

fetch_balance method in ccxt won't return all assets

copy iconCopydownload iconDownload
import ccxt

exchange = ccxt.kucoinfutures( ... )
exchange.load_markets()

currency = exchange.currency('USDT')
balance = exchange.fetch_balance({'currency': currency['id']})
print(balance)

Installing private GitHub npm package in Firebase Cloud Functions

copy iconCopydownload iconDownload
"dependencies": {
    "@calugarul/ccxt.pro": "git+https://<GITHUB_PERSONAL_ACCESS_TOKEN>@github.com/kroitor/ccxt.pro.git",
    "dotenv": "^10.0.0",
    "firebase-admin": "^9.8.0",
    "firebase-functions": "^3.16.0",
    "moment": "^2.29.1"
  },

Sticky Header using shell less command

copy iconCopydownload iconDownload
--header
   Sets  the  number  of  header lines and columns displayed on the
   screen.  The value may be of the form "N,M" where N  and  M  are
   integers, to set the header lines to N and the header columns to
   M, or it may be a single integer "N" which sets the header lines
   to  N  and  the  header columns to zero.  When N is nonzero, the
   first N lines at the top of the screen  are  replaced  with  the
   first  N  lines of the file, regardless of what part of the file
   are being viewed.  When M is nonzero, the  characters  displayed
   at  the  beginning  of  each  line are replaced with the first M
   characters of the line, even if the rest of the line is scrolled
   horizontally.   If  either N or M is zero, less stops displaying
   header lines or columns, respectively.  (Note  that  it  may  be
   necessary  to change the setting of the -j option to ensure that
   the target line is not obscured by the header line(s).)

Can the amount be in USDT on Binanace Api Future Trade?

copy iconCopydownload iconDownload
usdt_amount = 10
market['contractSize'] * price * usdt_amount
with open("D:/api.txt") as f:
    lines = f.readlines()
    api_key = lines[0].strip()
    secret  = lines[1].strip()

binance = ccxt.binance({
    'apiKey' : api_key,
    'secret' :  secret,
    'enableRateLimit': True,
    'options': {
        'defaultType': 'future'
    }
})
tickers = binance.fetch_tickers()

price = 19.5
symbol = 'ENS/USDT'
market = binance.market(symbol)
usdt_amount = 10

order = binance.create_limit_buy_order(
    symbol = symbol,
    amount = market['contractSize'] * price * usdt_amount,
    price = price,
)
-----------------------
usdt_amount = 10
market['contractSize'] * price * usdt_amount
with open("D:/api.txt") as f:
    lines = f.readlines()
    api_key = lines[0].strip()
    secret  = lines[1].strip()

binance = ccxt.binance({
    'apiKey' : api_key,
    'secret' :  secret,
    'enableRateLimit': True,
    'options': {
        'defaultType': 'future'
    }
})
tickers = binance.fetch_tickers()

price = 19.5
symbol = 'ENS/USDT'
market = binance.market(symbol)
usdt_amount = 10

order = binance.create_limit_buy_order(
    symbol = symbol,
    amount = market['contractSize'] * price * usdt_amount,
    price = price,
)

Nestjs - What is the right approach to have custom classes using 3rd party libraries available

copy iconCopydownload iconDownload
import { DynamicModule, Module, Provider } from '@nestjs/common';
import { CryptoManagerService } from './crypto-manager.service';
import * as ccxt from 'ccxt';

// Add any config options you need, like API keys, etc
export interface CryptoManagerModuleOptions {
  global?: boolean;
}

export const KRAKEN_CLIENT_TOKEN = 'KRAKEN_CLIENT_TOKEN';

export class CryptoManagerModule {
  static forRoot(options: CryptoManagerModuleOptions): DynamicModule {
    // An example of injecting a single class of ccxt.  Note this is only available
    // within this module.
    const krakenProvider: Provider = {
      provide: KRAKEN_CLIENT_TOKEN,
      useValue: new ccxt.kraken(),
    };

    return {
      module: CryptoManagerModule,
      providers: [krakenProvider, CryptoManagerService],
      // Exports can be @Inject()'ed to other files, and if global
      // is set, then forRoot only needs to be called in the AppModule
      exports: [CryptoManagerService],
      global: options.global,
    };
  }
}

import { Inject, Injectable } from '@nestjs/common';
import { KRAKEN_CLIENT_TOKEN } from './crypto-manager.module';
import { kraken } from 'ccxt';

@Injectable()
export class CryptoManagerService {
  constructor(@Inject(KRAKEN_CLIENT_TOKEN) private kraken: kraken) {}

  loadKrakenMarkets() {
    return this.kraken.loadMarkets();
  }
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CryptoManagerModule } from './crypto-manager/crypto-manager.module';

@Module({
  controllers: [AppController],
  providers: [AppService],
  // Make sure to call forRoot
  imports: [CryptoManagerModule.forRoot({ global: true })],
})
export class AppModule {}

import { Inject, Injectable } from '@nestjs/common';
import { CryptoManagerService } from './crypto-manager/crypto-manager.service';

@Injectable()
export class AppService {
  constructor(private cryptoManagerService: CryptoManagerService) {}

  getHello(): string {
    this.cryptoManagerService.loadKrakenMarkets().then(console.log);
    return 'Hello World!';
  }
}
-----------------------
import { DynamicModule, Module, Provider } from '@nestjs/common';
import { CryptoManagerService } from './crypto-manager.service';
import * as ccxt from 'ccxt';

// Add any config options you need, like API keys, etc
export interface CryptoManagerModuleOptions {
  global?: boolean;
}

export const KRAKEN_CLIENT_TOKEN = 'KRAKEN_CLIENT_TOKEN';

export class CryptoManagerModule {
  static forRoot(options: CryptoManagerModuleOptions): DynamicModule {
    // An example of injecting a single class of ccxt.  Note this is only available
    // within this module.
    const krakenProvider: Provider = {
      provide: KRAKEN_CLIENT_TOKEN,
      useValue: new ccxt.kraken(),
    };

    return {
      module: CryptoManagerModule,
      providers: [krakenProvider, CryptoManagerService],
      // Exports can be @Inject()'ed to other files, and if global
      // is set, then forRoot only needs to be called in the AppModule
      exports: [CryptoManagerService],
      global: options.global,
    };
  }
}

import { Inject, Injectable } from '@nestjs/common';
import { KRAKEN_CLIENT_TOKEN } from './crypto-manager.module';
import { kraken } from 'ccxt';

@Injectable()
export class CryptoManagerService {
  constructor(@Inject(KRAKEN_CLIENT_TOKEN) private kraken: kraken) {}

  loadKrakenMarkets() {
    return this.kraken.loadMarkets();
  }
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CryptoManagerModule } from './crypto-manager/crypto-manager.module';

@Module({
  controllers: [AppController],
  providers: [AppService],
  // Make sure to call forRoot
  imports: [CryptoManagerModule.forRoot({ global: true })],
})
export class AppModule {}

import { Inject, Injectable } from '@nestjs/common';
import { CryptoManagerService } from './crypto-manager/crypto-manager.service';

@Injectable()
export class AppService {
  constructor(private cryptoManagerService: CryptoManagerService) {}

  getHello(): string {
    this.cryptoManagerService.loadKrakenMarkets().then(console.log);
    return 'Hello World!';
  }
}
-----------------------
import { DynamicModule, Module, Provider } from '@nestjs/common';
import { CryptoManagerService } from './crypto-manager.service';
import * as ccxt from 'ccxt';

// Add any config options you need, like API keys, etc
export interface CryptoManagerModuleOptions {
  global?: boolean;
}

export const KRAKEN_CLIENT_TOKEN = 'KRAKEN_CLIENT_TOKEN';

export class CryptoManagerModule {
  static forRoot(options: CryptoManagerModuleOptions): DynamicModule {
    // An example of injecting a single class of ccxt.  Note this is only available
    // within this module.
    const krakenProvider: Provider = {
      provide: KRAKEN_CLIENT_TOKEN,
      useValue: new ccxt.kraken(),
    };

    return {
      module: CryptoManagerModule,
      providers: [krakenProvider, CryptoManagerService],
      // Exports can be @Inject()'ed to other files, and if global
      // is set, then forRoot only needs to be called in the AppModule
      exports: [CryptoManagerService],
      global: options.global,
    };
  }
}

import { Inject, Injectable } from '@nestjs/common';
import { KRAKEN_CLIENT_TOKEN } from './crypto-manager.module';
import { kraken } from 'ccxt';

@Injectable()
export class CryptoManagerService {
  constructor(@Inject(KRAKEN_CLIENT_TOKEN) private kraken: kraken) {}

  loadKrakenMarkets() {
    return this.kraken.loadMarkets();
  }
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CryptoManagerModule } from './crypto-manager/crypto-manager.module';

@Module({
  controllers: [AppController],
  providers: [AppService],
  // Make sure to call forRoot
  imports: [CryptoManagerModule.forRoot({ global: true })],
})
export class AppModule {}

import { Inject, Injectable } from '@nestjs/common';
import { CryptoManagerService } from './crypto-manager/crypto-manager.service';

@Injectable()
export class AppService {
  constructor(private cryptoManagerService: CryptoManagerService) {}

  getHello(): string {
    this.cryptoManagerService.loadKrakenMarkets().then(console.log);
    return 'Hello World!';
  }
}
-----------------------
import { DynamicModule, Module, Provider } from '@nestjs/common';
import { CryptoManagerService } from './crypto-manager.service';
import * as ccxt from 'ccxt';

// Add any config options you need, like API keys, etc
export interface CryptoManagerModuleOptions {
  global?: boolean;
}

export const KRAKEN_CLIENT_TOKEN = 'KRAKEN_CLIENT_TOKEN';

export class CryptoManagerModule {
  static forRoot(options: CryptoManagerModuleOptions): DynamicModule {
    // An example of injecting a single class of ccxt.  Note this is only available
    // within this module.
    const krakenProvider: Provider = {
      provide: KRAKEN_CLIENT_TOKEN,
      useValue: new ccxt.kraken(),
    };

    return {
      module: CryptoManagerModule,
      providers: [krakenProvider, CryptoManagerService],
      // Exports can be @Inject()'ed to other files, and if global
      // is set, then forRoot only needs to be called in the AppModule
      exports: [CryptoManagerService],
      global: options.global,
    };
  }
}

import { Inject, Injectable } from '@nestjs/common';
import { KRAKEN_CLIENT_TOKEN } from './crypto-manager.module';
import { kraken } from 'ccxt';

@Injectable()
export class CryptoManagerService {
  constructor(@Inject(KRAKEN_CLIENT_TOKEN) private kraken: kraken) {}

  loadKrakenMarkets() {
    return this.kraken.loadMarkets();
  }
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CryptoManagerModule } from './crypto-manager/crypto-manager.module';

@Module({
  controllers: [AppController],
  providers: [AppService],
  // Make sure to call forRoot
  imports: [CryptoManagerModule.forRoot({ global: true })],
})
export class AppModule {}

import { Inject, Injectable } from '@nestjs/common';
import { CryptoManagerService } from './crypto-manager/crypto-manager.service';

@Injectable()
export class AppService {
  constructor(private cryptoManagerService: CryptoManagerService) {}

  getHello(): string {
    this.cryptoManagerService.loadKrakenMarkets().then(console.log);
    return 'Hello World!';
  }
}
-----------------------
import { CcxtModule } from 'nestjs-ccxt';

@Module({
  imports: [CcxtModule.forRoot({ ... })],
})
export class AppModule {}
@Injectable()
export class ExchangeService {
  constructor(private ccxtService: CcxtService) {}

  async getBtcUsdtTicker() {
    const client = await this.ccxtService.getClient('binance');
    const ticker = await client.fetchTicker('BTC/USDT');
    return ticker;
  }
}
-----------------------
import { CcxtModule } from 'nestjs-ccxt';

@Module({
  imports: [CcxtModule.forRoot({ ... })],
})
export class AppModule {}
@Injectable()
export class ExchangeService {
  constructor(private ccxtService: CcxtService) {}

  async getBtcUsdtTicker() {
    const client = await this.ccxtService.getClient('binance');
    const ticker = await client.fetchTicker('BTC/USDT');
    return ticker;
  }
}

How to set time zone for historical price quotes retrieved using ccxt?

copy iconCopydownload iconDownload
>>> exchange.parse8601('2017-08-17T00:00:00+08:00')
1502899200000
>>> exchange.parse8601('2017-08-17T00:00:00Z')
1502928000000
scrape_candles_to_csv('binance.csv', 'binance', 3, 'BTC/USDT', '1h', '2021-12-17T00:00:00+08:00', 100)
100 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-20T19:00:00.000Z
200 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-24T23:00:00.000Z
260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
Saved 260 candles from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z to binance.csv
1639670400000,48578.61,48717.43,48302.49,48506.58,1778.62433
1639674000000,48506.57,48520.73,48060.0,48084.14,1593.51908
1639677600000,48084.15,48313.29,47862.6,47983.5,1434.94112
1639681200000,47983.49,48129.67,47666.0,47866.01,1763.75104
1639684800000,47866.01,48387.54,47832.34,47929.53,1510.25811
1639688400000,47929.53,48167.75,47900.0,48089.61,766.62189
1639692000000,48089.61,48167.84,47511.0,47821.27,1428.35052
1639695600000,47821.27,47821.27,47532.86,47632.38,1046.44879
...
-----------------------
>>> exchange.parse8601('2017-08-17T00:00:00+08:00')
1502899200000
>>> exchange.parse8601('2017-08-17T00:00:00Z')
1502928000000
scrape_candles_to_csv('binance.csv', 'binance', 3, 'BTC/USDT', '1h', '2021-12-17T00:00:00+08:00', 100)
100 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-20T19:00:00.000Z
200 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-24T23:00:00.000Z
260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
Saved 260 candles from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z to binance.csv
1639670400000,48578.61,48717.43,48302.49,48506.58,1778.62433
1639674000000,48506.57,48520.73,48060.0,48084.14,1593.51908
1639677600000,48084.15,48313.29,47862.6,47983.5,1434.94112
1639681200000,47983.49,48129.67,47666.0,47866.01,1763.75104
1639684800000,47866.01,48387.54,47832.34,47929.53,1510.25811
1639688400000,47929.53,48167.75,47900.0,48089.61,766.62189
1639692000000,48089.61,48167.84,47511.0,47821.27,1428.35052
1639695600000,47821.27,47821.27,47532.86,47632.38,1046.44879
...
-----------------------
>>> exchange.parse8601('2017-08-17T00:00:00+08:00')
1502899200000
>>> exchange.parse8601('2017-08-17T00:00:00Z')
1502928000000
scrape_candles_to_csv('binance.csv', 'binance', 3, 'BTC/USDT', '1h', '2021-12-17T00:00:00+08:00', 100)
100 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-20T19:00:00.000Z
200 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-24T23:00:00.000Z
260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
Saved 260 candles from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z to binance.csv
1639670400000,48578.61,48717.43,48302.49,48506.58,1778.62433
1639674000000,48506.57,48520.73,48060.0,48084.14,1593.51908
1639677600000,48084.15,48313.29,47862.6,47983.5,1434.94112
1639681200000,47983.49,48129.67,47666.0,47866.01,1763.75104
1639684800000,47866.01,48387.54,47832.34,47929.53,1510.25811
1639688400000,47929.53,48167.75,47900.0,48089.61,766.62189
1639692000000,48089.61,48167.84,47511.0,47821.27,1428.35052
1639695600000,47821.27,47821.27,47532.86,47632.38,1046.44879
...
-----------------------
>>> exchange.parse8601('2017-08-17T00:00:00+08:00')
1502899200000
>>> exchange.parse8601('2017-08-17T00:00:00Z')
1502928000000
scrape_candles_to_csv('binance.csv', 'binance', 3, 'BTC/USDT', '1h', '2021-12-17T00:00:00+08:00', 100)
100 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-20T19:00:00.000Z
200 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-24T23:00:00.000Z
260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
260 candles in total from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z
Saved 260 candles from 2021-12-16T16:00:00.000Z to 2021-12-27T11:00:00.000Z to binance.csv
1639670400000,48578.61,48717.43,48302.49,48506.58,1778.62433
1639674000000,48506.57,48520.73,48060.0,48084.14,1593.51908
1639677600000,48084.15,48313.29,47862.6,47983.5,1434.94112
1639681200000,47983.49,48129.67,47666.0,47866.01,1763.75104
1639684800000,47866.01,48387.54,47832.34,47929.53,1510.25811
1639688400000,47929.53,48167.75,47900.0,48089.61,766.62189
1639692000000,48089.61,48167.84,47511.0,47821.27,1428.35052
1639695600000,47821.27,47821.27,47532.86,47632.38,1046.44879
...

Python: how to get the price of a crypto at a given time in the past

copy iconCopydownload iconDownload
timestamp = int(datetime.datetime.strptime("2018-01-24 11:20:00", "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
import ccxt
from pprint import pprint

print('CCXT Version:', ccxt.__version__)

exchange = ccxt.binance({
    'enableRateLimit': True,
    "apiKey": '...',
    "secret": '...',
})
timestamp = int(datetime.datetime.strptime("2018-01-24 11:20:00", "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
response = exchange.fetch_ohlcv('BTC/USDT', '1m', timestamp, 1)
pprint(response)
[ 
  1516792860000, // timestamp
  11110, // value at beginning of minute, so the value at exactly "2018-01-24 11:20:01"
  11110.29, // highest value between "2018-01-24 11:20:01" and "2018-01-24 11:20:02"
  11050.91, // lowest value between "2018-01-24 11:20:01" and "2018-01-24 11:20:02"
  11052.27, // value just before "2018-01-24 11:20:02"
  39.882601 // The volume traded during this minute
]
-----------------------
timestamp = int(datetime.datetime.strptime("2018-01-24 11:20:00", "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
import ccxt
from pprint import pprint

print('CCXT Version:', ccxt.__version__)

exchange = ccxt.binance({
    'enableRateLimit': True,
    "apiKey": '...',
    "secret": '...',
})
timestamp = int(datetime.datetime.strptime("2018-01-24 11:20:00", "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
response = exchange.fetch_ohlcv('BTC/USDT', '1m', timestamp, 1)
pprint(response)
[ 
  1516792860000, // timestamp
  11110, // value at beginning of minute, so the value at exactly "2018-01-24 11:20:01"
  11110.29, // highest value between "2018-01-24 11:20:01" and "2018-01-24 11:20:02"
  11050.91, // lowest value between "2018-01-24 11:20:01" and "2018-01-24 11:20:02"
  11052.27, // value just before "2018-01-24 11:20:02"
  39.882601 // The volume traded during this minute
]
-----------------------
timestamp = int(datetime.datetime.strptime("2018-01-24 11:20:00", "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
import ccxt
from pprint import pprint

print('CCXT Version:', ccxt.__version__)

exchange = ccxt.binance({
    'enableRateLimit': True,
    "apiKey": '...',
    "secret": '...',
})
timestamp = int(datetime.datetime.strptime("2018-01-24 11:20:00", "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
response = exchange.fetch_ohlcv('BTC/USDT', '1m', timestamp, 1)
pprint(response)
[ 
  1516792860000, // timestamp
  11110, // value at beginning of minute, so the value at exactly "2018-01-24 11:20:01"
  11110.29, // highest value between "2018-01-24 11:20:01" and "2018-01-24 11:20:02"
  11050.91, // lowest value between "2018-01-24 11:20:01" and "2018-01-24 11:20:02"
  11052.27, // value just before "2018-01-24 11:20:02"
  39.882601 // The volume traded during this minute
]

CCXT ByBit Close Position

copy iconCopydownload iconDownload
symbol = 'SOLUSDT'
trade_res = exchange.create_order(symbol, amount=1, type='Market', side='sell', params={'reduce_only': true})

Unable to plot multiple lines in a single graph

copy iconCopydownload iconDownload
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
fig, ax = plt.subplots()
ax.plot(df_binance['ts'], df_binance['v'], label='Binance')
ax.plot(df_ftx['ts'], df_ftx['v'], label='FTX')

ax.legend()
ax.set_yscale('log')  # resolve issues of scale with the y-axis values
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='c', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='c', label='FTX', ax=ax, alpha=0.5)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
>>> df_binance.c.sub(df_ftx.c)

0      1.00
1     -2.13
2      0.07
3     -2.44
4     -0.35
5      1.35
6     11.51
7     -6.17
8    -11.91
9     -2.86
10   -13.98
11    -7.40
12    -3.13
13     1.56
14   -15.52
15    -8.63
16     0.83
17    10.44
18     0.82
19    -0.95
20   -12.82
21    -2.54
22   -15.13
23   -14.46
24    -4.63
25   -12.60
26   -10.01
27   -17.00
28    -4.00
29   -16.00
30    -9.49
31    -5.18
32    -3.71
33    23.95
34    -4.71
35    -2.38
36   -11.53
37    -7.13
38   -10.78
39     1.85
40     0.01
41    -9.68
42     7.87
43     9.90
44    -4.65
45     2.83
46     5.91
47    -3.11
48   -14.48
49   -11.36
50    -0.86
51     2.64
52   -22.12
53    -8.10
54    -6.27
55    -3.69
56    -0.86
57     1.91
58     5.69
59     1.24
60    -1.27
61   -12.48
62    -1.59
63    -8.18
64     5.98
65    -6.26
66    -4.25
67    -2.38
68    11.38
69    -9.39
70    -4.74
71    -0.43
72    -9.36
73    -3.10
74    -0.65
75     1.54
76    -2.72
77    -1.90
78    -0.39
79    -9.10
80    -4.99
81    -6.06
82     6.99
83     0.00
84    -8.78
85     2.43
86    -2.28
87   -10.00
88    -9.65
89    -5.07
90    -1.00
91    -0.06
92   -28.58
93    -8.43
94    -8.67
95   -17.16
96    -3.41
97   -12.59
98    -1.85
99     5.99
Name: c, dtype: float64
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_binance.ts = pd.to_datetime(df_binance.ts, unit='ms')  # convert column to a datetime dtype

df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx.ts = pd.to_datetime(df_ftx.ts, unit='ms')  # convert column to a datetime dtype

# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6))
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax, secondary_y=True)

ax.legend(loc='upper left')
p2.legend(loc='upper right')
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
-----------------------
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
fig, ax = plt.subplots()
ax.plot(df_binance['ts'], df_binance['v'], label='Binance')
ax.plot(df_ftx['ts'], df_ftx['v'], label='FTX')

ax.legend()
ax.set_yscale('log')  # resolve issues of scale with the y-axis values
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='c', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='c', label='FTX', ax=ax, alpha=0.5)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
>>> df_binance.c.sub(df_ftx.c)

0      1.00
1     -2.13
2      0.07
3     -2.44
4     -0.35
5      1.35
6     11.51
7     -6.17
8    -11.91
9     -2.86
10   -13.98
11    -7.40
12    -3.13
13     1.56
14   -15.52
15    -8.63
16     0.83
17    10.44
18     0.82
19    -0.95
20   -12.82
21    -2.54
22   -15.13
23   -14.46
24    -4.63
25   -12.60
26   -10.01
27   -17.00
28    -4.00
29   -16.00
30    -9.49
31    -5.18
32    -3.71
33    23.95
34    -4.71
35    -2.38
36   -11.53
37    -7.13
38   -10.78
39     1.85
40     0.01
41    -9.68
42     7.87
43     9.90
44    -4.65
45     2.83
46     5.91
47    -3.11
48   -14.48
49   -11.36
50    -0.86
51     2.64
52   -22.12
53    -8.10
54    -6.27
55    -3.69
56    -0.86
57     1.91
58     5.69
59     1.24
60    -1.27
61   -12.48
62    -1.59
63    -8.18
64     5.98
65    -6.26
66    -4.25
67    -2.38
68    11.38
69    -9.39
70    -4.74
71    -0.43
72    -9.36
73    -3.10
74    -0.65
75     1.54
76    -2.72
77    -1.90
78    -0.39
79    -9.10
80    -4.99
81    -6.06
82     6.99
83     0.00
84    -8.78
85     2.43
86    -2.28
87   -10.00
88    -9.65
89    -5.07
90    -1.00
91    -0.06
92   -28.58
93    -8.43
94    -8.67
95   -17.16
96    -3.41
97   -12.59
98    -1.85
99     5.99
Name: c, dtype: float64
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_binance.ts = pd.to_datetime(df_binance.ts, unit='ms')  # convert column to a datetime dtype

df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx.ts = pd.to_datetime(df_ftx.ts, unit='ms')  # convert column to a datetime dtype

# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6))
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax, secondary_y=True)

ax.legend(loc='upper left')
p2.legend(loc='upper right')
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
-----------------------
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
fig, ax = plt.subplots()
ax.plot(df_binance['ts'], df_binance['v'], label='Binance')
ax.plot(df_ftx['ts'], df_ftx['v'], label='FTX')

ax.legend()
ax.set_yscale('log')  # resolve issues of scale with the y-axis values
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='c', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='c', label='FTX', ax=ax, alpha=0.5)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
>>> df_binance.c.sub(df_ftx.c)

0      1.00
1     -2.13
2      0.07
3     -2.44
4     -0.35
5      1.35
6     11.51
7     -6.17
8    -11.91
9     -2.86
10   -13.98
11    -7.40
12    -3.13
13     1.56
14   -15.52
15    -8.63
16     0.83
17    10.44
18     0.82
19    -0.95
20   -12.82
21    -2.54
22   -15.13
23   -14.46
24    -4.63
25   -12.60
26   -10.01
27   -17.00
28    -4.00
29   -16.00
30    -9.49
31    -5.18
32    -3.71
33    23.95
34    -4.71
35    -2.38
36   -11.53
37    -7.13
38   -10.78
39     1.85
40     0.01
41    -9.68
42     7.87
43     9.90
44    -4.65
45     2.83
46     5.91
47    -3.11
48   -14.48
49   -11.36
50    -0.86
51     2.64
52   -22.12
53    -8.10
54    -6.27
55    -3.69
56    -0.86
57     1.91
58     5.69
59     1.24
60    -1.27
61   -12.48
62    -1.59
63    -8.18
64     5.98
65    -6.26
66    -4.25
67    -2.38
68    11.38
69    -9.39
70    -4.74
71    -0.43
72    -9.36
73    -3.10
74    -0.65
75     1.54
76    -2.72
77    -1.90
78    -0.39
79    -9.10
80    -4.99
81    -6.06
82     6.99
83     0.00
84    -8.78
85     2.43
86    -2.28
87   -10.00
88    -9.65
89    -5.07
90    -1.00
91    -0.06
92   -28.58
93    -8.43
94    -8.67
95   -17.16
96    -3.41
97   -12.59
98    -1.85
99     5.99
Name: c, dtype: float64
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_binance.ts = pd.to_datetime(df_binance.ts, unit='ms')  # convert column to a datetime dtype

df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx.ts = pd.to_datetime(df_ftx.ts, unit='ms')  # convert column to a datetime dtype

# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6))
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax, secondary_y=True)

ax.legend(loc='upper left')
p2.legend(loc='upper right')
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
-----------------------
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
fig, ax = plt.subplots()
ax.plot(df_binance['ts'], df_binance['v'], label='Binance')
ax.plot(df_ftx['ts'], df_ftx['v'], label='FTX')

ax.legend()
ax.set_yscale('log')  # resolve issues of scale with the y-axis values
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='c', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='c', label='FTX', ax=ax, alpha=0.5)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
>>> df_binance.c.sub(df_ftx.c)

0      1.00
1     -2.13
2      0.07
3     -2.44
4     -0.35
5      1.35
6     11.51
7     -6.17
8    -11.91
9     -2.86
10   -13.98
11    -7.40
12    -3.13
13     1.56
14   -15.52
15    -8.63
16     0.83
17    10.44
18     0.82
19    -0.95
20   -12.82
21    -2.54
22   -15.13
23   -14.46
24    -4.63
25   -12.60
26   -10.01
27   -17.00
28    -4.00
29   -16.00
30    -9.49
31    -5.18
32    -3.71
33    23.95
34    -4.71
35    -2.38
36   -11.53
37    -7.13
38   -10.78
39     1.85
40     0.01
41    -9.68
42     7.87
43     9.90
44    -4.65
45     2.83
46     5.91
47    -3.11
48   -14.48
49   -11.36
50    -0.86
51     2.64
52   -22.12
53    -8.10
54    -6.27
55    -3.69
56    -0.86
57     1.91
58     5.69
59     1.24
60    -1.27
61   -12.48
62    -1.59
63    -8.18
64     5.98
65    -6.26
66    -4.25
67    -2.38
68    11.38
69    -9.39
70    -4.74
71    -0.43
72    -9.36
73    -3.10
74    -0.65
75     1.54
76    -2.72
77    -1.90
78    -0.39
79    -9.10
80    -4.99
81    -6.06
82     6.99
83     0.00
84    -8.78
85     2.43
86    -2.28
87   -10.00
88    -9.65
89    -5.07
90    -1.00
91    -0.06
92   -28.58
93    -8.43
94    -8.67
95   -17.16
96    -3.41
97   -12.59
98    -1.85
99     5.99
Name: c, dtype: float64
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_binance.ts = pd.to_datetime(df_binance.ts, unit='ms')  # convert column to a datetime dtype

df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx.ts = pd.to_datetime(df_ftx.ts, unit='ms')  # convert column to a datetime dtype

# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6))
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax, secondary_y=True)

ax.legend(loc='upper left')
p2.legend(loc='upper right')
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
-----------------------
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
fig, ax = plt.subplots()
ax.plot(df_binance['ts'], df_binance['v'], label='Binance')
ax.plot(df_ftx['ts'], df_ftx['v'], label='FTX')

ax.legend()
ax.set_yscale('log')  # resolve issues of scale with the y-axis values
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='c', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='c', label='FTX', ax=ax, alpha=0.5)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()
>>> df_binance.c.sub(df_ftx.c)

0      1.00
1     -2.13
2      0.07
3     -2.44
4     -0.35
5      1.35
6     11.51
7     -6.17
8    -11.91
9     -2.86
10   -13.98
11    -7.40
12    -3.13
13     1.56
14   -15.52
15    -8.63
16     0.83
17    10.44
18     0.82
19    -0.95
20   -12.82
21    -2.54
22   -15.13
23   -14.46
24    -4.63
25   -12.60
26   -10.01
27   -17.00
28    -4.00
29   -16.00
30    -9.49
31    -5.18
32    -3.71
33    23.95
34    -4.71
35    -2.38
36   -11.53
37    -7.13
38   -10.78
39     1.85
40     0.01
41    -9.68
42     7.87
43     9.90
44    -4.65
45     2.83
46     5.91
47    -3.11
48   -14.48
49   -11.36
50    -0.86
51     2.64
52   -22.12
53    -8.10
54    -6.27
55    -3.69
56    -0.86
57     1.91
58     5.69
59     1.24
60    -1.27
61   -12.48
62    -1.59
63    -8.18
64     5.98
65    -6.26
66    -4.25
67    -2.38
68    11.38
69    -9.39
70    -4.74
71    -0.43
72    -9.36
73    -3.10
74    -0.65
75     1.54
76    -2.72
77    -1.90
78    -0.39
79    -9.10
80    -4.99
81    -6.06
82     6.99
83     0.00
84    -8.78
85     2.43
86    -2.28
87   -10.00
88    -9.65
89    -5.07
90    -1.00
91    -0.06
92   -28.58
93    -8.43
94    -8.67
95   -17.16
96    -3.41
97   -12.59
98    -1.85
99     5.99
Name: c, dtype: float64
df_binance = pd.DataFrame(binance_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_binance.ts = pd.to_datetime(df_binance.ts, unit='ms')  # convert column to a datetime dtype

df_ftx = pd.DataFrame(ftx_btc_usdt_ohlcv, columns=['ts', 'o', 'h', 'l', 'c', 'v'])
df_ftx.ts = pd.to_datetime(df_ftx.ts, unit='ms')  # convert column to a datetime dtype

# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6))
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax, secondary_y=True)

ax.legend(loc='upper left')
p2.legend(loc='upper right')
plt.show()
# plot dataframe
ax = df_binance.plot(x='ts', y='v', label='Binance', figsize=(8, 6), logy=True)
p2 = df_ftx.plot(x='ts', y='v', label='FTX', ax=ax)

ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()

Python TA library, ATR getting errors in dataframe series

copy iconCopydownload iconDownload

import ta
import pandas as pd

df = pd.DataFrame({
    'high': [10, 10, 10],
    'low': [8, 8, 8],
    'open': [9, 9, 9],
    'close': [9, 9, 9]
})

df['atr'] = ta.volatility.AverageTrueRange(
    df.high,
    df.low,
    df.close,
    window=2,
    fillna=False
).average_true_range() # <- call function


print(df)

Community Discussions

Trending Discussions on ccxt
  • fetch_balance method in ccxt won't return all assets
  • Installing private GitHub npm package in Firebase Cloud Functions
  • Sticky Header using shell less command
  • Can the amount be in USDT on Binanace Api Future Trade?
  • Nestjs - What is the right approach to have custom classes using 3rd party libraries available
  • How to set time zone for historical price quotes retrieved using ccxt?
  • Python: how to get the price of a crypto at a given time in the past
  • CCXT ByBit Close Position
  • python When use vpn, urllib3 connect raise a error “SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1129)”
  • Unable to plot multiple lines in a single graph
Trending Discussions on ccxt

QUESTION

fetch_balance method in ccxt won't return all assets

Asked 2022-Mar-16 at 09:57

As I call the fetch_balance method from kucoinfutures in ccxt, it only returns BTC, not any other assets. Shouldn't there be other assets like USDT or ETH too?

Here's the python code:

exchange = ccxt.kucoinfutures(
    {
        'apiKey': API_KEY,
        'secret': API_SECRET,
        'password': API_PHRASE
    }
)

exchange.verbose = True
balance = exchange.fetch_balance()
print(balance)

Here's what I get from print(balance):

{'info': {'code': '200000', 'data': {'accountEquity': 0, 'unrealisedPNL': 0, 'marginBalance': 0, 'positionMargin': 0, 'orderMargin': 0, 'frozenFunds': 0, 'availableBalance': 0, 'currency': 'XBT'}}, 'timestamp': None, 'datetime': None, 'BTC': {'free': 0.0, 'used': 0.0, 'total': 0.0}, 'free': {'BTC': 0.0}, 'used': {'BTC': 0.0}, 'total': {'BTC': 0.0}}

Am I missing something?

ANSWER

Answered 2022-Mar-16 at 09:57

It seems like fetchBalance only returns one currency at a time. To get USDT as the asset to be returned, you must pass the param currency via params currently using the exchange-specific currency id.

import ccxt

exchange = ccxt.kucoinfutures( ... )
exchange.load_markets()

currency = exchange.currency('USDT')
balance = exchange.fetch_balance({'currency': currency['id']})
print(balance)

Source https://stackoverflow.com/questions/71454993

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install ccxt

The easiest way to install the CCXT library is to use a package manager:.
ccxt in NPM (JavaScript / Node v7.6+)
ccxt in PyPI (Python 3.5.3+)
ccxt in Packagist/Composer (PHP 5.4+)
js/ in JavaScript
python/ in Python (generated from JS)
php/ in PHP (generated from JS)

Support

The CCXT library currently supports the following 113 cryptocurrency exchange markets and trading APIs:. The list above is updated frequently, new crypto markets, exchanges, bug fixes, and API endpoints are introduced on a regular basis. See the Manual for more details. If you can't find a cryptocurrency exchange in the list above and want it to be added, post a link to it by opening an issue here on GitHub or send us an email. The library is under MIT license, that means it's absolutely free for any developer to build commercial and opensource software on top of it, but use it at your own risk with no warranties, as is.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Consider Popular Cryptocurrency Libraries
Try Top Libraries by ccxt
Compare Cryptocurrency Libraries with Highest Support
Compare Cryptocurrency Libraries with Highest Quality
Compare Cryptocurrency Libraries with Highest Security
Compare Cryptocurrency Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.