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

12 add examples to all clients #13

Merged
merged 3 commits into from
Jul 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,4 @@ dmypy.json

# Pyre type checker
.pyre/
.DS_Store
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@


https://docs.kraken.com/rest/


## Notes:
- Triggers: stop-loss, stop-loss-limit, take-profit and take-profit-limit orders.
34 changes: 18 additions & 16 deletions base_request/base_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import json
import requests
import logging
import hmac
import hashlib
import base64
Expand All @@ -15,16 +16,22 @@

class KrakenBaseRestAPI(object):

def __init__(self, key='', secret='', url='', api_version=0):
def __init__(self, key: str='', secret: str='', url: str='', futures: bool=False):

self._api_v = ''
if url: self.url = url
else: self.url = 'https://api.kraken.com'
elif futures:
self.url = 'https://futures.kraken.com/derivatives'
self._api_v = '/api/v3'
raise ValueError('Futures endpoints and clients not implemented yet.')
else:
self.url = 'https://api.kraken.com'
self._api_v = '/0'

self.key = key
self.secret = secret
self.api_v = api_version

def _request(self, method, uri, timeout=10, auth=True, params={}, do_json=False):
def _request(self, method: str, uri: str, timeout: int=10, auth: bool=True, params: dict={}, do_json: bool=False, return_raw: bool=False):
uri_path = uri
data_json = ''
params['nonce'] = str(int(time.time()*1000)) # generate nonce
Expand All @@ -37,34 +44,28 @@ def _request(self, method, uri, timeout=10, auth=True, params={}, do_json=False)
data_json += '&'.join(strl)
uri += f'?{data_json}'
uri_path = uri
else:
if params:
pass
#data_json = json.dumps(params)
#uri_path = f'{uri}{data_json}'

headers = {}
if auth:
if not self.key or self.key == '' or not self.secret or self.secret == '': raise ValueError('Missing credentials')
headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'API-Key': self.key,
'API-Sign': self.get_kraken_signature(f'/{self.api_v}{uri}', params)
'API-Sign': self.get_kraken_signature(f'{self._api_v}{uri}', params)
}

headers['User-Agent'] = 'Kraken-Python-SDK'
url = f'{self.url}/{self.api_v}{uri}'
url = f'{self.url}{self._api_v}{uri}'

print(url)
logging.info(f'Request: {url}')

if method in ['GET', 'DELETE']:
response_data = requests.request(method, url, headers=headers, timeout=timeout)
else:
if do_json:
response_data = requests.request(method, url, headers=headers, json=params, timeout=timeout)
return self.check_response_data(requests.request(method, url, headers=headers, json=params, timeout=timeout), return_raw)
else:
response_data = requests.request(method, url, headers=headers, data=params, timeout=timeout)
return self.check_response_data(response_data)
return self.check_response_data(requests.request(method, url, headers=headers, data=params, timeout=timeout), return_raw)

def get_kraken_signature(self, urlpath, data):
postdata = urllib.parse.urlencode(data)
Expand All @@ -76,8 +77,9 @@ def get_kraken_signature(self, urlpath, data):
return sigdigest.decode()

@staticmethod
def check_response_data(response_data):
def check_response_data(response_data, return_raw: bool=False):
if response_data.status_code == 200:
if return_raw: return response_data
try:
data = response_data.json()
except ValueError:
Expand Down
12 changes: 6 additions & 6 deletions client.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from market.market import MarketData
from trade.trade import TradeData
from user.user import UserData
from funding.funding import FundingData
from staking.staking import StakingData
from ws_client.ws_client import WsClientData
from kraken.market.market import MarketData
from kraken.trade.trade import TradeData
from kraken.user.user import UserData
from kraken.funding.funding import FundingData
from kraken.staking.staking import StakingData
from kraken.ws_client.ws_client import WsClientData

class User(UserData):
pass
Expand Down
161 changes: 161 additions & 0 deletions examples/examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import os, sys

sys.path.append('/Users/benjamin/repositories/Trading/')

import asyncio
import logging
import logging.config
from dotenv import dotenv_values
from datetime import datetime

from kraken.client import User, Market, Trade, Funding, Staking
from kraken.websocket.websocket import KrakenWsClient


logging.basicConfig(
format='%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
filemode='w',
level=logging.INFO
)
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)

def main() -> None:

key = dotenv_values('.env')['API_KEY']
secret = dotenv_values('.env')['SECRET_KEY']

# ---- R E S T - E N D P O I N T S ----

# ___User_________________________
user = User(key=key, secret=secret)

# print(user.get_account_balance())
# print(user.get_trade_balance())#asset='BTC'
# print(user.get_open_orders())
# print(user.get_closed_orders())
# print(user.get_orders_info(txid='someid')) # or txid='id1,id2,id3' or txid=['id1','id2']
# print(user.get_trades_history())
# print(user.get_trades_info(txid='someid'))
# print(user.get_open_positions())#txid='someid'
# print(user.get_ledgers_info())#asset='BTC' or asset='BTC,EUR' or asset=['BTC','EUR']
# print(user.get_ledgers(id='LNBK7T-BLEFU-C6NGIS'))
# print(user.get_trade_volume())#pair='BTC/EUR'

#____export_report____
# print(user.request_export_report(report='ledgers', description='myLedgers1', format='CSV'))#report='trades'
# print(user.get_export_report_status(report='ledgers'))

# save report to file
# response_data = user.retrieve_export(id='INSG')
# handle = open('myexport.zip', 'wb')
# for chunk in response_data.iter_content(chunk_size=512):
# if chunk: handle.write(chunk)
# handle.close()

#print(user.delete_export_report(id='INSG', type='delete'))#type=cancel


# ___Market___________________________
market = Market(key=key, secret=secret)

# print(market.get_assets(assets=['XBT']))
# print(market.get_tradable_asset_pair(pair=['BTCEUR','DOTEUR']))
# print(market.get_ticker(pair='BTCUSD'))
# print(market.get_ohlc(pair='BTCUSD', interval=5))
# print(market.get_order_book(pair='BTCUSDT', count=10))
# print(market.get_recent_trades(pair='BTCUSDT'))
# print(market.get_recend_spreads(pair='XBTUSD'))
# print(market.get_system_status())

# ____Trade_________________________
trade = Trade(key=key, secret=secret)

# print(trade.create_order(
# ordertype='limit',
# side='buy',
# volume=1,
# pair='BTC/EUR',
# price=20000
# ))
# print(trade.create_order_batch(
# orders=[{
# 'ordertype:': 'limit',
# 'price': 20000,
# 'type': 'buy',
# 'volume': 1

# },{
# 'ordertype': 'limit',
# 'type': 'buy',
# 'volume': '1',
# 'price': 19000
# },{
# 'close': {
# 'ordertype': 'stop-loss-limit',
# 'price': 37000,
# 'price2': 36000
# },
# 'ordertype': 'limit',
# 'price': 40000,
# 'price2': 39000,
# 'timeinforce': 'GTC',
# 'type': 'buy',
# 'userref': '12123123',
# 'volume': '0.5'
# }],
# deadline='2022-10-24T14:14:23Z',
# pair='BTC/EUR',
# validate=True
# ))

# print(trade.edit_order(
# txid='sometxid',
# pair='BTC/EUR',
# volume='4.2',
# price=17000
# ))

# print(trade.cancel_order(
# txid='sometxid'
# ))

# print(trade.cancel_all_orders())

# print(trade.cancel_all_orders_after_x(
# timeout=60
# ))

# print(trade.cancel_order_batch(
# orders=['OG5V2Y-RYKVL-DT3V3B','OP5V2Y-RYKVL-ET3V3B']
# ))


# ____Funding___________________________
funding = Funding(key=key, secret=secret)

# print(funding.get_deposit_methods(asset='DOT'))
# print(funding.get_deposit_address(asset='DOT', method='Polkadot'))
# print(funding.get_recend_deposits_status(asset='DOT'))
# print(funding.get_withdrawal_info(asset='DOT', key='MyPolkadotWallet', amount='200'))
# print(funding.withdraw_funds(asset='DOT', key='MyPolkadotWallet', amount=200))
# print(funding.get_recend_withdraw_status(asset='DOT' ))
# print(funding.cancel_widthdraw(asset='DOT', refid='12345'))
# print(funding.wallet_transfer(asset='ETH', amount=0.100, from_='Spot Wallet', to='Futures Wallet'))

# ____Staking___________________________
staking = Staking(key=key, secret=secret)

# print(staking.stake_asset(asset='DOT', amount=20, method='polkadot-staked'))
# print(staking.unstake_asset(asset='DOT.S', amount=20, method='polkadot-staked'))
# print(staking.list_stakeable_assets())
# print(staking.get_pending_staking_transactions())
# print(staking.list_staking_transactions())




if __name__ == '__main__':
main()
56 changes: 56 additions & 0 deletions examples/ws_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import os, sys

sys.path.append('/Users/benjamin/repositories/Trading/')

import asyncio
import logging
import logging.config
from dotenv import dotenv_values
from datetime import datetime

from kraken.client import WsClient
from kraken.websocket.websocket import KrakenWsClient

logging.basicConfig(
format='%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
filemode='w',
level=logging.INFO
)
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)

async def main() -> None:

key = dotenv_values('.env')['API_KEY']
secret = dotenv_values('.env')['SECRET_KEY']

# ___Custom_Trading_Bot______________
class Bot(KrakenWsClient):

async def on_message(self, event) -> None:
if 'event' in event:
topic = event['event']
if topic == 'heartbeat': return
elif topic == 'pong': return

print(f'--->{event}')
# await self._client.create_order(
# ordertype='limit',
# side='buy',
# pair='BTC/EUR',
# price=20000,
# volume=1
# )
# ... it is also possible to call regular REST endpoints
# but using the websocket messages is more efficient

bot = Bot(WsClient(key=key, secret=secret))
await bot.subscribe(pair=['BTC/EUR'], subscription={ 'name': 'ticker' }, private=False)

while True: await asyncio.sleep(6)

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
8 changes: 4 additions & 4 deletions funding/funding.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def get_deposit_methods(self, asset: str) -> dict:
params = { 'asset': asset }
return self._request('POST', '/private/DepositMethods', params=params)

def get_deposit_address(self, asset:str, method: str, new: bool=False) -> dict:
def get_deposit_address(self, asset: str, method: str, new: bool=False) -> dict:
'''https://docs.kraken.com/rest/#operation/getDepositAddresses'''
params = {
'asset': asset,
Expand All @@ -27,7 +27,7 @@ def get_withdrawal_info(self, asset: str, key: str, amount: str) -> dict:
'''https://docs.kraken.com/rest/#operation/getWithdrawalInformation'''
params = {
'asset': asset,
'key': key,
'key': str(key),
'amount': str(amount)
}
return self._request('POST', '/private/WithdrawInfo', params=params)
Expand All @@ -41,7 +41,7 @@ def withdraw_funds(self, asset: str, key: str, amount: str) -> dict:
}
return self._request('POST', '/private/Withdraw', params=params)

def get_recend_withdraw_status(self, asset: str, method:str=None) -> dict:
def get_recend_withdraw_status(self, asset: str, method: str=None) -> dict:
'''https://docs.kraken.com/rest/#operation/getStatusRecentWithdrawals'''
params = { 'asset': asset }
if method != None: params['method'] = method
Expand All @@ -61,6 +61,6 @@ def wallet_transfer(self, asset: str, from_: str, to: str, amount: str) -> dict:
'asset': asset,
'from': from_,
'to': to,
'amount': str(amount)
'amount': amount
}
return self._request('POST', '/private/WalletTransfer', params=params)
Loading