def __init__(self,Market,key,TradingAmount,BuyMargin=40.00,SellMargin=60.00): if TradingAmount < self.MINIMUMTRADE: raise ValueError("smaller than minimum trade size " + str(self.MINIMUMTRADE)) self.secret = "insert here!" self.key = key self.bittrexHandler = bittrex.Bittrex(api_key=key, api_secret=self.secret,api_version=bittrex.API_V2_0) self.market = Market #must be valid bittrex market self.BUYMARGIN = BuyMargin self.SELLMARGIN = SellMargin currencySplit = Market.split("-") self.currencyFrom = currencySplit[0] self.currencyTo = currencySplit[1] self.tradingAmount = TradingAmount self.JSONSTATE_NAME = Market + "-state.json" self.loadState() self.myLogger = logging.getLogger(Market + " Log") if not self.myLogger.handlers: fileHandler = logging.FileHandler(Market + " Log.txt") formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') fileHandler.setFormatter(formatter) self.myLogger.addHandler(fileHandler) self.myLogger.setLevel(logging.NOTSET)
def loop_execute(): global account data = open('account').readlines() key = data[0].strip() secret = data[1].strip() account = bittrex.Bittrex(key, secret) #account.buy('BTC-LTC', 0.1, 0.01) #account.cancel_orders() #adjust_position(account, {'LTC':{'Balance':0}}, {'LTC':0.2}) target_balance = {} global update_queue while True: try: coin = update_queue.get_nowait() except: time.sleep(1) continue update_target_balance(target_balance, coin) adjust_position(account, target_balance) time.sleep(SLEEP_TIME)
def __init__(self, pair: str, key, secret): """ Экземпляр биржи для работы на соответствубщей пары. :param pair: пара с которой будет работать объект """ self.api = bittrex.Bittrex(api_key=key, api_secret=secret) self.logger = setup_logger(name=__class__.__name__, level=INFO) self.pair = pair
def __init__(self): print("Initializing Watcher...") self.d_bittrex = bittrex.Bittrex("ad0c5a7966bb40f5bcdbaa0eb98fb090", "972fbf91ac2240608ae9cc1a68ed54f6") self.d_markets = self.parse_markets( self.d_bittrex.get_markets()["result"]) self.d_currentBTCPrice = self.d_bittrex.get_ticker( "USDT-BTC")["result"]["Last"]
def sell(self, amount): """self.bittrexHandler.trade_sell(market=self.market, quantity=amount, order_type=bittrex.ORDERTYPE_MARKET, time_in_effect=bittrex.TIMEINEFFECT_GOOD_TIL_CANCELLED, condition_type=bittrex.CONDITIONTYPE_NONE) - not working cos API 2 is bugged!""" sellHandler = bittrex.Bittrex(api_key=self.key, api_secret=self.secret, api_version=bittrex.API_V1_1) response = sellHandler.sell_limit(self.market, amount, self.getPrice(ordertype="SELLING")) return response
def bittrex_transactions(): transactions = [] with open("bittrex.txt", encoding="utf-8") as f: f.readline().split("\t") for line in f: rec = line.split("\t") # uuid = rec[0] base, quote = rec[1].split("-") order = rec[2] qty = Decimal(rec[3]) # limit = Decimal(rec[4]) commission = Decimal(rec[5]) price = Decimal(rec[6]) ts = dp(rec[8]) if "BUY" in order: transactions.append([ts, "bittrex", order, base, -price, rec]) transactions.append( [ts, "bittrex", "fee", base, -commission, rec]) transactions.append([ts, "bittrex", order, quote, qty, rec]) elif "SELL" in order: transactions.append([ts, "bittrex", order, base, price, rec]) transactions.append( [ts, "bittrex", "fee", base, -commission, rec]) transactions.append([ts, "bittrex", order, quote, -qty, rec]) else: print(f"unknown order type {rec}") apiclient = bittrex.Bittrex(apikeys.bittrex["apiKey"], apikeys.bittrex["secret"]) dh = apiclient.get_deposit_history() wh = apiclient.get_withdrawal_history() for tx in dh["result"]: ts = dp(tx["LastUpdated"]) transactions.append([ ts, "bittrex", "deposit", tx["Currency"], Decimal(tx["Amount"]), tx ]) for tx in wh["result"]: ts = dp(tx["Opened"]) transactions.append([ ts, "bittrex", "withdrawal", tx["Currency"], -Decimal(tx["Amount"]), tx ]) return transactions
def _get_balance(self): """ method to get bittrex balances Returns: wallet: list of dict e.g. [{'Available': 8011.86885714, 'Balance': 8011.86885714, 'CryptoAddress': None, 'Currency': 'ADA', 'Pending': 0.0}] """ logger = logging.getLogger(__name__) logger.debug("Retrieving Bittrex account balances...") client = bittrex.Bittrex(self._key, self._secret) resp = client.get_balances() if resp['success']: logger.debug(resp['result']) wallet = resp['result'] return wallet else: logging.error("Failed to get Bittrex account balances!")
def __init__(self, Market, key, TradingAmount, BuyMargin=40.00, SellMargin=60.00): if TradingAmount < self.MINIMUMTRADE: raise ValueError("smaller than minimum trade size " + str(self.MINIMUMTRADE)) exit(1) self.secret = input("secret:") self.key = key self.bittrexHandler = bittrex.Bittrex(api_key=key, api_secret=self.secret, api_version=bittrex.API_V2_0) self.market = Market self.BUYMARGIN = BuyMargin self.SELLMARGIN = SellMargin self.myLogger = logging.getLogger(Market + " Log") fileHandler = logging.FileHandler(Market + " Log.txt") formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') fileHandler.setFormatter(formatter) self.myLogger.addHandler(fileHandler) self.myLogger.setLevel(logging.NOTSET) currencySplit = Market.split("-") self.currencyFrom = currencySplit[0] self.currencyTo = currencySplit[1] self.currentState = FlipperStates.BUYING self.tradingAmount = TradingAmount #self.balance[self.currencyFrom],self.balance[self.currencyTo] = self.getBalances() self.lastBought = 0
# form datetime import datetime as dt import datetime import time import time import pandas as pd import os import bittrex @click.command() def cli(): """Example script.""" click.echo('Hello World!') obj = bittrex.Bittrex() @click.command() @click.option('--all', is_flag=True, help="Will returns also open and close.") @click.option('--csv', is_flag=True, help="Will returns the data in csv file.") @click.argument('ccy') @click.argument('initial_date') @click.argument('final_date') def hist_data(csv, all, ccy, initial_date, final_date): h_data = obj.hist_data(ccy, initial_date, final_date) if all: df = pd.DataFrame(h_data, columns=['H', 'L', 'O', 'C', 'T']) else: df = pd.DataFrame(h_data, columns=['H', 'L', 'T']) print(df)
def create_client(api_keys): credentials = open_credentials(api_keys) c = bittrex.Bittrex(api_key=credentials['api_key'], api_secret=credentials['api_secret'], api_version=bittrex.API_V1_1) return c
"Get the api wrapper bittrex.py from https://github.com/ericsomdahl/python-bittrex" ) sys.exit() import time import decimal try: sys.argv[2] except: print("Must have symbol then rate") sys.exit() api_key = '---YOUR-KEY-HERE---' api_secret = '---YOUR-SECRET-HERE---' b = bittrex.Bittrex(api_key, api_secret) symbol = sys.argv[1] rate = sys.argv[2] while True: try: quant = b.get_balance(symbol)['result']['Available'] print("Available: " + str(quant) + " " + symbol) if quant > 0: sell = b.sell_limit("BTC-" + symbol, quant, rate) print(sell) except Exception as e: print(e) time.sleep(122)
with open("api_key.json", 'r') as fp: api_key = json.load(fp) default_version = "v1.1" # strategy parameters market = "ETH-XRP" price_delta = .00005 max_quantity = 600 n_levels = 3 max_iters = 60 * 24 display_freq = 10 btrx = bittrex.Bittrex(api_key=api_key["api_key"], api_secret=api_key["api_secret"], calls_per_second=1 / 60, api_version=default_version) # get existing orders to be ignored by strategy existing_orders = btrx.get_open_orders(market=market)["result"] ignore_orders = [x["OrderUuid"] for x in existing_orders] ticker = btrx.get_ticker(market)["result"] initial_price = ticker["Last"] profit_per_flip = price_delta * (max_quantity // n_levels) - ( .005 * (max_quantity // n_levels) * initial_price) print("Approximate profit per flip: " + str(profit_per_flip) + " " + market.split("-")[0] + ".") # place initial orders
import bittrex import requests from datetime import datetime import collections bt = bittrex.Bittrex('APIKEY', 'APISECRET') buy_volume = {} sell_volume = {} market_history = requests.get('https://bittrex.com/api/v1.1/public/getmarkethistory?market=BTC-LTC').json()['result'] for order in market_history: timestamp = datetime.strptime(order['TimeStamp'], '%Y-%m-%dT%H:%M:%S.%f') seconds = datetime.strftime(timestamp, '%Y-%m-%d %H:%M:%S') if order['OrderType'] == 'SELL': sell_volume[seconds] = sell_volume.get(seconds, 0) + order['Quantity'] elif order['OrderType'] == 'BUY': buy_volume[seconds] = sell_volume.get(seconds, 0) + order['Quantity'] chronological_buy_volume = collections.OrderedDict(sorted(buy_volume.items())) print 'buy_volume: ' + str(chronological_buy_volume) print sell_volume
def __init__(self, name, wallet): self.name = name self.wallet = wallet self.c = bittrex.Bittrex(getenv('BITTREX_API_KEY'), getenv('BITTREX_API_SECRET'))
'getmarkets', 'getcurrencies', 'getticker', 'getmarketsummaries', 'getorderbook', 'getmarkethistory' ] MARKET_SET = [ 'getopenorders', 'cancel', 'sellmarket', 'selllimit', 'buymarket', 'buylimit' ] ACCOUNT_SET = [ 'getbalances', 'getbalance', 'getdepositaddress', 'withdraw', 'getorder', 'getorderhistory', 'getwithdrawalhistory', 'getdeposithistory' ] import bittrex btrx = bittrex.Bittrex(BITTREX_ID, BITTREX_SECRET) def get_markets(): markets = pd.DataFrame(btrx.get_markets()['result']) marketnames = markets.MarketName return list(marketnames) def get_tickers(markets): results = [] for x in markets: a = btrx.get_ticker(x) a['result']['Market'] = x results.append(a['result']) return pd.DataFrame(results)
#!/usr/bin/python """ the rex package is a bittrex exchange adapter. """ import bittrex from operator import itemgetter from helpers import find from config import env Rex = bittrex.Bittrex(api_key="", api_secret="") # blacklist is where coins who have too much non crypto currency meaning go. sorry :( blacklist = ["GLD", "1ST", "2GIVE", "EMC2"] def get_cream(list_of_things): """ get_cream gets the top 40% of the pack, no dregs please. """ return int(len(list_of_things) * 0.2) def get_market_summaries(): """ get_market_summaries gets the top 40% highest volume market summaries for btc, eth and usdt based markets TODO: how can we automate the btc/eth/usdt lists into automated list generation based on the split[0] for the MarketName? """ summaries = Rex.get_market_summaries()["result"] currencies = Rex.get_currencies()["result"] btc_summaries = []
def sell(self,amount): sellHandler = bittrex.Bittrex(api_key=self.key, api_secret=self.secret, api_version=bittrex.API_V1_1) response = sellHandler.sell_limit(self.market, amount, self.getPrice(ordertype="LASTPRICE")) return response