Code Monkey home page Code Monkey logo

gemini-python's Introduction

gemini-python

A python client for the Gemini API and Websocket

Getting Started

Installation

pip install gemini_python

PublicClient

This endpoint doesn't require an api-key and can be used without having a Gemini account. This README will document some of the methods and features of the class.

import gemini
r = gemini.PublicClient()
# Alternatively, for a sandbox environment, set sandbox=True
r = gemini.PublicClient(sandbox=True)

PublicClient Methods

r.symbols()
r.symbol_details("BTCUSD")
r.get_ticker("BTCUSD")
r.get_current_order_book("BTCUSD")
# Will get the latest 500 trades
r.get_trade_history("BTCUSD")
# Alternatively, it can be specified for a specific date
r.get_trade_history("BTCUSD", since="17/06/2017")
# Will get the latest 500 auctions
r.get_auction_history("BTCUSD")
# Alternatively, it can be specified for a specific date
r.get_auction_history("BTCUSD", since="17/06/2017")

PrivateClient

This endpoint requires both a public and private key to access the API. Hence, one must have an account with Gemini and register an application. So far, if the 'heartbeat' option is enabled for the API, the user must manually revive the heartbeat. Further options will be added in the future in order to avoid doing this manually.

The payload of the requests will be a JSON object. Rather than being sent as the body of the POST request, Gemini requires it to be base-64 encoded and stored as a header in the request. Adding a 'nonce' is optional for the API but is highly recommended. That's why the class will always send each request with a unique 'nonce'. An important point to note is that every argument for the methods of PrivateClient must be strings with the exception of 'options'.

import gemini
r = gemini.PrivateClient("EXAMPLE_PUBLIC_KEY", "EXAMPLE_PRIVATE_KEY")
# Alternatively, for a sandbox environment, set sandbox=True
r = gemini.PrivateClient("EXAMPLE_PUBLIC_KEY", "EXAMPLE_PRIVATE_KEY", sandbox=True)

PrivateClient Methods

r.new_order("BTCUSD", "200", "6000", "buy")
r.cancel_order("866403510")
r.wrap_order("GUSDUSD", "10", "buy")
r.cancel_session_orders()
r.cancel_all_orders()
r.status_of_order("866403510")
r.active_orders()
# Will get the last 500 past trades
r.get_past_trades("BTCUSD")
# Alternatively, you can set the limit_trades number to your liking
r.get_past_trades("BTCUSD", limit_trades="200")
r.get_trade_volume()
r.get_balance()
# This will create a new currency address
r.create_deposit_address("BTCUSD")
# Alternatively, you can specify the label
r.create_deposit_address("BTCUSD", label="Main Bitcoin Address")
r.withdraw_to_address("ETH", "0x0287b1B0032Dc42c16640F71BA06F1A87C3a7101", "20")
r.revive_hearbeat()

Websocket Client

If you'd prefer to recieve live updates you can either choose to subsribe to the public market data websocket or the private order events websocket. For more information about the difference between the two websockets visit the official Gemini documentation.

MarketData Websocket

Market data is a public API that streams all the market data on a given symbol.

import gemini
r = gemini.MarketDataWS('btcusd')
# Alternatively, for a sandbox environment, set sandbox=True
r = gemini.MarketDataWS('btcusd', sandbox=True)

MarketData Websocket Methods

  • get list of recorded trades
r.trades
  • get recorded bids
r.bids
  • get recorded asks
r.asks
  • get market book
r.get_market_book()
  • remove a recorded price from bids or asks
# To remove a price from bids
r.remove_from_bids('10000')
# To remove a price from asks
r.remove_from_asks('10000')
  • search for a particular price recorded
r.search_price('10000')
  • export recorded trades to csv
r.export_to_csv(r'/c/Users/user/Documents')
  • export recorded trades to xml
r.export_to_xml(r'/c/Users/user/Documents')

OrderEvents Websocket

Order events is a private API that gives you information about your orders in real time.When you connect, you get a book of your active orders. Then in real time you'll get information about order events like:

  • when your orders are accepted by the exchange
  • when your orders first appear on the book
  • fills
  • cancels
  • and more.

Support for subscription filters is currently under development

import gemini
r = gemini.OrderEventsWS("EXAMPLE_PUBLIC_KEY", "EXAMPLE_PRIVATE_KEY")
# Alternatively, for a sandbox environment, set sandbox=True
r = gemini.OrderEventsWS("EXAMPLE_PUBLIC_KEY", "EXAMPLE_PRIVATE_KEY", sandbox=True)

OrderEvents Websocket Methods

  • get order types
"""All trades are categorised in terms of either subscription_ack', 'heartbeat', 
'initial', 'accepted','rejected', 'booked', 'fill', 'cancelled', 
'cancel_rejected' or 'closed'. The following will print these types"""
r.get_order_types
  • get order book
# Will return all recorded orders
r.get_order_book
  • remove a recorded price from the order book
# Arguments are: type and order_id
r.remove_order('accepted', '12321123')
  • export recorded trades to csv
# Arguments are: directory and type
# The following will export all 'accepted' orders to a csv format
r.export_to_csv(r'/c/Users/user/Documents', 'accepted')
  • export recorded trades to xml
# Arguments are: directory and type. 
# The following will export all 'accepted' orders to a xml format
r.export_to_xml(r'/c/Users/user/Documents', 'accepted')

Under Development

  • Add filter options to order events websocket
  • Improve options to add and remove orders from market data websocket
  • Add options to choose whether a particular class is cached or not
  • Export recorded data from market data or order events websocket into a matplotlib graph
  • Export recorded data from market data or order events websocket into a sqlite, postgresl or sql database
  • Add test for the cached metaclass

Change Log

0.2.0

  • Created BaseWebsocket class
  • Created OrderEventsWS class to interact with the order events websocket
  • Created MarketDataWS class to interact with the market data websocket
  • Added greater support for heartbeat API's
  • Improved the Cached metaclass
  • Added support for sandbox urls

0.0.1

  • Original release

gemini-python's People

Contributors

mtusman avatar squilter avatar thetallman67 avatar yiwensong avatar

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  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

gemini-python's Issues

get_trade_history not working as expected

When I am using the get_trade_history I only get 50 trades, not 500 like the README claims. This doesn't change even when I use the since argument. The 50 trades also tend to be the same time no matter what the date in since is.

Mtusman

Let's try dysfunction can work or not

ImportError: cannot import name 'create_connection' from 'websocket'

I ran pip install gemini_python but when I try to run the following simple script to place an order:

import gemini
import secrets


def main():
    r = gemini.PrivateClient(secrets.api_key, secrets.api_secret)
    r.new_order("XTZUSD", "250", "6.6281", "buy")


if __name__ == '__main__':
    main()

I get the error:

Traceback (most recent call last):
  File "/Users/sergeiwallace/PycharmProjects/GeminiAPI/main.py", line 1, in <module>
    import gemini
  File "/Users/sergeiwallace/PycharmProjects/GeminiAPI/venv/lib/python3.9/site-packages/gemini/__init__.py", line 3, in <module>
    from .basewebsocket import BaseWebSocket
  File "/Users/sergeiwallace/PycharmProjects/GeminiAPI/venv/lib/python3.9/site-packages/gemini/basewebsocket.py", line 9, in <module>
    from websocket import create_connection, WebSocketConnectionClosedException
ImportError: cannot import name 'create_connection' from 'websocket' (/Users/sergeiwallace/PycharmProjects/GeminiAPI/venv/lib/python3.9/site-packages/websocket/__init__.py)

I've explicitly run pip install websocket-client but it says it's already installed.

Anyone know what the issue is?

ImportError: cannot import name 'create_connection' from 'websocket'

I get this error when i pip installed gemini-python. I checked the websocket library, it doesn't contain a create_connection function, help!!

import gemini
File "C:\Users\clone\Documents\InvestAndTrading\Crypto\DemonWicker\venv\lib\site-packages\gemini_init_.py", line 3, in
from .basewebsocket import BaseWebSocket
File "C:\Users\clone\Documents\InvestAndTrading\Crypto\DemonWicker\venv\lib\site-packages\gemini\basewebsocket.py", line 9, in
from websocket import create_connection, WebSocketConnectionClosedException
ImportError: cannot import name 'create_connection' from 'websocket' (C:\Users\clone\Documents\InvestAndTrading\Crypto\DemonWicker\venv\lib\site-packages\websocket_init_.py)

MarketData Websocket not getting updated

I tried running

r_ws = gemini.MarketDataWS('BTCUSD', sandbox=True)

but found that subsequently the class object is not getting updated (i.e. the dictionaries are always empty). Interestingly, using websocket-client WebSocketApp function directly does correctly trigger the on_message regularly. Does anyone have similar experience?

API Returns None To Successful Withdrawal Request

I've come across an issue with api_query() in the PrivateClient class. I executed a crypto withdrawal request and the r.json() return value came back as None which then causes the loader to throw a JSONDecodeError.

The call however did successfully execute on Gemini. In other words, the withdrawal request was successful, but the wrapper throws an exception.

Not sure if there is anyway this can be addressed, maybe check the status code of the response before returning the JSON. This way the caller may have a better idea of what actually occurred (what error code was returned by Gemini).

The fact that the withdrawal request was successful is the really confusing part... have you guys encountered any similar issues?

Return full response object from api_query

I noticed that in private_client.py the api_query method only returns the JSON data from the response object instead of the full response object. Is there a reason behind this?

My issue is that it would be useful to leverage the status code of the response to determine how to handle the response on the client. Currently, you would have to parse the JSON data for certain text in order to handle errors for example.

Market Data is not easy to use

I want to be able to get the current ask and bid price. MarketDataWS stores tons of info that I have to parse through. It would be nice if the parsing happened automatically so that I could easily figure out what the current ask is, or easily figure out the current volume at some bid price.

get_past_trades requires an optional argument

Problem: It looks like the get_past_trades method requires the symbol as an argument, but the gemini API does not require this. Doing it this way requires a user to make several requests if they are checking the status of orders across multiple currencies, or to completely sidestep the get_past_trades and directly call the api_query method (which I did).

Solution: make the symbol an optional keyword argument.

Market data wrapper keeps disconnecting

Hi,
I'm trying to use the MarketDataWS class to connect to Gemini's market data websocket. However, after a minute or so afterwards of initialising the class it keeps disconnecting and repeatedly showing the error message "socket is already closed" and doesn't record any trades.

This is my following code:

from gemini import MarketDataWS
a = MarketDataWS('btcusd')
a.start()

and after a minute or so the following message keeps repeating forever:

...
socket is already closed 
socket is already closed
socket is already closed
socket is already closed
socket is already closed
socket is already closed

Also when i try to force close the connection it just freezes and when I press CTRL + C , I get the following error:

>>> a.close()
^CTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/code/gemini/basewebsocket.py", line 54, in close
    self.thread.join()
  File "/usr/local/lib/python3.6/threading.py", line 1056, in join
    self._wait_for_tstate_lock()
  File "/usr/local/lib/python3.6/threading.py", line 1072, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt
>>> Connection is already closed.

--Ended Connection--

How to get transaction history without querying all trading pairs?

hi there,
It seems the only way to get your transaction history is to use the get_past_trades method and iterate through all the trading pairs. The website has a way to download a csv of all your trades, which looks like it's coming from https://exchange.gemini.com/history/trades. There has to be a simpler way to get all trades of all trading pairs. Do you have a sample script that can show how to do this programmatically?
thanks!
Chris

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.