Merge pull request #2 from Davi0k/fix/examples

Merge branch `fix/examples` in branch `master`.
This commit is contained in:
Davide Casale
2023-02-20 18:30:18 +01:00
committed by GitHub
44 changed files with 401 additions and 637 deletions

View File

@@ -9,13 +9,13 @@ class Notification(_Type, Generic[T]):
mts: int
type: str
message_id: Optional[int]
notify_info: T
data: T
code: Optional[int]
status: str
text: str
class _Notification(_Serializer, Generic[T]):
__LABELS = [ "mts", "type", "message_id", "_PLACEHOLDER", "notify_info", "code", "status", "text" ]
__LABELS = [ "mts", "type", "message_id", "_PLACEHOLDER", "data", "code", "status", "text" ]
def __init__(self, serializer: Optional[_Serializer] = None, is_iterable: bool = False):
super().__init__("Notification", Notification, _Notification.__LABELS, IGNORE = [ "_PLACEHOLDER" ])
@@ -26,13 +26,13 @@ class _Notification(_Serializer, Generic[T]):
notification = cast(Notification[T], Notification(**dict(self._serialize(*values))))
if isinstance(self.serializer, _Serializer):
NOTIFY_INFO = cast(List[Any], notification.notify_info)
data = cast(List[Any], notification.data)
if self.is_iterable == False:
if len(NOTIFY_INFO) == 1 and isinstance(NOTIFY_INFO[0], list):
NOTIFY_INFO = NOTIFY_INFO[0]
if len(data) == 1 and isinstance(data[0], list):
data = data[0]
notification.notify_info = cast(T, self.serializer.klass(**dict(self.serializer._serialize(*NOTIFY_INFO, skip=skip))))
else: notification.notify_info = cast(T, [ self.serializer.klass(**dict(self.serializer._serialize(*data, skip=skip))) for data in NOTIFY_INFO ])
notification.data = cast(T, self.serializer.klass(**dict(self.serializer._serialize(*data, skip=skip))))
else: notification.data = cast(T, [ self.serializer.klass(**dict(self.serializer._serialize(*sub_data, skip=skip))) for sub_data in data ])
return notification

View File

@@ -201,7 +201,7 @@ class RestAuthenticatedEndpoints(Middleware):
"rate": rate, "period": period
}))
def toggle_keep(self, type: Literal["credit", "loan"], ids: Optional[List[int]] = None, changes: Optional[Dict[int, bool]] = None) -> Notification[Literal[None]]:
def toggle_keep_funding(self, type: Literal["credit", "loan"], ids: Optional[List[int]] = None, changes: Optional[Dict[int, Literal[1, 2]]] = None) -> Notification[Literal[None]]:
return serializers._Notification[Literal[None]](None).parse(*self._POST("auth/w/funding/keep", body={
"type": type,
"id": ids,

View File

@@ -1,4 +1,4 @@
from typing import List, Dict, Optional, Literal, Any
from typing import *
from dataclasses import dataclass

View File

@@ -1,4 +1,4 @@
from typing import Optional
from typing import *
from dataclasses import dataclass

View File

View File

@@ -0,0 +1,19 @@
# python -c "import examples.rest.authenticated.claim_position"
import os
from bfxapi import Client, REST_HOST
from bfxapi.rest.types import Notification, PositionClaim
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
# Claims all active positions
for position in bfx.rest.auth.get_positions():
notification: Notification[PositionClaim] = bfx.rest.auth.claim_position(position.position_id)
claim: PositionClaim = notification.data
print(f"Position: {position} | PositionClaim: {claim}")

View File

@@ -0,0 +1,44 @@
# python -c "import examples.rest.authenticated.get_wallets"
import os
from bfxapi import Client, REST_HOST
from bfxapi.rest.types import List, Wallet, Transfer, \
DepositAddress, LightningNetworkInvoice, Withdrawal, \
Notification
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
# Gets all user's available wallets
wallets: List[Wallet] = bfx.rest.auth.get_wallets()
# Transfers funds (0.001 ETH) from exchange wallet to funding wallet
A: Notification[Transfer] = bfx.rest.auth.transfer_between_wallets(
from_wallet="exchange", to_wallet="funding", from_currency="ETH",
to_currency="ETH", amount=0.001)
print("Transfer:", A.data)
# Retrieves the deposit address for bitcoin currency in exchange wallet.
B: Notification[DepositAddress] = bfx.rest.auth.get_deposit_address(
wallet="exchange", method="bitcoin", renew=False)
print("Deposit address:", B.data)
# Generates a lightning network deposit invoice
C: Notification[LightningNetworkInvoice] = bfx.rest.auth.generate_deposit_invoice(
wallet="funding", currency="LNX", amount=0.001)
print("Lightning network invoice:", C.data)
# Withdraws 1.0 UST from user's exchange wallet to address 0x742d35Cc6634C0532925a3b844Bc454e4438f44e
D: Notification[Withdrawal] = bfx.rest.auth.submit_wallet_withdrawal(
wallet="exchange", method="tetheruse", address="0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
amount=1.0)
print("Withdrawal:", D.data)

View File

@@ -0,0 +1,36 @@
# python -c "import examples.rest.authenticated.set_derivatives_position_collateral"
import os
from bfxapi import Client, REST_HOST
from bfxapi.rest.types import DerivativePositionCollateral, DerivativePositionCollateralLimits
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
submit_order_notification = bfx.rest.auth.submit_order(
type="LIMIT",
symbol="tBTCF0:USTF0",
amount="0.015",
price="16700",
lev=10
)
print("New Order:", submit_order_notification.data)
# Update the amount of collateral for tBTCF0:USTF0 derivative position
derivative_position_collateral: DerivativePositionCollateral = \
bfx.rest.auth.set_derivative_position_collateral(symbol="tBTCF0:USTF0", collateral=50.0)
print("Status:", bool(derivative_position_collateral.status))
# Calculate the minimum and maximum collateral that can be assigned to tBTCF0:USTF0.
derivative_position_collateral_limits: DerivativePositionCollateralLimits = \
bfx.rest.auth.get_derivative_position_collateral_limits(symbol="tBTCF0:USTF0")
print(f"Minimum collateral: {derivative_position_collateral_limits.min_collateral} | \
Maximum collateral: {derivative_position_collateral_limits.max_collateral}")

View File

@@ -0,0 +1,30 @@
# python -c "import examples.rest.authenticated.submit_funding_offer"
import os
from bfxapi import Client, REST_HOST
from bfxapi.enums import FundingOfferType, Flag
from bfxapi.rest.types import Notification, FundingOffer
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
# Submit a new funding offer
notification: Notification[FundingOffer] = bfx.rest.auth.submit_funding_offer(
type=FundingOfferType.LIMIT,
symbol="fUSD",
amount=123.45,
rate=0.001,
period=2,
flags=Flag.HIDDEN
)
print("Funding Offer notification:", notification)
# Get all fUSD active funding offers
offers = bfx.rest.auth.get_funding_offers(symbol="fUSD")
print("Offers (fUSD):", offers)

View File

@@ -0,0 +1,42 @@
# python -c "import examples.rest.authenticated.submit_order"
import os
from bfxapi import Client, REST_HOST
from bfxapi.enums import OrderType, Flag
from bfxapi.rest.types import Notification, Order
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
# Submit a new order
submit_order_notification: Notification[Order] = bfx.rest.auth.submit_order(
type=OrderType.EXCHANGE_LIMIT,
symbol="tBTCUST",
amount=0.015,
price=10000,
flags=Flag.HIDDEN + Flag.OCO + Flag.CLOSE
)
print("Submit order notification:", submit_order_notification)
order: Order = submit_order_notification.data
# Update its amount and its price
update_order_notification: Notification[Order] = bfx.rest.auth.update_order(
id=order.id,
amount=0.020,
price=10150
)
print("Update order notification:", update_order_notification)
# Cancel it by its ID
cancel_order_notification: Notification[Order] = bfx.rest.auth.cancel_order(
id=order.id
)
print("Cancel order notification:", cancel_order_notification)

View File

@@ -0,0 +1,24 @@
# python -c "import examples.rest.authenticated.toggle_keep_funding"
import os
from bfxapi import Client, REST_HOST
from bfxapi.rest.types import List, FundingLoan, Notification
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
loans: List[FundingLoan] = bfx.rest.auth.get_funding_loans(symbol="fUSD")
# Set every loan's keep funding status to <off> (1: <on>, 2: <off>)
notification: Notification[None] = bfx.rest.auth.toggle_keep_funding(
funding_type="loan",
ids=[ loan.id for loan in loans ],
changes={ loan.id: 2 for loan in loans }
)
print("Toggle keep funding notification:", notification)

View File

@@ -1,19 +0,0 @@
# python -c "import examples.rest.claim_position"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
open_margin_positions = bfx.rest.auth.get_positions()
# claim all positions
for position in open_margin_positions:
print(f"Position {position}")
claim = bfx.rest.auth.claim_position(position.position_id, amount=0.000001)
print(f"PositionClaim {claim.notify_info}")

View File

@@ -1,32 +0,0 @@
# python -c "import examples.rest.create_funding_offer"
import os
from bfxapi.client import Client, REST_HOST
from bfxapi.enums import FundingOfferType, Flag
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
notification = bfx.rest.auth.submit_funding_offer(
type=FundingOfferType.LIMIT,
symbol="fUSD",
amount="123.45",
rate="0.001",
period=2,
flags=Flag.HIDDEN
)
print("Offer notification:", notification)
offers = bfx.rest.auth.get_funding_offers(symbol="fUSD")
print("Offers:", offers)
# Cancel all funding offers
notification = bfx.rest.auth.cancel_all_funding_offers(currency="fUSD")
print(notification)

View File

@@ -1,36 +0,0 @@
# python -c "import examples.rest.create_order"
import os
from bfxapi.client import Client, REST_HOST
from bfxapi.enums import OrderType, Flag
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
# Create a new order
submitted_order = bfx.rest.auth.submit_order(
type=OrderType.EXCHANGE_LIMIT,
symbol="tBTCUST",
amount="0.015",
price="10000",
flags=Flag.HIDDEN + Flag.OCO + Flag.CLOSE
)
print("Submit Order Notification:", submitted_order)
# Update it
updated_order = bfx.rest.auth.update_order(
id=submitted_order.notify_info.id,
amount="0.020",
price="10100"
)
print("Update Order Notification:", updated_order)
# Delete it
canceled_order = bfx.rest.auth.cancel_order(id=submitted_order.notify_info.id)
print("Cancel Order Notification:", canceled_order)

View File

@@ -1,31 +0,0 @@
# python -c "import examples.rest.derivatives"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
# Create a new order
submitted_order = bfx.rest.auth.submit_order(
symbol="tBTCF0:USTF0",
amount="0.015",
price="16700",
lev=10,
type="LIMIT"
)
print("Submit Order Notification:", submitted_order)
# Get position collateral limits
limits = bfx.rest.auth.get_derivative_position_collateral_limits(symbol="tBTCF0:USTF0")
print(f"Limits {limits}")
# Update position collateral
response = bfx.rest.auth.set_derivative_position_collateral(symbol="tBTCF0:USTF0", collateral=50)
print(response.status)

View File

@@ -1,28 +0,0 @@
# python -c "import examples.rest.extra_calcs"
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST
)
t_symbol_response = bfx.rest.public.get_trading_market_average_price(
symbol="tBTCUSD",
amount=-100,
price_limit="20000.5"
)
print(t_symbol_response.price_avg)
f_symbol_response = bfx.rest.public.get_funding_market_average_price(
symbol="fUSD",
amount=100,
period=2,
rate_limit="0.00015"
)
print(f_symbol_response.rate_avg)
fx_rate = bfx.rest.public.get_fx_rate(ccy1="USD", ccy2="EUR")
print(fx_rate.current_rate)

View File

@@ -1,21 +0,0 @@
# python -c "import examples.rest.funding_auto_renew"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
notification = bfx.rest.auth.toggle_auto_renew(
status=True,
currency="USD",
amount="150",
rate="0", # FRR
period=2
)
print("Renew toggle notification:", notification)

View File

@@ -1,123 +0,0 @@
# python -c "import examples.rest.get_authenticated_data"
import os
import time
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
now = int(round(time.time() * 1000))
def log_user_info():
user_info = bfx.rest.auth.get_user_info()
print(user_info)
def log_login_history():
login_history = bfx.rest.auth.get_login_history()
print(login_history)
def log_wallets():
wallets = bfx.rest.auth.get_wallets()
print("Wallets:")
[print(w) for w in wallets]
def log_orders():
orders = bfx.rest.auth.get_orders(symbol='tBTCUSD')
print("Orders:")
[print(o) for o in orders]
def log_orders_history():
orders = bfx.rest.auth.get_orders_history(symbol='tBTCUSD', start=0, end=now)
print("Orders:")
[print(o) for o in orders]
def log_positions():
positions = bfx.rest.auth.get_positions()
print("Positions:")
[print(p) for p in positions]
def log_trades():
trades = bfx.rest.auth.get_trades_history(symbol='tBTCUSD', start=0, end=now)
print("Trades:")
[print(t) for t in trades]
def log_order_trades():
order_id = 82406909127
trades = bfx.rest.auth.get_order_trades(symbol='tBTCUSD', id=order_id)
print("Trade orders:")
[print(t) for t in trades]
def log_funding_offers():
offers = bfx.rest.auth.get_funding_offers(symbol='fUSD')
print("Offers:")
[print(o) for o in offers]
def log_funding_offer_history():
offers = bfx.rest.auth.get_funding_offers_history(symbol='fUSD', start=0, end=now)
print("Offers history:")
[print(o) for o in offers]
def log_funding_loans():
loans = bfx.rest.auth.get_funding_loans(symbol='fUSD')
print("Funding loans:")
[print(l) for l in loans]
def log_funding_loans_history():
loans = bfx.rest.auth.get_funding_loans_history(symbol='fUSD', start=0, end=now)
print("Funding loan history:")
[print(l) for l in loans]
def log_funding_credits():
credits = bfx.rest.auth.get_funding_credits(symbol='fUSD')
print("Funding credits:")
[print(c) for c in credits]
def log_funding_credits_history():
credit = bfx.rest.auth.get_funding_credits_history(symbol='fUSD', start=0, end=now)
print("Funding credit history:")
[print(c) for c in credit]
def log_margin_info():
btcusd_margin_info = bfx.rest.auth.get_symbol_margin_info('tBTCUSD')
print(f"tBTCUSD margin info {btcusd_margin_info}")
sym_all_margin_info = bfx.rest.auth.get_all_symbols_margin_info()
print(f"Sym all margin info {sym_all_margin_info}")
base_margin_info = bfx.rest.auth.get_base_margin_info()
print(f"Base margin info {base_margin_info}")
def run():
log_user_info()
log_wallets()
log_orders()
log_orders_history()
log_positions()
log_trades()
log_order_trades()
log_funding_offers()
log_funding_offer_history()
log_funding_credits()
log_funding_credits_history()
log_margin_info()
run()

View File

@@ -1,13 +0,0 @@
# python -c "import examples.rest.get_funding_info"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
print(bfx.rest.auth.get_funding_info(key="fUSD"))

View File

@@ -1,13 +0,0 @@
# python -c "import examples.rest.get_funding_trades_history"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
print(bfx.rest.auth.get_funding_trades_history())

View File

@@ -1,14 +0,0 @@
# python -c "import examples.rest.get_liquidations"
import time
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST
)
now = int(round(time.time() * 1000))
liquidations = bfx.rest.public.get_liquidations(start=0, end=now)
print(f"Liquidations: {liquidations}")

View File

@@ -1,23 +0,0 @@
# python -c "import examples.rest.get_positions"
import os
import time
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
now = int(round(time.time() * 1000))
positions_snapshot = bfx.rest.auth.get_positions_snapshot(end=now, limit=50)
print(positions_snapshot)
positions_history = bfx.rest.auth.get_positions_history(end=now, limit=50)
print(positions_history)
positions_audit = bfx.rest.auth.get_positions_audit(end=now, limit=50)
print(positions_audit)

View File

@@ -1,52 +0,0 @@
# python -c "import examples.rest.get_public_data"
import time
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST
)
now = int(round(time.time() * 1000))
def log_historical_candles():
candles = bfx.rest.public.get_candles_hist(start=0, end=now, resource='trade:1m:tBTCUSD')
print("Candles:")
[print(c) for c in candles]
def log_historical_trades():
trades = bfx.rest.public.get_t_trades(pair='tBTCUSD', start=0, end=now)
print("Trades:")
[print(t) for t in trades]
def log_books():
orders = bfx.rest.public.get_t_book(pair='BTCUSD', precision='P0')
print("Order book:")
[print(o) for o in orders]
def log_tickers():
tickers = bfx.rest.public.get_t_tickers(pairs=['BTCUSD'])
print("Tickers:")
print(tickers)
def log_derivative_status():
status = bfx.rest.public.get_derivatives_status('ALL')
print("Deriv status:")
print(status)
def run():
log_historical_candles()
log_historical_trades()
log_books()
log_tickers()
log_derivative_status()
run()

View File

@@ -1,22 +0,0 @@
# python -c "import examples.rest.get_pulse_data"
import time
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST
)
now = int(round(time.time() * 1000))
messages = bfx.rest.public.get_pulse_history(end=now, limit=100)
for message in messages:
print(f"Message: {message}")
print(message.content)
print(message.profile.picture)
profile = bfx.rest.public.get_pulse_profile("News")
print(f"Profile: {profile}")
print(f"Profile picture: {profile.picture}")

View File

@@ -1,18 +0,0 @@
# python -c "import examples.rest.increase_position"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
increase_info = bfx.rest.auth.get_increase_position_info(symbol="tBTCUSD", amount=0.0001)
print(increase_info)
# increase a margin position
notification = bfx.rest.auth.increase_position(symbol="tBTCUSD", amount=0.0001)
print(notification.notify_info)

View File

@@ -1,26 +0,0 @@
# python -c "import examples.rest.keep_taken_funding"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
loans = bfx.rest.auth.get_funding_loans(symbol="fUSD")
for loan in loans:
print(f"Loan {loan}")
notification = bfx.rest.auth.toggle_keep(
funding_type="loan",
ids=[loan.id],
changes={
loan.id: 2 # (1 if true, 2 if false)
}
)
print("Funding keep notification:", notification)

View File

@@ -1,44 +0,0 @@
# python -c "import examples.rest.merchant"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
customer_info = {
"nationality": "GB",
"resid_country": "DE",
"resid_city": "Berlin",
"resid_zip_code": 1,
"resid_street": "Timechain",
"full_name": "Satoshi",
"email": "satoshi3@bitfinex.com"
}
invoice = bfx.rest.merchant.submit_invoice(
amount=1,
currency="USD",
duration=864000,
order_id="order123",
customer_info=customer_info,
pay_currencies=["ETH"]
)
print(bfx.rest.merchant.get_invoices())
print(bfx.rest.merchant.get_invoice_count_stats(status="CREATED", format="Y"))
print(bfx.rest.merchant.get_invoice_earning_stats(currency="USD", format="Y"))
print(bfx.rest.merchant.get_currency_conversion_list())
print(bfx.rest.merchant.complete_invoice(
id=invoice.id,
pay_currency="ETH",
deposit_id=1
))

View File

@@ -0,0 +1,43 @@
# python -c "import examples.rest.merchant.submit_invoice"
import os
from bfxapi import Client, REST_HOST
from bfxapi.rest.types import InvoiceSubmission
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
customer_info = {
"nationality": "DE",
"residCountry": "GB",
"residCity": "London",
"residZipCode": "WC2H 7NA",
"residStreet": "5-6 Leicester Square",
"residBuildingNo": "23 A",
"fullName": "John Doe",
"email": "john@example.com"
}
invoice: InvoiceSubmission = bfx.rest.merchant.submit_invoice(
amount=1.0,
currency="USD",
order_id="test",
customer_info=customer_info,
pay_currencies=["ETH"],
duration=86400 * 10
)
print("Invoice submission:", invoice)
print(bfx.rest.merchant.complete_invoice(
id=invoice.id,
pay_currency="ETH",
deposit_id=1
))
print(bfx.rest.merchant.get_invoices(limit=25))

View File

@@ -0,0 +1,24 @@
# python -c "import examples.rest.public.book"
from bfxapi import Client, PUB_REST_HOST
from bfxapi.rest.types import List, TradingPairBook, TradingPairRawBook, \
FundingCurrencyBook, FundingCurrencyRawBook
bfx = Client(REST_HOST=PUB_REST_HOST)
t_book: List[TradingPairBook] = bfx.rest.public.get_t_book("tBTCUSD", precision="P0", len=25)
print("25 price points of tBTCUSD order book (with precision P0):", t_book)
t_raw_book: List[TradingPairRawBook] = bfx.rest.public.get_t_raw_book("tBTCUSD")
print("tBTCUSD raw order book:", t_raw_book)
f_book: List[FundingCurrencyBook] = bfx.rest.public.get_f_book("fUSD", precision="P0", len=25)
print("25 price points of fUSD order book (with precision P0):", f_book)
f_raw_book: List[FundingCurrencyRawBook] = bfx.rest.public.get_f_raw_book("fUSD")
print("fUSD raw order book:", f_raw_book)

View File

@@ -0,0 +1,18 @@
# python -c "import examples.rest.public.conf"
from bfxapi import Client, PUB_REST_HOST
from bfxapi.rest.enums import Config
bfx = Client(REST_HOST=PUB_REST_HOST)
print("Available configs:", [ config.value for config in Config ])
# Prints a map from symbols to their API symbols (pub:map:currency:sym)
print (bfx.rest.public.conf(Config.MAP_CURRENCY_SYM))
# Prints all the available exchange trading pairs (pub:list:pair:exchange)
print(bfx.rest.public.conf(Config.LIST_PAIR_EXCHANGE))
# Prints all the available funding currencies (pub:list:currency)
print(bfx.rest.public.conf(Config.LIST_CURRENCY))

View File

@@ -1,10 +1,8 @@
# python -c "import examples.rest.get_candles_hist"
# python -c "import examples.rest.public.get_candles_hist"
from bfxapi.client import Client, REST_HOST
from bfxapi import Client, PUB_REST_HOST
bfx = Client(
REST_HOST=REST_HOST
)
bfx = Client(REST_HOST=PUB_REST_HOST)
print(f"Candles: {bfx.rest.public.get_candles_hist(symbol='tBTCUSD')}")

View File

@@ -0,0 +1,24 @@
# python -c "import examples.rest.public.pulse_endpoints"
import datetime
from bfxapi import Client, PUB_REST_HOST
from bfxapi.rest.types import List, PulseMessage, PulseProfile
bfx = Client(REST_HOST=PUB_REST_HOST)
# POSIX timestamp in milliseconds (check https://currentmillis.com/)
end = datetime.datetime(2020, 5, 2).timestamp() * 1000
# Retrieves 25 pulse messages up to 2020/05/02
messages: List[PulseMessage] = bfx.rest.public.get_pulse_history(end=end, limit=25)
for message in messages:
print(f"Message author: {message.profile.nickname} ({message.profile.puid})")
print(f"Title: <{message.title}>")
print(f"Tags: {message.tags}\n")
profile: PulseProfile = bfx.rest.public.get_pulse_profile("News")
URL = profile.picture.replace("size", "small")
print(f"<{profile.nickname}>'s profile picture: https://s3-eu-west-1.amazonaws.com/bfx-pub/{URL}")

View File

@@ -0,0 +1,28 @@
# python -c "import examples.rest.public.rest_calculation_endpoints"
from bfxapi import Client, PUB_REST_HOST
from bfxapi.rest.types import TradingMarketAveragePrice, FundingMarketAveragePrice, FxRate
bfx = Client(REST_HOST=PUB_REST_HOST)
trading_market_average_price: TradingMarketAveragePrice = bfx.rest.public.get_trading_market_average_price(
symbol="tBTCUSD",
amount=-100,
price_limit=20000.5
)
print("Average execution price for tBTCUSD:", trading_market_average_price.price_avg)
funding_market_average_price: FundingMarketAveragePrice = bfx.rest.public.get_funding_market_average_price(
symbol="fUSD",
amount=100,
period=2,
rate_limit=0.00015
)
print("Average execution rate for fUSD:", funding_market_average_price.rate_avg)
fx_rate: FxRate = bfx.rest.public.get_fx_rate(ccy1="USD", ccy2="EUR")
print("Exchange rate between USD and EUR:", fx_rate.current_rate)

View File

@@ -0,0 +1,17 @@
# python -c "import examples.rest.public.trades"
from bfxapi import Client, PUB_REST_HOST
from bfxapi.rest.enums import Sort
from bfxapi.rest.types import List, TradingPairTrade, FundingCurrencyTrade
bfx = Client(REST_HOST=PUB_REST_HOST)
t_trades: List[TradingPairTrade] = bfx.rest.public.get_t_trades("tBTCUSD", \
limit=15, sort=Sort.ASCENDING)
print("Latest 15 trades for tBTCUSD (in ascending order):", t_trades)
f_trades: List[FundingCurrencyTrade] = bfx.rest.public.get_f_trades("fUSD", \
limit=15, sort=Sort.DESCENDING)
print("Latest 15 trades for fUSD (in descending order):", f_trades)

View File

@@ -1,22 +0,0 @@
# python -c "import examples.rest.return_taken_funding"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
loans = bfx.rest.auth.get_funding_loans(symbol="fUSD")
for loan in loans:
print(f"Loan {loan}")
notification = bfx.rest.auth.submit_funding_close(
id=loan.id
)
print("Funding close notification:", notification)

View File

@@ -1,46 +0,0 @@
# python -c "import examples.rest.transfer_wallet"
import os
from bfxapi.client import Client, REST_HOST
bfx = Client(
REST_HOST=REST_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
def transfer_wallet():
response = bfx.rest.auth.transfer_between_wallets(from_wallet="exchange", to_wallet="funding", from_currency="ETH", to_currency="ETH", amount=0.001)
print("Transfer:", response.notify_info)
def get_existing_deposit_address():
response = bfx.rest.auth.get_deposit_address(wallet="exchange", method="bitcoin", renew=False)
print("Address:", response.notify_info)
def create_new_deposit_address():
response = bfx.rest.auth.get_deposit_address(wallet="exchange", method="bitcoin", renew=True)
print("Address:", response.notify_info)
def withdraw():
# tetheruse = Tether (ERC20)
response = bfx.rest.auth.submit_wallet_withdrawal(wallet="exchange", method="tetheruse", amount=1, address="0x742d35Cc6634C0532925a3b844Bc454e4438f44e")
print("Address:", response.notify_info)
def create_lighting_network_deposit_address():
invoice = bfx.rest.auth.generate_deposit_invoice(wallet="funding", currency="LNX", amount=0.001)
print("Invoice:", invoice)
def get_movements():
movements = bfx.rest.auth.get_movements(currency="BTC")
print("Movements:", movements)
def run():
transfer_wallet()
get_existing_deposit_address()
create_new_deposit_address()
withdraw()
create_lighting_network_deposit_address()
get_movements()
run()

View File

@@ -1,9 +1,9 @@
# python -c "import examples.websocket.create_order"
# python -c "import examples.websocket.authenticated.submit_order"
import os
from bfxapi.client import Client, WSS_HOST
from bfxapi.websocket.enums import Error, OrderType
from bfxapi import Client, WSS_HOST
from bfxapi.enums import Error, OrderType
from bfxapi.websocket.types import Notification, Order
bfx = Client(
@@ -18,7 +18,7 @@ def on_wss_error(code: Error, msg: str):
@bfx.wss.on("authenticated")
async def on_authenticated(event):
print(f"Authentication: {event}.")
print(f"Authentication: {event}")
await bfx.wss.inputs.submit_order(
type=OrderType.EXCHANGE_LIMIT,

View File

@@ -0,0 +1,30 @@
# python -c "import examples.websocket.authenticated.wallets"
import os
from bfxapi import Client
from bfxapi.enums import Error
from bfxapi.websocket.types import List, Wallet
bfx = Client(
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET"),
filter=["wallet"]
)
@bfx.wss.on("wss-error")
def on_wss_error(code: Error, msg: str):
print(code, msg)
@bfx.wss.on("wallet_snapshot")
def on_wallet_snapshot(wallets: List[Wallet]):
for wallet in wallets:
print(f"Wallet: {wallet.wallet_type} | {wallet.currency}")
print(f"Available balance: {wallet.available_balance}")
print(f"Wallet trade details: {wallet.trade_details}")
@bfx.wss.on("wallet_update")
def on_wallet_update(wallet: Wallet):
print(f"Wallet update: {wallet}")
bfx.wss.run()

View File

@@ -1,4 +1,4 @@
# python -c "import examples.websocket.derivatives_status"
# python -c "import examples.websocket.public.derivatives_status"
from bfxapi import Client, PUB_WSS_HOST
from bfxapi.websocket.enums import Error, Channel

View File

@@ -1,4 +1,4 @@
# python -c "import examples.websocket.order_book"
# python -c "import examples.websocket.public.order_book"
from collections import OrderedDict

View File

@@ -1,4 +1,4 @@
# python -c "import examples.websocket.raw_order_book"
# python -c "import examples.websocket.public.raw_order_book"
from collections import OrderedDict

View File

@@ -1,4 +1,4 @@
# python -c "import examples.websocket.ticker"
# python -c "import examples.websocket.public.ticker"
from bfxapi import Client, PUB_WSS_HOST

View File

@@ -1,4 +1,4 @@
# python -c "import examples.websocket.trades"
# python -c "import examples.websocket.public.trades"
from bfxapi import Client, PUB_WSS_HOST
from bfxapi.websocket.enums import Error, Channel

View File

@@ -1,30 +0,0 @@
# python -c "import examples.websocket.wallet_balance"
import os
from typing import List
from bfxapi import Client, WSS_HOST
from bfxapi.websocket.enums import Error
from bfxapi.websocket.types import Wallet
bfx = Client(
WSS_HOST=WSS_HOST,
API_KEY=os.getenv("BFX_API_KEY"),
API_SECRET=os.getenv("BFX_API_SECRET")
)
@bfx.wss.on("wallet_snapshot")
def log_snapshot(wallets: List[Wallet]):
for wallet in wallets:
print(f"Balance: {wallet}")
@bfx.wss.on("wallet_update")
def log_update(wallet: Wallet):
print(f"Balance update: {wallet}")
@bfx.wss.on("wss-error")
def on_wss_error(code: Error, msg: str):
print(code, msg)
bfx.wss.run()