def FCPrice(access,symbol): db = pymysql.connect( config.MySqlConfig.host, config.MySqlConfig.mysql_user, config.MySqlConfig.mysql_passwd, config.MySqlConfig.db, ) cursor = db.cursor() sql = 'SELECT api,api_secret FROM accesses WHERE name = "'+access+'"' cursor.execute(sql) res = cursor.fetchone() api=res[0] secret=res[1] #print(res[0],res[1]) # t cursor.close() db.close() bot = Binance( API_KEY=api, API_SECRET=secret ) price=bot.tickerPrice( symbol=symbol ) return price['price']
def __init__(self, market, type, stopsize, interval): self.binance = Binance(api_key=config.API_DETAILS['API_KEY'], api_secret=config.API_DETAILS['API_SECRET']) self.market = market self.type = type self.stopsize = stopsize self.interval = interval self.running = False self.stoploss = self.initialize_stop()
def test_authentication_from_json_file(): """ Test authentication with bad path to `json` format file. Expect `FileNotFoundError`. """ # Import third-party modules from pytest import raises with raises(FileNotFoundError) as invalidPath: Binance.from_json_file('noSuchPath/credentials.json') err = ("No such file or directory: 'noSuchPath/credentials.json'") err in str(invalidPath.value)
class TestBinance: exchange = Binance() @pytest.mark.asyncio async def test_connection(self): """ Check if Binance available """ response = await self.exchange.ping() assert type(response) == dict @pytest.mark.asyncio async def test_exchange_info(self): """ Check exchange info """ exchange_info = await self.exchange.get_info() assert 'symbols' in exchange_info.keys() @pytest.mark.asyncio async def test_symbols(self): """ Check symbols """ symbols = await self.exchange.get_symbols() assert len(symbols) > 0
def __init__(self, args): self._tz = timezone.utc # utc timezone self._ts = datetime.now(self._tz).timestamp() if len(args) != 3: print("number of args does not match") exit() with open(args[1], "r") as f: jsonData = json.load(f) self._config = jsonData print('Configuration file {} loaded'.format(args[1])) print(json.dumps(self._config, sort_keys=True, indent=4)) # logging configuration logger = getLogger(__name__) logger.setLevel(logging.DEBUG) # create file handler fh = logging.FileHandler('yourfilename.log') fh.setLevel(logging.DEBUG) fh_formatter = logging.Formatter( '%(levelname)s : %(asctime)s : %(message)s') fh.setFormatter(fh_formatter) # create console handler ch = logging.StreamHandler() ch.setLevel(logging.INFO) ch_formatter = logging.Formatter( '%(levelname)s : %(asctime)s : %(message)s') ch.setFormatter(ch_formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) self._logger = logger if "LOG_LEVEL" in self._config: if self._config["LOG_LEVEL"] in [ "CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", ]: self._logger.setLevel( eval("logging." + self._config["LOG_LEVEL"])) self._exchange = Binance(symbol=self._config["SYMBOL"], apiKey=self._config["APIKEY"], secret=self._config["SECRET"], logger=self._logger) # load your strategy module = machinery.SourceFileLoader("Strategy", args[2]).load_module() self._Strategy = module.Strategy(self) message = "Botter initialized with {}".format(args[1]) self._logger.info(message)
def on_status(self, status): if is_retweet(status._json): return msg = status.text if 'doge' in msg.lower() and status.author.id == 44196397: print( f'WOOOOOO ELON HAS TWEETED, LETS BUY!!!! here is the tweet: {msg}' ) Binance().buy() # the big elon has spoken, BUY DOGE!!!
def main(): my_instance = CoinCap() instance_binance = Binance() timestamp = strftime("%Y_%m_%d %H_%M_%S", gmtime()) filecoincap = open("coincapio_front_" + timestamp + ".txt", "w") front_list = my_instance.get_front() for front_item in front_list: for front_item_detail in front_item: filecoincap.write(front_item_detail + ": " + str(front_item.get(front_item_detail)) + "\n") filecoincap.close() filebinance = open("binance_klines_" + timestamp + ".txt", "w") kline = instance_binance.get_klines('BTCUSDT', '1m') filebinance.write(str(kline)) filebinance.close()
def binance() -> Binance: """ Instantiate `Binance` class. This object will be used throughout the testing of Binance API SDK. Currently, the API key and secret are sourced from a `.env` file. Since `.env` files are not being uploaded to project repositories, this has to change to sourcing the parameters from a vault. """ dotenv = '.env' # Relative path to `.env` file binance = Binance.from_env_file(dotenv) return binance
def __init__(self, ticker): super().__init__() self.setupUi(self) self.timer = QTimer(self) self.timer.start(3000) self.timer.timeout.connect(self.check) with open('key.txt', 'r') as f: keys = list(csv.reader(f, delimiter="/")) self.upbit = Upbit(upbit_access_key=keys[0][1], upbit_secret_key=keys[0][2]) self.binance = Binance(binance_access_key=keys[1][1], binance_secret_key=keys[1][2]) self.ticker = ticker
def __init__(self): self.bot = Telegram_bot() with open('key.txt', 'r') as f: keys = list(csv.reader(f, delimiter="/")) self.upbit = Upbit(upbit_access_key=keys[0][1], upbit_secret_key=keys[0][2]) self.binance = Binance(binance_access_key=keys[1][1], binance_secret_key=keys[1][2]) self.newest_news = {} self.url = 'https://api-manager.upbit.com/api/v1/notices?page=1&per_page=20&thread_name=general' self.listing_url = 'https://api-manager.upbit.com/api/v1/notices/search?search=%5B%EA%B1%B0%EB%9E%98%5D&page=1&per_page=20&before=&target=non_ios&thread_name=general' self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0", "Accept-Encoding": "*", "Connection": "keep-alive" }
res[p] = [] for trade in all_trades: for p in columns: res[p].append(trade[p]) return res if __name__ == '__main__': with open('keys.json') as key_file: keys = json.load(key_file) key_binance = keys['binance2'] # exchange instance binance = Binance(key_binance['key'], key_binance['secret']) # get all trading pairs all_tickers = binance.api.get_all_tickers() all_pairs = map(lambda x: x['symbol'], all_tickers) all_pairs = list(filter(lambda x: x[-3:] == 'BTC', all_pairs)) # calculate all trade profits print('calculating ...') all_trades = [] finished = 0 task_count = len(all_pairs) target = 0.1 for pair in all_pairs: # add all trades of this pair all_trades.extend(get_profit_details(pair))
from binance import Binance import json if __name__ == '__main__': api_key = 'key' secret_key = 'secret' binance = Binance(api_key, secret_key) # print binance.get_allPrices() print binance.get_balance('ETH') # print json.dumps(binance.get_withdraw_history(asset='ETH'), indent = 2) # print json.dumps(binance.get_deposit_history(), indent = 2) # for deposit in binance.get_deposit_history(asset='eth')['depositList']: # print json.dumps(deposit, indent = 2) # print json.dumps(binance.get_deposit_history(), indent = 2 ) # def on_message(ws, message): # print 'dodooo' # print message # # ws = binance.ws_depth('ethbTC') # ws = binance.ws_kline('MCOETH', '1m') # ws.on_message = on_message # ws.run_forever() # binance.ws_kline('ETHBTC', '1m', on_message) # binance.ws_aggTrade('ETHBTC', on_message) # binance.ws_user_data(on_message) # binance.get_server_time() # print binance.get_all_orders("LTCBTC")
# reload(sys) # sys.setdefaultencoding("utf-8") TULING_KEY = '12f1fc86573e49498efe7882746aa66d' # 初始化微信机器人 #bot = Bot(cache_path=True, console_qr=True) # 初始化tuling 机器人 # tuling = Tuling(api_key=TULING_KEY) # 进行测试的好友 #my_friend = ensure_one(bot.search('龙光')) #print(my_friend) ba = Binance() okex = OKEX() huobi = HuoBi() zb = ZB() coincap = CoinMarketCap() logger = Logger().get_log() def query_price_by_exchange(_exchange, _symbol): if _symbol and _exchange and len(_symbol) > 2 and len(_exchange) > 1: if 'HB' == _exchange: return huobi.get_coin_price_api(_symbol) elif 'BA' == _exchange: return ba.get_coin_price_api(_symbol) elif 'OK' == _exchange: return okex.get_coin_price_api(_symbol)
from utils import read_key_secret, draw_table from yobit import Yobit from crex import Crex from binance import Binance ##################### # DRAW CREX BINANCE # ##################### bn_key, bn_secret = read_key_secret('binance_token.txt') bn = Binance(bn_key, bn_secret) draw_table(bn.get_wallet()) ##################### # DRAW CREX WALLET # ##################### cr_key, cr_secret = read_key_secret('crex_token.txt') cr = Crex(cr_key, cr_secret) draw_table(cr.get_wallet()) ##################### # DRAW YOBIT WALLET # ##################### yb_key, yb_secret = read_key_secret('yobit_token.txt') yb = Yobit(yb_key, yb_secret) draw_table(yb.get_wallet())
if __name__ == "__main__": # data management lock = threading.Lock() orderbooks = { "Binance": {}, "Huobi": {}, "Upbit": {}, "last_update": None, } # create websocket threads binance = Binance( url="wss://stream.binance.com:9443/ws/steembtc@depth", exchange="Binance", orderbook=orderbooks, lock=lock, ) huobi = Huobi( url="wss://api.huobipro.com/ws", exchange="Huobi", orderbook=orderbooks, lock=lock, ) upbit = Upbit( url="wss://api.hitbtc.com/api/2/ws", exchange="Upbit", orderbook=orderbooks, lock=lock,
class StopTrail(): def __init__(self, market, type, stopsize, interval): self.binance = Binance(api_key=config.API_DETAILS['API_KEY'], api_secret=config.API_DETAILS['API_SECRET']) self.market = market self.type = type self.stopsize = stopsize self.interval = interval self.running = False self.stoploss = self.initialize_stop() def initialize_stop(self): if self.type == "buy": return (self.binance.get_price(self.market) + self.stopsize) else: return (self.binance.get_price(self.market) - self.stopsize) def update_stop(self): price = self.binance.get_price(self.market) if self.type == "sell": if (price - self.stopsize) > self.stoploss: self.stoploss = price - self.stopsize print("New high observed: Updating stop loss to %.8f" % self.stoploss) elif price <= self.stoploss: self.running = False amount = self.binance.get_balance(self.market.split("/")[0]) price = self.binance.get_price(self.market) self.binance.sell(self.market, amount, price) print("Sell triggered | Price: %.8f | Stop loss: %.8f" % (price, self.stoploss)) elif self.type == "buy": if (price + self.stopsize) < self.stoploss: self.stoploss = price + self.stopsize print("New low observed: Updating stop loss to %.8f" % self.stoploss) elif price >= self.stoploss: self.running = False balance = self.binance.get_balance(self.market.split("/")[1]) price = self.binance.get_price(self.market) amount = balance / price self.binance.buy(self.market, amount, price) print("Buy triggered | Price: %.8f | Stop loss: %.8f" % (price, self.stoploss)) def print_status(self): last = self.binance.get_price(self.market) print("---------------------") print("Trail type: %s" % self.type) print("Market: %s" % self.market) print("Stop loss: %.8f" % self.stoploss) print("Last price: %.8f" % last) print("Stop size: %.8f" % self.stopsize) print("---------------------") def run(self): self.running = True while (self.running): self.print_status() self.update_stop() time.sleep(self.interval)
ratio = 0.98 #设置利润 factor = 1.01 count = 0 # 终止程序的退出码 exit_code = 2 # 刷新时间 refreshTime = 1 # 操作等待时间 wait_time = 0.2 #设置查看的深度 depth_size = 5 # 设置btc的账户最小值 min_btc = 0.1 binance_instance = Binance() huobi_instance = Huobi() time.sleep(15) while(trade_time): # 查询账户余额是否足够交易 binance_btc_balance = binance_instance.balance(binance_btc_name) huobi_btc_balance = huobi_instance.balance(huobi_btc_name) binance_ont_balance = binance_instance.balance(binance_ont_name) huobi_ont_balance = huobi_instance.balance(huobi_ont_name) if float(binance_btc_balance) < min_btc or float(huobi_btc_balance) < min_btc: print("btc low!") time.sleep(60) continue
# - binance obs = None # obs = TickerObserver() Exchanges = [ # BitFinex(ticker_observer=obs, markets=BitFinex.all_markets), # BitMEX(ticker_observer=obs, markets=BitMEX.all_markets), # BitMEX(ticker_observer=obs, markets=['btc_usd', 'eth_btc', 'ltc_btc']), # BitFinex(ticker_observer=obs, markets=['btc_usd', 'eth_btc', 'btc_eur', 'eth_usd']), # GDAX(ticker_observer=obs, markets=['btc_usd', 'btc_eur', 'eth_eur', 'eth_usd', 'eth_btc']), # GDAX(ticker_observer=obs, markets=GDAX.all_markets), # GDAX(ticker_observer=obs, markets=['btc_usd']), Binance(ticker_observer=obs, markets=Binance.all_markets), # Binance(ticker_observer=obs, markets=['eth_btc', 'ltc_btc', ]), # Binance(markets=['eth_btc', ])#, 'bnb_btc', 'eos_btc']), # BitMEX(markets=['btc_usd'], ticker_observer=obs)#, 'ada_btc', 'bch_btc', 'xrp_btc', 'btc_usd', 'eth_btc', 'ltc_btc']), # Binance(markets=['eth_btc', ]) # GDAX(markets=['ltc_usd', ]), # CryptoExchange(url="wss://api.bitfinex.com/ws/", symbol="BTCUSD"), ] async def closer(): while True: await asyncio.sleep(5)
import websockets import time import datetime from binance import Binance from coinbase import Coinbase from bittrex import Bittrex host = 'localhost' port = 5678 loop = asyncio.get_event_loop() curr_time = lambda: datetime.datetime.fromtimestamp(int(time.time())).strftime( '%m-%d-%Y %H:%M:%S') BINANCE = Binance(ohlc='1m', depth=5, ping=3, hours=23) COINBASE = Coinbase() BITTREX = Bittrex() async def start(websocket, path): print('Opening Server @ {}'.format(curr_time())) tasks = [ loop.create_task(BINANCE.start(loop, websocket)), loop.create_task(COINBASE.start(loop, websocket)), loop.create_task(BITTREX.start(loop, websocket)) ] await asyncio.wait(tasks) def connection(loop, host='localhost', port=5678):
import requests import json import time import sys from your_keys import * from binance import Binance binance = Binance(BINANCE_KEY, BINANCE_SECRET) def find_and_do_trades(): rvn_price = float(binance.get_coin_price('RVNBTC')) rvn_24h_data = binance.get_24h_data('RVNBTC') rvn_24h_low = float(rvn_24h_data['low']) rvn_24h_high = float(rvn_24h_data['high']) if rvn_24h_high - rvn_24h_low < 0.00000020: return elif rvn_24h_high - (rvn_24h_high - rvn_24h_low) / 10 <= rvn_price: rvn_bal = binance.get_balance('RVN') if not '-q' in sys.argv or '--quiet' in sys.argv: print( f'Placed SELL Order on RVN @ {rvn_price + 0.00000002}\nRVN Balance: {rvn_bal}' ) binance.post_sell('RVNBTC', rvn_price + 0.00000002, rvn_bal / 10) elif rvn_24h_low + (rvn_24h_high - rvn_24h_low) / 10 >= rvn_price: btc_bal = binance.get_balance('BTC') if not '-q' in sys.argv or '--quiet' in sys.argv: print(