def historialVolumen(moneda): api = bitso.Api() pathname = os.path.dirname(sys.argv[0]) nombre = 'volumen_' + moneda + '.txt' trades = api.trades(moneda, limit='100') for p in reversed(trades): print p with open(pathname + "/" + nombre, 'a') as f: print >> f, p f.close() def difer(num): f2 = open(pathname + "/" + nombre, "r") line = f2.readlines() linea = line[-num] linea = re.search(r'(tid=.\d*)', linea).group() id = int(re.search(r'(\d+)', linea).group()) diferencia = trades[num - 1].tid - id #print trades[num-1].tid, id return diferencia while 1 > 0: trades = api.trades(moneda, limit='100') num = 1 with open(pathname + "/num.txt", 'a') as d: d.write(moneda + ': ' + str(difer(num)) + '\n') d.close() while difer(num) != 0: difer(num) with open(pathname + "/" + nombre, 'a') as f: f.write(str(trades[num - 1]) + '\n') f.close() num += 1 time.sleep(25)
def on_connect(self): logging.info('Websocket Connection Established') api = bitso.Api() rest_book = api.order_book('btc_mxn', aggregate=False) self.order_book = LiveOrderBook(rest_book) logging.info('Order Book Fetched. Best ask: %.4f, Best bid: %.4f, Spread: %.4f' % (self.order_book.asks.min_price, self.order_book.bids.max_price, self.order_book.asks.min_price - self.order_book.bids.max_price)) self.sequence_number = rest_book.sequence
def create_api(key=None, secret=None, get='bitso'): INFO = get_info() if not key: bitso_key = INFO[get]['key'] if not secret: bitso_secret = INFO[get]['secret'] api = bitso.Api(bitso_key, bitso_secret) return api
def __init__(self, api_key=None, secret=None): """ Constructor Params: ----- - api_key : (str) API KEY provided by Bitso - secret : (str) API SECRET provided by Bitso """ if api_key is not None and secret is not None: self.api = bitso.Api(api_key, secret) else: self.api = bitso.Api() # Show Books self.get_books() # Set True to show limits # Show Fees self.get_fees() # Show Account limits self.get_limits() # Get Balances self.get_balances()
def trade_process(): api = bitso.Api(settings.BITSO_KEY, settings.BITSO_SECRET) trade_side = redisCli.get_value_dict(my_sender_id, 'trade_side') trade_amount = parseNumber( redisCli.get_value_dict(my_sender_id, 'trade_amount')) trade_currency = redisCli.get_value_dict(my_sender_id, 'trade_currency') trade_type = redisCli.get_value_dict(my_sender_id, 'trade_type') order = None if trade_type == 'limit': trade_limit = parseNumber( redisCli.get_value_dict(my_sender_id, 'trade_limit')) if trade_side == 'buy': if trade_currency == 'xrp': major = "{0:.6f}".format(trade_amount / trade_limit) else: major = "{0:.8f}".format(trade_amount / trade_limit) elif trade_side == 'sell': major = str(trade_amount) try: order = api.place_order(book=trade_currency + '_mxn', side=trade_side, order_type=trade_type, major=major, price=str(trade_limit)) except Exception as e: bot.send(SimpleMessage(my_sender_id, "⛔ " + e.args[0]['message'])) elif trade_type == 'market': try: if trade_side == 'buy': order = api.place_order(book=trade_currency + '_mxn', side=trade_side, order_type=trade_type, minor=str(trade_amount)) elif trade_side == 'sell': order = api.place_order(book=trade_currency + '_mxn', side=trade_side, order_type=trade_type, major=str(trade_amount)) except Exception as e: bot.send(SimpleMessage(my_sender_id, "⛔ " + e.args[0]['message'])) if order: if 'oid' in order: bot.send( SimpleMessage(my_sender_id, "¡Orden exitosa! OID: " + order['oid']))
def show_open_orders(): api = bitso.Api(settings.BITSO_KEY, settings.BITSO_SECRET) order_count = 0 for currency in CURRENCIES: orders = api.open_orders(currency.lower() + '_mxn') for order in orders: order_count += 1 message = "{} {} {}, por ${} MXN a ${} MXN por {}. OID:".format( trade_dict[order.side.upper()], order.original_amount, currency, "{:,}".format(order.original_value), "{:,}".format(order.price), currency) bot.send(SimpleMessage(my_sender_id, message)) bot.send(SimpleMessage(my_sender_id, order.oid)) if order_count == 0: bot.send(SimpleMessage(my_sender_id, "No hay ordenes abiertas"))
def send_price_updates(): # #COINBASE # client = Client(settings.COINBASE_KEY, settings.COINBASE_SECRET, api_version='YYYY-MM-DD') # price_btc_usd = client.get_spot_price(currency_pair='BTC-USD') # price_eth_usd = client.get_spot_price(currency_pair='ETH-USD') # r = requests.get('https://coinmarketcap-nexuist.rhcloud.com/api/eth') # r = r.json() # ether_mxn = r['price']['mxn'] # message = "Ether mxn: {}".format(ether_mxn) # BITSO api = bitso.Api() percent_treshold = 5.0 for currency in CURRENCIES: # PRICE MXN currency_price = api.ticker(currency.lower() + '_mxn') # PRICE USD # r = requests.get('https://api.cryptonator.com/api/ticker/' + currency.lower() + '-usd') # r = r.json() #currency_price_usd = r['ticker']['price'] last_currency_percent = percentage_change(currency_price.last, 'last_' + currency.lower()) if last_currency_percent > percent_treshold: bot.send( SimpleMessage(my_sender_id, '{} {}'.format(currency, last_currency_percent))) bot.send(SimpleMessage(my_sender_id, up_gif_url, 'image')) elif last_currency_percent < (percent_treshold * -1): bot.send( SimpleMessage(my_sender_id, '{} {}'.format(currency, last_currency_percent))) bot.send(SimpleMessage(my_sender_id, down_gif_url, 'image')) redisCli.append_to_dict(my_sender_id, "saved_price_last_" + currency.lower(), currency_price.last) # currency_percent = percentage_change(currency_price.last, currency) #message = "1 {} = {} MXN | {} USD {}".format(currency, "{:,}".format(currency_price.last), "{:,.2f}".format(float(currency_price_usd)), percentage_rep(last_currency_percent)) message = "1 {} = {} MXN {}".format( currency, "{:,}".format(currency_price.last), percentage_rep(last_currency_percent)) bot.send(SimpleMessage(my_sender_id, message))
def getBitso(time): ''' This function returns the history of XRPMXN transactions on Bitso using the HTTP API. Args: time: the historical span in hours. Returns: List of XRPMXN transactions. ''' Bitso = bitso.Api() # prepare for using the paging mechanism begin = datetime.now(timezone.utc) - timedelta(hours=time) # fetch first page txs = Bitso.trades('xrp_mxn', limit=100) res = [ dict(amount=Decimal(tx.amount), type=tx.maker_side, dt=tx.created_at, price=Decimal(tx.price)) for tx in txs ] # fetch next pages until we hit the targeted historical span while len(res) > 0 and txs[-1].created_at > begin: txs = Bitso.trades('xrp_mxn', limit=100, marker=txs[-1].tid) res.extend([ dict(amount=Decimal(tx.amount), type=tx.maker_side, dt=tx.created_at, price=Decimal(tx.price)) for tx in txs ]) # sort by datetime res.sort(key=lambda x: x['dt']) return res
import bitso import datetime import decimal api = bitso.Api() def volBitso(moneda): trades = api.trades(moneda, limit='100') def transHora(trades): trades2 = [] tiempo1 = trades[0].created_at for p in trades: tiempo2 = p.created_at dif = tiempo1 - tiempo2 trades2.append(p) if dif.seconds // 3600 == 1: return trades2 def margen(trades): margen = decimal.Decimal(0.0) montoT = decimal.Decimal(0.0) for p in trades: precio = p.price monto = p.amount montoT += p.amount margen += precio * monto #return margen*decimal.Decimal(0.1), montoT #exacto #return float(margen*decimal.Decimal(0.1)), float(montoT) #aproximado return float(margen * decimal.Decimal(0.1))
def received_message(request, event, sender_id): recipient_id = event['recipient']['id'] time_of_message = event['timestamp'] message = event['message'] print "Received message for user {} and page {} at {} with message:".format( my_sender_id, recipient_id, time_of_message) # print repr(message) command = None if "quick_reply" in message: command = message['quick_reply']['payload'] elif 'text' in message: command = message['text'] message_attachments = message[ 'attachments'] if 'attachments' in message else None step = redisCli.get_value_dict(my_sender_id, 'step') if command: if parseNumber(command) and step == "1": redisCli.append_to_dict(my_sender_id, "trade_amount", command) redisCli.append_to_dict(my_sender_id, "step", "2") trade_side = redisCli.get_value_dict(my_sender_id, 'trade_side') trade_currency = redisCli.get_value_dict(my_sender_id, 'trade_currency') api = bitso.Api() currency_price = api.ticker(trade_currency + '_mxn') bot.send( StructuredMessage( my_sender_id, StructuredMessage.TYPE_BUTTON, { 'text': "¿A que precio quieres " + trade_dict[trade_side.upper()] + " " + trade_currency.upper() + "?" + ". El precio actual es de " + '{:,}'.format(currency_price.last) + " MXN", 'buttons': [ MessageButton( MessageButton.TYPE_POSTBACK, 'Fijar precio de ' + trade_currency.upper(), 'LIMIT'), MessageButton(MessageButton.TYPE_POSTBACK, 'Precio de mercado', 'MARKET'), ] })) elif command.isdigit() and step == "3": redisCli.append_to_dict(my_sender_id, "trade_limit", command) trade_side = redisCli.get_value_dict(my_sender_id, 'trade_side') trade_amount = parseNumber( redisCli.get_value_dict(my_sender_id, 'trade_amount')) trade_currency = redisCli.get_value_dict(my_sender_id, 'trade_currency') trade_limit = parseNumber( redisCli.get_value_dict(my_sender_id, 'trade_limit')) cur_format = "" if trade_side == 'buy': cur_format = "${} MXN de ".format("{:,}".format( float(trade_amount))) elif trade_side == 'sell': cur_format = "{:,}".format(float(trade_amount)) confirmation_msg = "Estas a punto de {} {} {} cuando tenga un valor de ${} MXN. ¿Estas seguro?".format( trade_dict[trade_side.upper()], cur_format, trade_currency.upper(), "{:,}".format(int(trade_limit))) bot.send( QuickReplay(my_sender_id, confirmation_msg, [ ButtonReplay('✅ Si, seguro 😎', 'TRADE_CONFIRMATION'), ButtonReplay('❌ Nooooo 😱', 'TRADE_CANCEL') ])) redisCli.append_to_dict(my_sender_id, "step", "4") elif command == 'TRADE_CONFIRMATION' and step == '4': if sender_id == my_sender_id: trade_process() redisCli.delete(my_sender_id) elif command == 'TRADE_CANCEL': redisCli.delete(my_sender_id) bot.send(SimpleMessage(my_sender_id, "Operación cancelada")) elif step == "10": api = bitso.Api(settings.BITSO_KEY, settings.BITSO_SECRET) if api.cancel_order(command): bot.send( SimpleMessage(my_sender_id, "Orden cancelada exitosamente")) else: bot.send( SimpleMessage(my_sender_id, "La orden ingresada no existe")) redisCli.append_to_dict(my_sender_id, "step", "0") else: #bot.send(SenderAction(my_sender_id, SenderAction.TYPING_ON)) #bot.send(SimpleMessage(my_sender_id, "command")) print "success" elif message_attachments: bot.send(SimpleMessage(my_sender_id, "Message with attachment"))
import bitso from secrets import bitso_api_key, bitso_api_secret api = bitso.Api(bitso_api_key, bitso_api_secret) def get_balance_mxn(): balances = api.balances() mxn_available = float(balances.mxn.available) return mxn_available def get_risk_level(): risk_level = input( "What level of risk are you comfortable with? high, medium, or low") if risk_level.lower( ) == "high" or "medium" or "low" or " high" or " medium" or " low": return risk_level else: get_risk_level() def place_order(mxn_available, risk_level): if risk_level == "high": btc_to_buy = str(int(mxn_available)) order = api.place_order(book='btc_mxn', side='buy', order_type='market', minor=btc_to_buy) elif risk_level == "medium": btc_to_buy = str(int(mxn_available * 0.5))
def setUp(self): self.api = bitso.Api('key', 'secret')
logging.basicConfig(filename='logs.log', level=logging.ERROR) tauros_key = settings.TAUR_API_KEY tauros_secret = settings.TAUR_API_SECRET is_production = settings.ENVIRONMENT == 'prod' if not tauros_key or not tauros_secret: raise ValueError('Tauros credentials not fund') tauros = TaurosPrivate(key=tauros_key, secret=tauros_secret, prod=is_production) tauros_public = TaurosPublic(prod=is_production) bisto_api = bitso.Api() def close_all_orders(): ''' This function queries all open orders in tauros and closes them. ''' open_orders = tauros.get_orders() if not open_orders['success']: logging.error( f'Querying open orders fail. Error: {open_orders["msg"]}') return orders_ids = [order['order_id'] for order in open_orders['data']] logging.info(f'Open orders: {orders_ids}') orders_closed = 0
print("7) Cancelar ordenes pendientes.") print("8) Meter orden a mano") print("9) Ver indicadores economicos") print("r) Refrescar datos") print("\n0) Salir") return input("? >").strip().lower() # --- inicio # arrancar la api de bitso con las keys secretas api = None try: api = bitso.Api(krono_bot_config.BITSO_API_KEY, krono_bot_config.BITSO_API_SECRET) status = api.account_status() print("Status cuenta:", status.status) except Exception as e: print("ERROR: no puedo obtener status de cuenta. Fin\n", e) exit() # parametros del trade use_book = '' # libro a usar cant_exchange_max = 0 # cantidad a cambiar de la moneda origen # ------ loop principal ------ opt = show_menu(api) while not opt == '0': ok_trade = False # proceder con el trade?
# -*- coding: cp1252 -*- #Gridso bot for grid trading v.1.0.1 #1.0.1 Update Notes: *Added first sell limit when starting the bot import bitso import time api = bitso.Api('your public key', 'your private key') starttime = time.time() #Tomar valor de la moneda una vez def start_ticker(crypto): tick = api.ticker(crypto) return tick #Pone una orden limit-Long def long_limit(quantity_crypto, price_to_long, crypto): order = api.place_order(book=crypto, side='buy', order_type='limit', major=quantity_crypto, price=price_to_long) #Orden limit-short def short_limit(quantity_crypto, price_to_short, crypto): order = api.place_order(book=crypto, side='sell', order_type='limit',
def setUp(self): self.api = bitso.Api()
''' Sencillo programilla ejemplo para adquirir los precios de Bitso para: Bitcoin, Etherium, Ripple y BTC Cash para luego agregarlos a una spreadsheet en Google Drive ''' import time import bitso import gspread from oauth2client.service_account import ServiceAccountCredentials import ticker_bitso as tick import spreadsheet_api as ss # Inicializamos la API de Bitso bitso = bitso.Api() # use creds to create a client to interact with the Google Drive API scope = ['https://spreadsheets.google.com/feeds'] creds = ServiceAccountCredentials.from_json_keyfile_name( 'client_secret.json', scope) client = gspread.authorize(creds) # Nombre de la spreadsheet en Google Drive Historical = client.open("Historical Bitso") # Sacamos todas las worksheets y valores de Bitso WS = ss.get_all_worksheets(Historical) Values = tick.get_all(bitso) # Insertamos todos los valores nuevos for x in range(0, 4): ss.insert_values(WS[x], Values[x])
def received_postback(request, event, sender_id): recipient_id = event['recipient']['id'] time_of_message = event['timestamp'] postback = event['postback'] payload = postback['payload'] print "Received postback for user {} and page {} at {} with payload: {}".format( my_sender_id, recipient_id, time_of_message, payload) if payload == 'GET_STARTED': send_price_updates() elif payload == 'SHOW_OPEN_ORDERS': show_open_orders() elif payload == 'CANCEL_ORDER': bot.send( SimpleMessage(my_sender_id, "Ingresa el ID de la orden que deseas cancelar")) redisCli.append_to_dict(my_sender_id, "step", "10") elif payload == 'TRADE': bot.send( StructuredMessage( my_sender_id, StructuredMessage.TYPE_BUTTON, { 'text': "¿Qué quieres hacer?", 'buttons': [ MessageButton(MessageButton.TYPE_POSTBACK, 'Comprar', 'BUY'), MessageButton(MessageButton.TYPE_POSTBACK, 'Vender', 'SELL'), ] })) elif payload in ['BUY', 'SELL']: redisCli.append_to_dict(my_sender_id, "trade_side", payload.lower()) bot.send( StructuredMessage( my_sender_id, StructuredMessage.TYPE_BUTTON, { 'text': "¿Qué moneda quieres " + trade_dict[payload] + "?", 'buttons': [ MessageButton(MessageButton.TYPE_POSTBACK, 'Bitcoin', 'BTC'), MessageButton(MessageButton.TYPE_POSTBACK, 'Ether', 'ETH'), MessageButton(MessageButton.TYPE_POSTBACK, 'Ripple', 'XRP'), ] })) elif payload in CURRENCIES: redisCli.append_to_dict(my_sender_id, "trade_currency", payload.lower()) redisCli.append_to_dict(my_sender_id, "step", "1") trade_side = redisCli.get_value_dict(my_sender_id, 'trade_side') api = bitso.Api(settings.BITSO_KEY, settings.BITSO_SECRET) balances = api.balances() balance = None print trade_side cur = 'MXN' if trade_side == 'buy': balance = balances.mxn.available else: cur = payload if payload == 'BTC': balance = balances.btc.available elif payload == 'ETH': balance = balances.eth.available elif payload == 'XRP': balance = balances.xrp.available bot.send( SimpleMessage( my_sender_id, "¿Cuanto " + payload + " quieres " + trade_dict[trade_side.upper()] + "?")) bot.send( SimpleMessage( my_sender_id, "Ingresa el monto en " + cur + ", \nSaldo en " + cur + ": ")) if balance: bot.send(SimpleMessage(my_sender_id, str(balance))) elif payload in ['LIMIT', 'MARKET']: redisCli.append_to_dict(my_sender_id, "trade_type", payload.lower()) trade_currency = redisCli.get_value_dict(my_sender_id, 'trade_currency') trade_side = redisCli.get_value_dict(my_sender_id, 'trade_side') trade_amount = parseNumber( redisCli.get_value_dict(my_sender_id, 'trade_amount')) if payload == 'LIMIT': bot.send( SimpleMessage( my_sender_id, "Ingresa el precio en pesos que debe alcanzar el " + trade_currency.upper() + " para " + trade_dict[trade_side.upper()])) redisCli.append_to_dict(my_sender_id, "step", "3") elif payload == 'MARKET': cur_format = "" if trade_side == 'buy': cur_format = "${} MXN de ".format("{:,}".format( float(trade_amount))) elif trade_side == 'sell': cur_format = "{:,}".format(float(trade_amount)) confirmation_msg = "Estas a punto de {} {} {} a precio de mercado. ¿Estas seguro?".format( trade_dict[trade_side.upper()], cur_format, trade_currency.upper()) bot.send( QuickReplay(my_sender_id, confirmation_msg, [ ButtonReplay('✅ Si, seguro 😎', 'TRADE_CONFIRMATION'), ButtonReplay('❌ Nooooo 😱', 'TRADE_CANCEL') ])) redisCli.append_to_dict(my_sender_id, "step", "4") else: print "no action"
def try_this(comando): sigue = True count = 0 while (sigue == True): try: return eval(comando) except: print('fallo: ' + comando) count = count + 1 if count > 10: sigue = False api = bitso.Api(API_KEY, API_SECRET) transcurrido = 30 #Tienen que transcurrir 30 seg para hacer una accion count = 0 while (True): if (transcurrido >= 29): transcurrido = 0 scope = ['https://spreadsheets.google.com/feeds'] creds = ServiceAccountCredentials.from_json_keyfile_name( 'client_secret.json', scope) client = try_this('gspread.authorize(creds)') Historical = client.open("Historical Bitso") #BTC = Historical.get_worksheet(0) #ETH = Historical.get_worksheet(1)
#---------------------------- def BalanceUpdate(privObj): bal = privObj.balances() mxnDis = bal.mxn.available xrpDis = bal.xrp.available print('balance disponible MXN %.2f \n balance disponible XRP %.2f ' % (mxnDis, xrpDis)) return mxnDis, xrpDis #Iniciar Api Bitso in clock try: #print('Priv') priv = bitso.Api('INCYsSeZSY', '2a729f941e968974ae12c9ec324f2bb2') #profitAfterLose(priv,'xrp_mxn','desc',True) except ApiError as error: restart(error) try: #print('Api') api = bitso.Api() except ApiError as error: restart(error) try: while True: ii += 1