Skip to content

Commit

Permalink
deleting open order, modified receiving orders and portfolio
Browse files Browse the repository at this point in the history
  • Loading branch information
lolokraus committed Jun 9, 2020
1 parent 65821f9 commit 61aadf7
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 40 deletions.
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ degiro.logout()
* product_info
* transactions
* orders
* delete_order
* get_stock_list
* buyorder
* sellorder
Expand All @@ -47,9 +48,9 @@ cashfunds = degiro.getdata(degiroapi.Data.Type.CASHFUNDS)
for data in cashfunds:
print(data)
```
Printing your current portfolio:
Printing your current portfolio, argument True to filter out products with a size of 0, False or no Argument to show all:
```
portfolio = degiro.getdata(degiroapi.Data.Type.PORTFOLIO)
portfolio = degiro.getdata(degiroapi.Data.Type.PORTFOLIO, True)
for data in portfolio:
print(data)
```
Expand All @@ -75,12 +76,27 @@ print(pretty_json(transactions))
```
## orders
Printing your order history(the maximum timespan is 90 days)
With argument True, this function only return open orders
```
from datetime import datetime, timedelta
orders = degiro.orders(datetime.now() - timedelta(days=90), datetime.now())
print(pretty_json(orders))
orders = degiro.orders(datetime.now() - timedelta(days=90), datetime.now(), True)
print(pretty_json(orders))
```

## delete_order
Deleting an open order with the orderId
```
orders = degiro.orders(datetime.now() - timedelta(days=1), datetime.now(), True)
degiro.delete_order(orders[0]['orderId'])
```
```
degiro.delete_order("f278d56f-eaa0-4dc7-b067-45c6b4b3d74f")
```

## get_stock_list
Get the symbols of the S&P500 stocks:
```
Expand Down
97 changes: 64 additions & 33 deletions degiroapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from degiroapi.client_info import ClientInfo
from degiroapi.datatypes import Data


class DeGiro:
__LOGIN_URL = 'https://trader.degiro.nl/login/secure/login'
__LOGOUT_URL = 'https://trader.degiro.nl/trading/secure/logout'
Expand All @@ -16,12 +17,13 @@ class DeGiro:
__ORDERS_URL = 'https://trader.degiro.nl/reporting/secure/v4/order-history'

__PLACE_ORDER_URL = 'https://trader.degiro.nl/trading/secure/v5/checkOrder'
__CONFIRM_ORDER_URL = 'https://trader.degiro.nl/trading/secure/v5/order/'
__ORDER_URL = 'https://trader.degiro.nl/trading/secure/v5/order/'

__DATA_URL = 'https://trader.degiro.nl/trading/secure/v5/update/'

__GET_REQUEST = 0
__POST_REQUEST = 1
__DELETE_REQUEST = 2

session_id = any
client_info = any
Expand Down Expand Up @@ -49,11 +51,16 @@ def logout(self):
'intAccount': self.client_info.account_id,
'sessionId': self.session_id,
}
self.__request(DeGiro.__LOGOUT_URL + ';jsessionid=' + self.session_id, logout_payload, error_message='Could not log out')
self.__request(DeGiro.__LOGOUT_URL + ';jsessionid=' + self.session_id, logout_payload,
error_message='Could not log out')

@staticmethod
def __request(url, payload, headers=None, data=None, post_params=None, request_type=__GET_REQUEST, error_message='An error occurred.'):
if request_type == DeGiro.__GET_REQUEST:
def __request(url, payload, headers=None, data=None, post_params=None, request_type=__GET_REQUEST,
error_message='An error occurred.'):

if request_type == DeGiro.__DELETE_REQUEST:
response = requests.delete(url, json=payload)
elif request_type == DeGiro.__GET_REQUEST:
response = requests.get(url, params=payload)
elif request_type == DeGiro.__POST_REQUEST and headers and data:
response = requests.post(url, headers=headers, params=payload, data=data)
Expand All @@ -80,23 +87,19 @@ def search_products(self, search_text, limit=1):
'intAccount': self.client_info.account_id,
'sessionId': self.session_id
}
return \
self.__request(DeGiro.__PRODUCT_SEARCH_URL, product_search_payload,
error_message='Could not get products.')[
'products']
return self.__request(DeGiro.__PRODUCT_SEARCH_URL, product_search_payload,
error_message='Could not get products.')['products']

def product_info(self, product_id):
product_info_payload = {
'intAccount': self.client_info.account_id,
'sessionId': self.session_id
}
return \
self.__request(DeGiro.__PRODUCT_INFO_URL,
product_info_payload,
headers={'content-type': 'application/json'},
data=json.dumps([str(product_id)]),
request_type=DeGiro.__POST_REQUEST,
error_message='Could not get product info.')['data'][str(product_id)]
return self.__request(DeGiro.__PRODUCT_INFO_URL, product_info_payload,
headers={'content-type': 'application/json'},
data=json.dumps([str(product_id)]),
request_type=DeGiro.__POST_REQUEST,
error_message='Could not get product info.')['data'][str(product_id)]

def transactions(self, from_date, to_date, group_transactions=False):
transactions_payload = {
Expand All @@ -106,12 +109,10 @@ def transactions(self, from_date, to_date, group_transactions=False):
'intAccount': self.client_info.account_id,
'sessionId': self.session_id
}
return \
self.__request(DeGiro.__TRANSACTIONS_URL, transactions_payload,
error_message='Could not get transactions.')[
'data']
return self.__request(DeGiro.__TRANSACTIONS_URL, transactions_payload,
error_message='Could not get transactions.')['data']

def orders(self, from_date, to_date):
def orders(self, from_date, to_date, not_executed=None):
orders_payload = {
'fromDate': from_date.strftime('%d/%m/%Y'),
'toDate': to_date.strftime('%d/%m/%Y'),
Expand All @@ -121,7 +122,25 @@ def orders(self, from_date, to_date):
# max 90 days
if (to_date - from_date).days > 90:
raise Exception('The maximum timespan is 90 days')
return self.__request(DeGiro.__ORDERS_URL, orders_payload, error_message='Could not get orders.')['data']
data = self.__request(DeGiro.__ORDERS_URL, orders_payload, error_message='Could not get orders.')['data']
data_not_executed = []
if not_executed:
for d in data:
if d['isActive']:
data_not_executed.append(d)
return data_not_executed
else:
return data

def delete_order(self, orderId):
delete_order_params = {
'intAccount': self.client_info.account_id,
'sessionId': self.session_id,
}

return self.__request(DeGiro.__ORDER_URL + orderId + ';jsessionid=' + self.session_id, delete_order_params,
request_type=DeGiro.__DELETE_REQUEST,
error_message='Could not delete order' + " " + orderId)

@staticmethod
def filtercashfunds(cashfunds):
Expand All @@ -132,13 +151,14 @@ def filtercashfunds(cashfunds):
return data

@staticmethod
def filterportfolio(portfolio):
def filterportfolio(portfolio, filter_zero=None):
data = []
data_non_zero = []
for item in portfolio['portfolio']['value']:
positionType = size = price = value = breakEvenPrice = None
for i in item['value']:
positionType = i['value'] if i['name'] == 'positionType' else positionType
size = i['value'] if i['name'] == 'size' else size
positionType = i['value'] if i['name'] == 'positionType' else positionType
price = i['value'] if i['name'] == 'price' else price
value = i['value'] if i['name'] == 'value' else value
breakEvenPrice = i['value'] if i['name'] == 'breakEvenPrice' else breakEvenPrice
Expand All @@ -149,25 +169,34 @@ def filterportfolio(portfolio):
"price": price,
"value": value,
"breakEvenPrice": breakEvenPrice
})
return data
})
if filter_zero:
for d in data:
if d['size'] != 0.0:
data_non_zero.append(d)
return data_non_zero
else:
return data

def getdata(self, datatype):
def getdata(self, datatype, filter_zero=None):
data_payload = {
datatype: 0
}

if datatype == Data.Type.CASHFUNDS:
return self.filtercashfunds(
self.__request(DeGiro.__DATA_URL + str(self.client_info.account_id) + ';jsessionid=' + self.session_id,
data_payload, error_message='Could not get data'))
data_payload,
error_message='Could not get data'))
elif datatype == Data.Type.PORTFOLIO:
return self.filterportfolio(
self.__request(DeGiro.__DATA_URL + str(self.client_info.account_id) + ';jsessionid=' + self.session_id,
data_payload, error_message='Could not get data'))
data_payload,
error_message='Could not get data'), filter_zero)
else:
return self.__request(
DeGiro.__DATA_URL + str(self.client_info.account_id) + ';jsessionid=' + self.session_id, data_payload, error_message='Could not get data')
DeGiro.__DATA_URL + str(self.client_info.account_id) + ';jsessionid=' + self.session_id, data_payload,
error_message='Could not get data')

def buyorder(self, orderType, productId, timeType, size, limit=None, stop_loss=None):
place_buy_order_params = {
Expand Down Expand Up @@ -197,8 +226,9 @@ def buyorder(self, orderType, productId, timeType, size, limit=None, stop_loss=N

self.confirmation_id = place_check_order_response['data']['confirmationId']

self.__request(DeGiro.__CONFIRM_ORDER_URL + self.confirmation_id + ';jsessionid=' + self.session_id,
place_buy_order_payload, place_buy_order_params, request_type=DeGiro.__POST_REQUEST,
self.__request(DeGiro.__ORDER_URL + self.confirmation_id + ';jsessionid=' + self.session_id,
place_buy_order_payload, place_buy_order_params,
request_type=DeGiro.__POST_REQUEST,
error_message='Could not confirm order')

def sellorder(self, orderType, productId, timeType, size, limit=None, stop_loss=None):
Expand Down Expand Up @@ -229,8 +259,9 @@ def sellorder(self, orderType, productId, timeType, size, limit=None, stop_loss=

self.confirmation_id = place_check_order_response['data']['confirmationId']

self.__request(DeGiro.__CONFIRM_ORDER_URL + self.confirmation_id + ';jsessionid=' + self.session_id,
place_sell_order_payload, place_sell_order_params, request_type=DeGiro.__POST_REQUEST,
self.__request(DeGiro.__ORDER_URL + self.confirmation_id + ';jsessionid=' + self.session_id,
place_sell_order_payload, place_sell_order_params,
request_type=DeGiro.__POST_REQUEST,
error_message='Could not confirm order')

def get_stock_list(self, indexId, stockCountryId):
Expand Down
2 changes: 1 addition & 1 deletion degiroapi/datatypes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class Data:
class Type:
PORTFOLIO = 'portfolio'
CASHFUNDS = 'cashFunds'
CASHFUNDS = 'cashFunds'
21 changes: 18 additions & 3 deletions examples/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
for data in cashfunds:
print(data)

# print the current portfolio
portfolio = degiro.getdata(degiroapi.Data.Type.PORTFOLIO)
# print the current portfolio (True to filter Products with size 0, False to show all)
portfolio = degiro.getdata(degiroapi.Data.Type.PORTFOLIO, True)
for data in portfolio:
print(data)

Expand All @@ -41,6 +41,11 @@
print(Product(products[1]).id)
print(Product(products[2]).id)

# P
# printing info for a specified product ID:
info = degiro.product_info(5322419)
print(info["id"], info["name"], info["currency"], info["closePrice"])

# print transactions
transactions = degiro.transactions(datetime(2019, 1, 1), datetime.now())
print(pretty_json(transactions))
Expand All @@ -49,6 +54,16 @@
orders = degiro.orders(datetime.now() - timedelta(days=90), datetime.now())
print(pretty_json(orders))

# printing order history (maximum timespan 90 days), with argument True return only open orders
orders = degiro.orders(datetime.now() - timedelta(days=90), datetime.now(), True)
print(pretty_json(orders))

# deleting an open order
orders = degiro.orders(datetime.now() - timedelta(days=1), datetime.now(), True)
degiro.delete_order(orders[0]['orderId'])

degiro.delete_order("f278d56f-eaa0-4dc7-b067-45c6b4b3d74f")

# get s&p 500 stock list
sp5symbols = []
products = degiro.get_stock_list(14, 846)
Expand Down Expand Up @@ -88,4 +103,4 @@
degiro.sellorder(Order.Type.MARKET, Product(products[0]).id, 3, 1)

# order type, product id, execution time type (either 1 for "valid on a daily basis", or 3 for "unlimited"), size, don't change none, stop_loss(stop loss price)
degiro.sellorder(Order.Type.STOPLOSS, Product(products[0]).id, 3, 1, None, 38)
degiro.sellorder(Order.Type.STOPLOSS, Product(products[0]).id, 3, 1, None, 38)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="degiroapi",
version="0.8.4",
version="0.9",
author="Lorenz Kraus",
author_email="lorenz.kraus@gmail.com",
description="An unofficial API for the trading platform Degiro written in Python",
Expand Down

0 comments on commit 61aadf7

Please sign in to comment.