def __init__(self, config, debug=True): key_config = config['apikey'] self.debug = debug self.exchanges = { 'zb': Zb(key_config['zb']['key'], key_config['zb']['secret']), 'okex': Okex(key_config['okex']['key'], key_config['okex']['secret']), 'weex': Weex(key_config['weex']['key'], key_config['weex']['secret']), # 'huobipro': Huobipro(key_config['huobipro']['key'], key_config['huobipro']['secret']), 'bithumb': ccxt.bithumb(), 'binance': ccxt.binance(), 'bitflyer': ccxt.bitflyer(), 'hitbtc': ccxt.hitbtc(), 'coincheck': ccxt.coincheck(), "quoinex": ccxt.quoinex(), "bitfinex": ccxt.bitfinex(), "hitbtc": ccxt.hitbtc(), } self.engine = MysqlEngine(config['db']['url']) self.pool = ThreadPoolExecutor( 3) # for many urls, this should probably be capped at some value. self. async = False
def main(): def load_executions(): executions = bf.fetch_my_trades('FX_BTC_JPY', limit=100) for exc in executions: counter.enqueue_exc(exc) bf = ccxt.bitflyer() bf.timeout = 30000 bf.apiKey = os.environ['BITFLYER_API_KEY'] bf.secret = os.environ['BITFLYER_API_SECRET'] bf.verbose = False redis = redispy.Redis(connection_pool=redispy.ConnectionPool( host='localhost', port=6379, db=0)) counter = PositionCounter(bf=bf, redis=redis, refresh_using='redis') set_interval(10, lambda: load_executions()) set_interval(1, lambda: counter.update()) set_interval(10, lambda: print(f'bF: {counter.fetch()} BTC')) while True: time.sleep(1) redis_pos = round(float(redis.get('position')), 8) print(f'Redis: {redis_pos} BTC') print(f'Counter: {counter.position} BTC') print(f'Redis ids: {redis.lrange("exec_ids", 0, -1)}')
def test_buy(self): """Test buy.""" settings = {'symbol': 'BTC/JPY', 'yen': 1000} bitflyer = ccxt.bitflyer() bitflyer.create_market_buy_order = Mock() controller = exchange.ExchangeController(settings, exchange=bitflyer) amount = 0.1 controller.buy(amount) bitflyer.create_market_buy_order.assert_called_once_with( 'BTC/JPY', amount)
def test_compute_amount_error(self): """Test compute amount with error.""" settings = {'symbol': 'BTC/JPY', 'yen': 1000} bitflyer = ccxt.bitflyer() bitflyer.fetch_order_book = Mock() bitflyer.fetch_order_book.side_effect = Exception("mock excepton") controller = exchange.ExchangeController(settings, exchange=bitflyer) with self.assertRaises(Exception): controller.compute_amount() bitflyer.fetch_order_book.assert_called_once_with('BTC/JPY')
def init_supported_exchanges(): objects = { "binance": ccxt.binance(), "bitfinex": ccxt.bitfinex(), "bitflyer": ccxt.bitflyer(), "bitstamp": ccxt.bitstamp(), "bittrex": ccxt.bittrex(), "coinbase": ccxt.coinbase(), "kraken": ccxt.kraken(), "poloniex": ccxt.poloniex() } return objects
def test_compute_amount_simple_case(self): """Test compute amount (simple_case).""" settings = {'symbol': 'BTC/JPY', 'yen': 1000} bitflyer = ccxt.bitflyer() bitflyer.fetch_order_book = Mock() bitflyer.fetch_order_book.return_value = { 'asks': [[1000000., 0.1], [1010000., 0.1]] } controller = exchange.ExchangeController(settings, exchange=bitflyer) amount = controller.compute_amount() bitflyer.fetch_order_book.assert_called_once_with('BTC/JPY') self.assertEqual(0.001, amount)
def exchangeObject(exchange_in): exchanges = [ccxt.acx(),ccxt.bitbay(),ccxt.bitfinex(),ccxt.bitflyer(),ccxt.bithumb(),ccxt.bitlish(),ccxt.bitmarket(),ccxt.bitmex(),ccxt.bitso(), ccxt.bitstamp(),ccxt.bitstamp1(),ccxt.bittrex(),ccxt.bl3p(),ccxt.bleutrade(),ccxt.btcbox(),ccxt.btcchina(),ccxt.btcexchange(),ccxt.btcmarkets(),ccxt.btctradeua(),ccxt.btcturk(), ccxt.btcx(),ccxt.bxinth(),ccxt.ccex(),ccxt.cex(),ccxt.chbtc(),ccxt.chilebit(),ccxt.coincheck(),ccxt.coinfloor(),ccxt.coingi(),ccxt.coinmarketcap(),ccxt.coinmate(), ccxt.coinsecure(),ccxt.coinspot(),ccxt.cryptopia(),ccxt.dsx(),ccxt.exmo(),ccxt.flowbtc(),ccxt.foxbit(),ccxt.fybse(),ccxt.fybsg(),ccxt.gatecoin(),ccxt.gateio(),ccxt.gdax(), ccxt.gemini(),ccxt.getbtc(),ccxt.hitbtc(),ccxt.huobi(),ccxt.huobicny(),ccxt.independentreserve(),ccxt.itbit(),ccxt.jubi(),ccxt.kraken(),ccxt.kucoin(), ccxt.kuna(),ccxt.lakebtc(),ccxt.liqui(),ccxt.livecoin(),ccxt.luno(),ccxt.mercado(),ccxt.mixcoins(),ccxt.nova(),ccxt.okcoincny(),ccxt.okcoinusd(),ccxt.okex(),ccxt.paymium(), ccxt.poloniex(),ccxt.qryptos(),ccxt.quadrigacx(),ccxt.southxchange(),ccxt.surbitcoin(),ccxt.therock(),ccxt.tidex(),ccxt.urdubit(),ccxt.vaultoro(),ccxt.vbtc(), ccxt.virwox(),ccxt.wex(),ccxt.xbtce(),ccxt.yobit(),ccxt.yunbi(),ccxt.zaif(),ccxt.zb()] for count, exchange in enumerate([str(x) for x in exchanges]): if exchange_in.lower() in exchange: return exchanges[count] break
def test_buy_error(self): """Test buy with error.""" settings = {'symbol': 'BTC/JPY', 'yen': 1000} bitflyer = ccxt.bitflyer() bitflyer.create_market_buy_order = Mock() bitflyer.create_market_buy_order.side_effect = Exception( "mock exception") controller = exchange.ExchangeController(settings, exchange=bitflyer) amount = 0.1 with self.assertRaises(Exception): controller.buy(amount) bitflyer.create_market_buy_order.assert_called_once_with( 'BTC/JPY', amount)
def main(): # 实例化市场 exchanges = [ccxt.bitstamp(), ccxt.bitflyer()] # 交易对 symbols = ['BTC/USD'] tasks = [] i = 0 j = 0 for i in range(len(exchanges)): for j in range(len(symbols)): # tasks.append(self.proxy_resource_Url + str(i)) task = getData(exchanges[i], symbols[j]) tasks.append(asyncio.ensure_future(task)) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks))
def initialize(cls): cls.secret_key = '' cls.api_key = '' cls.__read_keys() cls.bf = ccxt.bitflyer({ 'apiKey': cls.api_key, 'secret': cls.secret_key, }) cls.order_id = {} cls.spread_loss_profit = 0 cls.spread_loss_profit_log = [] cls.num_private_access = 0 cls.num_public_access = 0 cls.flg_api_limit = False cls.conti_order_error = 0 cls.adjusting_sleep = 0 cls.total_access_per_300s = 0 th = threading.Thread(target=cls.monitor_api) th.start()
def __init__(self, config, debug=True): key_config = config['apikey'] self.debug = debug self.exchanges = { 'zb': Zb(key_config['zb']['key'], key_config['zb']['secret']), 'okex': Okex(key_config['okex']['key'], key_config['okex']['secret']), 'weex': Weex(key_config['weex']['key'], key_config['weex']['secret']), # 'huobipro': Huobipro(key_config['huobipro']['key'], key_config['huobipro']['secret']), 'bithumb': ccxt.bithumb(), 'binance': ccxt.binance(), 'bitflyer': ccxt.bitflyer(), 'hitbtc': ccxt.hitbtc(), 'coincheck': ccxt.coincheck(), "quoinex": ccxt.quoinex(), "bitfinex": ccxt.bitfinex(), "hitbtc": ccxt.hitbtc(), } self.engine = MysqlEngine(config['db']['url']) self.pool = ThreadPoolExecutor(3) # for many urls, this should probably be capped at some value. self.async = False
import traceback import pprint import ccxt from botfw.bitflyer import * from botfw.etc.util import setup_logger account = json.loads(open('account_info.json').read()) KEY = account['key'] # YOUR_API_KEY SECRET = account['secret'] # YOUR_API_SECRET setup_logger(logging.INFO) log = logging.getLogger() api_ccxt = ccxt.bitflyer({'apiKey': KEY, 'secret': SECRET}) api = BitflyerApi(api_ccxt) ws = BitflyerWebsocket(KEY, SECRET) fx_trade = BitflyerTrade(FX_BTC_JPY, ws) fx_orderbook = BitflyerOrderbook(FX_BTC_JPY, ws) # btc_trade = BitflyerTrade(BTC_JPY, ws) # btc_orderbook = BitflyerOrderbook(BTC_JPY, ws) om = BitflyerOrderManager(api, ws, retention=10) ogm = BitflyerOrderGroupManager( om, trades={FX_BTC_JPY: fx_trade}, retention=10) fx_og = ogm.create_order_group('fx', FX_BTC_JPY) # fx2_og = ogm.create_order_group('fx2', FX_BTC_JPY) # btc_og = ogm.create_order_group('btc', BTC_JPY)
import threading import queue import liquidtap import json import websocket import ast import ccxt from time import sleep import pandas as pd liq = ccxt.liquid({ "apiKey": "XXXXX", "secret": "XXXXX", }) # APIキー,シークレットキーを設定 bitf = ccxt.bitflyer({ "apiKey": "XXXXX", "secret": "XXXXX", }) # APIキー,シークレットキーを設定 ccc = ccxt.coincheck({ "apiKey": "XXXXX", "secret": "XXXXX", }) # APIキー,シークレットキーを設定 bitb = ccxt.bitbank({ "apiKey": "XXXXX", "secret": "XXXXX", }) # APIキー,シークレットキーを設定 def bitflyer_ws(soushin_buy, soushin_sell): # print('bitflyer start') def on_message(ws, message): r = json.loads(message)
import logging import datetime import os import ccxt logging.basicConfig(filename='bot.log', encoding='utf-8', level=logging.INFO) today = datetime.date.today() logging.info(f'{today} : bot starting') API_KEY = os.getenv('API_KEY') API_SECRET = os.getenv('API_SECRET') BASE_JP_PRICE = 2000 bf = ccxt.bitflyer({ 'apiKey': API_KEY, 'secret': API_SECRET, }) # get last trading price ticker = bf.fetch_ticker(symbol='BTC/JPY') ltp = ticker['info']['ltp'] logging.info(f'ltp is {ltp}') # calculate size MINIMUM = 0.001 base_size = round(BASE_JP_PRICE / float(ltp), 7) size = base_size if base_size >= MINIMUM else MINIMUM logging.info(f'size is {size}') # send BUY order logging.info(f'send order')
import pandas as pd import numpy as np import talib import settings import time import joblib from logging import getLogger, Formatter, StreamHandler, FileHandler, INFO # モデルの読み込み model_y_buy = joblib.load('./model_y_buy.xz') model_y_sell = joblib.load('./model_y_sell.xz') # ccxtのパラメータ symbol = 'BTC/JPY' # 購入予定のシンボル product_code = 'FX_BTC_JPY' bitflyer = ccxt.bitflyer() # 使用する取引所を記入 bitflyer.apiKey = settings.apiKey bitflyer.secret = settings.secret #lot = 100 # 購入する数量 lot = 10 # 購入する数量 #max_lot = 1000 # 最大ロット max_lot = 100 # 最大ロット # 特徴量作成 def calc_features(df): open = df['op'] high = df['hi'] low = df['lo'] close = df['cl'] volume = df['volume']
'apiKey': config['apikey'], 'secret': config['secret'], }) # testnetを使うときのみ必要 # これを書くと、'https://www.bitmex.com' → 'https://testnet.bitmex.com'に接続先が変わる exchange.urls['api'] = exchange.urls['test'] else: # 本番 if TRADE_EXCHANGE == EXCHANGE_BITMEX: exchange = ccxt.bitmex({ 'apiKey': config['apikey'], 'secret': config['secret'], }) elif TRADE_EXCHANGE == EXCHANGE_BITFLYER: exchange = ccxt.bitflyer({ "apiKey": config['apikey'], "secret": config['secret'], }) def can_trade(retry_count=0): if is_bitflyer() == False: # BFのみ対応 print("get_exchange_state not support") sys.exit() try: response = exchange.public_get_gethealth( params={"product_code": TRADE_PAIR}) except Exception as e: print(e) if retry_count < API_RETRY_MAX:
elif flag["position"]["side"] == "buy": if signal["side"] == "sell": close_Mpos("sell") else: check_positions() elif flag["position"]["side"] == "sell": if signal["side"] == "buy": close_Mpos("buy") else: check_positions() #=====================================================# bitflyer = ccxt.bitflyer({ 'apiKey':'', 'secret':'' }) period = 60 flag = { 'position':{ 'side': 0, 'price': 0, }, 'trend': 0, } while True: data,ticker,df = create_df(60,-1) sp2,sm2 = BBAND() check_signal(sp2,sm2,data,ticker["last"],df) time.sleep(10)
def start(self): self.logger.info('Start Exchange') self.running = True # 取引所セットアップ self.exchange = ccxt.bitflyer({ 'apiKey': self.apiKey, 'secret': self.secret }) self.exchange.urls['api'] = 'https://api.bitflyer.com' self.exchange.timeout = 60 * 1000 # 応答時間計測用にラッパーをかぶせる # self.wait_for_completion = stop_watch(self.wait_for_completion) self.safe_create_order = self.safe_api_call( self.__restapi_create_order) self.safe_cancel_order = self.safe_api_call( self.__restapi_cancel_order) self.safe_cancel_order_all = self.safe_api_call( self.__restapi_cancel_order_all) self.safe_fetch_collateral = self.safe_api_call( self.__restapi_fetch_collateral) self.safe_fetch_position = self.safe_api_call( self.__restapi_fetch_position) self.safe_fetch_balance = self.safe_api_call( self.__restapi_fetch_balance) self.safe_fetch_orders = self.safe_api_call( self.__restapi_fetch_orders) self.safe_fetch_board_state = self.safe_api_call( self.__restapi_fetch_board_state) self.inter_check_order_status = self.__restapi_check_order_status # プライベートAPI有効判定 self.private_api_enabled = len(self.apiKey) > 0 and len( self.secret) > 0 # マーケット一覧表示 self.exchange.load_markets() for k, v in self.exchange.markets.items(): self.logger.info('Markets: ' + v['symbol']) # スレッドプール作成 self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=8) # 並列注文処理完了待ち用リスト self.parallel_orders = [] # 注文管理 self.om = OrderManager() # Lightningログイン if self.lightning_enabled: self.lightning.login() # LightningAPIに置き換える self.safe_create_order = self.safe_api_call( self.__lightning_create_order) # self.safe_cancel_order = self.safe_api_call(self.__lightning_cancel_order) self.safe_cancel_order_all = self.safe_api_call( self.__lightning_cancel_order_all) self.safe_fetch_position = self.safe_api_call( self.__lightning_fetch_position_and_collateral) self.safe_fetch_balance = self.safe_api_call( self.__lightning_fetch_balance)
def __init__(self): self.api = bitflyer({ 'apiKey': getenv('bitflyer_api_key'), 'secret': getenv('bitflyer_api_secret') })
# coding: utf-8 import ccxt import pandas as pd import numpy as np from pprint import pprint import time #各取引所のAPIを取得 cc = ccxt.coincheck() bf = ccxt.bitflyer() zaif = ccxt.zaif() bb = ccxt.bitbank() #for i in range(0, 3, 1): #各取引所のBTC価格(ticker)を取得 #CC ticker情報 cc_ticker = cc.fetch_ticker("BTC/JPY") ccask = cc_ticker["ask"] ccbid = cc_ticker["bid"] #bf ticker情報 bf_ticker = bf.fetch_ticker("BTC/JPY") bfask = bf_ticker["ask"] bfbid = bf_ticker["bid"] #zaif ticker情報 zaif_ticker = zaif.fetch_ticker("BTC/JPY") zaifask = zaif_ticker["ask"] zaifbid = zaif_ticker["bid"]
import ccxt exchanges = [ ccxt._1broker(), ccxt._1btcxe(), ccxt.acx(), ccxt.allcoin(), ccxt.anxpro(), ccxt.bibox(), ccxt.binance(), ccxt.bit2c(), ccxt.bitbank(), ccxt.bitbay(), ccxt.bitfinex(), ccxt.bitfinex2(), ccxt.bitflyer(), ccxt.bithumb(), ccxt.bitkk(), ccxt.bitlish(), ccxt.bitmarket(), ccxt.bitmex(), ccxt.bitso(), ccxt.bitstamp(), ccxt.bitstamp1(), ccxt.bittrex(), ccxt.bitz(), ccxt.bl3p(), ccxt.bleutrade(), ccxt.braziliex(), ccxt.btcbox(), ccxt.btcchina(),
import sys import time import ccxt import json import os print('shell start') interval = 1 ex = ccxt.bitflyer() ex_name = 'bf' filename = os.path.normpath(os.path.join(os.path.abspath(__name__),'../tickers/' + ex_name + '_ticker.json')) try: while True: ex_json = ex.fetch_ticker('BTC/JPY') with open(filename, 'w') as f: json.dump(ex_json, f, indent=2, ensure_ascii=False) time.sleep(interval) except: print('through any exception. exit get_' + ex_name + '_ticker.py') sys.exit()
# -*- coding: utf-8 -*- import argparse import time import json from operator import itemgetter import ccxt parser = argparse.ArgumentParser(description="") parser.add_argument("--pair", dest='pair', type=str, default='BTC_JPY') parser.add_argument("--before", dest='before', action="store_true") parser.add_argument("--id", dest='id', type=int, default=0) parser.add_argument("--waitsec", dest='waitsec', type=float, default=1) args = parser.parse_args() api = ccxt.bitflyer() api.urls['api'] = 'https://api.bitflyer.com' api_args = {} api_args['product_code'] = args.pair api_args['count'] = 500 if args.before: direction = 'before' else: direction = 'after' if args.id > 0: api_args[direction] = args.id last_id = 0 once = True
import bforder import cryptowatch #import talib as ta import numpy as np import pandas as pd #configの読み込み f = open('config/config.json', 'r', encoding="utf-8") config = json.load(f) order = bforder.BFOrder() cryptowatch = cryptowatch.CryptoWatch() bitflyer = ccxt.bitflyer({ 'apiKey': config["key"], 'secret': config["secret"], }) # 取引する通貨、シンボルを設定 COIN = 'BTC' PAIR = 'BTC/JPY' # プロダクトコードの指定 PRODUCT = config["product_code"] # ロット(単位はBTC) LOT = config["lotSize"] CANDLETERM = config["candleTerm"] # 最小注文数(取引所の仕様に応じて設定)
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
import ccxt # noqa: E402 from source import API_keys # 'Any Time' CryptoExchange Instantiation binance = ccxt.binance({ 'enableRateLimit': True, }) # enter your API public/secret keys here: binance.apiKey = API_keys.binance.apiKey binance.secret = API_keys.binance.secret bitflyer = ccxt.bitflyer({ 'enableRateLimit': True, }) # enter your API public/secret keys here: bitflyer.apiKey = API_keys.bitflyer.apiKey bitflyer.secret = API_keys.bitflyer.secret bitfinex = ccxt.bitfinex({ 'enableRateLimit': True, }) # enter your API public/secret keys here: bitfinex.apiKey = API_keys.bitfinex.apiKey bitfinex.secret = API_keys.bitfinex.secret bittrex = ccxt.bittrex({ 'enableRateLimit': True, }) # enter your API public/secret keys here: bittrex.apiKey = API_keys.bittrex.apiKey bittrex.secret = API_keys.bittrex.secret
# -*- coding: utf-8 -*- import sys import os import random import ccxt #### api keys ##### api_keys = [ {"api_key": "XLh5nLnMk9SArPwV9oEiRn", "api_secret": "SpPGllAzy1DiR3cuy1zrDlhRKRkpSfeMVtx0kY+mmCk="}, {"api_key": "XLh5nLnMk9SArPwV9oEiRn", "api_secret": "SpPGllAzy1DiR3cuy1zrDlhRKRkpSfeMVtx0kY+mmCk="}, {"api_key": "XLh5nLnMk9SArPwV9oEiRn", "api_secret": "SpPGllAzy1DiR3cuy1zrDlhRKRkpSfeMVtx0kY+mmCk="}, {"api_key": "XLh5nLnMk9SArPwV9oEiRn", "api_secret": "SpPGllAzy1DiR3cuy1zrDlhRKRkpSfeMVtx0kY+mmCk="}, {"api_key": "XLh5nLnMk9SArPwV9oEiRn", "api_secret": "SpPGllAzy1DiR3cuy1zrDlhRKRkpSfeMVtx0kY+mmCk="} ] num = random.randint(0,4) using_key = api_keys[num] API_KEY = using_key["api_key"] API_SECRET = using_key["api_secret"] ##### set ccxt ##### bitflyer = ccxt.bitflyer({ "apiKey" : API_KEY, "secret" : API_SECRET })
}.get(param, "") print(" '{}': fields.{}(required=False, description='{}', example='{}'),".format(param, fieldType, param, example)) print(" },") def generate_api(exchange: ccxt.Exchange): name = exchange.__class__.__name__ sigs = get_signatures(exchange) methods = list(sigs.keys()) env = Environment(loader=FileSystemLoader("../apis")) template = env.get_template("api.py.jinja2") text = template.render({"exchange_name": name, "methods": methods}) filename = "../apis/{}.py".format(name) with open(filename, "w") as f: f.write(text) print("Generated '{}'".format(filename)) if __name__ == '__main__': generate_api(ccxt.bittrex()) generate_api(ccxt.poloniex()) generate_api(ccxt.bitflyer()) sigs = get_signatures(ccxt.bittrex()) for method, sig in sigs.items(): signature_to_model_text(method, sig)
if flag["order"] == True: if flag["position"] == 'buy': if EMA(EMA_period, period) < data["close_price"] and EMA( EMA_period, period) > tmp["close_price"]: close_position("sell") elif flag["position"] == 'sell': if EMA(EMA_period, period) > data["close_price"] and EMA( EMA_period, period) < tmp["close_price"]: close_position("buy") else: if EMA(EMA_period, period) < data["close_price"] and EMA( EMA_period, period) > tmp["close_price"]: create_position("buy") elif EMA(EMA_period, period) > data["close_price"] and EMA( EMA_period, period) < tmp["close_price"]: create_position("sell") #=====================================================# bitflyer = ccxt.bitflyer({'apiKey': 'あなたのapikey', 'secret': 'あなたのsecret'}) tmp, unuse = get_price(60, -2) flag = {'order': False, 'position': 0} time.sleep(30) while True: data, full_data = get_price(60, -2) if data["close_time"] != tmp["close_time"]: check_order(14, 60) tmp["close_price"] = data["close_price"] tmp["close_time"] = data["close_time"] time.sleep(10)
import ccxt from pprint import pprint from PASSWORDS.password import * bitflyer = ccxt.bitflyer() bitflyer.apiKey = bitFlyer_apiKey # apiKeyのKのみ大文字注意 bitflyer.secret = bitFlyer_secret order = bitflyer.create_order( symbol = 'BTC/JPY', type='limit', side='buy', price='3100000', amount='0.01', params = {"product_code" : "FX_BTC_JPY"}) pprint(order)
import ccxt _exchanges = { "bittrex": ccxt.bittrex(), "poloniex": ccxt.poloniex(), "bitflyer": ccxt.bitflyer(), } def get_exchange(name: str): if name not in _exchanges: raise RuntimeError("Exchange {} not found".format(name)) return _exchanges[name]