Package: buycoins-client
Buycoins Python LibraryThe Buycoins GraphQL API Python library provides convenient access to the Buycoins API from
applications written in the Python language. It includes a pre-defined set of
functions for API resources that initialize themselves dynamically from API
responses which makes it compatible with a wide range of versions of the Buycoins
API.You don't need to know GraphQL to be able to use the package.Your basic understanding of calling functions and assigning variables in Python is more than enough.DocumentationSee theBuycoins GraphQL API docs.InstallationYou don't need this source code unless you want to modify the package. If you just
want to use the package, just run:pipinstall--upgradebuycoins_clientInstall from source with:pythonsetup.pyinstallRequirementsPython 3+ (PyPy supported)UsageThe library needs to be configured with your account's public and secret keys which is
available in your [Buycoins App settings][api-keys] after you make a request toBuycoins support.
value:importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")# list personal ordersmy_orders=buycoins.Orders.list_my_orders(status="open",fields=[])# list market book ordersmy_orders=buycoins.Orders.list_market_orders()ModulesThe package contains 6 core modules with related functions to adequately represent the queries and mutations on the main API. You don't need to know GraphQL to be able to use the package; this is because a dict to graphql parser has been created in the package. All you just have to do is specify arguments (where need be) or fields you want retrieved (else all the associated query fields are returned).These modules are:Auth - For authentication setup and modification. Contains a single function for setting up public and secret keys.Accounts - For creating cryptocurrency addresses and virtual bank accountsBalances - For retrieving your balances in all the cryptocurrencies supported as well as for a single cryptocurrency of your choiceOrders - For placing orders on the marketplace, viewing the market book as well as your personal orders on the platformPrices - For retrieving cryptocurrency prices on the platformTransfers - For checking transfer fees, sending, buying and selling cryptocurrencies via the API.Client ResponsesThe Client offers two kinds of responses. They are:failureandsuccessresponses. A failure response occurs when the API returns back a response with errors. A success response occurs when the API returns the result expected by the call. Every type of response has astatuskey that can only be any ofsuccessorfailure. Both responses aredictsand are represented as follows:A success response always has adatakey indicating the data returned from the API.Success Response>>>importbuycoins_clientasbuycoins>>>buycoins.Auth.setup("public_key_...","secret_key_...")>>>currency_prices=buycoins.Prices.list()>>>print(currency_prices)>>>{"status":"success","data":{"getPrices":[{"id":"QnV5Y29pbnNQcmljZS1mM2ZhOWI2Yy00MmM4LTQxMzAtOThmZC0zZGMwYjRjMmRlNjQ=","cryptocurrency":"bitcoin","sellPricePerCoin":"17827839.315","minSell":"0.001","maxSell":"0.35190587","expiresAt":1612391202}]}}Therawfield of afailureresponse is the raw error message from the API. However, an error response always has anerrorskey that's a list of errors. This list of errors contains adictwith keysreason(why the error happened) andfield(where the error happened).Failure Response>>>importbuycoins_clientasbuycoins>>>buycoins.Auth.setup("public_key_...","secret_key_...")>>>currency_prices=buycoins.Prices.list()>>>print(currency_prices)>>>#if the request were to fail by any means, the output of print would be:>>>{"status":"failure","errors":[{"reason":"Field 'cryptocrrency' doesn't exist on type 'BuycoinsPrice'","field":"query.getPrices.cryptocrrency"}],"raw":[{"message":"Field 'cryptocrrency' doesn't exist on type 'BuycoinsPrice'","locations":[{"line":1,"column":23}],"path":["query","getPrices","cryptocrrency"],"extensions":{"code":"undefinedField","typeName":"BuycoinsPrice","fieldName":"cryptocrrency"}}]Modules APIFieldsAn explanation on how to choose the data fields returned by each mutation or query
Everyqueryormutationcall on the package takes afieldsparameter that is optional. If thefieldsparameter is not provided, the API call defaults to returning all the data thequeryormutationcan provide since the API is a GraphQL API and developers are allowed to indicate the fields they want returned.Since the package is a wrapper on the main client and not all developers understand or want to learn how to use GraphQL, the package contains a parser that transforms an array of fields to an equivalent GraphQL schema. Thefieldsparameter which is a list only acceptsdictswith only one requireddictkey:field. The two other keys areargsandfields.argsis equivalent to arguments being passed to a GraphQL node. It is adictcontaining the argument name with its corresponding value. Thefieldskey is a recursive pattern of thefieldsdata structure. It is also alistjust like the parentfieldsparameter. The nesting can be done to any depth of choice as in GraphQL.The fields parameter is shown below:>>>fields=[{'field':"cryptocurrency"},{"field":"id"}},{"field":"minSell"}]# An example request>>>currency_prices=buycoins.Prices.list(fields=fields)# This would normally return all the data available in the getPrices Query>>>print(currency_prices)>>>{"data":{"getPrices":[{"id":"aEDA324fafdjlfda","cryptocurrency":"bitcoin","minSell":0.002},{"id":"qAF82fa2fal3ai","cryptocurrency":"litecoin","minSell":0.002}]}}>>>fields_with_args=[{'field':"cryptocurrency"},{"field":"price","args":{"time":13435929,"type":"min"}}]>>>fields_with_other_fields=[{'field':"cryptocurrency"},{"field":"price","args":{"time":13435929,"type":"min"}},{"field":"fees","args":{"time":13435929,"type":"min"},"fields":[{"field":"day"},{"field":"name"}]}]>>># an example of field with sub-fields with getMarketBook query>>>fields=[{"field":"dynamicPriceExpiry"},{"field":"orders","fields":[{"field":"edges","fields":[{"field":"node","fields":[{"field":"id"},{"field":"cryptocurrency"},{"field":"coinAmount"},{"field":"side"},{"field":"status"},{"field":"createdAt"},{"field":"pricePerCoin"},{"field":"priceType"},{"field":"staticPrice"},{"field":"dynamicExchangeRate"}]}]}]}]>>>market_orders=buycoins.Orders.list_market_orders(fields=fields)>>>print(market_orders)The parser for the fields-graphql schema parser can be found in the/buycoins_client/components/utilities.pyfile and can be copied to create similar functionality in any package of choice.AuthIt requires that you utilize the public and secret keys as specified in theAuthentication documentationTo set up authentication credentials just call thesetupfunction of theAuthmodule with the public and secret keys respectively. It raises an exception if any of both parameters is not provided or aren't of typestr. You can set it up as follows:importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")AccountsTheAccountsmodule is used for creating virtual bank accounts and for creating cryptocurrency addresses. It contains two functions, these functions are:createfor creating a virtual account andcreate_addressfor creating a cryptocurrency address. For creating a virtual account, see the documentation from the  API hereCreate a virtual account.
For creating a cryptocurrency address, see the main documentation here:Create cryptocurrency addresscreateThis function takes a single compulsory parameter which is the account name to use for the new virtual bank account. Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data themutationcan return. The function raises an exception if a validaccount_nameparameter is not provided or thefieldsparameter provided contains an invalid field dict.It returns the newly created virtual bank accountdictor an error responsedictif the request to the Buycoins API fails.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")new_account=buycoins.Accounts.create("Chukwuemeka Ajah")print(new_account)create_addressCreates a cryptocurrency address to receive money in. You should send this address to your prospective sender.This function takes a single compulsory parameter which is the cryptocurrency name you want to create an address for. Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thecreateAddress mutationcan return. The function raises an exception if a validcrypto_currencyparameter is not provided or thefieldsparameter provided contains an invalid field dict.It returns the newly created cryptocurrency addressdictor an error responsedictif the request to the Buycoins API fails.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")new_address=buycoins.Accounts.create_address("litecoin")print(new_address)BalancesTheBalancesmodule is used for retrieving your account balances in different cryptocurrencies on the Buycoins platform. It contains two functions. They aregetfor retrieving a single cryptocurrency balance andlistfor retrieving balances of all the cryptocurrencies you own.
The Buycoins documentation on retrieving balances can be foundheregetRetrieve a single cryptocurrency balance on your walletsThis function takes a single compulsory parameter which is the cryptocurrency name you want to get its balance. Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thegetBalances querycan return. The function raises an exception if a validcryptocurrencystring parameter is not provided or thefieldsparameter provided contains an invalid field dict.It returns the wallet balance in the specified currency.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")wallet_balance=buycoins.Balances.get("litecoin")print(wallet_balance)listRetrieve a list of balances in all supported cryptocurrencies you own on your wallet.This function takes no compulsory parameter. Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thegetBalances querycan return. The function raises an exception if thefieldsparameter provided contains an invalid field dict.It returns your wallet balances in all the cryptocurrencies that are supported on the Buycoins platform.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")wallet_balances=buycoins.Balances.list()print(wallet_balances)PricesThePricesmodule is used for retrieving the current prices of cryptocurrencies supported on the Buycoins platform. It contains only one function. The function name islist.The Buycoins documentation on retrieving the prices of cryptocurrencies can be foundherelistRetrieve a list of cryptocurrency pricesThis function takes no compulsory parameter. Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thegetPrices querycan return. The function raises an exception if thefieldsparameter provided contains an invalid field dict.It returns the current prices of cryptocurrencies supported on the Buycoins platform.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")currency_prices=buycoins.Prices.list()print(currency_prices)TransfersTheTransfersmodule contains functions for retrieving cryptocurrency transfer fees, sending cryptocurrencies, placing orders for buying as well as selling cryptocurrencies. It implements GraphQL API calls to the Buycoins API as stated in the following links of the API documentation.feesgetEstimatedNetworkFee documentationsendSend cryptocurrency documentationbuyBuy documentationsellSell documentationfeesRetrieve fees for sending a cryptocurrency to an addressThis function takes a single compulsory parameter which is a dict containing the required arguments needed for retrieving the transfer fee when agetEstimatedNetworkFee queryis called on the Buycoins API. These arguments are:cryptocurrencyandamountas stated in the main API documentation.Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thegetEstimatedNetworkFee querycan return. The function raises an exception if an invalidargsfield value is provided or required field in the dict is absent or thefieldsparameter provided contains an invalid field dict.It returns the fees in the specified cryptocurrency required to make a transfer possible on the Buycoins platform.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")fees=buycoins.Transfers.fees({"cryptocurrency":"bitcoin","amount":0.02})print(fees)sendSend cryptocurrency to a cryptocurrency addressThis function takes a single compulsory parameter which is a dict containing the required arguments needed for sending cryptocurrency to a specified address via thesend mutationon the Buycoins API documentation. These arguments are:cryptocurrency,addressandamountas stated in the main API documentation.Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thesend mutationcan return. The function raises an exception if an invalidargsfield value is provided or required field in theargsdict is absent or thefieldsparameter provided contains an invalid field dict.It returns the transaction details.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")transaction_info=buycoins.Transfers.send({"cryptocurrency":"bitcoin","amount":0.02,"address":"vdADFaj7f89dfkadf="})print(transaction_info)buyBuy cryptocurrency on the Buycoins platform.This function takes a single compulsory parameter which is a dict containing the required arguments needed for buying cryptocurrency via thebuy mutationon the Buycoins API documentation. These arguments are:cryptocurrency,priceandcoin_amountas stated in the main API documentation. Thepricefield is theidof the cryptocurrency price returned from callingPrices.getfunction for the cryptocurrency.Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thebuy mutationcan return. The function raises an exception if an invalidargsfield value is provided or required field in theargsdict is absent or thefieldsparameter provided contains an invalid field dict.It returns the transaction details.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")transaction_info=buycoins.Transfers.buy({"cryptocurrency":"bitcoin","coin_amount":0.02,"price":"vdADFaj7f89dfkadf="})print(transaction_info)sellSell a cryptocurrency on the Buycoins platform.This function takes a single compulsory parameter which is a dict containing the required arguments needed for selling cryptocurrency via thesell mutationon the Buycoins API documentation. These arguments are:cryptocurrency,priceandcoin_amountas stated in the main API documentation. Thepricefield is theidof the cryptocurrency price returned from callingPrices.getfunction for the cryptocurrency.Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thesell mutationcan return. The function raises an exception if an invalidargsfield value is provided or required field in theargsdict is absent or thefieldsparameter provided contains an invalid field dict.It returns the transaction details.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")transaction_info=buycoins.Transfers.sell({"cryptocurrency":"bitcoin","coin_amount":0.02,"price":"vdADFaj7f89dfkadf="})print(transaction_info)OrdersTheOrdersmodule contains functions for retrieving personal orders made on the platform, marketplace orders as well as posting personal and marketplace orders. It implements GraphQL API calls to the Buycoins API as stated in the following links of the API documentation.list_my_ordersGet list orders documentationlist_market_ordersGet market book documentationpost_limit_orderPost limit order documentationpost_market_orderPost market order documentationlist_my_ordersRetrieve a list of orders made by you on the platform.This function takes a single compulsory parameter which is a string indicating the status of the order required for retrieving limit orders using thegetOrders queryon the Buycoins API documentation. These argument isstatusand it defaults toopen. It can be any ofopenorcompleted.Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thegetOrders querycan return. The function raises an exception if an invalidstatusvalue is provided or thefieldsparameter provided contains an invalid field dict.It returns all the limit orders made by you on the Buycoins platform.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")orders=buycoins.Orders.list_my_orders(status="completed")print(orders)list_market_ordersRetrieve a list of orders made on the marketplace platform.This functionnocompulsory parameters. It's a call on thegetMarketBook queryon the Buycoins API documentation.Just like in GraphQL where you specify the fields you want returned, it accepts an optional fields parameter that's a list. If a fields list is not provided, it defaults to returning all the data thegetMarketBook querycan return. The function raises an exception iffieldsparameter provided contains an invalid field dict.It returns all the limit orders made by you on the Buycoins platform.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")orders=buycoins.Orders.list_market_orders()print(orders)post_limit_orderPost a limit order and have the transaction details returnedThis function takes a single compulsory parameter which is a dict containing the required arguments needed for posting an order via thepostLimitOrder mutationon the Buycoins API documentation. These arguments are:cryptocurrency,orderSide,priceType,staticPrice,dynamicExchangeRateandcoinAmountas stated in the main API documentation. TheorderSidecan only be either ofbuyorsell. ThepriceTypecan only be either ofstaticordynamic. ThestaticPriceanddynamicExchangeRatearguments areoptionalas stated in the API.The function raises an exception if a validargsparameter argument is not provided or thefieldsparameter provided contains an invalid field dict.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")posted_order=buycoins.Orders.post_limit_order({"orderSide":"buy","cryptocurrency":"bitcoin","coinAmount":0.002,"priceType":"dynamic"})print(posted_order)post_market_orderPost a market order and have the transaction details returnedThis function takes a single compulsory parameter which is a dict containing the required arguments needed for posting an order via thepostMarketOrder mutationon the Buycoins API documentation. These arguments are:cryptocurrency,orderSide, andcoinAmountas stated in the main API documentation. TheorderSidecan only be either ofbuyorsell.The function raises an exception if a validargsparameter argument is not provided or thefieldsparameter provided contains an invalid field dict.importbuycoins_clientasbuycoinsbuycoins.Auth.setup("public_key_...","secret_key_...")posted_order=buycoins.Orders.post_market_order({"orderSide":"buy","cryptocurrency":"bitcoin","coinAmount":0.002})print(posted_order)TestingAll tests for the modules are in the tests folder. In order to run the tests, run the command below in a shell within the project folder.python-munittestdiscovertestsorpytestHandling exceptionsInvalid parameter types or absent parameters without a default raise an Exception. All excepts are of the generic Exception class.Per-request ConfigurationConfigure individual requests with keyword arguments.
Also, make sure to have called theAuth.setupfunction at the beginning of your code file with your public and secret keys before making any calls to the API else the package would raise an exception.importbuycoins_clientasbuycoins# buy cryptocurrencyresponse=buycoins.Orders.buy(args={"price":"QnV5Y29pbnNQcmljZS0zOGIwYTg1Yi1jNjA1LTRhZjAtOWQ1My01ODk1MGVkMjUyYmQ=","coin_amount":0.02,"cryptocurrency":"bitcoin"})