Move API urls to `.venues`

Also add a lookup helper for getting addrs by venue:
`get_api_eps()` which returns the rest and wss values.
basic_buy_bot
Tyler Goodlet 2023-06-14 18:27:26 -04:00
parent 9972bd387a
commit 0c74a67ee1
4 changed files with 66 additions and 54 deletions

View File

@ -59,6 +59,8 @@ from .venues import (
PAIRTYPES, PAIRTYPES,
Pair, Pair,
MarketType, MarketType,
_spot_url,
_futes_url,
) )
log = get_logger('piker.brokers.binance') log = get_logger('piker.brokers.binance')
@ -81,29 +83,6 @@ def get_config() -> dict:
log = get_logger(__name__) log = get_logger(__name__)
_domain: str = 'binance.com'
_spot_url = _url = f'https://api.{_domain}'
_futes_url = f'https://fapi.{_domain}'
# test nets
_testnet_futes_url = 'https://testnet.binancefuture.com'
# WEBsocketz
# NOTE XXX: see api docs which show diff addr?
# https://developers.binance.com/docs/binance-trading-api/websocket_api#general-api-information
_spot_ws: str = 'wss://stream.binance.com/ws'
# 'wss://ws-api.binance.com:443/ws-api/v3',
# NOTE: spot test network only allows certain ep sets:
# https://testnet.binance.vision/
_testnet_spot_ws: str = 'wss://testnet.binance.vision/ws-api/v3'
# https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams
_futes_ws: str = f'wss://fstream.{_domain}/ws/'
_auth_futes_ws: str = 'wss://fstream-auth.{_domain}/ws/'
# Broker specific ohlc schema (rest) # Broker specific ohlc schema (rest)
# XXX TODO? some additional fields are defined in the docs: # XXX TODO? some additional fields are defined in the docs:
# https://binance-docs.github.io/apidocs/spot/en/#kline-candlestick-data # https://binance-docs.github.io/apidocs/spot/en/#kline-candlestick-data
@ -181,11 +160,11 @@ class Client:
# spot EPs sesh # spot EPs sesh
self._sesh = asks.Session(connections=4) self._sesh = asks.Session(connections=4)
self._sesh.base_location: str = _url self._sesh.base_location: str = _spot_url
# margin and extended spot endpoints session. # margin and extended spot endpoints session.
self._sapi_sesh = asks.Session(connections=4) self._sapi_sesh = asks.Session(connections=4)
self._sapi_sesh.base_location: str = _url self._sapi_sesh.base_location: str = _spot_url
# futes EPs sesh # futes EPs sesh
self._fapi_sesh = asks.Session(connections=4) self._fapi_sesh = asks.Session(connections=4)
@ -193,7 +172,9 @@ class Client:
# for creating API keys see, # for creating API keys see,
# https://www.binance.com/en/support/faq/how-to-create-api-keys-on-binance-360002502072 # https://www.binance.com/en/support/faq/how-to-create-api-keys-on-binance-360002502072
conf: dict = get_config() root_conf: dict = get_config()
conf: dict = root_conf['futes']
self.api_key: str = conf.get('api_key', '') self.api_key: str = conf.get('api_key', '')
self.api_secret: str = conf.get('api_secret', '') self.api_secret: str = conf.get('api_secret', '')
@ -213,7 +194,7 @@ class Client:
# 'futes_coin': self._dapi, # TODO # 'futes_coin': self._dapi, # TODO
} }
def _get_signature(self, data: OrderedDict) -> str: def _mk_sig(self, data: OrderedDict) -> str:
# XXX: Info on security and authentification # XXX: Info on security and authentification
# https://binance-docs.github.io/apidocs/#endpoint-security-type # https://binance-docs.github.io/apidocs/#endpoint-security-type
@ -226,7 +207,9 @@ class Client:
query_str = '&'.join([ query_str = '&'.join([
f'{_key}={value}' f'{_key}={value}'
for _key, value in data.items()]) for _key, value in data.items()])
log.info(query_str) log.info(query_str)
msg_auth = hmac.new( msg_auth = hmac.new(
self.api_secret.encode('utf-8'), self.api_secret.encode('utf-8'),
query_str.encode('utf-8'), query_str.encode('utf-8'),
@ -255,7 +238,7 @@ class Client:
''' '''
if signed: if signed:
params['signature'] = self._get_signature(params) params['signature'] = self._mk_sig(params)
resp = await getattr(self._sesh, action)( resp = await getattr(self._sesh, action)(
path=f'/api/v3/{method}', path=f'/api/v3/{method}',
@ -282,7 +265,7 @@ class Client:
''' '''
if signed: if signed:
params['signature'] = self._get_signature(params) params['signature'] = self._mk_sig(params)
resp = await getattr(self._fapi_sesh, action)( resp = await getattr(self._fapi_sesh, action)(
path=f'/fapi/v1/{method}', path=f'/fapi/v1/{method}',
@ -311,7 +294,7 @@ class Client:
''' '''
if signed: if signed:
params['signature'] = self._get_signature(params) params['signature'] = self._mk_sig(params)
resp = await getattr(self._sapi_sesh, action)( resp = await getattr(self._sapi_sesh, action)(
path=f'/sapi/v1/{method}', path=f'/sapi/v1/{method}',
@ -539,6 +522,7 @@ class Client:
async def get_withdrawls( async def get_withdrawls(
self, self,
recv_window: int = 60000 recv_window: int = 60000
) -> list: ) -> list:
params = OrderedDict([ params = OrderedDict([

View File

@ -103,7 +103,6 @@ async def handle_order_requests(
@tractor.context @tractor.context
async def open_trade_dialog( async def open_trade_dialog(
ctx: tractor.Context, ctx: tractor.Context,
loglevel: str = None
) -> AsyncIterator[dict[str, Any]]: ) -> AsyncIterator[dict[str, Any]]:

View File

@ -73,6 +73,7 @@ from .api import (
from .venues import ( from .venues import (
Pair, Pair,
FutesPair, FutesPair,
get_api_eps,
) )
log = get_logger('piker.brokers.binance') log = get_logger('piker.brokers.binance')
@ -416,23 +417,10 @@ async def stream_quotes(
FeedInit(mkt_info=mkt) FeedInit(mkt_info=mkt)
) )
# TODO: detect whether futes or spot contact was requested
from .api import (
_futes_ws,
_spot_ws,
)
async with open_cached_client(
'binance',
) as client:
wsep: str = {
'usdtm_futes': _futes_ws,
'spot': _spot_ws,
}[client.mkt_mode]
async with ( async with (
open_cached_client('binance') as client,
open_autorecon_ws( open_autorecon_ws(
wsep, url=get_api_eps(client.mkt_mode)[1], # 2nd elem is wss url
fixture=partial( fixture=partial(
subscribe, subscribe,
symbols=[mkt.bs_mktid], symbols=[mkt.bs_mktid],

View File

@ -30,6 +30,55 @@ from decimal import Decimal
from piker.data.types import Struct from piker.data.types import Struct
# API endpoint paths by venue / sub-API
_domain: str = 'binance.com'
_spot_url = f'https://api.{_domain}'
_futes_url = f'https://fapi.{_domain}'
# WEBsocketz
# NOTE XXX: see api docs which show diff addr?
# https://developers.binance.com/docs/binance-trading-api/websocket_api#general-api-information
_spot_ws: str = 'wss://stream.binance.com/ws'
# 'wss://ws-api.binance.com:443/ws-api/v3',
# NOTE: spot test network only allows certain ep sets:
# https://testnet.binance.vision/
_testnet_spot_ws: str = 'wss://testnet.binance.vision/ws-api/v3'
# https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams
_futes_ws: str = f'wss://fstream.{_domain}/ws/'
_auth_futes_ws: str = 'wss://fstream-auth.{_domain}/ws/'
# test nets
_testnet_futes_url: str = 'https://testnet.binancefuture.com'
_testnet_futes_ws: str = 'wss://stream.binancefuture.com'
MarketType = Literal[
'spot',
# 'margin',
'usdtm_futes',
# 'coin_futes',
]
def get_api_eps(venue: MarketType) -> tuple[str, str]:
'''
Return API ep root paths per venue.
'''
return {
'spot': (
_spot_url,
_spot_ws,
),
'usdtm_futes': (
_futes_url,
_futes_ws,
),
}[venue]
class Pair(Struct, frozen=True): class Pair(Struct, frozen=True):
symbol: str symbol: str
status: str status: str
@ -144,14 +193,6 @@ class FutesPair(Pair):
MarketType = Literal[
'spot',
# 'margin',
'usdtm_futes',
# 'coin_futes',
]
PAIRTYPES: dict[MarketType, Pair] = { PAIRTYPES: dict[MarketType, Pair] = {
'spot': SpotPair, 'spot': SpotPair,
'usdtm_futes': FutesPair, 'usdtm_futes': FutesPair,