def test_get_buys(self): client = Client(api_key, api_secret) buys = client.get_buys('foo') self.assertIsInstance(buys, APIObject) self.assertEqual(buys.data, mock_collection) for buy in buys.data: self.assertIsInstance(buy, Buy)
def test_get_checkouts(self): client = Client(api_key, api_secret) checkouts = client.get_checkouts() self.assertIsInstance(checkouts, APIObject) self.assertEqual(checkouts.data, mock_collection) for checkout in checkouts.data: self.assertIsInstance(checkout, Checkout)
def test_get_payment_methods(self): client = Client(api_key, api_secret) payment_methods = client.get_payment_methods() self.assertIsInstance(payment_methods, APIObject) self.assertEqual(payment_methods.data, mock_collection) for payment_method in payment_methods.data: self.assertIsInstance(payment_method, PaymentMethod)
def test_get_deposits(self): client = Client(api_key, api_secret) deposits = client.get_deposits('foo') self.assertIsInstance(deposits, APIObject) self.assertEqual(deposits.data, mock_collection) for deposit in deposits.data: self.assertIsInstance(deposit, Deposit)
def test_get_sells(self): client = Client(api_key, api_secret) sells = client.get_sells('foo') self.assertIsInstance(sells, APIObject) self.assertEqual(sells.data, mock_collection) for sell in sells.data: self.assertIsInstance(sell, Sell)
def test_get_reports(self): client = Client(api_key, api_secret) reports = client.get_reports() self.assertIsInstance(reports, APIObject) self.assertEqual(reports.data, mock_collection) for report in reports.data: self.assertIsInstance(report, Report)
def test_get_checkout_orders(self): client = Client(api_key, api_secret) orders = client.get_checkout_orders('foo') self.assertIsInstance(orders, APIObject) self.assertEqual(orders.data, mock_collection) for order in orders.data: self.assertIsInstance(order, Order)
def test_get_addresses(self): client = Client(api_key, api_secret) addresses = client.get_addresses('foo') self.assertIsInstance(addresses, APIObject) self.assertEqual(addresses.data, mock_collection) for address in addresses.data: self.assertIsInstance(address, Address)
def test_get_transactions(self): client = Client(api_key, api_secret) transactions = client.get_transactions('foo') self.assertIsInstance(transactions, APIObject) self.assertEqual(transactions.data, mock_collection) for transaction in transactions.data: self.assertIsInstance(transaction, Transaction)
def test_get_accounts(self): client = Client(api_key, api_secret) accounts = client.get_accounts() self.assertIsInstance(accounts, APIObject) self.assertEqual(accounts.data, mock_collection) for account in accounts.data: self.assertIsInstance(account, Account)
def test_base_api_uri_used_instead_of_default(self): # Requests to the default BASE_API_URI will noticeably fail by raising an # AssertionError. Requests to the new URL will respond HTTP 200. new_base_api_uri = 'http://example.com/api/v1/' # If any error is raised by the server, the test suite will never exit when # using Python 3. This strange technique is used to raise the errors # outside of the mocked server environment. errors_in_server = [] def server_response(request, uri, headers): try: self.assertEqual(uri, new_base_api_uri) except AssertionError as e: errors_in_server.append(e) return (200, headers, "") hp.register_uri(hp.GET, Client.BASE_API_URI, body=server_response) hp.register_uri(hp.GET, new_base_api_uri, body=server_response) client2 = Client(api_key, api_secret, new_base_api_uri) self.assertEqual(client2._get().status_code, 200) client = Client(api_key, api_secret) with self.assertRaises(AssertionError): client._get() if errors_in_server: raise errors_in_server.pop()
def test_request_helper_automatically_encodes_data(self): client = Client(api_key, api_secret) def server_response(request, uri, headers): self.assertIsInstance(request.body, six.binary_type) return 200, headers, '{}' hp.register_uri(hp.POST, re.compile('.*foo$'), server_response) self.assertEqual(client._post('foo', data={'name': 'example'}).status_code, 200)
def test_get_withdrawals(self): client = Client(api_key, api_secret) withdrawals = client.get_withdrawals('foo') self.assertIsInstance(withdrawals, APIObject) self.assertEqual(withdrawals.data, mock_collection) for withdrawal in withdrawals.data: self.assertIsInstance(withdrawal, Withdrawal)
def verifyCallbackAuthenticity(request): """https://github.com/coinbase/coinbase-python#merchant-callbacks verify_callback() IS BROKEN! See https://github.com/drandreaskrueger/coinbaseTestbed/blob/master/bugs/verify_callback()_False.md """ try: client = Client(API_KEY, API_SECRET, base_api_uri=API_BACKEND_URL) # verify=client.verify_callback(request.body, request.META['X-Signature']) print "request.body:" print request.body print "request.META:" print request.META print request.META.keys() verify=client.verify_callback(request.body, request.META['HTTP_CB_SIGNATURE']) except Exception as e: print "verify_callback EXCEPTION: ", type(e), e return False return verify
def test_sell(self): client = Client(api_key, api_secret) with self.assertRaises(ValueError): client.sell('foo') for valid_kwargs in [{'amount': '1.0'}, {'total': '1.0'}]: sell = client.sell('foo', **valid_kwargs) self.assertIsInstance(sell, Sell) self.assertEqual(sell, mock_item)
def test_buy(self): client = Client(api_key, api_secret) with self.assertRaises(ValueError): client.buy('foo') for valid_kwargs in [{'amount': '1.0'}, {'total': '1.0'}]: buy = client.buy('foo', **valid_kwargs) self.assertIsInstance(buy, Buy) self.assertEqual(buy, mock_item)
class Trader(threading.Thread): def __init__(self, api_key, api_secret, alpha=0.5): assert 0 < alpha <= 1.0 # smoothing factor for the exponential moving avg function super(threading.Thread, self).__init__() self.alpha = alpha self.client = Client(api_key, api_secret) self.user = self.client.get_current_user() self.buys = [] self.sells = [] print 'Trading As: %s (%s)' % (self.user['name'], self.user['email']) print 'Starting Balance: $%s (%s BTC @ $%s/BTC)' % (self.balance['USD'], self.balance['BTC'], self.get_price()) @property def account(self): return [acct for acct in self.client.get_accounts()['data'] if acct['balance']['currency'] == 'BTC'][0] @property def balance(self): return { self.account['balance']['currency']: float(self.account['balance']['amount']), self.account['native_balance']['currency']: float(self.account['native_balance']['amount']), } def get_price(self): return float(self.client.get_spot_price()['amount']) def buy(self, amount): buy_obj = self.account.buy(amount, 'USD') self.buys.append(buy_obj) def sell(self, amount): sell_obj = self.account.sell(amount, 'USD') self.sells.append(sell_obj) def analyze(self): for idx, buy in enumerate(self.buys): if self.get_price() > buy['price'] + market_fees + min_profit_margin: self.buys.pop(idx) self.sell(buy['amount']) # if price rises above buy price + market fees by a certain amount, sell early and reap the tiny profits elif self.get_price() < buy['price']: self.buys.pop(idx) self.sell(buy['amount']) # if price drops below the price it was bought at, sell immediately to minimize losses else: pass # do nothing until the price fluctuates enough to make more of a difference for idx, sell in enumerate(self.sells): if self.get_price() > sell['price']: self.sells.pop(idx) self.buy(sell['amount']) # if price starts to rise above the amount we sold it for, rebuy the same amount else: # if market trends downwards we'll lose (number of transactions * (market fee per transaction + min profit margin)) pass # price is below the amount we sold for, don't do anything until it's passing break-even again def run(self): self.keep_running = True while self.keep_running: self.analyze()
def get_coinbase(key, secret): """Get balance from coinbase exchange API.""" client = Client(key, secret) accounts = client.get_accounts() df = pd.DataFrame([row.balance for row in accounts.data]) df['source'] = 'coinbase' df.columns = ['balance', 'coin', 'source'] data.append(df)
def verify_callback(body, headers, dbg=False): """ Verifies that the body is correctly signed, with 'coinbase-callback.pub' public key See 'verify_callback()_False.md' """ if dbg: print headers['Cb-Signature'] if dbg: print body client = Client(API_KEY, API_SECRET, base_api_uri=API_BACKEND_URL) return client.verify_callback(body, headers['Cb-Signature'])
def cbCheckoutUrl(webhook, amount="0.000101", currency="BTC", dbg=True): """get payment URL from coinbase""" client = Client(API_KEY, API_SECRET, base_api_uri=API_BACKEND_URL) parameters={"amount": amount, "currency": currency, "name": "test", "notifications_url" : webhook } checkout = client.create_checkout(**parameters) embed_code=checkout["embed_code"] # print embed_code payment_url='%s/checkouts/%s' % (API_FRONTEND_URL, embed_code) if dbg: print "checkout created, with notifications_url=%s" % webhook return payment_url
def test_buy(self): client = Client(api_key, api_secret) with self.assertRaises(ValueError): client.buy('foo') kwargs_list = [ {'amount': '1.0', 'payment_method': 'bar', 'currency': 'USD'}, {'total': '1.0', 'payment_method': 'bar', 'currency': 'USD'} ] for valid_kwargs in kwargs_list: buy = client.buy('foo', **valid_kwargs) self.assertIsInstance(buy, Buy) self.assertEqual(buy, mock_item)
def connectAndGetPrimaryAccount(): from coinbase.wallet.client import Client SANDBOX_URL = 'https://api.sandbox.coinbase.com' client = Client(API_KEY, API_SECRET, base_api_uri=SANDBOX_URL) print "\nGet your primary coinbase account:", primary_account = client.get_primary_account() print type(primary_account), primary_account["id"] return primary_account
def test_request_includes_auth_headers(self): client = Client(api_key, api_secret) def server_response(request, uri, response_headers): keys = [ 'CB-VERSION', 'CB-ACCESS-KEY', 'CB-ACCESS-SIGN', 'CB-ACCESS-TIMESTAMP', 'Accept', 'Content-Type', 'User-Agent'] for key in keys: self.assertIn(key, request.headers) self.assertNotEqual(request.headers[key], '') return 200, response_headers, '{}' hp.register_uri(hp.GET, re.compile('.*test$'), server_response) self.assertEqual(client._get('test').status_code, 200)
def test_response_handling(self): client = Client(api_key, api_secret) # Check that 2XX responses always return the response error_response = { 'errors': [{ 'id': 'fakeid', 'message': 'some error message', }], 'data': mock_item, } error_str = json.dumps(error_response) for code in [200, 201, 204]: hp.register_uri( hp.GET, re.compile('.*' + str(code) + '$'), lambda r, u, h: (code, h, error_str)) response = client._get(str(code)) self.assertEqual(response.status_code, code) # Check that when the error data is in the response, that's what is used. import coinbase.wallet.error for eid, eclass in six.iteritems( coinbase.wallet.error._error_id_to_class): error_response = { 'errors': [{ 'id': eid, 'message': 'some message', }], 'data': mock_item, } error_str = json.dumps(error_response) hp.reset() hp.register_uri( hp.GET, re.compile('.*test$'), lambda r, u, h: (400, h, error_str)) with self.assertRaises(eclass): client._get('test') # Check that when the error data is missing, the status code is used # instead. error_response = {'data': mock_item} for code, eclass in six.iteritems( coinbase.wallet.error._status_code_to_class): hp.reset() hp.register_uri( hp.GET, re.compile('.*test$'), lambda r, u, h: (code, h, json.dumps(error_response))) with self.assertRaises(eclass): client._get('test') # Check that when the response code / error id is unrecognized, a generic # APIError is returned hp.reset() hp.register_uri(hp.GET, re.compile('.*test$'), lambda r, u, h: (418, h, '{}')) with self.assertRaises(APIError): client._get('test')
def test_withdraw(self): client = Client(api_key, api_secret) # Start with none of the required arguments, and slowly make requests with # an additional required argument, expecting failure until all arguments # are present. send_kwargs = {} required_kwargs = {'payment_method': 'bar', 'amount': '1.0', 'currency': 'USD'} while required_kwargs: with self.assertRaises(ValueError): client.withdraw('foo', **send_kwargs) for key in required_kwargs: send_kwargs[key] = required_kwargs.pop(key) break withdrawal = client.withdraw('foo', **send_kwargs) self.assertIsInstance(withdrawal, Withdrawal) self.assertEqual(withdrawal, mock_item)
def test_create_checkout(self): client = Client(api_key, api_secret) # Start with none of the required arguments, and slowly make requests with # an additional required argument, expecting failure until all arguments # are present. send_kwargs = {} required_kwargs = {'name': 'bar', 'amount': '1.0', 'currency': 'USD'} while required_kwargs: with self.assertRaises(ValueError): client.create_checkout(**send_kwargs) for key in required_kwargs: send_kwargs[key] = required_kwargs.pop(key) break checkout = client.create_checkout(**send_kwargs) self.assertIsInstance(checkout, Checkout) self.assertEqual(checkout, mock_item)
def test_auth_succeeds_with_bytes_and_unicode(self): api_key = 'key' api_secret = 'secret' self.assertIsInstance(api_key, six.text_type) # Unicode self.assertIsInstance(api_secret, six.text_type) # Unicode client = Client(api_key, api_secret) self.assertEqual(client._get('test').status_code, 200) api_key = api_key.encode('utf-8') api_secret = api_secret.encode('utf-8') self.assertIsInstance(api_key, six.binary_type) # Bytes self.assertIsInstance(api_secret, six.binary_type) # Bytes client = Client(api_key, api_secret) self.assertEqual(client._get('test').status_code, 200)
def test_refund_order(self): client = Client(api_key, api_secret) # Start with none of the required arguments, and slowly make requests with # an additional required argument, expecting failure until all arguments # are present. send_kwargs = {} required_kwargs = {'currency': 'USD'} while required_kwargs: with self.assertRaises(ValueError): client.refund_order('foo', **send_kwargs) for key in required_kwargs: send_kwargs[key] = required_kwargs.pop(key) break order = client.refund_order('foo', **send_kwargs) self.assertIsInstance(order, Order) self.assertEqual(order, mock_item)
def test_transfer_money(self): client = Client(api_key, api_secret) # Start with none of the required arguments, and slowly make requests with # an additional required argument, expecting failure until all arguments # are present. send_kwargs = {} required_kwargs = {'to': 'bar', 'amount': '1.0', 'currency': 'USD'} while required_kwargs: with self.assertRaises(ValueError): transaction = client.transfer_money('foo', **send_kwargs) for key in required_kwargs: send_kwargs[key] = required_kwargs.pop(key) break transaction = client.transfer_money('foo', **send_kwargs) self.assertIsInstance(transaction, Transaction) self.assertEqual(transaction, mock_item)
class CoinbaseData: """Get the latest data and update the states.""" def __init__(self, api_key, api_secret): """Init the coinbase data object.""" from coinbase.wallet.client import Client self.client = Client(api_key, api_secret) self.update() @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from coinbase.""" from coinbase.wallet.error import AuthenticationError try: self.accounts = self.client.get_accounts() self.exchange_rates = self.client.get_exchange_rates() except AuthenticationError as coinbase_error: _LOGGER.error("Authentication error connecting" " to coinbase: %s", coinbase_error)
#!/usr/bin/env python from dot3k import backlight api_key = 'REPLACE' api_secret = 'REPLACE' # blue, use (255,0,0) for red, (0,0,255) for green backlight.rgb(0, 255, 0) currency_code = 'USD' # EUR / any currency code # don't change below that line # ---------------------------------------------------------- from coinbase.wallet.client import Client client = Client(api_key, api_secret) client.get_exchange_rates() bitcoinPrice = client.get_spot_price(currency=currency_code) ethereumPrice = client.get_spot_price(currency_pair= 'ETH-USD') # clear LCD import dothat.lcd as lcd lcd.clear() # first line lcd.set_cursor_position(0, 0) import datetime datetime.datetime.now() dateTimeNow = (datetime.datetime.now()) from time import gmtime, strftime
import coinbase as cb from coinbase.wallet.client import Client import json API_KEY = '' # your API key API_SECRET = '' # your API secret client = Client(API_KEY, API_SECRET) user = client.get_current_user() user_as_json_string = json.dumps(user) def get_account_balance(client, ifUSD=True): all_accounts_dict = json.loads(json.dumps(client.get_accounts())) cleaned_accounts_json_string = json.dumps(all_accounts_dict['data']) cleaned_accounts_dict = json.loads(cleaned_accounts_json_string) num_of_accounts = len(cleaned_accounts_dict) res = {} if ifUSD: for a in range(num_of_accounts): res.update({ cleaned_accounts_dict[a].get('balance').get('currency') + str(' in USD'): cleaned_accounts_dict[a].get('native_balance').get('amount') }) else: for a in range(num_of_accounts): res.update({ cleaned_accounts_dict[a].get('balance').get('currency'): cleaned_accounts_dict[a].get('balance').get('amount') }) return res
def connectClient(): return Client(constants.api_key, constants.api_secret)
from __future__ import absolute_import, unicode_literals import operator from decimal import Decimal from django.conf import settings from alerts.celery import app from coinbase.wallet.client import Client from alerts.models import Alerts from alerts.enums.operator import OPERATOR, EQ, GT, GTE, LT, LTE from .utils import send_alert_email client = Client(settings.COINBASE_API_KEY, settings.COINBASE_API_KEY) @app.task(name='periodically_check_bitcoin_price') def periodically_check_bitcoin_price(): data_btc = client.get_buy_price(currency_pair='BTC-USD') price_btc = Decimal(data_btc['amount']) # Get alerts which are not sent yet alerts = Alerts.objects.filter(sent_at__isnull=True).only('price', 'operator', 'created_by',) for alert in alerts: alert_price = Decimal(alert.price) alert_operator = alert.operator compare_function = { EQ: operator.eq, GT: operator.gt, GTE: operator.ge, LT: operator.lt, LTE: operator.le,
CheckBalance = input("Enter Your Bitcoin Address: ") print("Your Balance Details \n") print(get_address_overview(CheckBalance)) #Hashing Address if answer == "6": print("Enter Your Bitcoin Address") WalletAddress = input() Hashed = txhash(WalletAddress) print(Hashed) # Sending Bitcoins if answer == "7": client = Client('Your API KEY', 'Your Secret Key') tx = client.send_money('2bbf394c-193b-5b2a-9155-3b4732659ede', to='1AUJ8z5RuHRTqD1eikyfUUetzGmdWLGkpT', amount='0.1', currency='BTC', idem='9316dd16-0c05') # Pushing Transactions to Email if answer == "8": HexTransaction = input("Insert your raw transaction: ") #example: 0100000001fd468e431cf5797b108e4d22724e1e055b3ecec59af4ef17b063afd36d3c5cf6010000008c4930460221009918eee8be186035be8ca573b7a4ef7bc672c59430785e5390cc375329a2099702210085b86387e3e15d68c847a1bdf786ed0fdbc87ab3b7c224f3c5490ac19ff4e756014104fe2cfcf0733e559cbf28d7b1489a673c0d7d6de8470d7ff3b272e7221afb051b777b5f879dd6a8908f459f950650319f0e83a5cf1d7c1dfadf6458f09a84ba80ffffffff01185d2033000000001976a9144be9a6a5f6fb75765145d9c54f1a4929e407d2ec88ac00000000 pushtx.pushtx(HexTransaction) #Sending info to Email
def test_get_transaction(self): client = Client(api_key, api_secret) account = new_api_object(client, mock_account, Account) transaction = account.get_transaction('bar') self.assertIsInstance(transaction, Transaction) self.assertEqual(transaction, mock_item)
def test_commit_buy(self): client = Client(api_key, api_secret) account = new_api_object(client, mock_account, Account) buy = account.commit_buy('bar') self.assertIsInstance(buy, Buy) self.assertEqual(buy, mock_item)
from coinbase.wallet.client import Client import time from elasticsearch import Elasticsearch from datetime import datetime # GitPython # python-dateutil # https://elasticsearch-py.readthedocs.io/en/master/ # https://docs.objectrocket.com/elastic_python_examples.html INDEX = 'coinbase' DOC_TYPE = 'rates' client = Client("zhtXa1PEK0J6tzZ2", "pS9sqBNMAWVLfJWGXk36wLuCb1OMQnIF") rates = client.get_exchange_rates(currency='BTC') rates['time'] = time.time() print(rates) es = Elasticsearch( ['192.168.1.7'], scheme="http", port=9200 ) res = es.index(index=INDEX, doc_type=DOC_TYPE, body=rates) print(res)
class RoyTrader(): client = Client(api_key, api_secret) user = client.get_current_user() account = client.get_accounts() #tbuys = client.get_buys() buys = [] sells = [] prices = [] signals = [] args = [] transactions_plot = [] fibo = BotIndicators() buy_count = 0 #print(account) print ('Trading As: %s (%s)' % (user['name'], user['email'])) #print ('Starting Balance: $%s (%s BTC @ $%s/BTC)' % (balance['EUR'], balance['BTC'], self.get_price())) print (account) def __init__(self, api_key, api_secret): #coinbase #poloniex self.startTrading() def startTrading(self): #prices = [] currentMovingAverage = 0; startTime = False endTime = False historicalData = False tradePlaced = False typeOfTrade = False dataDate = "" orderNumber = "" market_fees = 0.15 # coinbase per-transaction fee in dollars min_profit_margin = 2.0 # minimum price increase before we sell out MACD = 0 if webserver: try: WebServer.initialize_web_server() except Exception as e: raise e finally: WebServer.stop_web_server() idloop = 0 #self.sync_buys_sells_operations() while True: try: if idloop < lengthOfMA: idloop = idloop + 1 if strategy == "RSI": self.classic_strategy() elif strategy == "MACD": self.MACD_Strategy() elif strategy == "combined": self.MACD_RSI_Strategy(idloop) time.sleep(int(period)) except KeyboardInterrupt: print("Bye") if webserver: WebServer.stop_web_server() sys.exit() def MACD_Strategy(self): vectorEMAS_AMAF_MACD = [] MACD = 0 MACD_point = 0 RSI_point = 0 #lastprice = self.get_price(pair) lastprice = self.get_sell_price(pair) # use sell price instead of spot_price for more precise value buyprice = self.get_buy_price(pair) sellprice = self.get_sell_price(pair) currentMovingAverage = 0 previousPrice = 0 emaSlow = 0 emaFast = 0 dataDate = datetime.datetime.now().strftime('%H:%M:%S') if len(self.args)>1: currentMovingAverage = sum(self.prices) / float(len(self.prices)) appendLine = datetime.datetime.now(),lastprice,buyprice,sellprice,previousPrice, 2 self.args.append(appendLine) self.prices.append(float(lastprice)) if len(self.args) > 26: vectorEMAS_AMAF_MACD = self.fibo.MACD(self.prices) emaSlow = vectorEMAS_AMAF_MACD[0] emaFast = vectorEMAS_AMAF_MACD[1] MACD = vectorEMAS_AMAF_MACD[2] MACD_point = MACD[-1] RSI = self.fibo.rsiFunc(self.prices) RSI_point = RSI[-1] print ("Date: ",str(dataDate)," Pair: ",str(pair)," Price: ",str(lastprice)," BUY: ", buyprice, "SELL: ", sellprice ," EMA: ",str(currentMovingAverage)," MACD: ",str(MACD_point), " RSI: ", RSI_point) if len(self.args) > 27: transactions_plot = self.findSignals_MACD(self.args, RSI, MACD) if graphical: self.fibo.plot3(self.args, self.prices, self.signals,emaSlow, emaFast, MACD, RSI, transactions_plot) if len(self.args) == lengthOfMA: self.prices.pop(0) self.args.pop(0) #if len(self.signals) > int(ignore_signals_after): #self.signals.pop(0) #print("************************** SIGNALS POPPED *******************************" ) if len(self.signals) > 0 and len(self.args) > ignore_signals_after and self.signals[0][0] < self.args[-(ignore_signals_after)][0]: self.signals.pop(0) print("************************** SIGNALS POPPED *******************************" ) def MACD_RSI_Strategy(self, idloop): vectorEMAS_AMAF_MACD = [] MACD = 0 MACD_point = 0 RSI_point = 0 #lastprice = self.get_price(pair) lastprice = self.get_sell_price(pair) # use sell price instead of spot_price for more precise value buyprice = self.get_buy_price(pair) sellprice = self.get_sell_price(pair) currentMovingAverage = 0 previousPrice = 0 emaSlow = 0 emaFast = 0 dataDate = datetime.datetime.now().strftime('%H:%M:%S') if len(self.args)>1: currentMovingAverage = sum(self.prices) / float(len(self.prices)) appendLine = datetime.datetime.now(),lastprice,buyprice,sellprice,previousPrice, 2 self.args.append(appendLine) self.prices.append(float(lastprice)) if len(self.args) > 26: vectorEMAS_AMAF_MACD = self.fibo.MACD(self.prices) emaSlow = vectorEMAS_AMAF_MACD[0] emaFast = vectorEMAS_AMAF_MACD[1] MACD = vectorEMAS_AMAF_MACD[2] MACD_point = MACD[-1] RSI = self.fibo.rsiFunc(self.prices) RSI_point = RSI[-1] print ("Date: ",str(dataDate)," Pair: ",str(pair)," Price: ",str(lastprice)," BUY: ", buyprice, "SELL: ", sellprice ," EMA: ",str(currentMovingAverage)," MACD: ",str(MACD_point), " RSI: ", RSI_point) if len(self.args) > 27: transactions_plot = self.findSignals_MACD_RSI(self.args, RSI, MACD) if graphical: self.fibo.plot3(self.args, self.prices, self.signals,emaSlow, emaFast, MACD, RSI, transactions_plot) if len(self.args) == lengthOfMA: self.prices.pop(0) self.args.pop(0) #if len(self.signals) > int(ignore_signals_after): #self.signals.pop(0) #print("************************** SIGNALS POPPED *******************************" ) if len(self.signals) > 0 and len(self.args) > ignore_signals_after and self.signals[0][0] < self.args[-(ignore_signals_after)][0]: self.signals.pop(0) print("************************** SIGNALS POPPED *******************************" ) @property def get_account(self): return [acct for acct in self.client.get_accounts()['data'] if acct['balance']['currency'] == 'BTC'][0] @property def get_balance(self): return { account['balance']['currency']: float(account['balance']['amount']), account['native_balance']['currency']: float(account['native_balance']['amount']), } @property def account(self): return [acct for acct in self.client.get_accounts()['data'] if acct['balance']['currency'] == 'BTC'][0] @property def balance(self): return { self.account['balance']['currency']: float(self.account['balance']['amount']), self.account['native_balance']['currency']: float(self.account['native_balance']['amount']), } def get_price(self,pair): return float(self.client.get_spot_price(currency_pair = pair)['amount']) def get_price_LTC(self): print (self.client.get_spot_price(currency_pair = pair)) def get_buy_price(self, pair): return float(self.client.get_buy_price(currency_pair = pair)['amount']) def get_sell_price(self, pair): return float(self.client.get_sell_price(currency_pair = pair)['amount']) def buy(self, amount): buy_obj = self.account.buy(amount, 'EUR') self.buys.append(buy_obj) self.transactions_plot.append([date, float(price), "BUY"]) with open("transactions/BUY_Report", "a") as buyfile: buyfile.write(buy_obj+"\n") buyfile.close() def sell(self, amount): sell_obj = self.account.sell(amount, 'EUR') self.sells.append(sell_obj) self.transactions_plot.append([date, float(price), "SELL"]) with open("transactions/SELL_Report", "a") as sellfile: sellfile.write(sell_obj+"\n") sellfile.close() def localbuy(self, date, amount, price): buy_obj = json.dumps({'date': str(date),'amount': amount, 'price': price}) self.buys.append(buy_obj) self.transactions_plot.append([date, float(price), "BUY"]) with open("www/report.csv", "a") as myfile: myfile.write("BUY,"+ str(date)+","+str(amount)+","+str(price)+","+str(int(price*amount))+"\n") myfile.close() with open("www/index.html", "a") as htmlreport: htmlreport.write("<br> BUY Operation at: " + str(date) +" <b>amount:</b> "+str(amount)+" <b> buy price:</b>"+str(price)+" <b>total:</b> "+str(int(price*amount))+"\n") htmlreport.close() def localsell(self,date, amount, price): sell_obj = json.dumps({'date': str(date), 'amount': amount, 'price': price}) self.sells.append(sell_obj) self.transactions_plot.append([date, float(price), "SELL"]) with open("www/report.csv", "a") as myfile: myfile.write("SELL,"+ str(date)+","+str(amount)+","+str(price)+","+str(price*amount)+"\n") myfile.close() with open("www/index.html", "a") as htmlreport: htmlreport.write("<br> SELL Operation at: " + str(date) +" <b>amount:</b> "+str(amount)+" <b> sell price:</b>"+str(price)+" <b>total:</b> "+str(int(price*amount))+"\n") htmlreport.close() def sync_buys_sells_operations(self): json_buys = self.client.get_buys() print(json_buys) ''' for idx, gdax_buy in enumerate(self.buys): resp = json.loads(buy) if percent((float(sellprice)-(float(resp['price'])-float(market_fees)),buyprice)) > 0: print("GAIN %:", float(sellprice)-(float(buyprice)-float(market_fees))) return True else: return False ''' def get_buy_count(self): print("pre buy count") global buy_count buy_count = len(self.buys) print("after buy count") return buy_count def bytedate2num(self, fmt): def converter(b): return mdates.strpdate2num(fmt)(b.decode('ascii')) return converter def bytespdate2num(self, fmt, encoding='utf-8'): strconverter = mdates.strpdate2num(fmt) def bytesconverter(b): s = b.decode(encoding) return strconverter(s) return bytesconverter def findSignals_MACD(self, args, RSI, MACD): date = [x[0] for x in args] prices = [x[1] for x in args] buyprices = [x[2] for x in args] sellprices = [x[3] for x in args] dataDate = datetime.datetime.now().strftime('%H:%M:%S') lastprice = prices[-1] buyprice = buyprices[-1] sellprice = sellprices[-1] if MACD[-1] > 0 and MACD[-2] < 0 and MACD[-3] < 0: self.signals.append([date[-1],float(lastprice),"buy", "MACD"]) print("Date: " + str(dataDate) + " *** MACD *** BUY SIGNAL INTERCEPTED @ " + str(buyprice)) if MACD[-1] < 0 and MACD[-2] > 0 and MACD[-3] > 0: self.signals.append([date[-1],float(lastprice),"sell", "MACD"]) print("Date: " + str(dataDate) + " *** MACD *** SELL SIGNAL INTERCEPTED @ " + str(sellprice)) if len(self.signals) > 0: if self.signals[-1][2] == "buy": if len(self.buys) < buy_limit: print("Executing BUY. Limit is:" + str(buy_limit)) self.localbuy(self.args[-1][0],buy_sell_amount,buyprice) else: print("Date: " + str(dataDate) + "BUY limit reached") elif self.signals[-1][2] == "sell": if self.gainCheckLite(sellprice): self.localsell(self.args[-1][0],buy_sell_amount,sellprice) return self.transactions_plot def findSignals_MACD_RSI(self, args, RSI, MACD): date = [x[0] for x in args] prices = [x[1] for x in args] buyprices = [x[2] for x in args] sellprices = [x[3] for x in args] dataDate = datetime.datetime.now().strftime('%H:%M:%S') lastprice = prices[-1] buyprice = buyprices[-1] sellprice = sellprices[-1] #TODO controllare i signals del periodo predecedente #TODO vendere anche senza nessun signal se il prezzo raggiunge il target if MACD[-1] > 0 and MACD[-2] < 0 and MACD[-3] < 0: self.signals.append([date[-1],float(lastprice),"buy", "MACD"]) print("Date: " + str(dataDate) + " *** MACD *** BUY SIGNAL INTERCEPTED @ " + str(buyprice)) if MACD[-1] < 0 and MACD[-2] > 0 and MACD[-3] > 0: self.signals.append([date[-1],float(lastprice),"sell", "MACD"]) print("Date: " + str(dataDate) + " *** MACD *** SELL SIGNAL INTERCEPTED @ " + str(sellprice)) if RSI[-1] < RSI_down_lim: self.signals.append([date[-1],float(lastprice),"buy", "RSI"]) print("Date: " + str(dataDate) + " *** RSI *** BUY SIGNAL INTERCEPTED @ " + str(buyprice)) elif RSI[-1] > RSI_top_lim: self.signals.append([date[-1],float(lastprice),"sell", "RSI"]) print("Date: " + str(dataDate) + " *** RSI *** SELL SIGNAL INTERCEPTED @ " + str(sellprice)) if len(self.signals) > 1: # if we have 2 according signals of buy if self.signals[-1][2] == "buy" and self.signals[-2][2] == "buy": #and if the 2 signals according for MACD and RSI if self.signals [-1][3] == "RSI" and self.signals [-2][3] == "MACD": if len(self.buys) < buy_limit: print("Executing BUY. Limit is:" + str(buy_limit)) self.localbuy(self.args[-1][0],buy_sell_amount,buyprice) elif self.signals [-1][3] == "MACD" and self.signals [-2][3] == "RSI": if len(self.buys) < buy_limit: print("Executing BUY. Limit is:" + str(buy_limit)) self.localbuy(self.args[-1][0],buy_sell_amount,buyprice) elif self.signals [-1][3] == "RSI" and self.signals [-2][3] == "RSI": self.signals.pop(-2) # if we have 2 according signals of sell elif self.signals[-1][2] == "sell" and self.signals[-2][2] == "sell": #and if the 2 signals give the same result from MACD and RSI if self.signals [-1][3] == "RSI" and self.signals [-2][3] == "MACD": #TODO: rimuovere il gaincheck. Serve vendere per riacquistare a prezzo più basso. if self.gainCheckLite(sellprice): self.localsell(self.args[-1][0],buy_sell_amount,sellprice) elif self.signals [-1][3] == "MACD" and self.signals [-2][3] == "RSI": #check if we are rich :) #TODO: rimuovere il gaincheck. Serve vendere per riacquistare a prezzo più basso. # serve vendere per evitare il down che abbiamo previsto grazie a MACD e RSI if self.gainCheckLite(sellprice): self.localsell(self.args[-1][0],buy_sell_amount,sellprice) elif self.signals [-1][3] == "RSI" and self.signals [-2][3] == "RSI": self.signals.pop(-2) # only 1 signal but hard conditions elif self.signals[-1][2] == "buy" and self.signals [-1][3] == "RSI" and (MACD[-1] > 0): if len(self.buys) < buy_limit: self.localbuy(self.args[-1][0],buy_sell_amount,buyprice) else: print("Date: " + str(dataDate) + "BUY limit reached") else: print("Date: " + str(dataDate) + " BUY signal and SELL signal discording. HOLD POSITION... ") return self.transactions_plot def percent(self, part, whole): return 100 * float(part)/float(whole) def percentage(self, percent, whole): return (percent * whole) / 100.0 def gainCheck(self, sellprice): #ensure coverage of market fees and gain target for idx, buy in enumerate(self.buys): resp = json.loads(buy) if self.percent((float(sellprice)-(float(resp['price'])-float(self.getFees(resp['amount'])))-float(self.percentage(min_profit_margin,float(resp['price'])))),float(resp['price'])) > 0: return True else: Print ("SELL ABORTED: SellPrice:", float(sellprice), " BUY Price:", float(resp['price']), " Gain:", float(sellprice)-(float(resp['price'])-float(market_fees)-float(percentage(min_profit_margin,float(resp['price']))), "% Target: ", float(percentage(min_profit_margin,float(resp['price']))), "%" )) return False def gainCheckLite(self, sellprice): #ensure coverage of market fees for idx, buy in enumerate(self.buys): resp = json.loads(buy) if self.percent((float(sellprice)-(float(resp['price'])-float(self.getFees(resp['amount'])))),float(resp['price'])) > 0: return True else: print ("SELL ABORTED: SellPrice:", float(sellprice), "< (BUY Price:", float(resp['price']), " + Market Fee:", float(market_fees),")") return False def getFees(self, amount): return (market_fees * amount) / 100
import time from coinbase.wallet.client import Client # your secret blockchain.info wallet (see secret_wallet.py) bitcoin_address_of_secret_wallet = "" # USD amount to send to final target eg. "5000" usd_amount = "" # register coinbase account and enable API keys # https://developers.coinbase.com/docs/wallet/api-key-authentication coinbase_api_key = "" coinbase_api_secret = "" # create coinbase client with your credentials client = Client(coinbase_api_key, coinbase_api_secret) # fetch default account ID from your coinbase account print(term.format("Fetch Account Info\n", term.Attr.BOLD)) accounts_response = client.get_accounts() print(term.format(accounts_response, term.Color.BLUE)) account_id = json.loads(accounts_response)["data"][0]["id"] # check real time bitcoin price (total USD to buy one bitcoin) print(term.format("Check Bitcoin Price\n", term.Attr.BOLD)) bitcoin_price_response = client.get_buy_price(currency_pair='BTC-USD') print(term.format(bitcoin_price_response, term.Color.BLUE)) bitcoin_price = float(json.loads(bitcoin_price_response)["data"]["amount"]) # convert USD amount to bitcoin bitcoin_amount = str(usd_amount / bitcoin_price)
def __get_client(self): if not self.__client: self.__client = Client(self.api_key, self.api_secret) return self.__client
def get_user_from_client(api_key, api_token): """Get the user name from Coinbase API credentials.""" client = Client(api_key, api_token) user = client.get_current_user() return user
headers = { 'x-rapidapi-host': "weatherbit-v1-mashape.p.rapidapi.com", 'x-rapidapi-key': "RAPIDAPI-KEY" } response = requests.request("GET", url, headers=headers, params=querystring) response = response.json() temp_c = int(response['data'][0]['temp']) temp_f = str(temp_c * 1.8 + 32) weather = response['data'][0]['weather']['description'] api_key = 'COINBASE_API_KEY' api_secret = 'COINBASE_API_KEY' client = Client(api_key, api_secret) rates = client.get_exchange_rates(currency='BTC') price = rates['rates']['USD'] image = Image.open('ORIGINAL_WALLPAPER_FILE') drawing = ImageDraw.Draw(image) font_large = ImageFont.truetype('FONT_TTF_FILE', size=100) font_small = ImageFont.truetype('FONT_TTF_FILE', size=40) color = 'rgb(255, 255, 255)' now = datetime.now() now = now.strftime('%H:%M') drawing.text((3400, 75), now, fill=color, font=font_large)
#Defining a static mapping of all object types, corresponding text, and value with open('pricing.json', 'r') as f: mapping = json.load(f) scanAndPurchase = False lookForFace = True nextScan = True bill = 5 _btcAddress = '<bit coin address>' try: coinbaseClient = Client(_API_KEY, _API_SECRET) except: print ("Error creating the coinbase client") def handle_object_appeared(robot, event_type, event): """ Handler for whenever an object appears """ global bill global scanAndPurchase global nextScan # This will be called whenever an EvtObjectAppeared is dispatched - # whenever an Object comes into view. print("--------- Vector started seeing an object --------- \n{event.obj}") if scanAndPurchase and nextScan: nextScan = False
def test_delete(self): client = Client(api_key, api_secret) account = new_api_object(client, mock_account, Account) data = account.delete() self.assertIs(data, None)
def test_commit_deposit(self): client = Client(api_key, api_secret) account = new_api_object(client, mock_account, Account) deposit = account.commit_deposit('bar') self.assertIsInstance(deposit, Deposit) self.assertEqual(deposit, mock_item)
def test_create_address(self): client = Client(api_key, api_secret) account = new_api_object(client, mock_account, Account) address = account.create_address() self.assertIsInstance(address, Address) self.assertEqual(address, mock_item)
def test_create_order(self): client = Client(api_key, api_secret) checkout = new_api_object(client, mock_checkout, Checkout) order = checkout.create_order() self.assertIsInstance(order, Order) self.assertEqual(order, mock_item)
def test_get_report(self): client = Client(api_key, api_secret) account = new_api_object(client, mock_account, Account) report = account.get_report('testreportid') self.assertIsInstance(report, Report) self.assertEqual(report, mock_item)
print('Please specify your API key and secret key inside the script.') quit() # Connect to Coinbase print('###################################') print(' .(-._. ~Coinbase Failsafe~ ._.-). ') print('###################################') print('') sleep(1) print('[*] Wait time is set to %s seconds.' % (time_delay)) print('[*] Acceptable relative loss from maximum is set to %s %%.' % (margin)) print('[*] The currency code chosen is %s.' % (currency_code)) print('[*] Connecting to Coinbase..') # Connects to Coinbase client = Client(api_key, api_secret, api_version=version) # Gets primary account account = client.get_primary_account() price = client.get_spot_price(currency=currency_code) print('[*] Connected. You currently have %s. Starting..' % (account.balance)) print('') # Defines starting maximum value max_price = float(price.amount) # Defines starting acceptable loss margin_value = (1 - float(margin) / 100) * max_price sleep(5) # Main code while True:
def test_commit_sell(self): client = Client(api_key, api_secret) account = new_api_object(client, mock_account, Account) sell = account.commit_sell('bar') self.assertIsInstance(sell, Sell) self.assertEqual(sell, mock_item)
def __init__(self): self.CLIENT = Client(os.environ["Coinbase_API_Key"], os.environ["Coinbase_API_Secret"])
def test_commit_withdrawal(self): client = Client(api_key, api_secret) account = new_api_object(client, mock_account, Account) withdrawal = account.commit_withdrawal('bar') self.assertIsInstance(withdrawal, Withdrawal) self.assertEqual(withdrawal, mock_item)
def price(): client = Client('api-user-name', 'api-key') price = client.get_spot_price(currency_pair='BTC-USD') result = price['amount'] print(result) return render_template('index.html', price=result)
def test_resend(self): client = Client(api_key, api_secret) transaction = new_api_object(client, mock_transaction, Transaction) response = transaction.resend() self.assertIsInstance(response, APIObject) self.assertEqual(response, mock_item)
#!/usr/bin/env python import json import time from coinbase.wallet.client import Client from kafka import KafkaProducer client = Client("xxxxxxx", "XXXXXXXXX", api_version='2018-05-06') while True: # Make the request to coinbase for the currency_pair ETH-EUR # price = {"base":"BTC","currency":"USD","amount":"7209.98"} price = client.get_spot_price(currency_pair='BTC-EUR') # when actual price != kafka last message read # pricewithdate = {"date": "1527612815.19", "currency": "EUR", "amount": "6429.87", "base": "BTC"} pricewithdate = '{"base":"' + str(price["base"]) + '","currency":"' + str( price["currency"]) + '","amount":"' + str( price["amount"]) + '","date":"' + str(time.time()) + '"}' # Insert coinbase json data in coinbasetest kafka topic producer = KafkaProducer(bootstrap_servers='localhost:9092') producer = KafkaProducer( value_serializer=lambda v: json.dumps(v).encode('utf-8')) producer.send('coinbasetest', json.loads(pricewithdate)) # Insert every second time.sleep(10.0)
def GetClient(self): client = Client(self.api_key, self.secret_key) return client
:rtype: int, int, int """ maximum = 0 buy_day = 0 sell_day = 0 for i in range(len(prices) - 1): sell_price = max(prices[i + 1:]) buy_price = min(prices[:i + 1]) profit = sell_price - buy_price transaction_cost = buy_price * .03 + sell_price * .03 if profit > transaction_cost: maximum = max(maximum, profit) return maximum, buy_day, sell_day client = Client(api_key='', api_secret='') historic_prices = client.get_historic_prices() price_list = [float(day['price']) for day in historic_prices['prices']] print(price_list) max_profit = maxProfit(price_list) print("Max profit: $" + str(max_profit)) for i in range(10): time.sleep(10) print("Buy price " + str(client.get_buy_price(currency_pair='BTC-USD'))) print("Sell price " + str(client.get_sell_price(currency_pair='BTC-USD'))) print("Spot price " + str(client.get_spot_price(currency_pair='BTC-USD')))
def __init__(self, name, wallet): self.name = name self.wallet = wallet self.c = Client(getenv("COINBASE_API_KEY"), getenv("COINBASE_API_SECRET"))
continue if pid == 0: config = configparser.ConfigParser() config.read( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'settings.ini')) api_key = config.get('coinbase_api', 'api_key', fallback=False) api_secret = config.get('coinbase_api', 'api_secret', fallback=False) prometheus_addr = config.get('prometheus_server', 'addr', fallback=False) client = Client( api_key, api_secret, api_version='2017-12-02', ) random.seed() client_id = random.random() histogram_reg = CollectorRegistry() counter_reg = CollectorRegistry() c = Counter('coinbase_http_response_total', 'HTTP responses counted by status_code', ['client', 'method', 'code', 'message'], registry=counter_reg) req_time = Histogram('coinbase_request_seconds', 'Time spent processing request',