from time import sleep from lib import bitmex from setting import API_KEY, API_SECRET, API_BASE from oauth2client.service_account import ServiceAccountCredentials from datetime import datetime pp = pprint.PrettyPrinter(indent=4) scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name('secret.json', scope) client = gspread.authorize(creds) sheet = client.open('Auto Journal') #Change this to spreadsheet name worksheet = sheet.worksheet('Journal') #Change this to worksheet name # Create connector connector = bitmex.BitMEX(base_url=API_BASE, apiKey=API_KEY, apiSecret=API_SECRET) # Do trade history query count = 5 query = { 'reverse': 'true', 'count': count } def retrieve(): position = connector._curl_bitmex(path="position", verb="GET", timeout=10) history = connector._curl_bitmex(path="execution/tradeHistory", verb="GET", query=query, timeout=10) wallet = connector._curl_bitmex(path="user/walletHistory", verb="GET", query=query, timeout=10) data = worksheet.get_all_records() try:
if not args.apiKey or not args.apiSecret: print('Please fill in API_KEY and API_SECRET in settings.py!\n' + 'You can create an API key from https://www.bitmex.com/app/apiKeys') sys.exit(1) if args.filter: # Verify if it's proper JSON try: json.loads(args.filter) except ValueError as e: raise ValueError( "Filter is not valid JSON! Make sure to single-quote the string.") # Create connector connector = bitmex.BitMEX(base_url=API_BASE, apiKey=args.apiKey, apiSecret=args.apiSecret) # Do trade history query count = 500 # max API will allow query = {'reverse': 'true', 'start': 0, 'count': count, 'filter': args.filter} out = [] while True: data = connector._curl_bitmex(path="execution/tradeHistory", verb="GET", query=query, timeout=10) out.extend(data) query['start'] += count if len(data) < count:
parser.add_argument('--binSize', type=str, help='Bin Size.') parser.add_argument('--sleep', type=float, help='Sleep time for big requests.') args = parser.parse_args() # Validate Args if args.filter: # Verify if it's proper JSON try: json.loads(args.filter) except ValueError as e: raise ValueError( "Filter is not valid JSON! Make sure to single-quote the string.") # Create connector connector = bitmex.BitMEX(base_url=API_BASE) # Do trade history query path = "trade" if args.path: path = args.path count = 500 # max API will allow query = {'reverse': 'false', 'start': 0, 'count': count, 'filter': args.filter} if args.symbol: query['symbol'] = args.symbol if args.binSize: query['binSize'] = args.binSize csvwriter = None while True:
def fetch_endpoints(args): # Validate Args fileType = args.fileType if fileType not in ('json', 'csv'): raise Exception('Output file type must be json or csv! Given: %s' % fileType) if args.filter: # Verify if it's proper JSON try: json.loads(args.filter) except ValueError as e: raise ValueError("Filter is not valid JSON! Make sure to single-quote the string.") # Create connector connector = bitmex.BitMEX(base_url=API_BASE, apiKey=API_KEY, apiSecret=API_SECRET) # Do trade history query count = 500 # max API will allow query = { 'reverse': 'true', 'start': 0, 'count': count, 'filter': args.filter } out = [] json_data_dict_list = [] # bitcoin_rate = get_bitcoin_rate() while True: path = args.endpoint print(path) if args.isquery: data = connector._curl_bitmex(path=path, verb="GET", query=query, timeout=10) else: data = connector._curl_bitmex(path=path, verb="GET", timeout=10) out.extend(data) # print(out) query['start'] += count if len(data) < count: break if len(out) == 0: print('No trade history found for this account. Exiting.', file=sys.stderr) exit(1) # Write to stdout if fileType == 'csv': df = pd.DataFrame() for d in out: # csv requires dict keys # keys = out[0].keys() # keys = sorted(keys) # csvwriter = csv.DictWriter(sys.stdout, fieldnames=keys) # csvwriter.writeheader() # csvwriter.writerows(out) temp = pd.DataFrame([d]) df = df.append(temp) output_filename = path[1:] + '.csv' output_filename = output_filename.replace('/', '_') output_path = 'data/' + output_filename df.to_csv(output_path, index=False) elif fileType == 'json': for i in out: d = json.dumps(i, sort_keys=True, indent=4, separators=(',', ': ')) # json_data = json.dumps(out) json_data = json.loads(d) # print(json_data) if args.endpoint == '/position': columns = ['currentCost', 'realisedCost', 'unrealisedCost', 'posCost', 'posCost2', 'posComm', 'unrealisedGrossPnl' ] for col in columns: # if json_data[col] != None: # json_data[col] = float(json_data[col]) * 0.00000001 * bitcoin_rate pass # print(json_data) json_data_dict_list.append(json_data) else: json_data_dict_list.append(json_data) # print(json_data_dict) return json_data_dict_list else: # Shouldn't happen raise Exception('Unknown output file type.')
def run(): symbol = 'XBTUSD' max_shares = 500 key_id='6YOT6PXt7MmygYpVAD8wtaX4' secret_key='Aq-82FDxlEZMrKnsCEeHCn5TqASDxQIJEM5pRYczMrwG9z5p' baseUrl='https://www.bitmex.com/api/v1/' print(baseUrl) symbol = symbol.upper() quote = Quote() # qc = 'Q.%s' % symbol # tc = 'T.%s' % symbol position = Position() # Establish streaming connection # conn = tradeapi.StreamConn(**opts) conn = bitmex.BitMEX(base_url=baseUrl, symbol=symbol, apiKey=key_id, apiSecret=secret_key) # Define our message handling data = conn.market_depth() json_data = json.dumps(data) loaded_json = json.loads(json_data) quote.update(loaded_json) trade_data = conn.recent_trades() # if quote.traded: # return # # We've received a trade and might be ready to follow it # if ( # data.timestamp <= ( # quote.time + pd.Timedelta(np.timedelta64(50, 'ms')) # ) # ): # # The trade came too close to the quote update # # and may have been for the previous level # return for x in trade_data: if x['size'] >= 100: if (x['price'] > quote.ask and quote.bid_size > (quote.ask_size * 1.8) and (position.total_shares + position.pending_buy_shares) < max_shares - 100): # Everything looks right, so we submit our buy at the ask try: o = conn.buy(500, quote.ask) # Approximate an IOC order by immediately cancelling conn.cancel(o['orderID']) position.update_pending_buy_shares(100) position.orders_filled_amount[o['orderID']] = 0 print('Buy at', quote.ask, flush=True) quote.traded = True except Exception as e: print(e) elif (x['price'] == quote.bid and quote.ask_size > (quote.bid_size * 1.8) and (position.total_shares - position.pending_sell_shares) >= 100): # Everything looks right, so we submit our sell at the bid try: o = conn.sell(quantity=100, price=quote.bid) # Approximate an IOC order by immediately cancelling conn.cancel(o['orderID']) position.update_pending_sell_shares(100) position.orders_filled_amount[o['orderID']] = 0 print('Sell at', quote.bid, flush=True) quote.traded = True except Exception as e: print(e)