Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented wallet class for buying, selling, creating and retrieving… #4

Merged
merged 10 commits into from Jan 31, 2021
20 changes: 15 additions & 5 deletions buycoins/client.py
@@ -1,5 +1,6 @@
from python_graphql_client import GraphqlClient
from requests.auth import HTTPBasicAuth
from requests.exceptions import HTTPError

from buycoins.exceptions import QueryError

Expand All @@ -15,13 +16,22 @@ def _split_auth_key(self):

def _initiate_client(self):
self._split_auth_key()
self.__auth = HTTPBasicAuth(self.__username, self.__password)
self.__client = GraphqlClient(self.__endpoint, auth=self.__auth)
return self.__client
try:
self.__auth = HTTPBasicAuth(self.__username, self.__password)
self.__client = GraphqlClient(self.__endpoint, auth=self.__auth)
except HTTPError as e:
return e
else:
return self.__client

def _execute_request(self, query: str, variables: dict= {}):
if not query or query == "":
raise QueryError("Invalid query passed!")

self._initiate_client()
return self.__client.execute(query=query, variables=variables)
try:
self._initiate_client()
request = self.__client.execute(query=query, variables=variables)
except HTTPError as e:
return e
else:
return request
21 changes: 21 additions & 0 deletions buycoins/errors.py
@@ -0,0 +1,21 @@
from requests import HTTPError

from buycoins.exceptions import ClientError


def check_response(exception, response):
"""Checks for exceptions and raises them.

Args:
exception (): Class of exception to be raised.
response (): Response object to be checked against.

Returns:

"""
if type(response) == HTTPError:
raise ClientError("Invalid Authentication Key!")

if "errors" in response:
error = response["errors"]
raise exception(error[0]["message"])
38 changes: 32 additions & 6 deletions buycoins/exceptions/exceptions.py
@@ -1,3 +1,16 @@
class ClientError(Exception):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None

def __str__(self):
if self.message:
return "ClientError, {0}".format(self.message)
else:
return "A ClientError has been raised"

class QueryError(Exception):
def __init__(self, *args):
if args:
Expand All @@ -7,9 +20,9 @@ def __init__(self, *args):

def __str__(self):
if self.message:
return 'QueryError, {0} '.format(self.message)
return "QueryError, {0} ".format(self.message)
else:
return 'A QueryError has been raised'
return "A QueryError has been raised"

class P2PError(Exception):
def __init__(self, *args):
Expand All @@ -20,9 +33,9 @@ def __init__(self, *args):

def __str__(self):
if self.message:
return 'P2PError, {0} '.format(self.message)
return "P2PError, {0} ".format(self.message)
else:
return 'A P2P has been raised'
return "A P2P has been raised"

class AccountError(Exception):
def __init__(self, *args):
Expand All @@ -33,7 +46,20 @@ def __init__(self, *args):

def __str__(self):
if self.message:
return 'AccountError, {0} '.format(self.message)
return "AccountError, {0} ".format(self.message)
else:
return "An AccountError has been raised"

class WalletError(Exception):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None

def __str__(self):
if self.message:
return 'Wallet, {0} '.format(self.message)
else:
return 'An AccountError has been raised'
return 'A WalletError has been raised'

36 changes: 33 additions & 3 deletions buycoins/ngnt.py
@@ -1,5 +1,6 @@
from buycoins.client import BuyCoinsClient
from buycoins.exceptions import AccountError
from buycoins.errors import check_response
from buycoins.exceptions import AccountError, ClientError


class NGNT(BuyCoinsClient):
Expand Down Expand Up @@ -45,7 +46,36 @@ def createDepositAccount(self, accountName: str):
}
}
"""
try:
response = self._execute_request(query=self.__query, variables=__variables)
check_response(AccountError, response)
except (AccountError, ClientError) as e:
return e.args
else:
return response["data"]["createDepositAccount"]

response = self._execute_request(query=self.__query, variables=__variables)
def getBalances(self):
"""Retrieves user cryptocurrency balances>

return response['data']['createDepositAccount']
Returns:
response: A JSON object containing the user crypotcurrency balances.

"""

self.__query = """
query {
getBalances {
id
cryptocurrency
confirmedBalance
}
}
"""

try:
response = self._execute_request(query=self.__query)
check_response(AccountError, response)
except (AccountError, ClientError) as e:
return e.args
else:
return response["data"]["getBalances"]
66 changes: 48 additions & 18 deletions buycoins/p2p.py
@@ -1,5 +1,6 @@
from buycoins.client import BuyCoinsClient
from buycoins.exceptions import P2PError
from buycoins.errors import check_response
from buycoins.exceptions import P2PError, ClientError


class P2P(BuyCoinsClient):
Expand Down Expand Up @@ -30,7 +31,7 @@ def getCurrentPrice(self, side: str = "buy", currency: str = "bitcoin"):
raise P2PError("Invalid or unsupported cryptocurrency")

if side not in self.side:
return P2PError("Invalid order side")
raise P2PError("Invalid order side")

self.__query = """
query GetBuyCoinsPrices($side: OrderSide, $currency: Cryptocurrency) {
Expand All @@ -54,8 +55,13 @@ def getCurrentPrice(self, side: str = "buy", currency: str = "bitcoin"):
"currency": currency
}

response = self._execute_request(self.__query, variables)
return response
try:
response = self._execute_request(query=self.__query, variables=__variables)
check_response(P2PError, response)
except P2PError as e:
return e.args
else:
return response["data"]["getPrices"]

def getDynamicPriceExpiry(self, status: str = "open", side: str = "buy", currency: str = "bitcoin"):
"""Retrieves the dynamic price for the supplied cryptocurrency.
Expand Down Expand Up @@ -93,8 +99,13 @@ def getDynamicPriceExpiry(self, status: str = "open", side: str = "buy", currenc
"currency": currency
}

response = self._execute_request(query=self.__query, variables=variables)
return response
try:
response = self._execute_request(query=self.__query, variables=__variables)
check_response(P2PError, response)
except P2PError as e:
return e.args
else:
return response["data"]["getOrders"]

def placeLimitOrder(self, orderSide: str = "buy", coinAmount: float = 0.01, currency: str = "bitcoin",
staticPrice: int = 100000, priceType: str = "static"):
Expand Down Expand Up @@ -136,15 +147,20 @@ def placeLimitOrder(self, orderSide: str = "buy", coinAmount: float = 0.01, curr
"""

__variables = {
"orderside": orderSide,
"orderSide": orderSide,
"coinAmount": coinAmount,
"cryptocurrency": currency,
"staticPrice": staticPrice,
"priceType": priceType
}

response = self._execute_request(query=self.__query, variables=variables)
return response
try:
response = self._execute_request(query=self.__query, variables=__variables)
check_response(P2PError, response)
except P2PError as e:
return e.args
else:
return response["data"]["postLimitOrder"]

def postMarketOrder(self, orderSide: str = "buy", coinAmount: float = 0.01, currency: str = "bitcoin"):
"""Posts a market order for the supplied cryptocurrency.
Expand All @@ -165,7 +181,7 @@ def postMarketOrder(self, orderSide: str = "buy", coinAmount: float = 0.01, curr
raise P2PError("Invalid or unsupported cryptocurrency")

self.__query = """
mutation PostMarketOrder($ordersSide: OrderSide!, $coinAmount: BigDecimal!, $cryptocurrency: Cryptocurrency){
mutation PostMarketOrder($orderSide: OrderSide!, $coinAmount: BigDecimal!, $cryptocurrency: Cryptocurrency){
postMarketOrder(orderSide: $orderSide, coinAmount: $coinAmount, cryptocurrency: $cryptocurrency){
id
cryptocurrency
Expand All @@ -182,13 +198,18 @@ def postMarketOrder(self, orderSide: str = "buy", coinAmount: float = 0.01, curr
"""

__variables = {
"orderside": orderSide,
"orderSide": orderSide,
"coinAmount": coinAmount,
"cryptocurrency": currency,
}

response = self._execute_request(query=self.__query, variables=variables)
return response
try:
response = self._execute_request(query=self.__query, variables=__variables)
check_response(P2PError, response)
except P2PError as e:
return e.args
else:
return response["data"]["postMarketOrder"]

def getOrders(self, status: str = "open"):
"""Retrieves orders based on their status.
Expand All @@ -206,7 +227,7 @@ def getOrders(self, status: str = "open"):

self.__query = """
query GetOrders($status: GetOrdersStatus!){
getOrders(status: $status, side: $side, cryptocurrency: $currency) {
getOrders(status: $status) {
dynamicPriceExpiry
orders {
edges {
Expand All @@ -232,8 +253,13 @@ def getOrders(self, status: str = "open"):
"status": status
}

response = self._execute_request(query=self.__query, variables=variables)
return response
try:
response = self._execute_request(query=self.__query, variables=__variables)
check_response(P2PError, response)
except (P2PError, ClientError) as e:
return e.args
else:
return response["data"]["getOrders"]

def getMarketBook(self):
"""Retrieves market history.
Expand Down Expand Up @@ -266,5 +292,9 @@ def getMarketBook(self):
}
"""

response = self._execute_request(query=self.__query)
return response
try:
response = self._execute_request(query=self.__query)
check_response(P2PError, response)
except (P2PError, ClientError) as e:
return e.args
return response['data']['getMarketBook']