def __init__(self, *args, **kwargs): self.api = ccxt.bybit() super().__init__(*args, **kwargs) symbol = {"symbol": self.market} self.position = self.api.private_get_position_list(symbol) self.account = self.api.private_get_wallet_balance()
def _create_bybit(self): bybit = ccxt.bybit({ 'enableRateLimit': False, }) wrap_object(bybit, rate_limiter_group=self.bybit_rate_limiter, wrap_defs=bybit_wrap_defs()) return bybit
def __init__(self): self.bb_api = ccxt.bybit({ "apiKey": API_KEY, "secret": SECRET, "urls": { "api": "https://api-testnet.bybit.com/" # testnet(デモ版)を使用する場合はこの記述が必要 } })
def BB_with_ip_init(n): if n==1: apiKey=API_KEY_BB1_WITH_IP apiSecret=API_SECRET_BB1_WITH_IP elif n==2: apiKey=API_KEY_BB2_WITH_IP apiSecret = API_SECRET_BB2_WITH_IP elif n==3: apiKey=API_KEY_BB3_WITH_IP apiSecret = API_SECRET_BB3_WITH_IP else: sys.exit(1) return ccxt.bybit({'apiKey': apiKey, 'secret': apiSecret, 'enableRateLimit': True, 'nonce': lambda: ccxt.Exchange.milliseconds()})
def initialize(cls): api_info = open('./ignore/api.json', "r") json_data = json.load(api_info) # JSON形式で読み込む id = json_data['id'] secret = json_data['secret'] api_info.close() cls.bb = ccxt.bybit({ 'apiKey': id, 'secret': secret, }) cls.num_private_access = 0 cls.num_public_access = 0 cls.error_trial = 3 cls.rest_interval = 1
def _loop(self, raise_error=False): intervals = [ 60, 3 * 60, 5 * 60, 15 * 60, 30 * 60, 60 * 60, 120 * 60, 240 * 60, 360 * 60, 720 * 60, 24 * 60 * 60, ] price_types = [ None, 'mark', 'index', 'premium_index', ] bybit = ccxt.bybit() symbols = bybit.v2PublicGetSymbols()['result'] symbols = map(lambda x: x['name'], symbols) for symbol in symbols: # 期限付き先物は未対応 if re.search(r'\d', symbol): continue for interval in intervals: for price_type in price_types: is_premium_index_minute = price_type == 'premium_index' and interval == 60 # fr計算に必要 if self.min_interval is not None and interval < self.min_interval and not is_premium_index_minute: continue try: self.store.get_df_ohlcv( exchange='bybit', market=symbol, interval=interval, price_type=price_type, force_fetch=True ) except KeyboardInterrupt: raise except Exception as e: if raise_error: raise self.logger.error('exception ' + traceback.format_exc()) time.sleep(60)
def initialize(cls): api_info = open('./ignore/api.json', "r") json_data = json.load(api_info) # JSON形式で読み込む id = json_data['id'] secret = json_data['secret'] api_info.close() cls.bb = ccxt.bybit({ 'enableRateLimit': True, 'options': { 'adjustForTimeDifference': True, }, 'apiKey': id, 'secret': secret, }) cls.num_private_access = 0 cls.num_public_access = 0 cls.error_trial = 3 cls.rest_interval = 1
from datetime import datetime, timedelta import ccxt def timestamp_millisecond(dt=None, delta=None): if not dt: dt = datetime.now() if delta is not None: dt = dt + delta return int(dt.timestamp() * 1000) bybit = ccxt.bybit( { "enableRateLimit": True, "options": {"adjustForTimeDifference": True, "recvWindow": 10 * 1000}, } ) bybit.set_sandbox_mode(enabled=True) bybit.apiKey = "MkFogsh7NCl9OOoAlP" bybit.secret = "Mqov7GGjV5apciGEb2VKDyAswESvXPUYgJU2" res = bybit.fetch_closed_orders( symbol="BTC/USD", # since=timestamp_millisecond(dt=datetime.now(), delta=timedelta(hours=-1)), params={"order_status": "Filled"}, ) pprint(res)
import os import sys root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 from pprint import pprint print('CCXT Version:', ccxt.__version__) exchange = ccxt.bybit({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', 'enableRateLimit': True, # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit }) # https://github.com/ccxt/ccxt/wiki/Manual#loading-markets markets = exchange.load_markets() # exchange.verbose = True # uncomment for debugging # https://github.com/ccxt/ccxt/wiki/Manual#implicit-api-methods # ----------------------------------------------------------------------------- symbol = 'BTC/USDT' market = exchange.market(symbol)
import sys import time import ccxt from datetime import datetime from pprint import pprint from localmodules import readsetup print(datetime.now()) # パラメータ########################################### GOAL = 100000 # [USD]決済価格 LEVE = 1.5 # 維持するレバレッジ print("deffence", 100 / (LEVE + 1), "%") # 最高値からこれだけの調整は耐えるよという表示 LOT = 10 # [USD]一度に注文する量 STIME = 3 # [sec]ループ頻度。多分3以上じゃないとだめ bybit = ccxt.bybit() bybit.apiKey = readsetup.apikey() bybit.secret = readsetup.secret() # 初期処理######################################### bybit.set_sandbox_mode(True) # 全注文キャンセル bybit.cancelAllOrders("BTC/USD") # 証拠金を取得 res = bybit.fetch_balance() # ポジションを取得 pos = bybit.v2PrivateGetPositionList({"symbol": "BTCUSD"}) balance = (float(res["BTC"]["free"]) + float(res["BTC"]["used"]) + float(pos["result"]["unrealised_pnl"])) print("balance+unreal:", balance, "BTC") print("pos", pos["result"]["size"], "USD")
# -*- coding: utf-8 -*- import os import sys from pprint import pprint root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt # noqa: E402 exchange = ccxt.bybit({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', }) markets = exchange.load_markets() # exchange.verbose = True # uncomment for debugging purposes params = {'stop_px': 9750, 'base_price': 11152} order = exchange.create_order('BTC/USD', 'market', 'buy', 911, None, params) pprint(order)
def init_supported_exchanges(): objects = { "acx": ccxt.acx(), "aofex": ccxt.aofex(), "bequant": ccxt.bequant(), "bibox": ccxt.bibox(), "bigone": ccxt.bigone(), "binance": ccxt.binance(), "bitbank": ccxt.bitbank(), "bitbay": ccxt.bitbay(), "bitfinex": ccxt.bitfinex(), "bitflyer": ccxt.bitflyer(), "bitforex": ccxt.bitforex(), "bithumb": ccxt.bithumb(), "bitkk": ccxt.bitkk(), "bitmax": ccxt.bitmax(), "bitstamp": ccxt.bitstamp(), "bittrex": ccxt.bittrex(), "bitz": ccxt.bitz(), "bl3p": ccxt.bl3p(), "bleutrade": ccxt.bleutrade(), "braziliex": ccxt.braziliex(), "btcalpha": ccxt.btcalpha(), "btcbox": ccxt.btcbox(), "btcmarkets": ccxt.btcmarkets(), "btctradeua": ccxt.btctradeua(), "bw": ccxt.bw(), "bybit": ccxt.bybit(), "bytetrade": ccxt.bytetrade(), "cex": ccxt.cex(), "chilebit": ccxt.chilebit(), "coinbase": ccxt.coinbase(), "coinbasepro": ccxt.coinbasepro(), "coincheck": ccxt.coincheck(), "coinegg": ccxt.coinegg(), "coinex": ccxt.coinex(), "coinfalcon": ccxt.coinfalcon(), "coinfloor": ccxt.coinfloor(), "coinmate": ccxt.coinmate(), "coinone": ccxt.coinone(), "crex24": ccxt.crex24(), "currencycom": ccxt.currencycom(), "digifinex": ccxt.digifinex(), "dsx": ccxt.dsx(), "eterbase": ccxt.eterbase(), "exmo": ccxt.exmo(), "exx": ccxt.exx(), "foxbit": ccxt.foxbit(), "ftx": ccxt.ftx(), "gateio": ccxt.gateio(), "gemini": ccxt.gemini(), "hbtc": ccxt.hbtc(), "hitbtc": ccxt.hitbtc(), "hollaex": ccxt.hollaex(), "huobipro": ccxt.huobipro(), "ice3x": ccxt.ice3x(), "independentreserve": ccxt.independentreserve(), "indodax": ccxt.indodax(), "itbit": ccxt.itbit(), "kraken": ccxt.kraken(), "kucoin": ccxt.kucoin(), "lakebtc": ccxt.lakebtc(), "latoken": ccxt.latoken(), "lbank": ccxt.lbank(), "liquid": ccxt.liquid(), "livecoin": ccxt.livecoin(), "luno": ccxt.luno(), "lykke": ccxt.lykke(), "mercado": ccxt.mercado(), "oceanex": ccxt.oceanex(), "okcoin": ccxt.okcoin(), "okex": ccxt.okex(), "paymium": ccxt.paymium(), "poloniex": ccxt.poloniex(), "probit": ccxt.probit(), "southxchange": ccxt.southxchange(), "stex": ccxt.stex(), "surbitcoin": ccxt.surbitcoin(), "therock": ccxt.therock(), "tidebit": ccxt.tidebit(), "tidex": ccxt.tidex(), "upbit": ccxt.upbit(), "vbtc": ccxt.vbtc(), "wavesexchange": ccxt.wavesexchange(), "whitebit": ccxt.whitebit(), "yobit": ccxt.yobit(), "zaif": ccxt.zaif(), "zb": ccxt.zb() } return objects
def bybit(accountDB, key, secret, start, nickname, asset): print("Checking Bybit") bybit = ccxt.bybit({ 'apiKey': key, 'secret': secret, }) # get Account Balance params = { 'coin': asset } data = bybit.fetch_balance(params=params) account = data['info']['result'][asset] balance = round(float(account['wallet_balance']), 7) ostart = start todayCalc = datetime.date.today() yesterdayCalc = todayCalc - datetime.timedelta(days=1) today = str(todayCalc) yesterday = str(yesterdayCalc) pnl = 0 daily = 0 overall = 0 # read Current Data in DB conn = sqlite3.connect('tracker.db') c = conn.cursor() # see if today already exists try: print("Checking for Todays Data") c.execute('SELECT * FROM ' + accountDB) data = c.fetchall() # [print(row) for row in data] # grab yestersterdays data print("Grabbing Yesterdays Data") c.execute('SELECT * FROM ' + accountDB + ' WHERE date = ?', (yesterday,)) dates = c.fetchall() if dates: for data in dates: print("Calculating PNL $$$") pnl = round(data[2] - data[1], 6) daily = round(pnl / data[1] * 100, 6) start = data[2] overall = ((balance/ostart)-1) * 100 else: pnl = round(balance - start, 6 ) daily = round(pnl / start * 100, 6) overall = ((balance/ostart)-1) * 100 except OperationalError: #print("Error in Line") create(accountDB, start) return # print Exisiting Data in Table # [print(row) for row in data] print("Inserting New Values") # Delete Existting Data when updating try: c.execute('SELECT * FROM ' + accountDB) c.execute('DELETE FROM ' + accountDB + ' WHERE date = ?', (today,)) conn.commit() start = data[2] pnl = balance - start daily = pnl / start * 100 overall = ((balance/ostart)-1) * 100 c.execute('INSERT INTO ' + accountDB + ' VALUES (?, ?, ? , ?, ?, ?, ?)', (today, start, balance, pnl, daily, overall, nickname)) conn.commit() conn.close() except OperationalError: print("Error In line 2") create(accountDB, start) return except IndexError: c.execute('SELECT * FROM ' + accountDB) c.execute('DELETE FROM ' + accountDB + ' WHERE date = ?', (today,)) conn.commit() start = start pnl = round(balance - start, 6) daily = round(pnl / start * 100, 6) overall = ((balance/ostart)-1) * 100 c.execute('INSERT INTO ' + accountDB + ' VALUES (?, ?, ? , ?, ?, ?, ?)', (today, start, balance, pnl, daily, overall, nickname)) conn.commit() conn.close() print("Data Added")
import ccxt import pandas as pd ######## # Params ######## ccy = 'WAVES' ###### # Main ###### apiKey = API_KEYS_BB[0] apiSecret = API_SECRETS_BB[0] d = { 'apiKey': apiKey, 'secret': apiSecret, 'enableRateLimit': True, 'nonce': lambda: ccxt.Exchange.milliseconds() } for proxy in PROXIES_BB: z = 'socks5://' + proxy + ':1080' print(z) d['proxies'] = {'http': z, 'https': z} bb = ccxt.bybit(d) bb.options['recvWindow'] = 50000 df = pd.DataFrame( bb.private_linear_get_position_list({'symbol': ccy + 'USDT' })['result']).set_index('side') print(float(df.loc['Buy', 'size']) - float(df.loc['Sell', 'size'])) print()
def crawl_bybit_datas(symbol, start_time, end_time): """ 爬取交易所数据的方法. :param symbol: 请求的symbol: like BTC/USDT, ETH/USD等。 :param start_time: like 2018-1-1 :param end_time: like 2019-1-1 :return: """ print(ccxt.__version__) # 1.18.1213 1.26.50 # pip install ccxt==1.26.50 通过这个命令来安装最新的版本. # exchange_class = getattr(ccxt, 'bybit') # 获取交易所的名称 ccxt.binance # exchange = exchange_class() # 交易所的类. 类似 ccxt.bitfinex() exchange = ccxt.bybit() print(exchange) # exit() current_path = os.getcwd() file_dir = os.path.join(current_path, symbol.replace('/', '')) print(file_dir) if not os.path.exists(file_dir): # 如果这个文件路径不存在,则创建这个文件夹,来存放数据. os.makedirs(file_dir) start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d') end_time = datetime.datetime.strptime(end_time, '%Y-%m-%d') start_time_stamp = int(time.mktime(start_time.timetuple())) * 1000 end_time_stamp = int(time.mktime(end_time.timetuple())) * 1000 limit_count = 200 # bybit 请求的数据有限制,每次只能请求200个. while True: try: print(start_time_stamp) data = exchange.fetch_ohlcv(symbol, timeframe='1m', since=start_time_stamp, limit=limit_count) df = pd.DataFrame(data) df.rename(columns={ 0: 'open_time', 1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume' }, inplace=True) start_time_stamp = int(df.iloc[-1]['open_time']) # 获取下一个次请求的时间. filename = str(start_time_stamp) + '.csv' save_file_path = os.path.join(file_dir, filename) print("文件保存路径为:%s" % save_file_path) df.set_index('open_time', drop=True, inplace=True) df.to_csv(save_file_path) if start_time_stamp > end_time_stamp: print("完成数据的请求.") break time.sleep(0.2) # 1/25 except Exception as error: print(error) time.sleep(10)