GithubHelp home page GithubHelp logo

luno-python's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

luno-python's Issues

Posting examples

Adding examples on how to do post_limit_order and post_market_order.

My attempts fail for c.post_market_order('ETHZAR','SELL') I get the following:
File "C:\Users\chase\anaconda3\lib\site-packages\luno_python\client.py", line 655, in post_market_order
return self.do('POST', '/api/1/marketorder', req=req, auth=True)

File "C:\Users\chase\anaconda3\lib\site-packages\luno_python\base_client.py", line 86, in do
raise APIError(e['error_code'], e['error'])

APIError: ('ErrInvalidBaseVolume', 'Invalid base volume for sell order.')

and for c.post_limit_order('ETHZAR', str(price-100), 'ASK', float(ETH)) I get:

File "C:\Users\chase\OneDrive\bot code\awesome-DESKTOP-9UVSN7B.py", line 135, in
c.post_limit_order('ETHZAR', str(price-100), 'ASK', float(ETH))

File "C:\Users\chase\anaconda3\lib\site-packages\luno_python\client.py", line 609, in post_limit_order
return self.do('POST', '/api/1/postorder', req=req, auth=True)

File "C:\Users\chase\anaconda3\lib\site-packages\luno_python\base_client.py", line 86, in do
raise APIError(e['error_code'], e['error'])

APIError: ('ErrInvalidArguments', 'One or more arguments are invalid')

I am working on a code for algo trading, I have few errors to take care, if any one could please help.

2021-07-03 19:14:00,463 ERROR :: Connection error while making GET request to /fapi/v1/exchangeInfo: HTTPSConnectionPool(host='testnet.binancefuture.com', port=443): Max retries exceeded with url: /fapi/v1/exchangeInfo (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:852)'),))

2021-07-03 19:14:00,560 ERROR :: Connection error while making GET request to /fapi/v1/account: HTTPSConnectionPool(host='testnet.binancefuture.com', port=443): Max retries exceeded with url: /fapi/v1/account?timestamp=1625319840464&signature=57782e074e32f5e5095081f693835fe99deba5650885893ddfb3efbaa171c0a2 (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:852)'),))

2021-07-03 19:14:01,085 ERROR :: error from callback <bound method BinanceClient._on_open of <connectors.binance.BinanceClient object at 0x000002626EE2E7F0>>: 'BTCUSDT'

File "C:\Users\Chandrashekar.KB\PycharmProjects\TRADE BOT\venv\lib\site-packages\websocket_app.py", line 388, in _callback

callback(self, *args)

File "C:\Users\Chandrashekar.KB\PycharmProjects\TRADE BOT\connectors\binance.py", line 399, in _on_open

self.subscribe_channel([self.contracts["BTCUSDT"]], "bookTicker")

"create_quote" throws exception

Starting on 24/03/2021, when creating a quote, the following exception is returned

Traceback (most recent call last):
  File "/home/pi/Desktop/LTB/LunoApi.py", line 130, in Quote
    res = c.create_quote(base_amount = b, pair = p, type = t)
  File "/usr/local/lib/python3.7/dist-packages/luno_python/client.py", line 115, in create_quote
    return self.do('POST', '/api/1/quotes', req=req, auth=True)
  File "/usr/local/lib/python3.7/dist-packages/luno_python/base_client.py", line 84, in do
    e = res.json()
  File "/usr/lib/python3/dist-packages/requests/models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 518, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 373, in decode
    raise JSONDecodeError("Extra data", s, end, len(s))
simplejson.errors.JSONDecodeError: Extra data: line 1 column 5 - line 2 column 1 (char 4 - 19)

Example
create_quote(base_amount = "100" , pair = "XRPZAR", type = "SELL")

LUNO is a SCAM, don't use it

Don't use it, they STOLE your money and don't let you withdraw with escuses after escuses, when they answer at all.

pip repository not up to date

Hello

It seems that the pip repository is still on version 0.0.4. Will you be able to update?

Alternatively, I used:
pip install --upgrade https://github.com/luno/luno-python/archive/v0.0.7.tar.gz
to install the latest version (Version 0.0.7) at the time of writing.

Thanks

LUNO:Creating two Variables for the ('ZAR','balance':) & ('ETH','balance':).

Hello again, everybody. Three quick questions
BalR= c.get_balances(assets=['ZAR'])
BalR=BalR['balance']
print(BalR)

{'account_id': '619', 'asset': 'ZAR', 'balance': '6.19', 'reserved': '6.19', 'unconfirmed': '6.19'}
1)How do I create a Variable for the (‘ZAR’,’balance’) ?
I can’t use: BalR[2] because: len(BalR) equals to 1
If, I add another row of: BalR=BalR['balance'] under: BalR=BalR['balance'] then I get the following error
list indices must be integers or slices, not str
If I try a: print(BalR('balance')) I get the following error
TypeError: 'list' object is not callable
If I add: BalR=BalR[2] under: BalR=BalR[0] then: 2 is returned
I even went as far as poking in the dark with json with this

BalR=BalR['balance']
readable_json = json.loads(BalR)
BalR = readable_json['balance']
for i in BalR:
print(i['balance'])
the JSON object must be str, bytes or bytearray, not list
BalR= c.get_balances(assets=['ZAR'])
BalR=BalR['balance']
readable_json = json.loads(BalR)
for i in readable_json:
print(i['balance'])

the JSON object must be str, bytes or bytearray, not list

`BalR= c.get_balances(assets=['ZAR'])`
`BalR=BalR['balance']`
`readable_json = json.loads(BalR)`
`for i in readable_json[2]['balance']:`

print(i['balance'])

the JSON object must be str, bytes or bytearray, not list

The second Question is almost identical to the first, only difference being needing to make a Variable for (‘ETH’,’balance’).
Or is there another way to automatically add the maximum updated Zar to a buy order and automatically add the maximum amount of updated Eth to a sell order?

Please advise.

Invalid value error

Hi Guys,
While trying to post a market order using the following,
cl.post_market_order(min_name, 'BUY', base_account_id=buy_id, counter_volume=float(truncate(buy_val,buy_scale)), counter_account_id=btc_id)
I get the error:
('ErrInvalidValue', 'Invalid value provided for counter_volume')

I'm buying on the pair 'ADAXBT'

The value is above the indicated min value and truncated to the indicated precision as per: https://api.luno.com/api/exchange/1/markets

I have no idea what could be wrong.

Help please!!!

Kind Regards
MrBlindMouse

Post Limit Order just hangs

I am trying to use the Post Limit Order call on the API to sell BTC for ZAR. My script goes right up until trying to make the call to the Luno API using this library.

The Luno API key and secret are fine as I am pulling account balance just fine.

print('before call')
res = c.post_limit_order('XBTZAR', price, 'ASK', volume)
print('after call')

Using the above code, I only get the "before call" printed out, nothing else. No errors pop up either.

post_market_order error

Hello Everyone.

I have a problem regarding post_market_order which causes this error

image

Below is the code without api id and secret key

# Try 
from luno_python.client import Client

if __name__ == '__main__':

    # Get Balances
    c = Client(api_key_id='',api_key_secret='')
    res = c.get_balances()
    print(res)
    
    # Market Order BUY
    buy=c.post_market_order('ADAMYR','BUY',counter_volume=10.0)
    print(buy)

I hope you guys can help me solve this problem. Thank you in advance

JSON Dumped data is string, not float for "price", "value" etc.

The JSON dump that's returned as a dict has all numerical values returned as strings. Would be useful if the API could handle this natively. Doing it after the fact is painful.

def convert_json_to_float(obj):
    if isinstance(obj, dict):
        if "price" in obj:
            obj["price"] = float(obj["price"])
        if "volume" in obj:
            obj["volume"] = float(obj["volume"])
        return obj
    else:
        return obj

# instead, do this now using "object_hook" attr for json.loads method in base_client.py:
try:
    params = json.loads(json.dumps(req), object_hook=convert_json_to_float)
except Exception:
    params = None

I just don't know all the api k/v pairs that need to be accounted for other than "price" and "volume"...

It's clean, and supported in 2.7 and 3.x... Thoughts?

API error 401 for account related calls

Hi, I'm having some trouble with API calls in this library that relate to account specific information like balances or placing orders. I can use calls like "get_ticker" and "markets" for example without any issues, but calls like "get_balances" and "post_limit_order" return the same unknown API error 401. I've set my API settings on my account to allow trading. Not sure if there is something I missed in the setup. I would appreciate any help. Thanks.

How to detect pending order of stop limit order?

Hi,

I already have a pending/open stop-limit order.
Then I try to use list_orders(state='PENDING').
But it return None.

If i open limit order, then list_orders(state='PENDING'), it is working.

This list_orders(state='PENDING') is not working for stop limit order.
Do you know why?

list_orders limit

The list is truncated after 100 items. Is there anyway to increase it beyond 100?

tt1 is an unexpected argument

Hi,

I am trying to code post_limit_order with tt1 argument. Somehow I get an error saying "Client.post_limit_order() got an unexpected keyword argument 'tt1'".

I am wondering this tt1 is it meant for canceling a limit order after a certain amount of time has exceeded (specify by tt1) ?

Thanks.

Package on PyPi is outdated

The latest release for this project is 0.0.8, but the latest version on PyPi is 0.0.7.
@adamhicks or @neilgarb can you please update the package on PyPi?
I am happy to do it as well, but I obviously don't have permissions to do so on PyPi.

Luno:ConnectionError: ('Connection aborted.', ConnectionResetError . . .

Good day everyone, so this is the error I'm getting when I launch my script. If anybody could help, I'd be grateful.

`---------------------------------------------------------------------------
ConnectionResetError Traceback (most recent call last)
~\anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
698 # Make the request on the httplib connection object.
--> 699 httplib_response = self._make_request(
700 conn,

~\anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
444 # Otherwise it looks like a bug in the code.
--> 445 six.raise_from(e, None)
446 except (SocketTimeout, BaseSSLError, SocketError) as e:

~\anaconda3\lib\site-packages\urllib3\packages\six.py in raise_from(value, from_value)

~\anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
439 try:
--> 440 httplib_response = conn.getresponse()
441 except BaseException as e:

~\anaconda3\lib\http\client.py in getresponse(self)
1346 try:
-> 1347 response.begin()
1348 except ConnectionError:

~\anaconda3\lib\http\client.py in begin(self)
306 while True:
--> 307 version, status, reason = self._read_status()
308 if status != CONTINUE:

~\anaconda3\lib\http\client.py in _read_status(self)
267 def _read_status(self):
--> 268 line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
269 if len(line) > _MAXLINE:

~\anaconda3\lib\socket.py in readinto(self, b)
668 try:
--> 669 return self._sock.recv_into(b)
670 except timeout:

~\anaconda3\lib\ssl.py in recv_into(self, buffer, nbytes, flags)
1240 self.class)
-> 1241 return self.read(nbytes, buffer)
1242 else:

~\anaconda3\lib\ssl.py in read(self, len, buffer)
1098 if buffer is not None:
-> 1099 return self._sslobj.read(len, buffer)
1100 else:

ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

ProtocolError Traceback (most recent call last)
~\anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
439 if not chunked:
--> 440 resp = conn.urlopen(
441 method=request.method,

~\anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
754
--> 755 retries = retries.increment(
756 method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]

~\anaconda3\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
531 if read is False or not self._is_method_retryable(method):
--> 532 raise six.reraise(type(error), error, _stacktrace)
533 elif read is not None:

~\anaconda3\lib\site-packages\urllib3\packages\six.py in reraise(tp, value, tb)
733 if value.traceback is not tb:
--> 734 raise value.with_traceback(tb)
735 raise value

~\anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
698 # Make the request on the httplib connection object.
--> 699 httplib_response = self._make_request(
700 conn,

~\anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
444 # Otherwise it looks like a bug in the code.
--> 445 six.raise_from(e, None)
446 except (SocketTimeout, BaseSSLError, SocketError) as e:

~\anaconda3\lib\site-packages\urllib3\packages\six.py in raise_from(value, from_value)

~\anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
439 try:
--> 440 httplib_response = conn.getresponse()
441 except BaseException as e:

~\anaconda3\lib\http\client.py in getresponse(self)
1346 try:
-> 1347 response.begin()
1348 except ConnectionError:

~\anaconda3\lib\http\client.py in begin(self)
306 while True:
--> 307 version, status, reason = self._read_status()
308 if status != CONTINUE:

~\anaconda3\lib\http\client.py in _read_status(self)
267 def _read_status(self):
--> 268 line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
269 if len(line) > _MAXLINE:

~\anaconda3\lib\socket.py in readinto(self, b)
668 try:
--> 669 return self._sock.recv_into(b)
670 except timeout:

~\anaconda3\lib\ssl.py in recv_into(self, buffer, nbytes, flags)
1240 self.class)
-> 1241 return self.read(nbytes, buffer)
1242 else:

~\anaconda3\lib\ssl.py in read(self, len, buffer)
1098 if buffer is not None:
-> 1099 return self._sslobj.read(len, buffer)
1100 else:

ProtocolError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

~\anaconda3\lib\site-packages\luno_python\client.py in post_market_order(self, pair, type, base_account_id, base_volume, client_order_id, counter_account_id, counter_volume, timestamp, ttl)
771 'ttl': ttl,
772 }
--> 773 return self.do('POST', '/api/1/marketorder', req=req, auth=True)
774
775 def send(self, address, amount, currency, description=None, destination_tag=None, external_id=None, has_destination_tag=None, message=None):

~\anaconda3\lib\site-packages\luno_python\base_client.py in do(self, method, path, req, auth)
80 args['auth'] = (self.api_key_id, self.api_key_secret)
81 url = self.make_url(path, params)
---> 82 res = self.session.request(method, url, **args)
83 try:
84 e = res.json()

~\anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
527 }
528 send_kwargs.update(settings)
--> 529 resp = self.send(prep, **send_kwargs)
530
531 return resp

~\anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
643
644 # Send the request
--> 645 r = adapter.send(request, **kwargs)
646
647 # Total elapsed time of the request (approximately)

~\anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
499
500 except (ProtocolError, socket.error) as err:
--> 501 raise ConnectionError(err, request=request)
502
503 except MaxRetryError as e:

ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))`

Luno: Difficulties adding the API_KEY_SECRET.

Hello Everybody, I'm having trouble adding the Api_Key_Secret in my little python script on Jupyter. when I add it I get the following error

Timeout value connect was 9oJvvYd463YtdV64_C6f4UiOl9834ysFelP90cvD, but it must be an int,
float or None.

please advise.

Get a pairs full history

Gooday

Is there a way to get the full candle history?

I'm currently doing this but doesn't seem to be working correctly. For example ETH/ZAR the start date is 2019-07-09 14:00:00 but should be 2017-08-28.

def get_history(c, Pair):
exits=True
stamp=3600
since=int(int(time.time())1000-315360320001*30)
raw_data=c.get_candles(stamp,Pair,since)
candles=pd.DataFrame(raw_data["candles"],dtype=float)
candles['timestamp']=pd.to_datetime(candles['timestamp'],unit= 'ms',utc=False)+pd.Timedelta(hours=3)
candles.to_csv("history.csv",mode='w',index=False)
while since<int(int(time.time())) * 1000 and exits==True:
since=int(raw_data["candles"][-1]["timestamp"]+stamp * 1000)
if since<int(int(time.time())) * 1000-stamp * 1000:
raw_data.clear()
del candles
raw_data=c.get_candles(stamp,Pair,since)
candles=pd.DataFrame(raw_data["candles"],dtype=float)
candles['timestamp']=pd.to_datetime(candles['timestamp'],unit= 'ms')
candles.to_csv("history.csv",mode='a',index=False,header=False)
else:
exits=False
return 0

Regards

luno trading bot

C:\Users\gwill\PycharmProjects\pythonProject2\luno\venv\Scripts\python.exe C:/Users/gwill/luno.py
Traceback (most recent call last):
File "C:\Users\gwill\luno.py", line 2, in
from luno_python.client import Client
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named 'luno_python'

Process finished with exit code 1

Anyone that can give advice on how to solve this issue?
Thanks in advance

Get_Candle seems to be missing

It seems like the API function for get_candle hasn't been made yet. Is there any plans to have it added or am I missing something?

Can't seem to be able to initialise the client

Hi I have just recently started to learn some basic python programming. I am trying to build an automated trading bot for Luno. However, I have an issue with even the first step of running the code from luno_python.client import client

Have already installed the luno_python library via pip install luno-python

This issue doesn't happen when I tried to do the same for binance using the github codes.

The results of the issue
Traceback (most recent call last):
File "algo.py", line 43, in
from luno_python.client import client
ImportError: cannot import name 'client' from 'luno_python.client' (C:\Users\xxxx\anaconda3\lib\site-packages\luno_python\client.py)

post_limit_orders issue

Please can you give an example of the type of value that the post_only parameter can take. I still get trading fee even after using the post_limit_order.

get_balances() and list_user_trades() returning APIError

I have created my client as:

c = Client(api_key_id=os.getenv('LUNO_API_KEY_ID'),
api_key_secret=os.getenv('LUNO_API_KEY_SECRET'))

c.get_tickers(), c.list_trades() return the expected results.

c.get_balances() and c.list_user_trades() return: APIError: ('ErrAPIKeyNotFound', 'API key not found').

I see in the code: Permissions required: Perm_R_Orders. What can I do to get this to work?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.