Compare commits
44 Commits
main
...
fix_deribi
| Author | SHA1 | Date |
|---|---|---|
|
|
2256cdf190 | |
|
|
8d00151aee | |
|
|
05bdec7d1d | |
|
|
5aad43378c | |
|
|
ab9789d35e | |
|
|
a6d6700b07 | |
|
|
8ecfbd77ac | |
|
|
a8ca901ddd | |
|
|
4dbf5b1c10 | |
|
|
4d92d925b6 | |
|
|
fc40612ca6 | |
|
|
d0a12069eb | |
|
|
d2f6a31883 | |
|
|
4f4cb29a4c | |
|
|
d30cfeab2c | |
|
|
8165c684e5 | |
|
|
ddf47c4555 | |
|
|
c196188eaa | |
|
|
dd0d2bd07f | |
|
|
3a7a983451 | |
|
|
7d62b9d5e7 | |
|
|
c96e3d377a | |
|
|
04e03be475 | |
|
|
e87939e1f2 | |
|
|
3630c02f48 | |
|
|
fdf34e51bb | |
|
|
a0b540022e | |
|
|
20f6343be2 | |
|
|
2f30fc4fb8 | |
|
|
76b5547c2d | |
|
|
08811f9a61 | |
|
|
b577180773 | |
|
|
f12c452d96 | |
|
|
3531c2edc1 | |
|
|
97dd7e766a | |
|
|
ab1463d942 | |
|
|
5314cb79d4 | |
|
|
0c0b7116e3 | |
|
|
19c343e8b2 | |
|
|
b7883325a9 | |
|
|
37ca081555 | |
|
|
44b8c70521 | |
|
|
e6af97c596 | |
|
|
95ace5acb8 |
269
README.rst
269
README.rst
|
|
@ -1,196 +1,162 @@
|
||||||
piker
|
piker
|
||||||
-----
|
-----
|
||||||
trading gear for hackers
|
trading gear for hackers.
|
||||||
|
|
||||||
|gh_actions|
|
|gh_actions|
|
||||||
|
|
||||||
.. |gh_actions| image:: https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fpikers%2Fpiker%2Fbadge&style=popout-square
|
.. |gh_actions| image:: https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fpikers%2Fpiker%2Fbadge&style=popout-square
|
||||||
:target: https://actions-badge.atrox.dev/piker/pikers/goto
|
:target: https://actions-badge.atrox.dev/piker/pikers/goto
|
||||||
|
|
||||||
``piker`` is a broker agnostic, next-gen FOSS toolset and runtime for
|
``piker`` is a broker agnostic, next-gen FOSS toolset for real-time
|
||||||
real-time computational trading targeted at `hardcore Linux users
|
computational trading targeted at `hardcore Linux users <comp_trader>`_ .
|
||||||
<comp_trader>`_ .
|
|
||||||
|
|
||||||
we use much bleeding edge tech including (but not limited to):
|
we use as much bleeding edge tech as possible including (but not limited to):
|
||||||
|
|
||||||
- latest python for glue_
|
- latest python for glue_
|
||||||
- uv_ for packaging and distribution
|
- trio_ & tractor_ for our distributed, multi-core, real-time streaming
|
||||||
- trio_ & tractor_ for our distributed `structured concurrency`_ runtime
|
`structured concurrency`_ runtime B)
|
||||||
- Qt_ for pristine low latency UIs
|
- Qt_ for pristine high performance UIs
|
||||||
- pyqtgraph_ (which we've extended) for real-time charting and graphics
|
- pyqtgraph_ for real-time charting
|
||||||
- ``polars`` ``numpy`` and ``numba`` for redic `fast numerics`_
|
- ``polars`` ``numpy`` and ``numba`` for `fast numerics`_
|
||||||
- `apache arrow and parquet`_ for time-series storage
|
- `apache arrow and parquet`_ for time series history management
|
||||||
|
persistence and sharing
|
||||||
|
- (prototyped) techtonicdb_ for L2 book storage
|
||||||
|
|
||||||
potential projects we might integrate with soon,
|
.. |travis| image:: https://img.shields.io/travis/pikers/piker/master.svg
|
||||||
|
:target: https://travis-ci.org/pikers/piker
|
||||||
- (already prototyped in ) techtonicdb_ for L2 book storage
|
|
||||||
|
|
||||||
.. _comp_trader: https://jfaleiro.wordpress.com/2019/10/09/computational-trader/
|
|
||||||
.. _glue: https://numpy.org/doc/stable/user/c-info.python-as-glue.html#using-python-as-glue
|
|
||||||
.. _uv: https://docs.astral.sh/uv/
|
|
||||||
.. _trio: https://github.com/python-trio/trio
|
.. _trio: https://github.com/python-trio/trio
|
||||||
.. _tractor: https://github.com/goodboy/tractor
|
.. _tractor: https://github.com/goodboy/tractor
|
||||||
.. _structured concurrency: https://trio.discourse.group/
|
.. _structured concurrency: https://trio.discourse.group/
|
||||||
|
.. _marketstore: https://github.com/alpacahq/marketstore
|
||||||
|
.. _techtonicdb: https://github.com/0b01/tectonicdb
|
||||||
.. _Qt: https://www.qt.io/
|
.. _Qt: https://www.qt.io/
|
||||||
.. _pyqtgraph: https://github.com/pyqtgraph/pyqtgraph
|
.. _pyqtgraph: https://github.com/pyqtgraph/pyqtgraph
|
||||||
|
.. _glue: https://numpy.org/doc/stable/user/c-info.python-as-glue.html#using-python-as-glue
|
||||||
.. _apache arrow and parquet: https://arrow.apache.org/faq/
|
.. _apache arrow and parquet: https://arrow.apache.org/faq/
|
||||||
.. _fast numerics: https://zerowithdot.com/python-numpy-and-pandas-performance/
|
.. _fast numerics: https://zerowithdot.com/python-numpy-and-pandas-performance/
|
||||||
.. _techtonicdb: https://github.com/0b01/tectonicdb
|
.. _comp_trader: https://jfaleiro.wordpress.com/2019/10/09/computational-trader/
|
||||||
|
|
||||||
|
|
||||||
focus and feats:
|
focus and features:
|
||||||
****************
|
*******************
|
||||||
fitting with these tenets, we're always open to new
|
- 100% federated: your code, your hardware, your data feeds, your broker fills.
|
||||||
framework/lib/service interop suggestions and ideas!
|
- zero web: low latency, native software that doesn't try to re-invent the OS
|
||||||
|
- maximal **privacy**: prevent brokers and mms from knowing your
|
||||||
|
planz; smack their spreads with dark volume.
|
||||||
|
- zero clutter: modal, context oriented UIs that echew minimalism, reduce
|
||||||
|
thought noise and encourage un-emotion.
|
||||||
|
- first class parallelism: built from the ground up on next-gen structured concurrency
|
||||||
|
primitives.
|
||||||
|
- traders first: broker/exchange/asset-class agnostic
|
||||||
|
- systems grounded: real-time financial signal processing that will
|
||||||
|
make any queuing or DSP eng juice their shorts.
|
||||||
|
- non-tina UX: sleek, powerful keyboard driven interaction with expected use in tiling wms
|
||||||
|
- data collaboration: every process and protocol is multi-host scalable.
|
||||||
|
- fight club ready: zero interest in adoption by suits; no corporate friendly license, ever.
|
||||||
|
|
||||||
- **100% federated**:
|
fitting with these tenets, we're always open to new framework suggestions and ideas.
|
||||||
your code, your hardware, your data feeds, your broker fills.
|
|
||||||
|
|
||||||
- **zero web**:
|
building the best looking, most reliable, keyboard friendly trading
|
||||||
low latency as a prime objective, native UIs and modern IPC
|
platform is the dream; join the cause.
|
||||||
protocols without trying to re-invent the "OS-as-an-app"..
|
|
||||||
|
|
||||||
- **maximal privacy**:
|
|
||||||
prevent brokers and mms from knowing your planz; smack their
|
|
||||||
spreads with dark volume from a VPN tunnel.
|
|
||||||
|
|
||||||
- **zero clutter**:
|
|
||||||
modal, context oriented UIs that echew minimalism, reduce thought
|
|
||||||
noise and encourage un-emotion.
|
|
||||||
|
|
||||||
- **first class parallelism**:
|
|
||||||
built from the ground up on a next-gen structured concurrency
|
|
||||||
supervision sys.
|
|
||||||
|
|
||||||
- **traders first**:
|
|
||||||
broker/exchange/venue/asset-class/money-sys agnostic
|
|
||||||
|
|
||||||
- **systems grounded**:
|
|
||||||
real-time financial signal processing (fsp) that will make any
|
|
||||||
queuing or DSP eng juice their shorts.
|
|
||||||
|
|
||||||
- **non-tina UX**:
|
|
||||||
sleek, powerful keyboard driven interaction with expected use in
|
|
||||||
tiling wms (or maybe even a DDE).
|
|
||||||
|
|
||||||
- **data collab at scale**:
|
|
||||||
every actor-process and protocol is multi-host aware.
|
|
||||||
|
|
||||||
- **fight club ready**:
|
|
||||||
zero interest in adoption by suits; no corporate friendly license,
|
|
||||||
ever.
|
|
||||||
|
|
||||||
building the hottest looking, fastest, most reliable, keyboard
|
|
||||||
friendly FOSS trading platform is the dream; join the cause.
|
|
||||||
|
|
||||||
|
|
||||||
a sane install with `uv`
|
sane install with `poetry`
|
||||||
************************
|
**************************
|
||||||
bc why install with `python` when you can faster with `rust` ::
|
TODO!
|
||||||
|
|
||||||
uv sync
|
|
||||||
|
|
||||||
# ^ astral's docs,
|
|
||||||
# https://docs.astral.sh/uv/concepts/projects/sync/
|
|
||||||
|
|
||||||
include all GUIs (ex. for charting)::
|
|
||||||
|
|
||||||
uv sync --extra uis
|
|
||||||
|
|
||||||
AND with all our hacking tools and WIP integrations::
|
|
||||||
|
|
||||||
uv sync --dev --all-extras
|
|
||||||
|
|
||||||
|
|
||||||
Ensure you can run the root-daemon::
|
rigorous install on ``nixos`` using ``poetry2nix``
|
||||||
|
**************************************************
|
||||||
uv run pikerd [-l info --pdb]
|
TODO!
|
||||||
|
|
||||||
|
|
||||||
install on nix(os)
|
hacky install on nixos
|
||||||
******************
|
**********************
|
||||||
``NixOS`` is our core devs' distro of choice for which we offer
|
`NixOS` is our core devs' distro of choice for which we offer
|
||||||
a stringently defined development shell envoirment that can currently
|
a stringently defined development shell envoirment that can be loaded with::
|
||||||
be applied in one of 2 ways::
|
|
||||||
|
|
||||||
# ONLY if running on X11
|
nix-shell develop.nix
|
||||||
nix-shell default.nix
|
|
||||||
|
|
||||||
Or if you prefer flakes style and a modern DE::
|
this will setup the required python environment to run piker, make sure to
|
||||||
|
run::
|
||||||
|
|
||||||
# ONLY if also running on Wayland
|
pip install -r requirements.txt -e .
|
||||||
nix develop # for default bash
|
|
||||||
nix develop -c uv run xonsh # for @goodboy's preferred sh B)
|
once after loading the shell
|
||||||
|
|
||||||
|
|
||||||
start a chart
|
install wild-west style via `pip`
|
||||||
*************
|
*********************************
|
||||||
run a realtime OHLCV chart stand-alone::
|
``piker`` is currently under heavy pre-alpha development and as such
|
||||||
|
should be cloned from this repo and hacked on directly.
|
||||||
|
|
||||||
[uv run] piker -l info chart btcusdt.spot.binance xmrusdt.spot.kraken
|
for a development install::
|
||||||
|
|
||||||
# ^^^ iff you haven't activated the py-env,
|
git clone git@github.com:pikers/piker.git
|
||||||
# - https://docs.astral.sh/uv/concepts/projects/run/
|
cd piker
|
||||||
#
|
virtualenv env
|
||||||
# in order to create an explicit virt-env see,
|
source ./env/bin/activate
|
||||||
# - https://docs.astral.sh/uv/concepts/projects/layout/#the-project-environment
|
pip install -r requirements.txt -e .
|
||||||
# - https://docs.astral.sh/uv/pip/environments/
|
|
||||||
#
|
|
||||||
# use $UV_PROJECT_ENVIRONMENT to select any non-`.venv/`
|
|
||||||
# as the venv sudir in the repo's root.
|
|
||||||
# - https://docs.astral.sh/uv/reference/environment/#uv_project_environment
|
|
||||||
|
|
||||||
this runs a chart UI (with 1m sampled OHLCV) and shows 2 spot markets from 2 diff cexes
|
|
||||||
overlayed on the same graph. Use of `piker` without first starting
|
|
||||||
a daemon (`pikerd` - see below) means there is an implicit spawning of the
|
|
||||||
multi-actor-runtime (implemented as a `tractor` app).
|
|
||||||
|
|
||||||
For additional subsystem feats available through our chart UI see the
|
|
||||||
various sub-readmes:
|
|
||||||
|
|
||||||
- order control using a mouse-n-keyboard UX B)
|
|
||||||
- cross venue market-pair (what most call "symbol") search, select, overlay Bo
|
|
||||||
- financial-signal-processing (`piker.fsp`) write-n-reload to sub-chart BO
|
|
||||||
- src-asset derivatives scan for anal, like the infamous "max pain" XO
|
|
||||||
|
|
||||||
|
|
||||||
spawn a daemon standalone
|
check out our charts
|
||||||
*************************
|
********************
|
||||||
we call the root actor-process the ``pikerd``. it can be (and is
|
bet you weren't expecting this from the foss::
|
||||||
recommended normally to be) started separately from the ``piker
|
|
||||||
chart`` program::
|
piker -l info -b kraken -b binance chart btcusdt.binance --pdb
|
||||||
|
|
||||||
|
|
||||||
|
this runs the main chart (currently with 1m sampled OHLC) in in debug
|
||||||
|
mode and you can practice paper trading using the following
|
||||||
|
micro-manual:
|
||||||
|
|
||||||
|
``order_mode`` (
|
||||||
|
edge triggered activation by any of the following keys,
|
||||||
|
``mouse-click`` on y-level to submit at that price
|
||||||
|
):
|
||||||
|
|
||||||
|
- ``f``/ ``ctl-f`` to stage buy
|
||||||
|
- ``d``/ ``ctl-d`` to stage sell
|
||||||
|
- ``a`` to stage alert
|
||||||
|
|
||||||
|
|
||||||
|
``search_mode`` (
|
||||||
|
``ctl-l`` or ``ctl-space`` to open,
|
||||||
|
``ctl-c`` or ``ctl-space`` to close
|
||||||
|
) :
|
||||||
|
|
||||||
|
- begin typing to have symbol search automatically lookup
|
||||||
|
symbols from all loaded backend (broker) providers
|
||||||
|
- arrow keys and mouse click to navigate selection
|
||||||
|
- vi-like ``ctl-[hjkl]`` for navigation
|
||||||
|
|
||||||
|
|
||||||
|
you can also configure your position allocation limits from the
|
||||||
|
sidepane.
|
||||||
|
|
||||||
|
|
||||||
|
run in distributed mode
|
||||||
|
***********************
|
||||||
|
start the service manager and data feed daemon in the background and
|
||||||
|
connect to it::
|
||||||
|
|
||||||
pikerd -l info --pdb
|
pikerd -l info --pdb
|
||||||
|
|
||||||
the daemon does nothing until a ``piker``-client (like ``piker
|
|
||||||
chart``) connects and requests some particular sub-system. for
|
|
||||||
a connecting chart ``pikerd`` will spawn and manage at least,
|
|
||||||
|
|
||||||
- a data-feed daemon: ``datad`` which does all the work of comms with
|
connect your chart::
|
||||||
the backend provider (in this case the ``binance`` cex).
|
|
||||||
- a paper-trading engine instance, ``paperboi.binance``, (if no live
|
|
||||||
account has been configured) which allows for auto/manual order
|
|
||||||
control against the live quote stream.
|
|
||||||
|
|
||||||
*using* an actor-service (aka micro-daemon) manager which dynamically
|
piker -l info -b kraken -b binance chart xmrusdt.binance --pdb
|
||||||
supervises various sub-subsystems-as-services throughout the ``piker``
|
|
||||||
runtime-stack.
|
|
||||||
|
|
||||||
now you can (implicitly) connect your chart::
|
|
||||||
|
|
||||||
piker chart btcusdt.spot.binance
|
enjoy persistent real-time data feeds tied to daemon lifetime. the next
|
||||||
|
time you spawn a chart it will load much faster since the data feed has
|
||||||
since ``pikerd`` was started separately you can now enjoy a persistent
|
been cached and is now always running live in the background until you
|
||||||
real-time data stream tied to the daemon-tree's lifetime. i.e. the next
|
kill ``pikerd``.
|
||||||
time you spawn a chart it will obviously not only load much faster
|
|
||||||
(since the underlying ``datad.binance`` is left running with its
|
|
||||||
in-memory IPC data structures) but also the data-feed and any order
|
|
||||||
mgmt states should be persistent until you finally cancel ``pikerd``.
|
|
||||||
|
|
||||||
|
|
||||||
if anyone asks you what this project is about
|
if anyone asks you what this project is about
|
||||||
*********************************************
|
*********************************************
|
||||||
you don't talk about it; just use it.
|
you don't talk about it.
|
||||||
|
|
||||||
|
|
||||||
how do i get involved?
|
how do i get involved?
|
||||||
|
|
@ -200,15 +166,6 @@ enter the matrix.
|
||||||
|
|
||||||
how come there ain't that many docs
|
how come there ain't that many docs
|
||||||
***********************************
|
***********************************
|
||||||
i mean we want/need them but building the core right has been higher
|
suck it up, learn the code; no one is trying to sell you on anything.
|
||||||
prio then marketting (and likely will stay that way Bp).
|
also, we need lotsa help so if you want to start somewhere and can't
|
||||||
|
necessarily write serious code, this might be the place for you!
|
||||||
soo, suck it up bc,
|
|
||||||
|
|
||||||
- no one is trying to sell you on anything
|
|
||||||
- learning the code base is prolly way more valuable
|
|
||||||
- the UI/UXs are intended to be "intuitive" for any hacker..
|
|
||||||
|
|
||||||
we obviously need tonz help so if you want to start somewhere and
|
|
||||||
can't necessarily write "advanced" concurrent python/rust code, this
|
|
||||||
helping document literally anything might be the place for you!
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
|
################
|
||||||
# ---- CEXY ----
|
# ---- CEXY ----
|
||||||
|
################
|
||||||
[binance]
|
[binance]
|
||||||
accounts.paper = 'paper'
|
accounts.paper = 'paper'
|
||||||
|
|
||||||
|
|
@ -12,41 +13,28 @@ accounts.spot = 'spot'
|
||||||
spot.use_testnet = false
|
spot.use_testnet = false
|
||||||
spot.api_key = ''
|
spot.api_key = ''
|
||||||
spot.api_secret = ''
|
spot.api_secret = ''
|
||||||
# ------ binance ------
|
|
||||||
|
|
||||||
|
|
||||||
[deribit]
|
[deribit]
|
||||||
# std assets
|
|
||||||
key_id = ''
|
key_id = ''
|
||||||
key_secret = ''
|
key_secret = ''
|
||||||
# options
|
|
||||||
accounts.option = 'option'
|
|
||||||
option.use_testnet = false
|
|
||||||
option.key_id = ''
|
|
||||||
option.key_secret = ''
|
|
||||||
# aux logging from `cryptofeed`
|
|
||||||
option.log.filename = 'cryptofeed.log'
|
|
||||||
option.log.level = 'DEBUG'
|
|
||||||
option.log.disabled = true
|
|
||||||
# ------ deribit ------
|
|
||||||
|
|
||||||
|
|
||||||
[kraken]
|
[kraken]
|
||||||
key_descr = ''
|
key_descr = ''
|
||||||
api_key = ''
|
api_key = ''
|
||||||
secret = ''
|
secret = ''
|
||||||
# ------ kraken ------
|
|
||||||
|
|
||||||
|
|
||||||
[kucoin]
|
[kucoin]
|
||||||
key_id = ''
|
key_id = ''
|
||||||
key_secret = ''
|
key_secret = ''
|
||||||
key_passphrase = ''
|
key_passphrase = ''
|
||||||
# ------ kucoin ------
|
|
||||||
|
|
||||||
|
|
||||||
|
################
|
||||||
# -- BROKERZ ---
|
# -- BROKERZ ---
|
||||||
|
################
|
||||||
[questrade]
|
[questrade]
|
||||||
refresh_token = ''
|
refresh_token = ''
|
||||||
access_token = ''
|
access_token = ''
|
||||||
|
|
@ -54,55 +42,44 @@ api_server = 'https://api06.iq.questrade.com/'
|
||||||
expires_in = 1800
|
expires_in = 1800
|
||||||
token_type = 'Bearer'
|
token_type = 'Bearer'
|
||||||
expires_at = 1616095326.355846
|
expires_at = 1616095326.355846
|
||||||
# ------ questrade ------
|
|
||||||
|
|
||||||
|
|
||||||
[ib]
|
[ib]
|
||||||
# define the (set of) host-port socketaddrs that
|
|
||||||
# brokerd.ib will scan to connect to an API endpoint
|
|
||||||
# (ib-gw or ib-tws listening instances)
|
|
||||||
hosts = [
|
hosts = [
|
||||||
'127.0.0.1',
|
'127.0.0.1',
|
||||||
]
|
]
|
||||||
|
# XXX: the order in which ports will be scanned
|
||||||
|
# (by the `brokerd` daemon-actor)
|
||||||
|
# is determined # by the line order here.
|
||||||
|
# TODO: when we eventually spawn gateways in our
|
||||||
|
# container, we can just dynamically allocate these
|
||||||
|
# using IBC.
|
||||||
ports = [
|
ports = [
|
||||||
4002, # gw
|
4002, # gw
|
||||||
7497, # tws
|
7497, # tws
|
||||||
]
|
]
|
||||||
|
|
||||||
# When API endpoints are being scanned durin startup, the order
|
# XXX: for a paper account the flex web query service
|
||||||
# of user-defined-account "names" (as defined below) here
|
# is not supported so you have to manually download
|
||||||
# determines which py-client connection is given priority to be
|
# and XML report and put it in a location that can be
|
||||||
# used for data-feed-requests by according to whichever client
|
# accessed by the ``brokerd.ib`` backend code for parsing.
|
||||||
# connected to an API endpoing which reported the equivalent
|
flex_token = ''
|
||||||
# account number for that name.
|
flex_trades_query_id = '' # live account
|
||||||
|
|
||||||
|
# when clients are being scanned this determines
|
||||||
|
# which clients are preferred to be used for data
|
||||||
|
# feeds based on the order of account names, if
|
||||||
|
# detected as active on an API client.
|
||||||
prefer_data_account = [
|
prefer_data_account = [
|
||||||
'paper',
|
'paper',
|
||||||
'margin',
|
'margin',
|
||||||
'ira',
|
'ira',
|
||||||
]
|
]
|
||||||
|
|
||||||
# For long-term trades txn (transaction) history
|
|
||||||
# processing (i.e your txn ledger with IB) you can
|
|
||||||
# (automatically for live accounts) query the FLEX
|
|
||||||
# report system for past history.
|
|
||||||
#
|
|
||||||
# (For paper accounts the web query service
|
|
||||||
# is not supported so you have to manually download
|
|
||||||
# an XML report and put it in a location that can be
|
|
||||||
# accessed by our `brokerd.ib` backend code for parsing).
|
|
||||||
#
|
|
||||||
flex_token = ''
|
|
||||||
flex_trades_query_id = '' # live account
|
|
||||||
|
|
||||||
# define "aliases" (names) for each account number
|
|
||||||
# such that the names can be reffed and logged throughout
|
|
||||||
# `piker.accounting` subsys and more easily
|
|
||||||
# referred to by the user.
|
|
||||||
#
|
|
||||||
# These keys will be the set exposed through the order-mode
|
|
||||||
# account-selection UI so that numbers are never shown.
|
|
||||||
[ib.accounts]
|
[ib.accounts]
|
||||||
paper = 'DU0000000' # <- literal account #
|
# the order in which accounts will be selectable
|
||||||
margin = 'U0000000'
|
# in the order mode UI (if found via clients during
|
||||||
ira = 'U0000000'
|
# API-app scanning)when a new symbol is loaded.
|
||||||
# ------ ib ------
|
paper = 'XX0000000'
|
||||||
|
margin = 'X0000000'
|
||||||
|
ira = 'X0000000'
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,7 @@
|
||||||
[network]
|
[network]
|
||||||
pikerd = [
|
tsdb.backend = 'marketstore'
|
||||||
'/ipv4/127.0.0.1/tcp/6116', # std localhost daemon-actor tree
|
tsdb.host = 'localhost'
|
||||||
# '/uds/6116', # TODO std uds socket file
|
tsdb.grpc_port = 5995
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
[ui]
|
[ui]
|
||||||
# set custom font + size which will scale entire UI
|
# set custom font + size which will scale entire UI
|
||||||
|
|
|
||||||
37
default.nix
37
default.nix
|
|
@ -11,12 +11,11 @@ let
|
||||||
libxkbcommonStorePath = lib.getLib libxkbcommon;
|
libxkbcommonStorePath = lib.getLib libxkbcommon;
|
||||||
xcbutilcursorStorePath = lib.getLib xcb-util-cursor;
|
xcbutilcursorStorePath = lib.getLib xcb-util-cursor;
|
||||||
|
|
||||||
pypkgs = python313Packages;
|
qtpyStorePath = lib.getLib python312Packages.qtpy;
|
||||||
qtpyStorePath = lib.getLib pypkgs.qtpy;
|
pyqt6StorePath = lib.getLib python312Packages.pyqt6;
|
||||||
pyqt6StorePath = lib.getLib pypkgs.pyqt6;
|
pyqt6SipStorePath = lib.getLib python312Packages.pyqt6-sip;
|
||||||
pyqt6SipStorePath = lib.getLib pypkgs.pyqt6-sip;
|
rapidfuzzStorePath = lib.getLib python312Packages.rapidfuzz;
|
||||||
rapidfuzzStorePath = lib.getLib pypkgs.rapidfuzz;
|
qdarkstyleStorePath = lib.getLib python312Packages.qdarkstyle;
|
||||||
qdarkstyleStorePath = lib.getLib pypkgs.qdarkstyle;
|
|
||||||
|
|
||||||
xorgLibX11StorePath = lib.getLib xorg.libX11;
|
xorgLibX11StorePath = lib.getLib xorg.libX11;
|
||||||
xorgLibxcbStorePath = lib.getLib xorg.libxcb;
|
xorgLibxcbStorePath = lib.getLib xorg.libxcb;
|
||||||
|
|
@ -52,12 +51,12 @@ stdenv.mkDerivation {
|
||||||
xorg.xcbutilrenderutil
|
xorg.xcbutilrenderutil
|
||||||
|
|
||||||
# Python requirements.
|
# Python requirements.
|
||||||
python313
|
python312Full
|
||||||
uv
|
python312Packages.uv
|
||||||
pypkgs.qdarkstyle
|
python312Packages.qdarkstyle
|
||||||
pypkgs.rapidfuzz
|
python312Packages.rapidfuzz
|
||||||
pypkgs.pyqt6
|
python312Packages.pyqt6
|
||||||
pypkgs.qtpy
|
python312Packages.qtpy
|
||||||
];
|
];
|
||||||
src = null;
|
src = null;
|
||||||
shellHook = ''
|
shellHook = ''
|
||||||
|
|
@ -114,11 +113,11 @@ stdenv.mkDerivation {
|
||||||
|
|
||||||
export LD_LIBRARY_PATH
|
export LD_LIBRARY_PATH
|
||||||
|
|
||||||
RPDFUZZ_PATH="${rapidfuzzStorePath}/lib/python3.13/site-packages"
|
RPDFUZZ_PATH="${rapidfuzzStorePath}/lib/python3.12/site-packages"
|
||||||
QDRKSTYLE_PATH="${qdarkstyleStorePath}/lib/python3.13/site-packages"
|
QDRKSTYLE_PATH="${qdarkstyleStorePath}/lib/python3.12/site-packages"
|
||||||
QTPY_PATH="${qtpyStorePath}/lib/python3.13/site-packages"
|
QTPY_PATH="${qtpyStorePath}/lib/python3.12/site-packages"
|
||||||
PYQT6_PATH="${pyqt6StorePath}/lib/python3.13/site-packages"
|
PYQT6_PATH="${pyqt6StorePath}/lib/python3.12/site-packages"
|
||||||
PYQT6_SIP_PATH="${pyqt6SipStorePath}/lib/python3.13/site-packages"
|
PYQT6_SIP_PATH="${pyqt6SipStorePath}/lib/python3.12/site-packages"
|
||||||
|
|
||||||
PATCH="$PATCH:$RPDFUZZ_PATH"
|
PATCH="$PATCH:$RPDFUZZ_PATH"
|
||||||
PATCH="$PATCH:$QDRKSTYLE_PATH"
|
PATCH="$PATCH:$QDRKSTYLE_PATH"
|
||||||
|
|
@ -128,8 +127,8 @@ stdenv.mkDerivation {
|
||||||
|
|
||||||
export PATCH
|
export PATCH
|
||||||
|
|
||||||
# install all dev and extras
|
# Install deps
|
||||||
uv sync --dev --all-extras
|
uv lock
|
||||||
|
|
||||||
'';
|
'';
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,138 +1,30 @@
|
||||||
running ``ib`` gateway in ``docker``
|
running ``ib`` gateway in ``docker``
|
||||||
------------------------------------
|
------------------------------------
|
||||||
We have a config based on a well maintained community
|
We have a config based on the (now defunct)
|
||||||
image from `@gnzsnz`:
|
image from "waytrade":
|
||||||
|
|
||||||
https://github.com/gnzsnz/ib-gateway-docker
|
https://github.com/waytrade/ib-gateway-docker
|
||||||
|
|
||||||
|
To startup this image with our custom settings
|
||||||
To startup this image simply run the command::
|
simply run the command::
|
||||||
|
|
||||||
docker compose up
|
docker compose up
|
||||||
|
|
||||||
(For further usage^ see the official `docker-compose`_ docs)
|
And you should have the following socket-available services:
|
||||||
|
|
||||||
|
- ``x11vnc1@127.0.0.1:3003``
|
||||||
And you should have the following socket-available services by
|
|
||||||
default:
|
|
||||||
|
|
||||||
- ``x11vnc1 @ 127.0.0.1:5900``
|
|
||||||
- ``ib-gw@127.0.0.1:4002``
|
- ``ib-gw@127.0.0.1:4002``
|
||||||
|
|
||||||
You can now attach to the container via a VNC client with password-auth;
|
You can attach to the container via a VNC client
|
||||||
here is an example using ``vncclient`` on ``linux``::
|
without password auth.
|
||||||
|
|
||||||
vncviewer localhost:5900
|
SECURITY STUFF!?!?!
|
||||||
|
-------------------
|
||||||
now enter the pw (password) you set via an (see second code blob)
|
Though "``ib``" claims they host filter connections outside
|
||||||
`.env file`_ or pw-file according to the `credentials section`_.
|
localhost (aka ``127.0.0.1``) it's probably better if you filter
|
||||||
|
the socket at the OS level using a stateless firewall rule::
|
||||||
If you want to change away from their default config see the example
|
|
||||||
`docker-compose.yml`-config issue and config-section of the readme,
|
|
||||||
|
|
||||||
- https://github.com/gnzsnz/ib-gateway-docker?tab=readme-ov-file#configuration
|
|
||||||
- https://github.com/gnzsnz/ib-gateway-docker/discussions/103
|
|
||||||
|
|
||||||
.. _.env file: https://github.com/gnzsnz/ib-gateway-docker?tab=readme-ov-file#how-to-use-it
|
|
||||||
.. _docker-compose: https://docs.docker.com/compose/
|
|
||||||
.. _credentials section: https://github.com/gnzsnz/ib-gateway-docker?tab=readme-ov-file#credentials
|
|
||||||
|
|
||||||
|
|
||||||
Connecting to the API from `piker`
|
|
||||||
---------------------------------
|
|
||||||
In order to expose the container's API endpoint to the
|
|
||||||
`brokerd/datad/ib` actor, we need to add a section to the user's
|
|
||||||
`brokers.toml` config (note the below is similar to the repo-shipped
|
|
||||||
template file),
|
|
||||||
|
|
||||||
.. code:: toml
|
|
||||||
|
|
||||||
[ib]
|
|
||||||
# define the (set of) host-port socketaddrs that
|
|
||||||
# brokerd.ib will scan to connect to an API endpoint
|
|
||||||
# (ib-gw or ib-tws listening instances)
|
|
||||||
hosts = [
|
|
||||||
'127.0.0.1',
|
|
||||||
]
|
|
||||||
ports = [
|
|
||||||
4002, # gw
|
|
||||||
7497, # tws
|
|
||||||
]
|
|
||||||
|
|
||||||
# When API endpoints are being scanned durin startup, the order
|
|
||||||
# of user-defined-account "names" (as defined below) here
|
|
||||||
# determines which py-client connection is given priority to be
|
|
||||||
# used for data-feed-requests by according to whichever client
|
|
||||||
# connected to an API endpoing which reported the equivalent
|
|
||||||
# account number for that name.
|
|
||||||
prefer_data_account = [
|
|
||||||
'paper',
|
|
||||||
'margin',
|
|
||||||
'ira',
|
|
||||||
]
|
|
||||||
|
|
||||||
# define "aliases" (names) for each account number
|
|
||||||
# such that the names can be reffed and logged throughout
|
|
||||||
# `piker.accounting` subsys and more easily
|
|
||||||
# referred to by the user.
|
|
||||||
#
|
|
||||||
# These keys will be the set exposed through the order-mode
|
|
||||||
# account-selection UI so that numbers are never shown.
|
|
||||||
[ib.accounts]
|
|
||||||
paper = 'XX0000000'
|
|
||||||
margin = 'X0000000'
|
|
||||||
ira = 'X0000000'
|
|
||||||
|
|
||||||
|
|
||||||
the broker daemon can also connect to the container's VNC server for
|
|
||||||
added functionalies including,
|
|
||||||
|
|
||||||
- viewing the API endpoint program's GUI for manual interventions,
|
|
||||||
- workarounds for historical data throttling using hotkey hacks,
|
|
||||||
|
|
||||||
Add a further section to `brokers.toml` which maps each API-ep's
|
|
||||||
port to a table of VNC server connection info like,
|
|
||||||
|
|
||||||
.. code:: toml
|
|
||||||
|
|
||||||
[ib.vnc_addrs]
|
|
||||||
4002 = {host = 'localhost', port = 5900, pw = 'doggy'}
|
|
||||||
|
|
||||||
The `pw = 'doggy'` here ^ should the same value as the particular
|
|
||||||
container instances `.env` file setting (when it was run),
|
|
||||||
|
|
||||||
.. code:: ini
|
|
||||||
|
|
||||||
VNC_SERVER_PASSWORD='doggy'
|
|
||||||
|
|
||||||
|
|
||||||
IF you also want to run ``TWS``
|
|
||||||
-------------------------------
|
|
||||||
You can also run it containerized,
|
|
||||||
|
|
||||||
https://github.com/gnzsnz/ib-gateway-docker?tab=readme-ov-file#using-tws
|
|
||||||
|
|
||||||
|
|
||||||
SECURITY stuff (advanced, only if you're paranoid)
|
|
||||||
--------------------------------------------------
|
|
||||||
First and foremost if doing a "distributed" container setup where you
|
|
||||||
run the ``ib-gw`` docker container and your connecting API client
|
|
||||||
(likely ``ib_async`` from python) on **different hosts** be sure to
|
|
||||||
read the `security considerations`_ section!
|
|
||||||
|
|
||||||
And for a further (somewhat paranoid) perspective from
|
|
||||||
a long-time-ago serious devops eng..
|
|
||||||
|
|
||||||
Though "``ib``" claims they filter remote host connections outside
|
|
||||||
``localhost`` (aka ``127.0.0.1`` on ipv4) it's prolly justified if
|
|
||||||
you'd like to filter the socket at the *OS level* using a stateless
|
|
||||||
firewall rule::
|
|
||||||
|
|
||||||
ip rule add not unicast iif lo to 0.0.0.0/0 dport 4002
|
ip rule add not unicast iif lo to 0.0.0.0/0 dport 4002
|
||||||
|
|
||||||
|
We will soon have this baked into our own custom image but for
|
||||||
We will soon have this either baked into our own custom derivative
|
now you'll have to do it urself dawgy.
|
||||||
image (or patched into the current upstream one after further testin)
|
|
||||||
but for now you'll have to do it urself, diggity dawg.
|
|
||||||
|
|
||||||
.. _security considerations: https://github.com/gnzsnz/ib-gateway-docker?tab=readme-ov-file#security-considerations
|
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,10 @@
|
||||||
# a community maintained IB API container!
|
# rework from the original @
|
||||||
#
|
# https://github.com/waytrade/ib-gateway-docker/blob/master/docker-compose.yml
|
||||||
# https://github.com/gnzsnz/ib-gateway-docker
|
version: "3.5"
|
||||||
#
|
|
||||||
# For piker we (currently) include some minor deviations
|
|
||||||
# for some config files in the `volumes` section.
|
|
||||||
#
|
|
||||||
# See full configuration settings @
|
|
||||||
# - https://github.com/gnzsnz/ib-gateway-docker?tab=readme-ov-file#configuration
|
|
||||||
# - https://github.com/gnzsnz/ib-gateway-docker/discussions/103
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
|
|
||||||
ib_gw_paper:
|
ib_gw_paper:
|
||||||
|
|
||||||
# apparently java is a mega cukc:
|
# apparently java is a mega cukc:
|
||||||
|
|
@ -55,22 +50,16 @@ services:
|
||||||
target: /root/scripts/run_x11_vnc.sh
|
target: /root/scripts/run_x11_vnc.sh
|
||||||
read_only: true
|
read_only: true
|
||||||
|
|
||||||
# NOTE: an alt method to fill these out is to
|
# NOTE:to fill these out, define an `.env` file in the same dir as
|
||||||
# define an `.env` file in the same dir as
|
# this compose file which looks something like:
|
||||||
# this compose file.
|
# TWS_USERID='myuser'
|
||||||
|
# TWS_PASSWORD='guest'
|
||||||
environment:
|
environment:
|
||||||
TWS_USERID: ${TWS_USERID}
|
TWS_USERID: ${TWS_USERID}
|
||||||
# TWS_USERID: 'myuser'
|
|
||||||
TWS_PASSWORD: ${TWS_PASSWORD}
|
TWS_PASSWORD: ${TWS_PASSWORD}
|
||||||
# TWS_PASSWORD: 'guest'
|
TRADING_MODE: 'paper'
|
||||||
TRADING_MODE: ${TRADING_MODE}
|
VNC_SERVER_PASSWORD: 'doggy'
|
||||||
# TRADING_MODE: 'paper'
|
VNC_SERVER_PORT: '3003'
|
||||||
VNC_SERVER_PASSWORD: ${VNC_SERVER_PASSWORD}
|
|
||||||
# VNC_SERVER_PASSWORD: 'doggy'
|
|
||||||
|
|
||||||
# TODO, see if we can get this supported like it
|
|
||||||
# was on the old `waytrade` image?
|
|
||||||
# VNC_SERVER_PORT: '3003'
|
|
||||||
|
|
||||||
# ports:
|
# ports:
|
||||||
# - target: 4002
|
# - target: 4002
|
||||||
|
|
@ -87,9 +76,6 @@ services:
|
||||||
# - "127.0.0.1:4002:4002"
|
# - "127.0.0.1:4002:4002"
|
||||||
# - "127.0.0.1:5900:5900"
|
# - "127.0.0.1:5900:5900"
|
||||||
|
|
||||||
# TODO, a masked but working example of dual paper + live
|
|
||||||
# ib-gw instances running in a single app run!
|
|
||||||
#
|
|
||||||
# ib_gw_live:
|
# ib_gw_live:
|
||||||
# image: waytrade/ib-gateway:1012.2i
|
# image: waytrade/ib-gateway:1012.2i
|
||||||
# restart: no
|
# restart: no
|
||||||
|
|
|
||||||
|
|
@ -121,7 +121,6 @@ async def bot_main():
|
||||||
# tick_throttle=10,
|
# tick_throttle=10,
|
||||||
) as feed,
|
) as feed,
|
||||||
|
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
):
|
):
|
||||||
assert accounts
|
assert accounts
|
||||||
|
|
|
||||||
127
flake.lock
127
flake.lock
|
|
@ -1,24 +1,135 @@
|
||||||
{
|
{
|
||||||
"nodes": {
|
"nodes": {
|
||||||
"nixpkgs": {
|
"flake-utils": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems"
|
||||||
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1765779637,
|
"lastModified": 1689068808,
|
||||||
"narHash": "sha256-KJ2wa/BLSrTqDjbfyNx70ov/HdgNBCBBSQP3BIzKnv4=",
|
"narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=",
|
||||||
"owner": "nixos",
|
"owner": "numtide",
|
||||||
"repo": "nixpkgs",
|
"repo": "flake-utils",
|
||||||
"rev": "1306659b587dc277866c7b69eb97e5f07864d8c4",
|
"rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
"owner": "nixos",
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-utils_2": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems_2"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1689068808,
|
||||||
|
"narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nix-github-actions": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"poetry2nix",
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1688870561,
|
||||||
|
"narHash": "sha256-4UYkifnPEw1nAzqqPOTL2MvWtm3sNGw1UTYTalkTcGY=",
|
||||||
|
"owner": "nix-community",
|
||||||
|
"repo": "nix-github-actions",
|
||||||
|
"rev": "165b1650b753316aa7f1787f3005a8d2da0f5301",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-community",
|
||||||
|
"repo": "nix-github-actions",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1692174805,
|
||||||
|
"narHash": "sha256-xmNPFDi/AUMIxwgOH/IVom55Dks34u1g7sFKKebxUm0=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "caac0eb6bdcad0b32cb2522e03e4002c8975c62e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
"ref": "nixos-unstable",
|
"ref": "nixos-unstable",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"poetry2nix": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-utils": "flake-utils_2",
|
||||||
|
"nix-github-actions": "nix-github-actions",
|
||||||
|
"nixpkgs": [
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1692048894,
|
||||||
|
"narHash": "sha256-cDw03rso2V4CDc3Mll0cHN+ztzysAvdI8pJ7ybbz714=",
|
||||||
|
"ref": "refs/heads/pyqt6",
|
||||||
|
"rev": "b059ad4c3051f45d6c912e17747aae37a9ec1544",
|
||||||
|
"revCount": 2276,
|
||||||
|
"type": "git",
|
||||||
|
"url": "file:///home/lord_fomo/repos/poetry2nix"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "file:///home/lord_fomo/repos/poetry2nix"
|
||||||
|
}
|
||||||
|
},
|
||||||
"root": {
|
"root": {
|
||||||
"inputs": {
|
"inputs": {
|
||||||
"nixpkgs": "nixpkgs"
|
"flake-utils": "flake-utils",
|
||||||
|
"nixpkgs": "nixpkgs",
|
||||||
|
"poetry2nix": "poetry2nix"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems_2": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
|
||||||
243
flake.nix
243
flake.nix
|
|
@ -1,103 +1,180 @@
|
||||||
# An "impure" template thx to `pyproject.nix`,
|
# NOTE: to convert to a poetry2nix env like this here are the
|
||||||
# https://pyproject-nix.github.io/pyproject.nix/templates.html#impure
|
# steps:
|
||||||
# https://github.com/pyproject-nix/pyproject.nix/blob/master/templates/impure/flake.nix
|
# - install poetry in your system nix config
|
||||||
{
|
# - convert the repo to use poetry using `poetry init`:
|
||||||
description = "An impure `piker` overlay using `uv` with Nix(OS)";
|
# https://python-poetry.org/docs/basic-usage/#initialising-a-pre-existing-project
|
||||||
|
# - then manually ensuring all deps are converted over:
|
||||||
|
# - add this file to the repo and commit it
|
||||||
|
# -
|
||||||
|
|
||||||
inputs = {
|
# GROKin tips:
|
||||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
# - CLI eps are (ostensibly) added via an `entry_points.txt`:
|
||||||
|
# - https://packaging.python.org/en/latest/specifications/entry-points/#file-format
|
||||||
|
# - https://github.com/nix-community/poetry2nix/blob/master/editable.nix#L49
|
||||||
|
{
|
||||||
|
description = "piker: trading gear for hackers (pkged with poetry2nix)";
|
||||||
|
|
||||||
|
inputs.flake-utils.url = "github:numtide/flake-utils";
|
||||||
|
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
|
||||||
|
# see https://github.com/nix-community/poetry2nix/tree/master#api
|
||||||
|
inputs.poetry2nix = {
|
||||||
|
# url = "github:nix-community/poetry2nix";
|
||||||
|
# url = "github:K900/poetry2nix/qt5-explicit-deps";
|
||||||
|
url = "/home/lord_fomo/repos/poetry2nix";
|
||||||
|
|
||||||
|
inputs.nixpkgs.follows = "nixpkgs";
|
||||||
};
|
};
|
||||||
|
|
||||||
outputs =
|
outputs = {
|
||||||
{ nixpkgs, ... }:
|
self,
|
||||||
|
nixpkgs,
|
||||||
|
flake-utils,
|
||||||
|
poetry2nix,
|
||||||
|
}:
|
||||||
|
# TODO: build cross-OS and use the `${system}` var thingy..
|
||||||
|
flake-utils.lib.eachDefaultSystem (system:
|
||||||
let
|
let
|
||||||
inherit (nixpkgs) lib;
|
# use PWD as sources
|
||||||
forAllSystems = lib.genAttrs lib.systems.flakeExposed;
|
projectDir = ./.;
|
||||||
in
|
pyproject = ./pyproject.toml;
|
||||||
{
|
poetrylock = ./poetry.lock;
|
||||||
devShells = forAllSystems (
|
|
||||||
system:
|
|
||||||
let
|
|
||||||
pkgs = nixpkgs.legacyPackages.${system};
|
|
||||||
|
|
||||||
# do store-path extractions
|
# TODO: port to 3.11 and support both versions?
|
||||||
qt6baseStorePath = lib.getLib pkgs.qt6.qtbase;
|
python = "python3.10";
|
||||||
# ?TODO? can remove below since manual linking not needed?
|
|
||||||
# qt6QtWaylandStorePath = lib.getLib pkgs.qt6.qtwayland;
|
|
||||||
|
|
||||||
# XXX NOTE XXX, for now we overlay specific pkgs via
|
# for more functions and examples.
|
||||||
# a major-version-pinned-`cpython`
|
# inherit
|
||||||
cpython = "python313";
|
# (poetry2nix.legacyPackages.${system})
|
||||||
pypkgs = pkgs."${cpython}Packages";
|
# mkPoetryApplication;
|
||||||
in
|
# pkgs = nixpkgs.legacyPackages.${system};
|
||||||
{
|
|
||||||
default = pkgs.mkShell {
|
|
||||||
|
|
||||||
packages = with pkgs; [
|
pkgs = nixpkgs.legacyPackages.x86_64-linux;
|
||||||
# XXX, ensure sh completions active!
|
lib = pkgs.lib;
|
||||||
bashInteractive
|
p2npkgs = poetry2nix.legacyPackages.x86_64-linux;
|
||||||
bash-completion
|
|
||||||
|
|
||||||
# dev utils
|
# define all pkg overrides per dep, see edgecases.md:
|
||||||
ruff
|
# https://github.com/nix-community/poetry2nix/blob/master/docs/edgecases.md
|
||||||
pypkgs.ruff
|
# TODO: add these into the json file:
|
||||||
|
# https://github.com/nix-community/poetry2nix/blob/master/overrides/build-systems.json
|
||||||
|
pypkgs-build-requirements = {
|
||||||
|
asyncvnc = [ "setuptools" ];
|
||||||
|
eventkit = [ "setuptools" ];
|
||||||
|
ib-insync = [ "setuptools" "flake8" ];
|
||||||
|
msgspec = [ "setuptools"];
|
||||||
|
pdbp = [ "setuptools" ];
|
||||||
|
pyqt6-sip = [ "setuptools" ];
|
||||||
|
tabcompleter = [ "setuptools" ];
|
||||||
|
tractor = [ "setuptools" ];
|
||||||
|
tricycle = [ "setuptools" ];
|
||||||
|
trio-typing = [ "setuptools" ];
|
||||||
|
trio-util = [ "setuptools" ];
|
||||||
|
xonsh = [ "setuptools" ];
|
||||||
|
};
|
||||||
|
|
||||||
qt6.qtwayland
|
# auto-generate override entries
|
||||||
qt6.qtbase
|
p2n-overrides = p2npkgs.defaultPoetryOverrides.extend (self: super:
|
||||||
|
builtins.mapAttrs (package: build-requirements:
|
||||||
|
(builtins.getAttr package super).overridePythonAttrs (old: {
|
||||||
|
buildInputs = (
|
||||||
|
old.buildInputs or [ ]
|
||||||
|
) ++ (
|
||||||
|
builtins.map (
|
||||||
|
pkg: if builtins.isString pkg then builtins.getAttr pkg super else pkg
|
||||||
|
) build-requirements
|
||||||
|
);
|
||||||
|
})
|
||||||
|
) pypkgs-build-requirements
|
||||||
|
);
|
||||||
|
|
||||||
uv
|
# override some ahead-of-time compiled extensions
|
||||||
python313 # ?TODO^ how to set from `cpython` above?
|
# to be built with their wheels.
|
||||||
pypkgs.pyqt6
|
ahot_overrides = p2n-overrides.extend(
|
||||||
pypkgs.pyqt6-sip
|
final: prev: {
|
||||||
pypkgs.qtpy
|
|
||||||
pypkgs.qdarkstyle
|
|
||||||
pypkgs.rapidfuzz
|
|
||||||
];
|
|
||||||
|
|
||||||
shellHook = ''
|
# llvmlite = prev.llvmlite.override {
|
||||||
# unmask to debug **this** dev-shell-hook
|
# preferWheel = false;
|
||||||
# set -e
|
# };
|
||||||
|
|
||||||
# set qt-base/plugin path(s)
|
# TODO: get this workin with p2n and nixpkgs..
|
||||||
QTBASE_PATH="${qt6baseStorePath}/lib"
|
# pyqt6 = prev.pyqt6.override {
|
||||||
QT_PLUGIN_PATH="${qt6baseStorePath}/lib/qt-6/plugins"
|
# preferWheel = true;
|
||||||
QT_QPA_PLATFORM_PLUGIN_PATH="$QT_PLUGIN_PATH/platforms"
|
# };
|
||||||
|
|
||||||
# link in Qt cc lib paths from <nixpkgs>
|
# NOTE: this DOESN'T work atm but after a fix
|
||||||
LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$QTBASE_PATH"
|
# to poetry2nix, it will and actually this line
|
||||||
LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$QT_PLUGIN_PATH"
|
# won't be needed - thanks @k900:
|
||||||
LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$QT_QPA_PLATFORM_PLUGIN_PATH"
|
# https://github.com/nix-community/poetry2nix/pull/1257
|
||||||
|
pyqt5 = prev.pyqt5.override {
|
||||||
|
# withWebkit = false;
|
||||||
|
preferWheel = true;
|
||||||
|
};
|
||||||
|
|
||||||
# link-in c++ stdlib for various AOT-ext-pkgs (numpy, etc.)
|
# see PR from @k900:
|
||||||
LD_LIBRARY_PATH="${pkgs.stdenv.cc.cc.lib}/lib:$LD_LIBRARY_PATH"
|
# https://github.com/nix-community/poetry2nix/pull/1257
|
||||||
|
# pyqt5-qt5 = prev.pyqt5-qt5.override {
|
||||||
|
# withWebkit = false;
|
||||||
|
# preferWheel = true;
|
||||||
|
# };
|
||||||
|
|
||||||
export LD_LIBRARY_PATH
|
# TODO: patch in an override for polars to build
|
||||||
|
# from src! See the details likely needed from
|
||||||
# RUNTIME-SETTINGS
|
# the cryptography entry:
|
||||||
#
|
# https://github.com/nix-community/poetry2nix/blob/master/overrides/default.nix#L426-L435
|
||||||
# ------ Qt ------
|
polars = prev.polars.override {
|
||||||
# XXX, unmask to debug qt .so linking/loading deats
|
preferWheel = true;
|
||||||
# export QT_DEBUG_PLUGINS=1
|
|
||||||
#
|
|
||||||
# ALSO, for *modern linux* DEs,
|
|
||||||
# - maybe set wayland-mode (TODO, parametrtize this!)
|
|
||||||
# * a chosen wayland-mode shell-integration
|
|
||||||
export QT_QPA_PLATFORM="wayland"
|
|
||||||
export QT_WAYLAND_SHELL_INTEGRATION="xdg-shell"
|
|
||||||
|
|
||||||
# ------ uv ------
|
|
||||||
# - always use the ./py313/ venv-subdir
|
|
||||||
export UV_PROJECT_ENVIRONMENT="py313"
|
|
||||||
# sync project-env with all extras
|
|
||||||
uv sync --dev --all-extras --no-group lint
|
|
||||||
|
|
||||||
# ------ TIPS ------
|
|
||||||
# NOTE, to launch the py-venv installed `xonsh` (like @goodboy)
|
|
||||||
# run the `nix develop` cmd with,
|
|
||||||
# >> nix develop -c uv run xonsh
|
|
||||||
'';
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
# WHY!? -> output-attrs that `nix develop` scans for:
|
||||||
|
# https://nixos.org/manual/nix/stable/command-ref/new-cli/nix3-develop.html#flake-output-attributes
|
||||||
|
in
|
||||||
|
rec {
|
||||||
|
packages = {
|
||||||
|
# piker = poetry2nix.legacyPackages.x86_64-linux.mkPoetryEditablePackage {
|
||||||
|
# editablePackageSources = { piker = ./piker; };
|
||||||
|
|
||||||
|
piker = p2npkgs.mkPoetryApplication {
|
||||||
|
projectDir = projectDir;
|
||||||
|
|
||||||
|
# SEE ABOVE for auto-genned input set, override
|
||||||
|
# buncha deps with extras.. like `setuptools` mostly.
|
||||||
|
# TODO: maybe propose a patch to p2n to show that you
|
||||||
|
# can even do this in the edgecases docs?
|
||||||
|
overrides = ahot_overrides;
|
||||||
|
|
||||||
|
# XXX: won't work on llvmlite..
|
||||||
|
# preferWheels = true;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
# devShells.default = pkgs.mkShell {
|
||||||
|
# projectDir = projectDir;
|
||||||
|
# python = "python3.10";
|
||||||
|
# overrides = ahot_overrides;
|
||||||
|
# inputsFrom = [ self.packages.x86_64-linux.piker ];
|
||||||
|
# packages = packages;
|
||||||
|
# # packages = [ poetry2nix.packages.${system}.poetry ];
|
||||||
|
# };
|
||||||
|
|
||||||
|
# TODO: grok the difference here..
|
||||||
|
# - avoid re-cloning git repos on every develop entry..
|
||||||
|
# - ideally allow hacking on the src code of some deps
|
||||||
|
# (tractor, pyqtgraph, tomlkit, etc.) WITHOUT having to
|
||||||
|
# re-install them every time a change is made.
|
||||||
|
# - boot a usable xonsh inside the poetry virtualenv when
|
||||||
|
# defined via a custom entry point?
|
||||||
|
devShells.default = p2npkgs.mkPoetryEnv {
|
||||||
|
# env = p2npkgs.mkPoetryEnv {
|
||||||
|
projectDir = projectDir;
|
||||||
|
python = pkgs.python310;
|
||||||
|
overrides = ahot_overrides;
|
||||||
|
editablePackageSources = packages;
|
||||||
|
# piker = "./";
|
||||||
|
# tractor = "../tractor/";
|
||||||
|
# }; # wut?
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
); # end of .outputs scope
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,7 @@ from ._pos import (
|
||||||
Account,
|
Account,
|
||||||
load_account,
|
load_account,
|
||||||
load_account_from_ledger,
|
load_account_from_ledger,
|
||||||
|
open_pps,
|
||||||
open_account,
|
open_account,
|
||||||
Position,
|
Position,
|
||||||
)
|
)
|
||||||
|
|
@ -41,6 +42,7 @@ from ._mktinfo import (
|
||||||
dec_digits,
|
dec_digits,
|
||||||
digits_to_dec,
|
digits_to_dec,
|
||||||
MktPair,
|
MktPair,
|
||||||
|
Symbol,
|
||||||
unpack_fqme,
|
unpack_fqme,
|
||||||
_derivs as DerivTypes,
|
_derivs as DerivTypes,
|
||||||
)
|
)
|
||||||
|
|
@ -58,6 +60,7 @@ __all__ = [
|
||||||
'Asset',
|
'Asset',
|
||||||
'MktPair',
|
'MktPair',
|
||||||
'Position',
|
'Position',
|
||||||
|
'Symbol',
|
||||||
'Transaction',
|
'Transaction',
|
||||||
'TransactionLedger',
|
'TransactionLedger',
|
||||||
'dec_digits',
|
'dec_digits',
|
||||||
|
|
@ -67,6 +70,7 @@ __all__ = [
|
||||||
'load_account_from_ledger',
|
'load_account_from_ledger',
|
||||||
'mk_allocator',
|
'mk_allocator',
|
||||||
'open_account',
|
'open_account',
|
||||||
|
'open_pps',
|
||||||
'open_trade_ledger',
|
'open_trade_ledger',
|
||||||
'unpack_fqme',
|
'unpack_fqme',
|
||||||
'DerivTypes',
|
'DerivTypes',
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ import tomli_w # for fast ledger writing
|
||||||
|
|
||||||
from piker.types import Struct
|
from piker.types import Struct
|
||||||
from piker import config
|
from piker import config
|
||||||
from piker.log import get_logger
|
from ..log import get_logger
|
||||||
from .calc import (
|
from .calc import (
|
||||||
iter_by_dt,
|
iter_by_dt,
|
||||||
)
|
)
|
||||||
|
|
@ -239,9 +239,7 @@ class TransactionLedger(UserDict):
|
||||||
|
|
||||||
symcache: SymbologyCache = self._symcache
|
symcache: SymbologyCache = self._symcache
|
||||||
towrite: dict[str, Any] = {}
|
towrite: dict[str, Any] = {}
|
||||||
for tid, txdict in self.tx_sort(
|
for tid, txdict in self.tx_sort(self.data.copy()):
|
||||||
self.data.copy()
|
|
||||||
):
|
|
||||||
# write blank-str expiry for non-expiring assets
|
# write blank-str expiry for non-expiring assets
|
||||||
if (
|
if (
|
||||||
'expiry' in txdict
|
'expiry' in txdict
|
||||||
|
|
@ -379,7 +377,7 @@ def open_trade_ledger(
|
||||||
account,
|
account,
|
||||||
dirpath=_fp,
|
dirpath=_fp,
|
||||||
)
|
)
|
||||||
cpy: dict = ledger_dict.copy()
|
cpy = ledger_dict.copy()
|
||||||
|
|
||||||
# XXX NOTE: if not provided presume we are being called from
|
# XXX NOTE: if not provided presume we are being called from
|
||||||
# sync code and need to maybe run `trio` to generate..
|
# sync code and need to maybe run `trio` to generate..
|
||||||
|
|
@ -408,13 +406,7 @@ def open_trade_ledger(
|
||||||
account=account,
|
account=account,
|
||||||
mod=mod,
|
mod=mod,
|
||||||
symcache=symcache,
|
symcache=symcache,
|
||||||
|
tx_sort=getattr(mod, 'tx_sort', tx_sort),
|
||||||
# NOTE: allow backends to provide custom ledger sorting
|
|
||||||
tx_sort=getattr(
|
|
||||||
mod,
|
|
||||||
'tx_sort',
|
|
||||||
tx_sort,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
yield ledger
|
yield ledger
|
||||||
|
|
|
||||||
|
|
@ -305,8 +305,8 @@ class MktPair(Struct, frozen=True):
|
||||||
# config right?
|
# config right?
|
||||||
# src_type: AssetTypeName
|
# src_type: AssetTypeName
|
||||||
|
|
||||||
# for derivs, info describing contract, egs. strike price, call
|
# for derivs, info describing contract, egs.
|
||||||
# or put, swap type, exercise model, etc.
|
# strike price, call or put, swap type, exercise model, etc.
|
||||||
contract_info: list[str] | None = None
|
contract_info: list[str] | None = None
|
||||||
|
|
||||||
# TODO: rename to sectype since all of these can
|
# TODO: rename to sectype since all of these can
|
||||||
|
|
@ -677,3 +677,90 @@ def unpack_fqme(
|
||||||
# '.'.join([mkt_ep, venue]),
|
# '.'.join([mkt_ep, venue]),
|
||||||
suffix,
|
suffix,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Symbol(Struct):
|
||||||
|
'''
|
||||||
|
I guess this is some kinda container thing for dealing with
|
||||||
|
all the different meta-data formats from brokers?
|
||||||
|
|
||||||
|
'''
|
||||||
|
key: str
|
||||||
|
|
||||||
|
broker: str = ''
|
||||||
|
venue: str = ''
|
||||||
|
|
||||||
|
# precision descriptors for price and vlm
|
||||||
|
tick_size: Decimal = Decimal('0.01')
|
||||||
|
lot_tick_size: Decimal = Decimal('0.0')
|
||||||
|
|
||||||
|
suffix: str = ''
|
||||||
|
broker_info: dict[str, dict[str, Any]] = {}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_fqme(
|
||||||
|
cls,
|
||||||
|
fqsn: str,
|
||||||
|
info: dict[str, Any],
|
||||||
|
|
||||||
|
) -> Symbol:
|
||||||
|
broker, mktep, venue, suffix = unpack_fqme(fqsn)
|
||||||
|
tick_size = info.get('price_tick_size', 0.01)
|
||||||
|
lot_size = info.get('lot_tick_size', 0.0)
|
||||||
|
|
||||||
|
return Symbol(
|
||||||
|
broker=broker,
|
||||||
|
key=mktep,
|
||||||
|
tick_size=tick_size,
|
||||||
|
lot_tick_size=lot_size,
|
||||||
|
venue=venue,
|
||||||
|
suffix=suffix,
|
||||||
|
broker_info={broker: info},
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def type_key(self) -> str:
|
||||||
|
return list(self.broker_info.values())[0]['asset_type']
|
||||||
|
|
||||||
|
@property
|
||||||
|
def tick_size_digits(self) -> int:
|
||||||
|
return float_digits(self.tick_size)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def lot_size_digits(self) -> int:
|
||||||
|
return float_digits(self.lot_tick_size)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def price_tick(self) -> Decimal:
|
||||||
|
return Decimal(str(self.tick_size))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def size_tick(self) -> Decimal:
|
||||||
|
return Decimal(str(self.lot_tick_size))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def broker(self) -> str:
|
||||||
|
return list(self.broker_info.keys())[0]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def fqme(self) -> str:
|
||||||
|
return maybe_cons_tokens([
|
||||||
|
self.key, # final "pair name" (eg. qqq[/usd], btcusdt)
|
||||||
|
self.venue,
|
||||||
|
self.suffix, # includes expiry and other con info
|
||||||
|
self.broker,
|
||||||
|
])
|
||||||
|
|
||||||
|
def quantize(
|
||||||
|
self,
|
||||||
|
size: float,
|
||||||
|
) -> Decimal:
|
||||||
|
digits = float_digits(self.lot_tick_size)
|
||||||
|
return Decimal(size).quantize(
|
||||||
|
Decimal(f'1.{"0".ljust(digits, "0")}'),
|
||||||
|
rounding=ROUND_HALF_EVEN
|
||||||
|
)
|
||||||
|
|
||||||
|
# NOTE: when cast to `str` return fqme
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return self.fqme
|
||||||
|
|
|
||||||
|
|
@ -356,20 +356,17 @@ class Position(Struct):
|
||||||
) -> bool:
|
) -> bool:
|
||||||
'''
|
'''
|
||||||
Update clearing table by calculating the rolling ppu and
|
Update clearing table by calculating the rolling ppu and
|
||||||
(accumulative) size in both the clears entry and local attrs
|
(accumulative) size in both the clears entry and local
|
||||||
state.
|
attrs state.
|
||||||
|
|
||||||
Inserts are always done in datetime sorted order.
|
Inserts are always done in datetime sorted order.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
# added: bool = False
|
||||||
tid: str = t.tid
|
tid: str = t.tid
|
||||||
if tid in self._events:
|
if tid in self._events:
|
||||||
log.debug(
|
log.warning(f'{t} is already added?!')
|
||||||
f'Txn is already added?\n'
|
# return added
|
||||||
f'\n'
|
|
||||||
f'{t}\n'
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
|
|
||||||
# TODO: apparently this IS possible with a dict but not
|
# TODO: apparently this IS possible with a dict but not
|
||||||
# common and probably not that beneficial unless we're also
|
# common and probably not that beneficial unless we're also
|
||||||
|
|
@ -450,12 +447,6 @@ class Position(Struct):
|
||||||
# def suggest_split(self) -> float:
|
# def suggest_split(self) -> float:
|
||||||
# ...
|
# ...
|
||||||
|
|
||||||
# ?TODO, for sending rendered state over the wire?
|
|
||||||
# def summary(self) -> PositionSummary:
|
|
||||||
# do minimal conversion to a subset of fields
|
|
||||||
# currently defined in `.clearing._messages.BrokerdPosition`
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class Account(Struct):
|
class Account(Struct):
|
||||||
'''
|
'''
|
||||||
|
|
@ -740,7 +731,7 @@ class Account(Struct):
|
||||||
else:
|
else:
|
||||||
# TODO: we reallly need a diff set of
|
# TODO: we reallly need a diff set of
|
||||||
# loglevels/colors per subsys.
|
# loglevels/colors per subsys.
|
||||||
log.debug(
|
log.warning(
|
||||||
f'Recent position for {fqme} was closed!'
|
f'Recent position for {fqme} was closed!'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -754,7 +745,7 @@ class Account(Struct):
|
||||||
# XXX WTF: if we use a tomlkit.Integer here we get this
|
# XXX WTF: if we use a tomlkit.Integer here we get this
|
||||||
# super weird --1 thing going on for cumsize!?1!
|
# super weird --1 thing going on for cumsize!?1!
|
||||||
# NOTE: the fix was to always float() the size value loaded
|
# NOTE: the fix was to always float() the size value loaded
|
||||||
# in open_account() below!
|
# in open_pps() below!
|
||||||
config.write(
|
config.write(
|
||||||
config=self.conf,
|
config=self.conf,
|
||||||
path=self.conf_path,
|
path=self.conf_path,
|
||||||
|
|
@ -938,6 +929,7 @@ def open_account(
|
||||||
clears_table['dt'] = dt
|
clears_table['dt'] = dt
|
||||||
trans.append(Transaction(
|
trans.append(Transaction(
|
||||||
fqme=bs_mktid,
|
fqme=bs_mktid,
|
||||||
|
# sym=mkt,
|
||||||
bs_mktid=bs_mktid,
|
bs_mktid=bs_mktid,
|
||||||
tid=tid,
|
tid=tid,
|
||||||
# XXX: not sure why sometimes these are loaded as
|
# XXX: not sure why sometimes these are loaded as
|
||||||
|
|
@ -960,18 +952,7 @@ def open_account(
|
||||||
):
|
):
|
||||||
expiry: pendulum.DateTime = pendulum.parse(expiry)
|
expiry: pendulum.DateTime = pendulum.parse(expiry)
|
||||||
|
|
||||||
# !XXX, should never be duplicates over
|
pp = pp_objs[bs_mktid] = Position(
|
||||||
# a backend-(broker)-system's unique market-IDs!
|
|
||||||
if pos := pp_objs.get(bs_mktid):
|
|
||||||
if mkt != pos.mkt:
|
|
||||||
log.warning(
|
|
||||||
f'Duplicated position but diff `MktPair.fqme` ??\n'
|
|
||||||
f'bs_mktid: {bs_mktid!r}\n'
|
|
||||||
f'pos.mkt: {pos.mkt}\n'
|
|
||||||
f'mkt: {mkt}\n'
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
pos = pp_objs[bs_mktid] = Position(
|
|
||||||
mkt,
|
mkt,
|
||||||
split_ratio=split_ratio,
|
split_ratio=split_ratio,
|
||||||
bs_mktid=bs_mktid,
|
bs_mktid=bs_mktid,
|
||||||
|
|
@ -983,13 +964,8 @@ def open_account(
|
||||||
# state, since today's records may have already been
|
# state, since today's records may have already been
|
||||||
# processed!
|
# processed!
|
||||||
for t in trans:
|
for t in trans:
|
||||||
added: bool = pos.add_clear(t)
|
pp.add_clear(t)
|
||||||
if not added:
|
|
||||||
log.warning(
|
|
||||||
f'Txn already recorded in pp ??\n'
|
|
||||||
f'\n'
|
|
||||||
f'{t}\n'
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
yield acnt
|
yield acnt
|
||||||
finally:
|
finally:
|
||||||
|
|
@ -997,6 +973,20 @@ def open_account(
|
||||||
acnt.write_config()
|
acnt.write_config()
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: drop the old name and THIS!
|
||||||
|
@cm
|
||||||
|
def open_pps(
|
||||||
|
*args,
|
||||||
|
**kwargs,
|
||||||
|
) -> Generator[Account, None, None]:
|
||||||
|
log.warning(
|
||||||
|
'`open_pps()` is now deprecated!\n'
|
||||||
|
'Please use `with open_account() as cnt:`'
|
||||||
|
)
|
||||||
|
with open_account(*args, **kwargs) as acnt:
|
||||||
|
yield acnt
|
||||||
|
|
||||||
|
|
||||||
def load_account_from_ledger(
|
def load_account_from_ledger(
|
||||||
|
|
||||||
brokername: str,
|
brokername: str,
|
||||||
|
|
|
||||||
|
|
@ -22,9 +22,7 @@ you know when you're losing money (if possible) XD
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from collections.abc import ValuesView
|
from collections.abc import ValuesView
|
||||||
from contextlib import contextmanager as cm
|
from contextlib import contextmanager as cm
|
||||||
from functools import partial
|
|
||||||
from math import copysign
|
from math import copysign
|
||||||
from pprint import pformat
|
|
||||||
from typing import (
|
from typing import (
|
||||||
Any,
|
Any,
|
||||||
Callable,
|
Callable,
|
||||||
|
|
@ -32,7 +30,6 @@ from typing import (
|
||||||
TYPE_CHECKING,
|
TYPE_CHECKING,
|
||||||
)
|
)
|
||||||
|
|
||||||
from tractor.devx import maybe_open_crash_handler
|
|
||||||
import polars as pl
|
import polars as pl
|
||||||
from pendulum import (
|
from pendulum import (
|
||||||
DateTime,
|
DateTime,
|
||||||
|
|
@ -40,16 +37,12 @@ from pendulum import (
|
||||||
parse,
|
parse,
|
||||||
)
|
)
|
||||||
|
|
||||||
from ..log import get_logger
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from ._ledger import (
|
from ._ledger import (
|
||||||
Transaction,
|
Transaction,
|
||||||
TransactionLedger,
|
TransactionLedger,
|
||||||
)
|
)
|
||||||
|
|
||||||
log = get_logger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def ppu(
|
def ppu(
|
||||||
clears: Iterator[Transaction],
|
clears: Iterator[Transaction],
|
||||||
|
|
@ -245,9 +238,6 @@ def iter_by_dt(
|
||||||
|
|
||||||
def dyn_parse_to_dt(
|
def dyn_parse_to_dt(
|
||||||
tx: tuple[str, dict[str, Any]] | Transaction,
|
tx: tuple[str, dict[str, Any]] | Transaction,
|
||||||
|
|
||||||
debug: bool = False,
|
|
||||||
_invalid: list|None = None,
|
|
||||||
) -> DateTime:
|
) -> DateTime:
|
||||||
|
|
||||||
# handle `.items()` inputs
|
# handle `.items()` inputs
|
||||||
|
|
@ -260,90 +250,33 @@ def iter_by_dt(
|
||||||
# get best parser for this record..
|
# get best parser for this record..
|
||||||
for k in parsers:
|
for k in parsers:
|
||||||
if (
|
if (
|
||||||
(v := getattr(tx, k, None))
|
isdict and k in tx
|
||||||
or
|
or getattr(tx, k, None)
|
||||||
(
|
|
||||||
isdict
|
|
||||||
and
|
|
||||||
(v := tx.get(k))
|
|
||||||
)
|
|
||||||
):
|
):
|
||||||
|
v = tx[k] if isdict else tx.dt
|
||||||
|
assert v is not None, f'No valid value for `{k}`!?'
|
||||||
|
|
||||||
# only call parser on the value if not None from
|
# only call parser on the value if not None from
|
||||||
# the `parsers` table above (when NOT using
|
# the `parsers` table above (when NOT using
|
||||||
# `.get()`), otherwise pass through the value and
|
# `.get()`), otherwise pass through the value and
|
||||||
# sort on it directly
|
# sort on it directly
|
||||||
if (
|
if (
|
||||||
not isinstance(v, DateTime)
|
not isinstance(v, DateTime)
|
||||||
and
|
and (parser := parsers.get(k))
|
||||||
(parser := parsers.get(k))
|
|
||||||
):
|
):
|
||||||
ret = parser(v)
|
return parser(v)
|
||||||
else:
|
else:
|
||||||
ret = v
|
return v
|
||||||
|
|
||||||
return ret
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
log.debug(
|
# XXX: should never get here..
|
||||||
f'Parser-field not found in txn\n'
|
breakpoint()
|
||||||
f'\n'
|
|
||||||
f'parser-field: {k!r}\n'
|
|
||||||
f'txn: {tx!r}\n'
|
|
||||||
f'\n'
|
|
||||||
f'Trying next..\n'
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
# XXX: we should never really get here bc it means some kinda
|
|
||||||
# bad txn-record (field) data..
|
|
||||||
#
|
|
||||||
# -> set the `debug_mode = True` if you want to trace such
|
|
||||||
# cases from REPL ;)
|
|
||||||
else:
|
|
||||||
# XXX: we should really never get here..
|
|
||||||
# only if a ledger record has no expected sort(able)
|
|
||||||
# field will we likely hit this.. like with ze IB.
|
|
||||||
# if no sortable field just deliver epoch?
|
|
||||||
log.warning(
|
|
||||||
'No (time) sortable field for TXN:\n'
|
|
||||||
f'{tx!r}\n'
|
|
||||||
)
|
|
||||||
report: str = (
|
|
||||||
f'No supported time-field found in txn !?\n'
|
|
||||||
f'\n'
|
|
||||||
f'supported-time-fields: {parsers!r}\n'
|
|
||||||
f'\n'
|
|
||||||
f'txn: {tx!r}\n'
|
|
||||||
)
|
|
||||||
if debug:
|
|
||||||
with maybe_open_crash_handler(
|
|
||||||
pdb=debug,
|
|
||||||
raise_on_exit=False,
|
|
||||||
):
|
|
||||||
raise ValueError(report)
|
|
||||||
else:
|
|
||||||
log.error(report)
|
|
||||||
|
|
||||||
if _invalid is not None:
|
|
||||||
_invalid.append(tx)
|
|
||||||
return from_timestamp(0.)
|
|
||||||
|
|
||||||
entry: tuple[str, dict] | Transaction
|
entry: tuple[str, dict] | Transaction
|
||||||
invalid: list = []
|
|
||||||
for entry in sorted(
|
for entry in sorted(
|
||||||
records,
|
records,
|
||||||
key=key or partial(
|
key=key or dyn_parse_to_dt,
|
||||||
dyn_parse_to_dt,
|
|
||||||
_invalid=invalid,
|
|
||||||
),
|
|
||||||
):
|
):
|
||||||
if entry in invalid:
|
|
||||||
log.warning(
|
|
||||||
f'Ignoring txn w invalid timestamp ??\n'
|
|
||||||
f'{pformat(entry)}\n'
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
# NOTE the type sig above; either pairs or txns B)
|
# NOTE the type sig above; either pairs or txns B)
|
||||||
yield entry
|
yield entry
|
||||||
|
|
||||||
|
|
@ -406,7 +339,6 @@ def open_ledger_dfs(
|
||||||
acctname: str,
|
acctname: str,
|
||||||
|
|
||||||
ledger: TransactionLedger | None = None,
|
ledger: TransactionLedger | None = None,
|
||||||
debug_mode: bool = False,
|
|
||||||
|
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
|
||||||
|
|
@ -421,10 +353,8 @@ def open_ledger_dfs(
|
||||||
can update the ledger on exit.
|
can update the ledger on exit.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
with maybe_open_crash_handler(
|
from piker.toolz import open_crash_handler
|
||||||
pdb=debug_mode,
|
with open_crash_handler():
|
||||||
# raise_on_exit=False,
|
|
||||||
):
|
|
||||||
if not ledger:
|
if not ledger:
|
||||||
import time
|
import time
|
||||||
from ._ledger import open_trade_ledger
|
from ._ledger import open_trade_ledger
|
||||||
|
|
@ -516,7 +446,7 @@ def ledger_to_dfs(
|
||||||
|
|
||||||
df = dfs[key] = ldf.with_columns([
|
df = dfs[key] = ldf.with_columns([
|
||||||
|
|
||||||
pl.cum_sum('size').alias('cumsize'),
|
pl.cumsum('size').alias('cumsize'),
|
||||||
|
|
||||||
# amount of source asset "sent" (via buy txns in
|
# amount of source asset "sent" (via buy txns in
|
||||||
# the market) to acquire the dst asset, PER txn.
|
# the market) to acquire the dst asset, PER txn.
|
||||||
|
|
@ -531,7 +461,7 @@ def ledger_to_dfs(
|
||||||
]).with_columns([
|
]).with_columns([
|
||||||
|
|
||||||
# rolling balance in src asset units
|
# rolling balance in src asset units
|
||||||
(pl.col('dst_bot').cum_sum() * -1).alias('src_balance'),
|
(pl.col('dst_bot').cumsum() * -1).alias('src_balance'),
|
||||||
|
|
||||||
# "position operation type" in terms of increasing the
|
# "position operation type" in terms of increasing the
|
||||||
# amount in the dst asset (entering) or decreasing the
|
# amount in the dst asset (entering) or decreasing the
|
||||||
|
|
@ -673,7 +603,7 @@ def ledger_to_dfs(
|
||||||
# cost that was included in the least-recently
|
# cost that was included in the least-recently
|
||||||
# entered txn that is still part of the current CSi
|
# entered txn that is still part of the current CSi
|
||||||
# set.
|
# set.
|
||||||
# => we look up the cost-per-unit cum_sum and apply
|
# => we look up the cost-per-unit cumsum and apply
|
||||||
# if over the current txn size (by multiplication)
|
# if over the current txn size (by multiplication)
|
||||||
# and then reverse that previusly applied cost on
|
# and then reverse that previusly applied cost on
|
||||||
# the txn_cost for this record.
|
# the txn_cost for this record.
|
||||||
|
|
|
||||||
|
|
@ -300,8 +300,7 @@ def disect(
|
||||||
assert not df.is_empty()
|
assert not df.is_empty()
|
||||||
|
|
||||||
# muck around in pdbp REPL
|
# muck around in pdbp REPL
|
||||||
# tractor.devx.mk_pdb().set_trace()
|
breakpoint()
|
||||||
# breakpoint()
|
|
||||||
|
|
||||||
# TODO: we REALLY need a better console REPL for this
|
# TODO: we REALLY need a better console REPL for this
|
||||||
# kinda thing..
|
# kinda thing..
|
||||||
|
|
|
||||||
|
|
@ -51,6 +51,7 @@ __brokers__: list[str] = [
|
||||||
'ib',
|
'ib',
|
||||||
'kraken',
|
'kraken',
|
||||||
'kucoin',
|
'kucoin',
|
||||||
|
'deribit',
|
||||||
|
|
||||||
# broken but used to work
|
# broken but used to work
|
||||||
# 'questrade',
|
# 'questrade',
|
||||||
|
|
@ -61,7 +62,6 @@ __brokers__: list[str] = [
|
||||||
# wstrade
|
# wstrade
|
||||||
# iex
|
# iex
|
||||||
|
|
||||||
# deribit
|
|
||||||
# bitso
|
# bitso
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -98,14 +98,13 @@ async def open_cached_client(
|
||||||
If one has not been setup do it and cache it.
|
If one has not been setup do it and cache it.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
brokermod: ModuleType = get_brokermod(brokername)
|
brokermod = get_brokermod(brokername)
|
||||||
|
|
||||||
# TODO: make abstract or `typing.Protocol`
|
|
||||||
# client: Client
|
|
||||||
async with maybe_open_context(
|
async with maybe_open_context(
|
||||||
acm_func=brokermod.get_client,
|
acm_func=brokermod.get_client,
|
||||||
kwargs=kwargs,
|
kwargs=kwargs,
|
||||||
|
|
||||||
) as (cache_hit, client):
|
) as (cache_hit, client):
|
||||||
|
|
||||||
if cache_hit:
|
if cache_hit:
|
||||||
log.runtime(f'Reusing existing {client}')
|
log.runtime(f'Reusing existing {client}')
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ from __future__ import annotations
|
||||||
from contextlib import (
|
from contextlib import (
|
||||||
asynccontextmanager as acm,
|
asynccontextmanager as acm,
|
||||||
)
|
)
|
||||||
|
from functools import partial
|
||||||
from types import ModuleType
|
from types import ModuleType
|
||||||
from typing import (
|
from typing import (
|
||||||
TYPE_CHECKING,
|
TYPE_CHECKING,
|
||||||
|
|
@ -96,10 +97,7 @@ async def _setup_persistent_brokerd(
|
||||||
# - `open_symbol_search()`
|
# - `open_symbol_search()`
|
||||||
# NOTE: see ep invocation details inside `.data.feed`.
|
# NOTE: see ep invocation details inside `.data.feed`.
|
||||||
try:
|
try:
|
||||||
async with (
|
async with trio.open_nursery() as service_nursery:
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as service_nursery
|
|
||||||
):
|
|
||||||
bus: _FeedsBus = feed.get_feed_bus(
|
bus: _FeedsBus = feed.get_feed_bus(
|
||||||
brokername,
|
brokername,
|
||||||
service_nursery,
|
service_nursery,
|
||||||
|
|
@ -193,14 +191,17 @@ def broker_init(
|
||||||
|
|
||||||
|
|
||||||
async def spawn_brokerd(
|
async def spawn_brokerd(
|
||||||
|
|
||||||
brokername: str,
|
brokername: str,
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
|
|
||||||
**tractor_kwargs,
|
**tractor_kwargs,
|
||||||
|
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
'''
|
||||||
|
Spawn a `brokerd.<backendname>` subactor service daemon
|
||||||
|
using `pikerd`'s service mngr.
|
||||||
|
|
||||||
|
'''
|
||||||
from piker.service._util import log # use service mngr log
|
from piker.service._util import log # use service mngr log
|
||||||
log.info(f'Spawning {brokername} broker daemon')
|
log.info(f'Spawning {brokername} broker daemon')
|
||||||
|
|
||||||
|
|
@ -220,27 +221,35 @@ async def spawn_brokerd(
|
||||||
|
|
||||||
# ask `pikerd` to spawn a new sub-actor and manage it under its
|
# ask `pikerd` to spawn a new sub-actor and manage it under its
|
||||||
# actor nursery
|
# actor nursery
|
||||||
from piker.service import Services
|
from piker.service import (
|
||||||
|
get_service_mngr,
|
||||||
dname: str = tractor_kwargs.pop('name') # f'brokerd.{brokername}'
|
ServiceMngr,
|
||||||
portal = await Services.actor_n.start_actor(
|
|
||||||
dname,
|
|
||||||
enable_modules=_data_mods + tractor_kwargs.pop('enable_modules'),
|
|
||||||
debug_mode=Services.debug_mode,
|
|
||||||
**tractor_kwargs
|
|
||||||
)
|
)
|
||||||
|
dname: str = tractor_kwargs.pop('name') # f'brokerd.{brokername}'
|
||||||
# NOTE: the service mngr expects an already spawned actor + its
|
mngr: ServiceMngr = get_service_mngr()
|
||||||
# portal ref in order to do non-blocking setup of brokerd
|
ctx: tractor.Context = await mngr.start_service(
|
||||||
# service nursery.
|
daemon_name=dname,
|
||||||
await Services.start_service_task(
|
ctx_ep=partial(
|
||||||
dname,
|
|
||||||
portal,
|
|
||||||
|
|
||||||
# signature of target root-task endpoint
|
# signature of target root-task endpoint
|
||||||
daemon_fixture_ep,
|
daemon_fixture_ep,
|
||||||
|
|
||||||
|
# passed to daemon_fixture_ep(**kwargs)
|
||||||
brokername=brokername,
|
brokername=brokername,
|
||||||
loglevel=loglevel,
|
loglevel=loglevel,
|
||||||
|
),
|
||||||
|
debug_mode=mngr.debug_mode,
|
||||||
|
loglevel=loglevel,
|
||||||
|
enable_modules=(
|
||||||
|
_data_mods
|
||||||
|
+
|
||||||
|
tractor_kwargs.pop('enable_modules')
|
||||||
|
),
|
||||||
|
**tractor_kwargs
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
not ctx.cancel_called
|
||||||
|
and ctx.portal # parent side
|
||||||
|
and dname in ctx.chan.uid # subactor is named as desired
|
||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
@ -265,8 +274,7 @@ async def maybe_spawn_brokerd(
|
||||||
from piker.service import maybe_spawn_daemon
|
from piker.service import maybe_spawn_daemon
|
||||||
|
|
||||||
async with maybe_spawn_daemon(
|
async with maybe_spawn_daemon(
|
||||||
|
service_name=f'brokerd.{brokername}',
|
||||||
f'brokerd.{brokername}',
|
|
||||||
service_task_target=spawn_brokerd,
|
service_task_target=spawn_brokerd,
|
||||||
spawn_args={
|
spawn_args={
|
||||||
'brokername': brokername,
|
'brokername': brokername,
|
||||||
|
|
|
||||||
|
|
@ -374,14 +374,9 @@ class Client:
|
||||||
pair: Pair = pair_type(**item)
|
pair: Pair = pair_type(**item)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
e.add_note(
|
e.add_note(
|
||||||
f'\n'
|
"\nDon't panic, prolly stupid binance changed their symbology schema again..\n"
|
||||||
f'New or removed field we need to codify!\n'
|
'Check out their API docs here:\n\n'
|
||||||
f'pair-type: {pair_type!r}\n'
|
'https://binance-docs.github.io/apidocs/spot/en/#exchange-information'
|
||||||
f'\n'
|
|
||||||
f"Don't panic, prolly stupid binance changed their symbology schema again..\n"
|
|
||||||
f'Check out their API docs here:\n'
|
|
||||||
f'\n'
|
|
||||||
f'https://binance-docs.github.io/apidocs/spot/en/#exchange-information\n'
|
|
||||||
)
|
)
|
||||||
raise
|
raise
|
||||||
pair_table[pair.symbol.upper()] = pair
|
pair_table[pair.symbol.upper()] = pair
|
||||||
|
|
|
||||||
|
|
@ -440,7 +440,6 @@ async def open_trade_dialog(
|
||||||
# - ledger: TransactionLedger
|
# - ledger: TransactionLedger
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
ctx.open_stream() as ems_stream,
|
ctx.open_stream() as ems_stream,
|
||||||
):
|
):
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,7 @@ from trio_typing import TaskStatus
|
||||||
from pendulum import (
|
from pendulum import (
|
||||||
from_timestamp,
|
from_timestamp,
|
||||||
)
|
)
|
||||||
|
from rapidfuzz import process as fuzzy
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import tractor
|
import tractor
|
||||||
|
|
||||||
|
|
@ -94,15 +95,13 @@ class L1(Struct):
|
||||||
|
|
||||||
|
|
||||||
# validation type
|
# validation type
|
||||||
# https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Aggregate-Trade-Streams#response-example
|
|
||||||
class AggTrade(Struct, frozen=True):
|
class AggTrade(Struct, frozen=True):
|
||||||
e: str # Event type
|
e: str # Event type
|
||||||
E: int # Event time
|
E: int # Event time
|
||||||
s: str # Symbol
|
s: str # Symbol
|
||||||
a: int # Aggregate trade ID
|
a: int # Aggregate trade ID
|
||||||
p: float # Price
|
p: float # Price
|
||||||
q: float # Quantity with all the market trades
|
q: float # Quantity
|
||||||
nq: float # Normal quantity without the trades involving RPI orders
|
|
||||||
f: int # First trade ID
|
f: int # First trade ID
|
||||||
l: int # noqa Last trade ID
|
l: int # noqa Last trade ID
|
||||||
T: int # Trade time
|
T: int # Trade time
|
||||||
|
|
@ -112,7 +111,6 @@ class AggTrade(Struct, frozen=True):
|
||||||
|
|
||||||
async def stream_messages(
|
async def stream_messages(
|
||||||
ws: NoBsWs,
|
ws: NoBsWs,
|
||||||
|
|
||||||
) -> AsyncGenerator[NoBsWs, dict]:
|
) -> AsyncGenerator[NoBsWs, dict]:
|
||||||
|
|
||||||
# TODO: match syntax here!
|
# TODO: match syntax here!
|
||||||
|
|
@ -223,8 +221,6 @@ def make_sub(pairs: list[str], sub_name: str, uid: int) -> dict[str, str]:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# TODO, why aren't frame resp `log.info()`s showing in upstream
|
|
||||||
# code?!
|
|
||||||
@acm
|
@acm
|
||||||
async def open_history_client(
|
async def open_history_client(
|
||||||
mkt: MktPair,
|
mkt: MktPair,
|
||||||
|
|
@ -450,6 +446,7 @@ async def subscribe(
|
||||||
|
|
||||||
|
|
||||||
async def stream_quotes(
|
async def stream_quotes(
|
||||||
|
|
||||||
send_chan: trio.abc.SendChannel,
|
send_chan: trio.abc.SendChannel,
|
||||||
symbols: list[str],
|
symbols: list[str],
|
||||||
feed_is_live: trio.Event,
|
feed_is_live: trio.Event,
|
||||||
|
|
@ -461,14 +458,11 @@ async def stream_quotes(
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
tractor.trionics.maybe_raise_from_masking_exc(),
|
|
||||||
send_chan as send_chan,
|
send_chan as send_chan,
|
||||||
open_cached_client('binance') as client,
|
open_cached_client('binance') as client,
|
||||||
):
|
):
|
||||||
init_msgs: list[FeedInit] = []
|
init_msgs: list[FeedInit] = []
|
||||||
for sym in symbols:
|
for sym in symbols:
|
||||||
mkt: MktPair
|
|
||||||
pair: Pair
|
|
||||||
mkt, pair = await get_mkt_info(sym)
|
mkt, pair = await get_mkt_info(sym)
|
||||||
|
|
||||||
# build out init msgs according to latest spec
|
# build out init msgs according to latest spec
|
||||||
|
|
@ -517,6 +511,7 @@ async def stream_quotes(
|
||||||
|
|
||||||
# start streaming
|
# start streaming
|
||||||
async for typ, quote in msg_gen:
|
async for typ, quote in msg_gen:
|
||||||
|
|
||||||
# period = time.time() - last
|
# period = time.time() - last
|
||||||
# hz = 1/period if period else float('inf')
|
# hz = 1/period if period else float('inf')
|
||||||
# if hz > 60:
|
# if hz > 60:
|
||||||
|
|
@ -552,7 +547,7 @@ async def open_symbol_search(
|
||||||
)
|
)
|
||||||
|
|
||||||
# repack in fqme-keyed table
|
# repack in fqme-keyed table
|
||||||
byfqme: dict[str, Pair] = {}
|
byfqme: dict[start, Pair] = {}
|
||||||
for pair in pairs.values():
|
for pair in pairs.values():
|
||||||
byfqme[pair.bs_fqme] = pair
|
byfqme[pair.bs_fqme] = pair
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -97,16 +97,6 @@ class Pair(Struct, frozen=True, kw_only=True):
|
||||||
baseAsset: str
|
baseAsset: str
|
||||||
baseAssetPrecision: int
|
baseAssetPrecision: int
|
||||||
|
|
||||||
permissionSets: list[list[str]]
|
|
||||||
|
|
||||||
# https://developers.binance.com/docs/binance-spot-api-docs#2025-08-26
|
|
||||||
# will become non-optional 2025-08-28?
|
|
||||||
# https://developers.binance.com/docs/binance-spot-api-docs#future-changes
|
|
||||||
pegInstructionsAllowed: bool = False
|
|
||||||
|
|
||||||
# https://developers.binance.com/docs/binance-spot-api-docs#2025-12-02
|
|
||||||
opoAllowed: bool = False
|
|
||||||
|
|
||||||
filters: dict[
|
filters: dict[
|
||||||
str,
|
str,
|
||||||
str | int | float,
|
str | int | float,
|
||||||
|
|
@ -152,11 +142,7 @@ class SpotPair(Pair, frozen=True):
|
||||||
defaultSelfTradePreventionMode: str
|
defaultSelfTradePreventionMode: str
|
||||||
allowedSelfTradePreventionModes: list[str]
|
allowedSelfTradePreventionModes: list[str]
|
||||||
permissions: list[str]
|
permissions: list[str]
|
||||||
|
permissionSets: list[list[str]]
|
||||||
# can the paint botz creat liq gaps even easier on this asset?
|
|
||||||
# Bp
|
|
||||||
# https://developers.binance.com/docs/binance-spot-api-docs/faqs/order_amend_keep_priority
|
|
||||||
amendAllowed: bool
|
|
||||||
|
|
||||||
# NOTE: see `.data._symcache.SymbologyCache.load()` for why
|
# NOTE: see `.data._symcache.SymbologyCache.load()` for why
|
||||||
ns_path: str = 'piker.brokers.binance:SpotPair'
|
ns_path: str = 'piker.brokers.binance:SpotPair'
|
||||||
|
|
@ -223,10 +209,7 @@ class FutesPair(Pair):
|
||||||
assert pair == self.pair # sanity
|
assert pair == self.pair # sanity
|
||||||
return f'{expiry}'
|
return f'{expiry}'
|
||||||
|
|
||||||
case (
|
case 'PERPETUAL':
|
||||||
'PERPETUAL'
|
|
||||||
| 'TRADIFI_PERPETUAL'
|
|
||||||
):
|
|
||||||
return 'PERP'
|
return 'PERP'
|
||||||
|
|
||||||
case '':
|
case '':
|
||||||
|
|
@ -255,10 +238,7 @@ class FutesPair(Pair):
|
||||||
margin: str = self.marginAsset
|
margin: str = self.marginAsset
|
||||||
|
|
||||||
match ctype:
|
match ctype:
|
||||||
case (
|
case 'PERPETUAL':
|
||||||
'PERPETUAL'
|
|
||||||
| 'TRADIFI_PERPETUAL'
|
|
||||||
):
|
|
||||||
return f'{margin}M'
|
return f'{margin}M'
|
||||||
|
|
||||||
case (
|
case (
|
||||||
|
|
|
||||||
|
|
@ -471,15 +471,11 @@ def search(
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# global opts
|
# global opts
|
||||||
brokermods: list[ModuleType] = list(config['brokermods'].values())
|
brokermods = list(config['brokermods'].values())
|
||||||
|
|
||||||
# TODO: this is coming from the `search --pdb` NOT from
|
|
||||||
# the `piker --pdb` XD ..
|
|
||||||
# -[ ] pull from the parent click ctx's values..dumdum
|
|
||||||
# assert pdb
|
|
||||||
|
|
||||||
# define tractor entrypoint
|
# define tractor entrypoint
|
||||||
async def main(func):
|
async def main(func):
|
||||||
|
|
||||||
async with maybe_open_pikerd(
|
async with maybe_open_pikerd(
|
||||||
loglevel=config['loglevel'],
|
loglevel=config['loglevel'],
|
||||||
debug_mode=pdb,
|
debug_mode=pdb,
|
||||||
|
|
|
||||||
|
|
@ -22,9 +22,7 @@ routines should be primitive data types where possible.
|
||||||
"""
|
"""
|
||||||
import inspect
|
import inspect
|
||||||
from types import ModuleType
|
from types import ModuleType
|
||||||
from typing import (
|
from typing import List, Dict, Any, Optional
|
||||||
Any,
|
|
||||||
)
|
|
||||||
|
|
||||||
import trio
|
import trio
|
||||||
|
|
||||||
|
|
@ -36,10 +34,8 @@ from ..accounting import MktPair
|
||||||
|
|
||||||
|
|
||||||
async def api(brokername: str, methname: str, **kwargs) -> dict:
|
async def api(brokername: str, methname: str, **kwargs) -> dict:
|
||||||
'''
|
"""Make (proxy through) a broker API call by name and return its result.
|
||||||
Make (proxy through) a broker API call by name and return its result.
|
"""
|
||||||
|
|
||||||
'''
|
|
||||||
brokermod = get_brokermod(brokername)
|
brokermod = get_brokermod(brokername)
|
||||||
async with brokermod.get_client() as client:
|
async with brokermod.get_client() as client:
|
||||||
meth = getattr(client, methname, None)
|
meth = getattr(client, methname, None)
|
||||||
|
|
@ -66,14 +62,10 @@ async def api(brokername: str, methname: str, **kwargs) -> dict:
|
||||||
|
|
||||||
async def stocks_quote(
|
async def stocks_quote(
|
||||||
brokermod: ModuleType,
|
brokermod: ModuleType,
|
||||||
tickers: list[str]
|
tickers: List[str]
|
||||||
|
) -> Dict[str, Dict[str, Any]]:
|
||||||
) -> dict[str, dict[str, Any]]:
|
"""Return quotes dict for ``tickers``.
|
||||||
'''
|
"""
|
||||||
Return a `dict` of snapshot quotes for the provided input
|
|
||||||
`tickers`: a `list` of fqmes.
|
|
||||||
|
|
||||||
'''
|
|
||||||
async with brokermod.get_client() as client:
|
async with brokermod.get_client() as client:
|
||||||
return await client.quote(tickers)
|
return await client.quote(tickers)
|
||||||
|
|
||||||
|
|
@ -82,15 +74,13 @@ async def stocks_quote(
|
||||||
async def option_chain(
|
async def option_chain(
|
||||||
brokermod: ModuleType,
|
brokermod: ModuleType,
|
||||||
symbol: str,
|
symbol: str,
|
||||||
date: str|None = None,
|
date: Optional[str] = None,
|
||||||
) -> dict[str, dict[str, dict[str, Any]]]:
|
) -> Dict[str, Dict[str, Dict[str, Any]]]:
|
||||||
'''
|
"""Return option chain for ``symbol`` for ``date``.
|
||||||
Return option chain for ``symbol`` for ``date``.
|
|
||||||
|
|
||||||
By default all expiries are returned. If ``date`` is provided
|
By default all expiries are returned. If ``date`` is provided
|
||||||
then contract quotes for that single expiry are returned.
|
then contract quotes for that single expiry are returned.
|
||||||
|
"""
|
||||||
'''
|
|
||||||
async with brokermod.get_client() as client:
|
async with brokermod.get_client() as client:
|
||||||
if date:
|
if date:
|
||||||
id = int((await client.tickers2ids([symbol]))[symbol])
|
id = int((await client.tickers2ids([symbol]))[symbol])
|
||||||
|
|
@ -108,7 +98,7 @@ async def option_chain(
|
||||||
# async def contracts(
|
# async def contracts(
|
||||||
# brokermod: ModuleType,
|
# brokermod: ModuleType,
|
||||||
# symbol: str,
|
# symbol: str,
|
||||||
# ) -> dict[str, dict[str, dict[str, Any]]]:
|
# ) -> Dict[str, Dict[str, Dict[str, Any]]]:
|
||||||
# """Return option contracts (all expiries) for ``symbol``.
|
# """Return option contracts (all expiries) for ``symbol``.
|
||||||
# """
|
# """
|
||||||
# async with brokermod.get_client() as client:
|
# async with brokermod.get_client() as client:
|
||||||
|
|
@ -120,24 +110,15 @@ async def bars(
|
||||||
brokermod: ModuleType,
|
brokermod: ModuleType,
|
||||||
symbol: str,
|
symbol: str,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
) -> dict[str, dict[str, dict[str, Any]]]:
|
) -> Dict[str, Dict[str, Dict[str, Any]]]:
|
||||||
'''
|
"""Return option contracts (all expiries) for ``symbol``.
|
||||||
Return option contracts (all expiries) for ``symbol``.
|
"""
|
||||||
|
|
||||||
'''
|
|
||||||
async with brokermod.get_client() as client:
|
async with brokermod.get_client() as client:
|
||||||
return await client.bars(symbol, **kwargs)
|
return await client.bars(symbol, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
async def search_w_brokerd(
|
async def search_w_brokerd(name: str, pattern: str) -> dict:
|
||||||
name: str,
|
|
||||||
pattern: str,
|
|
||||||
) -> dict:
|
|
||||||
|
|
||||||
# TODO: WHY NOT WORK!?!
|
|
||||||
# when we `step` through the next block?
|
|
||||||
# import tractor
|
|
||||||
# await tractor.pause()
|
|
||||||
async with open_cached_client(name) as client:
|
async with open_cached_client(name) as client:
|
||||||
|
|
||||||
# TODO: support multiple asset type concurrent searches.
|
# TODO: support multiple asset type concurrent searches.
|
||||||
|
|
@ -149,12 +130,12 @@ async def symbol_search(
|
||||||
pattern: str,
|
pattern: str,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
|
||||||
) -> dict[str, dict[str, dict[str, Any]]]:
|
) -> Dict[str, Dict[str, Dict[str, Any]]]:
|
||||||
'''
|
'''
|
||||||
Return symbol info from broker.
|
Return symbol info from broker.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
results: list[str] = []
|
results = []
|
||||||
|
|
||||||
async def search_backend(
|
async def search_backend(
|
||||||
brokermod: ModuleType
|
brokermod: ModuleType
|
||||||
|
|
@ -162,13 +143,6 @@ async def symbol_search(
|
||||||
|
|
||||||
brokername: str = mod.name
|
brokername: str = mod.name
|
||||||
|
|
||||||
# TODO: figure this the FUCK OUT
|
|
||||||
# -> ok so obvi in the root actor any async task that's
|
|
||||||
# spawned outside the main tractor-root-actor task needs to
|
|
||||||
# call this..
|
|
||||||
# await tractor.devx._debug.maybe_init_greenback()
|
|
||||||
# tractor.pause_from_sync()
|
|
||||||
|
|
||||||
async with maybe_spawn_brokerd(
|
async with maybe_spawn_brokerd(
|
||||||
mod.name,
|
mod.name,
|
||||||
infect_asyncio=getattr(
|
infect_asyncio=getattr(
|
||||||
|
|
@ -188,6 +162,7 @@ async def symbol_search(
|
||||||
))
|
))
|
||||||
|
|
||||||
async with trio.open_nursery() as n:
|
async with trio.open_nursery() as n:
|
||||||
|
|
||||||
for mod in brokermods:
|
for mod in brokermods:
|
||||||
n.start_soon(search_backend, mod.name)
|
n.start_soon(search_backend, mod.name)
|
||||||
|
|
||||||
|
|
@ -197,13 +172,11 @@ async def symbol_search(
|
||||||
async def mkt_info(
|
async def mkt_info(
|
||||||
brokermod: ModuleType,
|
brokermod: ModuleType,
|
||||||
fqme: str,
|
fqme: str,
|
||||||
|
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
|
||||||
) -> MktPair:
|
) -> MktPair:
|
||||||
'''
|
'''
|
||||||
Return the `piker.accounting.MktPair` info struct from a given
|
Return MktPair info from broker including src and dst assets.
|
||||||
backend broker tradable src/dst asset pair.
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
async with open_cached_client(brokermod.name) as client:
|
async with open_cached_client(brokermod.name) as client:
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ from .api import (
|
||||||
get_client,
|
get_client,
|
||||||
)
|
)
|
||||||
from .feed import (
|
from .feed import (
|
||||||
|
get_mkt_info,
|
||||||
open_history_client,
|
open_history_client,
|
||||||
open_symbol_search,
|
open_symbol_search,
|
||||||
stream_quotes,
|
stream_quotes,
|
||||||
|
|
@ -34,15 +35,20 @@ from .feed import (
|
||||||
# open_trade_dialog,
|
# open_trade_dialog,
|
||||||
# norm_trade_records,
|
# norm_trade_records,
|
||||||
# )
|
# )
|
||||||
|
from .venues import (
|
||||||
|
OptionPair,
|
||||||
|
)
|
||||||
|
|
||||||
log = get_logger(__name__)
|
log = get_logger(__name__)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'get_client',
|
'get_client',
|
||||||
# 'trades_dialogue',
|
# 'trades_dialogue',
|
||||||
|
'get_mkt_info',
|
||||||
'open_history_client',
|
'open_history_client',
|
||||||
'open_symbol_search',
|
'open_symbol_search',
|
||||||
'stream_quotes',
|
'stream_quotes',
|
||||||
|
'OptionPair',
|
||||||
# 'norm_trade_records',
|
# 'norm_trade_records',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -18,38 +18,59 @@
|
||||||
Deribit backend.
|
Deribit backend.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
from contextlib import asynccontextmanager as acm
|
from contextlib import asynccontextmanager as acm
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any, Optional, Callable
|
from typing import (
|
||||||
|
# Any,
|
||||||
|
# Optional,
|
||||||
|
Callable,
|
||||||
|
)
|
||||||
|
# from pprint import pformat
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
import cryptofeed
|
||||||
import trio
|
import trio
|
||||||
from trio_typing import TaskStatus
|
from trio_typing import TaskStatus
|
||||||
import pendulum
|
from pendulum import (
|
||||||
from rapidfuzz import process as fuzzy
|
from_timestamp,
|
||||||
|
)
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import tractor
|
import tractor
|
||||||
|
|
||||||
from piker.brokers import open_cached_client
|
from piker.accounting import (
|
||||||
from piker.log import get_logger, get_console_log
|
Asset,
|
||||||
from piker.data import ShmArray
|
MktPair,
|
||||||
from piker.brokers._util import (
|
unpack_fqme,
|
||||||
BrokerError,
|
)
|
||||||
|
from piker.brokers import (
|
||||||
|
open_cached_client,
|
||||||
|
NoData,
|
||||||
DataUnavailable,
|
DataUnavailable,
|
||||||
)
|
)
|
||||||
|
from piker._cacheables import (
|
||||||
from cryptofeed import FeedHandler
|
async_lifo_cache,
|
||||||
from cryptofeed.defines import (
|
|
||||||
DERIBIT, L1_BOOK, TRADES, OPTION, CALL, PUT
|
|
||||||
)
|
)
|
||||||
from cryptofeed.symbols import Symbol
|
from piker.log import (
|
||||||
|
get_logger,
|
||||||
|
mk_repr,
|
||||||
|
)
|
||||||
|
from piker.data.validate import FeedInit
|
||||||
|
|
||||||
|
|
||||||
from .api import (
|
from .api import (
|
||||||
Client, Trade,
|
Client,
|
||||||
get_config,
|
# get_config,
|
||||||
str_to_cb_sym, piker_sym_to_cb_sym, cb_sym_to_deribit_inst,
|
piker_sym_to_cb_sym,
|
||||||
|
cb_sym_to_deribit_inst,
|
||||||
|
str_to_cb_sym,
|
||||||
maybe_open_price_feed
|
maybe_open_price_feed
|
||||||
)
|
)
|
||||||
|
from .venues import (
|
||||||
|
Pair,
|
||||||
|
OptionPair,
|
||||||
|
Trade,
|
||||||
|
)
|
||||||
|
|
||||||
_spawn_kwargs = {
|
_spawn_kwargs = {
|
||||||
'infect_asyncio': True,
|
'infect_asyncio': True,
|
||||||
|
|
@ -64,90 +85,215 @@ async def open_history_client(
|
||||||
mkt: MktPair,
|
mkt: MktPair,
|
||||||
) -> tuple[Callable, int]:
|
) -> tuple[Callable, int]:
|
||||||
|
|
||||||
fnstrument: str = mkt.bs_fqme
|
|
||||||
# TODO implement history getter for the new storage layer.
|
# TODO implement history getter for the new storage layer.
|
||||||
async with open_cached_client('deribit') as client:
|
async with open_cached_client('deribit') as client:
|
||||||
|
|
||||||
|
pair: OptionPair = client._pairs[mkt.dst.name]
|
||||||
|
# XXX NOTE, the cuckers use ms !!!
|
||||||
|
creation_time_s: int = pair.creation_timestamp/1000
|
||||||
|
|
||||||
async def get_ohlc(
|
async def get_ohlc(
|
||||||
end_dt: Optional[datetime] = None,
|
timeframe: float,
|
||||||
start_dt: Optional[datetime] = None,
|
end_dt: datetime | None = None,
|
||||||
|
start_dt: datetime | None = None,
|
||||||
|
|
||||||
) -> tuple[
|
) -> tuple[
|
||||||
np.ndarray,
|
np.ndarray,
|
||||||
datetime, # start
|
datetime, # start
|
||||||
datetime, # end
|
datetime, # end
|
||||||
]:
|
]:
|
||||||
|
if timeframe != 60:
|
||||||
|
raise DataUnavailable('Only 1m bars are supported')
|
||||||
|
|
||||||
array = await client.bars(
|
array: np.ndarray = await client.bars(
|
||||||
instrument,
|
mkt,
|
||||||
start_dt=start_dt,
|
start_dt=start_dt,
|
||||||
end_dt=end_dt,
|
end_dt=end_dt,
|
||||||
)
|
)
|
||||||
if len(array) == 0:
|
if len(array) == 0:
|
||||||
raise DataUnavailable
|
if (
|
||||||
|
end_dt is None
|
||||||
|
):
|
||||||
|
raise DataUnavailable(
|
||||||
|
'No history seems to exist yet?\n\n'
|
||||||
|
f'{mkt}'
|
||||||
|
)
|
||||||
|
elif (
|
||||||
|
end_dt
|
||||||
|
and
|
||||||
|
end_dt.timestamp() < creation_time_s
|
||||||
|
):
|
||||||
|
# the contract can't have history
|
||||||
|
# before it was created.
|
||||||
|
pair_type_str: str = type(pair).__name__
|
||||||
|
create_dt: datetime = from_timestamp(creation_time_s)
|
||||||
|
raise DataUnavailable(
|
||||||
|
f'No history prior to\n'
|
||||||
|
f'`{pair_type_str}.creation_timestamp: int = '
|
||||||
|
f'{pair.creation_timestamp}\n\n'
|
||||||
|
f'------ deribit sux ------\n'
|
||||||
|
f'WHICH IN "NORMAL PEOPLE WHO USE EPOCH TIME" form is,\n'
|
||||||
|
f'creation_time_s: {creation_time_s}\n'
|
||||||
|
f'create_dt: {create_dt}\n'
|
||||||
|
)
|
||||||
|
raise NoData(
|
||||||
|
f'No frame for {start_dt} -> {end_dt}\n'
|
||||||
|
)
|
||||||
|
|
||||||
start_dt = pendulum.from_timestamp(array[0]['time'])
|
start_dt = from_timestamp(array[0]['time'])
|
||||||
end_dt = pendulum.from_timestamp(array[-1]['time'])
|
end_dt = from_timestamp(array[-1]['time'])
|
||||||
|
|
||||||
|
times = array['time']
|
||||||
|
if not times.any():
|
||||||
|
raise ValueError(
|
||||||
|
'Bad frame with null-times?\n\n'
|
||||||
|
f'{times}'
|
||||||
|
)
|
||||||
|
|
||||||
|
if end_dt is None:
|
||||||
|
inow: int = round(time.time())
|
||||||
|
if (inow - times[-1]) > 60:
|
||||||
|
await tractor.pause()
|
||||||
|
|
||||||
return array, start_dt, end_dt
|
return array, start_dt, end_dt
|
||||||
|
|
||||||
yield get_ohlc, {'erlangs': 3, 'rate': 3}
|
yield (
|
||||||
|
get_ohlc,
|
||||||
|
{ # backfill config
|
||||||
|
'erlangs': 3,
|
||||||
|
'rate': 3,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@async_lifo_cache()
|
||||||
|
async def get_mkt_info(
|
||||||
|
fqme: str,
|
||||||
|
|
||||||
|
) -> tuple[MktPair, Pair|OptionPair] | None:
|
||||||
|
|
||||||
|
# uppercase since kraken bs_mktid is always upper
|
||||||
|
if 'deribit' not in fqme.lower():
|
||||||
|
fqme += '.deribit'
|
||||||
|
|
||||||
|
mkt_mode: str = ''
|
||||||
|
broker, mkt_ep, venue, expiry = unpack_fqme(fqme)
|
||||||
|
|
||||||
|
# NOTE: we always upper case all tokens to be consistent with
|
||||||
|
# binance's symbology style for pairs, like `BTCUSDT`, but in
|
||||||
|
# theory we could also just keep things lower case; as long as
|
||||||
|
# we're consistent and the symcache matches whatever this func
|
||||||
|
# returns, always!
|
||||||
|
expiry: str = expiry.upper()
|
||||||
|
venue: str = venue.upper()
|
||||||
|
# venue_lower: str = venue.lower()
|
||||||
|
|
||||||
|
mkt_mode: str = 'option'
|
||||||
|
|
||||||
|
async with open_cached_client(
|
||||||
|
'deribit',
|
||||||
|
) as client:
|
||||||
|
|
||||||
|
assets: dict[str, Asset] = await client.get_assets()
|
||||||
|
pair_str: str = mkt_ep.lower()
|
||||||
|
|
||||||
|
pair: Pair = await client.exch_info(
|
||||||
|
sym=pair_str,
|
||||||
|
)
|
||||||
|
mkt_mode = pair.venue
|
||||||
|
client.mkt_mode = mkt_mode
|
||||||
|
|
||||||
|
dst: Asset | None = assets.get(pair.bs_dst_asset)
|
||||||
|
src: Asset | None = assets.get(pair.bs_src_asset)
|
||||||
|
|
||||||
|
mkt = MktPair(
|
||||||
|
dst=dst,
|
||||||
|
src=src,
|
||||||
|
price_tick=pair.price_tick,
|
||||||
|
size_tick=pair.size_tick,
|
||||||
|
bs_mktid=pair.symbol,
|
||||||
|
venue=mkt_mode,
|
||||||
|
broker='deribit',
|
||||||
|
_atype=mkt_mode,
|
||||||
|
_fqme_without_src=True,
|
||||||
|
|
||||||
|
# expiry=pair.expiry,
|
||||||
|
# XXX TODO, currently we don't use it since it's
|
||||||
|
# already "described" in the `OptionPair.symbol: str`
|
||||||
|
# and if we slap in the ISO repr it's kinda hideous..
|
||||||
|
# -[ ] figure out the best either std
|
||||||
|
)
|
||||||
|
return mkt, pair
|
||||||
|
|
||||||
|
|
||||||
async def stream_quotes(
|
async def stream_quotes(
|
||||||
|
|
||||||
send_chan: trio.abc.SendChannel,
|
send_chan: trio.abc.SendChannel,
|
||||||
symbols: list[str],
|
symbols: list[str],
|
||||||
feed_is_live: trio.Event,
|
feed_is_live: trio.Event,
|
||||||
loglevel: str = None,
|
|
||||||
|
|
||||||
# startup sync
|
# startup sync
|
||||||
task_status: TaskStatus[tuple[dict, dict]] = trio.TASK_STATUS_IGNORED,
|
task_status: TaskStatus[tuple[dict, dict]] = trio.TASK_STATUS_IGNORED,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
# XXX: required to propagate ``tractor`` loglevel to piker logging
|
'''
|
||||||
get_console_log(loglevel or tractor.current_actor().loglevel)
|
Open a live quote stream for the market set defined by `symbols`.
|
||||||
|
|
||||||
sym = symbols[0]
|
Internally this starts a `cryptofeed.FeedHandler` inside an `asyncio`-side
|
||||||
|
task and relays through L1 and `Trade` msgs here to our `trio.Task`.
|
||||||
|
|
||||||
|
'''
|
||||||
|
sym = symbols[0].split('.')[0]
|
||||||
|
init_msgs: list[FeedInit] = []
|
||||||
|
|
||||||
|
# multiline nested `dict` formatter (since rn quote-msgs are
|
||||||
|
# just that).
|
||||||
|
pfmt: Callable[[str], str] = mk_repr(
|
||||||
|
# so we can see `deribit`'s delightfully mega-long bs fields..
|
||||||
|
maxstring=100,
|
||||||
|
)
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
open_cached_client('deribit') as client,
|
open_cached_client('deribit') as client,
|
||||||
send_chan as send_chan
|
send_chan as send_chan
|
||||||
):
|
):
|
||||||
|
mkt: MktPair
|
||||||
|
pair: Pair
|
||||||
|
mkt, pair = await get_mkt_info(sym)
|
||||||
|
|
||||||
init_msgs = {
|
# build out init msgs according to latest spec
|
||||||
# pass back token, and bool, signalling if we're the writer
|
init_msgs.append(
|
||||||
# and that history has been written
|
FeedInit(
|
||||||
sym: {
|
mkt_info=mkt,
|
||||||
'symbol_info': {
|
)
|
||||||
'asset_type': 'option',
|
)
|
||||||
'price_tick_size': 0.0005
|
# build `cryptofeed` feed-handle
|
||||||
},
|
cf_sym: cryptofeed.Symbol = piker_sym_to_cb_sym(sym)
|
||||||
'shm_write_opts': {'sum_tick_vml': False},
|
|
||||||
'fqsn': sym,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
nsym = piker_sym_to_cb_sym(sym)
|
from_cf: tractor.to_asyncio.LinkedTaskChannel
|
||||||
|
async with maybe_open_price_feed(sym) as from_cf:
|
||||||
|
|
||||||
async with maybe_open_price_feed(sym) as stream:
|
# load the "last trades" summary
|
||||||
|
last_trades_res: cryptofeed.LastTradesResult = await client.last_trades(
|
||||||
|
cb_sym_to_deribit_inst(cf_sym),
|
||||||
|
count=1,
|
||||||
|
)
|
||||||
|
last_trades: list[Trade] = last_trades_res.trades
|
||||||
|
|
||||||
cache = await client.cache_symbols()
|
# TODO, do we even need this or will the above always
|
||||||
|
# work?
|
||||||
|
# if not last_trades:
|
||||||
|
# await tractor.pause()
|
||||||
|
# async for typ, quote in from_cf:
|
||||||
|
# if typ == 'trade':
|
||||||
|
# last_trade = Trade(**(quote['data']))
|
||||||
|
# break
|
||||||
|
|
||||||
last_trades = (await client.last_trades(
|
# else:
|
||||||
cb_sym_to_deribit_inst(nsym), count=1)).trades
|
last_trade = Trade(
|
||||||
|
**(last_trades[0])
|
||||||
|
)
|
||||||
|
|
||||||
if len(last_trades) == 0:
|
first_quote: dict = {
|
||||||
last_trade = None
|
|
||||||
async for typ, quote in stream:
|
|
||||||
if typ == 'trade':
|
|
||||||
last_trade = Trade(**(quote['data']))
|
|
||||||
break
|
|
||||||
|
|
||||||
else:
|
|
||||||
last_trade = Trade(**(last_trades[0]))
|
|
||||||
|
|
||||||
first_quote = {
|
|
||||||
'symbol': sym,
|
'symbol': sym,
|
||||||
'last': last_trade.price,
|
'last': last_trade.price,
|
||||||
'brokerd_ts': last_trade.timestamp,
|
'brokerd_ts': last_trade.timestamp,
|
||||||
|
|
@ -158,13 +304,84 @@ async def stream_quotes(
|
||||||
'broker_ts': last_trade.timestamp
|
'broker_ts': last_trade.timestamp
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
task_status.started((init_msgs, first_quote))
|
task_status.started((
|
||||||
|
init_msgs,
|
||||||
|
first_quote,
|
||||||
|
))
|
||||||
|
|
||||||
feed_is_live.set()
|
feed_is_live.set()
|
||||||
|
|
||||||
async for typ, quote in stream:
|
# NOTE XXX, static for now!
|
||||||
topic = quote['symbol']
|
# => since this only handles ONE mkt feed at a time we
|
||||||
await send_chan.send({topic: quote})
|
# don't need a lookup table to map interleaved quotes
|
||||||
|
# from multiple possible mkt-pairs
|
||||||
|
topic: str = mkt.bs_fqme
|
||||||
|
|
||||||
|
# deliver until cancelled
|
||||||
|
async for typ, ref in from_cf:
|
||||||
|
match typ:
|
||||||
|
case 'trade':
|
||||||
|
trade: cryptofeed.types.Trade = ref
|
||||||
|
|
||||||
|
# TODO, re-impl this according to teh ideal
|
||||||
|
# fqme for opts that we choose!!
|
||||||
|
bs_fqme: str = cb_sym_to_deribit_inst(
|
||||||
|
str_to_cb_sym(trade.symbol)
|
||||||
|
).lower()
|
||||||
|
|
||||||
|
piker_quote: dict = {
|
||||||
|
'symbol': bs_fqme,
|
||||||
|
'last': trade.price,
|
||||||
|
'broker_ts': time.time(),
|
||||||
|
# ^TODO, name this `brokerd/datad_ts` and
|
||||||
|
# use `time.time_ns()` ??
|
||||||
|
'ticks': [{
|
||||||
|
'type': 'trade',
|
||||||
|
'price': float(trade.price),
|
||||||
|
'size': float(trade.amount),
|
||||||
|
'broker_ts': trade.timestamp,
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
log.info(
|
||||||
|
f'deribit {typ!r} quote for {sym!r}\n\n'
|
||||||
|
f'{trade}\n\n'
|
||||||
|
f'{pfmt(piker_quote)}\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
case 'l1':
|
||||||
|
book: cryptofeed.types.L1Book = ref
|
||||||
|
|
||||||
|
# TODO, so this is where we can possibly change things
|
||||||
|
# and instead lever the `MktPair.bs_fqme: str` output?
|
||||||
|
bs_fqme: str = cb_sym_to_deribit_inst(
|
||||||
|
str_to_cb_sym(book.symbol)
|
||||||
|
).lower()
|
||||||
|
|
||||||
|
piker_quote: dict = {
|
||||||
|
'symbol': bs_fqme,
|
||||||
|
'ticks': [
|
||||||
|
|
||||||
|
{'type': 'bid',
|
||||||
|
'price': float(book.bid_price),
|
||||||
|
'size': float(book.bid_size)},
|
||||||
|
|
||||||
|
{'type': 'bsize',
|
||||||
|
'price': float(book.bid_price),
|
||||||
|
'size': float(book.bid_size),},
|
||||||
|
|
||||||
|
{'type': 'ask',
|
||||||
|
'price': float(book.ask_price),
|
||||||
|
'size': float(book.ask_size),},
|
||||||
|
|
||||||
|
{'type': 'asize',
|
||||||
|
'price': float(book.ask_price),
|
||||||
|
'size': float(book.ask_size),}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
await send_chan.send({
|
||||||
|
topic: piker_quote,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
@tractor.context
|
@tractor.context
|
||||||
|
|
@ -174,12 +391,21 @@ async def open_symbol_search(
|
||||||
async with open_cached_client('deribit') as client:
|
async with open_cached_client('deribit') as client:
|
||||||
|
|
||||||
# load all symbols locally for fast search
|
# load all symbols locally for fast search
|
||||||
cache = await client.cache_symbols()
|
# cache = client._pairs
|
||||||
await ctx.started()
|
await ctx.started()
|
||||||
|
|
||||||
async with ctx.open_stream() as stream:
|
async with ctx.open_stream() as stream:
|
||||||
|
pattern: str
|
||||||
async for pattern in stream:
|
async for pattern in stream:
|
||||||
# repack in dict form
|
|
||||||
await stream.send(
|
# NOTE: pattern fuzzy-matching is done within
|
||||||
await client.search_symbols(pattern))
|
# the methd impl.
|
||||||
|
pairs: dict[str, Pair] = await client.search_symbols(
|
||||||
|
pattern,
|
||||||
|
)
|
||||||
|
# repack in fqme-keyed table
|
||||||
|
byfqme: dict[str, Pair] = {}
|
||||||
|
for pair in pairs.values():
|
||||||
|
byfqme[pair.bs_fqme] = pair
|
||||||
|
|
||||||
|
await stream.send(byfqme)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,196 @@
|
||||||
|
# piker: trading gear for hackers
|
||||||
|
# Copyright (C) Tyler Goodlet (in stewardship for pikers)
|
||||||
|
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU Affero General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
# You should have received a copy of the GNU Affero General Public License
|
||||||
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
"""
|
||||||
|
Per market data-type definitions and schemas types.
|
||||||
|
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
import pendulum
|
||||||
|
from typing import (
|
||||||
|
Literal,
|
||||||
|
Optional,
|
||||||
|
)
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from piker.types import Struct
|
||||||
|
|
||||||
|
|
||||||
|
# API endpoint paths by venue / sub-API
|
||||||
|
_domain: str = 'deribit.com'
|
||||||
|
_url = f'https://www.{_domain}'
|
||||||
|
|
||||||
|
# WEBsocketz
|
||||||
|
_ws_url: str = f'wss://www.{_domain}/ws/api/v2'
|
||||||
|
|
||||||
|
# test nets
|
||||||
|
_testnet_ws_url: str = f'wss://test.{_domain}/ws/api/v2'
|
||||||
|
|
||||||
|
MarketType = Literal[
|
||||||
|
'option'
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def get_api_eps(venue: MarketType) -> tuple[str, str]:
|
||||||
|
'''
|
||||||
|
Return API ep root paths per venue.
|
||||||
|
|
||||||
|
'''
|
||||||
|
return {
|
||||||
|
'option': (
|
||||||
|
_ws_url,
|
||||||
|
),
|
||||||
|
}[venue]
|
||||||
|
|
||||||
|
|
||||||
|
class Pair(Struct, frozen=True, kw_only=True):
|
||||||
|
|
||||||
|
symbol: str
|
||||||
|
|
||||||
|
# src
|
||||||
|
quote_currency: str # 'BTC'
|
||||||
|
|
||||||
|
# dst
|
||||||
|
base_currency: str # "BTC",
|
||||||
|
|
||||||
|
tick_size: float # 0.0001 # [{'above_price': 0.005, 'tick_size': 0.0005}]
|
||||||
|
tick_size_steps: list[dict[str, float]]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def price_tick(self) -> Decimal:
|
||||||
|
return Decimal(str(self.tick_size_steps[0]['above_price']))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def size_tick(self) -> Decimal:
|
||||||
|
return Decimal(str(self.tick_size))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def bs_fqme(self) -> str:
|
||||||
|
return f'{self.symbol}'
|
||||||
|
|
||||||
|
@property
|
||||||
|
def bs_mktid(self) -> str:
|
||||||
|
return f'{self.symbol}.{self.venue}'
|
||||||
|
|
||||||
|
|
||||||
|
class OptionPair(Pair, frozen=True):
|
||||||
|
|
||||||
|
taker_commission: float # 0.0003
|
||||||
|
strike: float # 5000.0
|
||||||
|
settlement_period: str # 'day'
|
||||||
|
settlement_currency: str # "BTC",
|
||||||
|
rfq: bool # false
|
||||||
|
price_index: str # 'btc_usd'
|
||||||
|
option_type: str # 'call'
|
||||||
|
min_trade_amount: float # 0.1
|
||||||
|
maker_commission: float # 0.0003
|
||||||
|
kind: str # 'option'
|
||||||
|
is_active: bool # true
|
||||||
|
instrument_type: str # 'reversed'
|
||||||
|
instrument_name: str # 'BTC-1SEP24-55000-C'
|
||||||
|
instrument_id: int # 364671
|
||||||
|
expiration_timestamp: int # 1725177600000
|
||||||
|
creation_timestamp: int # 1724918461000
|
||||||
|
counter_currency: str # 'USD'
|
||||||
|
contract_size: float # '1.0'
|
||||||
|
block_trade_tick_size: float # '0.0001'
|
||||||
|
block_trade_min_trade_amount: int # '25'
|
||||||
|
block_trade_commission: float # '0.003'
|
||||||
|
|
||||||
|
# NOTE: see `.data._symcache.SymbologyCache.load()` for why
|
||||||
|
ns_path: str = 'piker.brokers.deribit:OptionPair'
|
||||||
|
|
||||||
|
# TODO, impl this without the MM:SS part of
|
||||||
|
# the `'THH:MM:SS..'` etc..
|
||||||
|
@property
|
||||||
|
def expiry(self) -> str:
|
||||||
|
iso_date = pendulum.from_timestamp(
|
||||||
|
self.expiration_timestamp / 1000
|
||||||
|
).isoformat()
|
||||||
|
return iso_date
|
||||||
|
|
||||||
|
@property
|
||||||
|
def venue(self) -> str:
|
||||||
|
return f'{self.instrument_type}_option'
|
||||||
|
|
||||||
|
@property
|
||||||
|
def bs_fqme(self) -> str:
|
||||||
|
return f'{self.symbol}'
|
||||||
|
|
||||||
|
@property
|
||||||
|
def bs_src_asset(self) -> str:
|
||||||
|
return f'{self.quote_currency}'
|
||||||
|
|
||||||
|
@property
|
||||||
|
def bs_dst_asset(self) -> str:
|
||||||
|
return f'{self.symbol}'
|
||||||
|
|
||||||
|
|
||||||
|
PAIRTYPES: dict[MarketType, Pair] = {
|
||||||
|
'option': OptionPair,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class JSONRPCResult(Struct):
|
||||||
|
id: int
|
||||||
|
usIn: int
|
||||||
|
usOut: int
|
||||||
|
usDiff: int
|
||||||
|
testnet: bool
|
||||||
|
jsonrpc: str = '2.0'
|
||||||
|
error: Optional[dict] = None
|
||||||
|
result: Optional[list[dict]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class JSONRPCChannel(Struct):
|
||||||
|
method: str
|
||||||
|
params: dict
|
||||||
|
jsonrpc: str = '2.0'
|
||||||
|
|
||||||
|
|
||||||
|
class KLinesResult(Struct):
|
||||||
|
low: list[float]
|
||||||
|
cost: list[float]
|
||||||
|
high: list[float]
|
||||||
|
open: list[float]
|
||||||
|
close: list[float]
|
||||||
|
ticks: list[int]
|
||||||
|
status: str
|
||||||
|
volume: list[float]
|
||||||
|
|
||||||
|
|
||||||
|
class Trade(Struct):
|
||||||
|
iv: float
|
||||||
|
price: float
|
||||||
|
amount: float
|
||||||
|
trade_id: str
|
||||||
|
contracts: float
|
||||||
|
direction: str
|
||||||
|
trade_seq: int
|
||||||
|
timestamp: int
|
||||||
|
mark_price: float
|
||||||
|
index_price: float
|
||||||
|
tick_direction: int
|
||||||
|
instrument_name: str
|
||||||
|
combo_id: Optional[str] = '',
|
||||||
|
combo_trade_id: Optional[int] = 0,
|
||||||
|
block_trade_id: Optional[str] = '',
|
||||||
|
block_trade_leg_count: Optional[int] = 0,
|
||||||
|
|
||||||
|
|
||||||
|
class LastTradesResult(Struct):
|
||||||
|
trades: list[Trade]
|
||||||
|
has_more: bool
|
||||||
|
|
@ -20,11 +20,6 @@ runnable script-programs.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from datetime import ( # noqa
|
|
||||||
datetime,
|
|
||||||
date,
|
|
||||||
tzinfo as TzInfo,
|
|
||||||
)
|
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from typing import (
|
from typing import (
|
||||||
Literal,
|
Literal,
|
||||||
|
|
@ -38,7 +33,7 @@ from piker.brokers._util import get_logger
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from .api import Client
|
from .api import Client
|
||||||
import i3ipc
|
from ib_insync import IB
|
||||||
|
|
||||||
log = get_logger('piker.brokers.ib')
|
log = get_logger('piker.brokers.ib')
|
||||||
|
|
||||||
|
|
@ -53,39 +48,8 @@ _reset_tech: Literal[
|
||||||
] = 'vnc'
|
] = 'vnc'
|
||||||
|
|
||||||
|
|
||||||
no_setup_msg:str = (
|
|
||||||
'No data reset hack test setup for {vnc_sockaddr}!\n'
|
|
||||||
'See config setup tips @\n'
|
|
||||||
'https://github.com/pikers/piker/tree/master/piker/brokers/ib'
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def try_xdo_manual(
|
|
||||||
client: Client,
|
|
||||||
):
|
|
||||||
'''
|
|
||||||
Do the "manual" `xdo`-based screen switch + click
|
|
||||||
combo since apparently the `asyncvnc` client ain't workin..
|
|
||||||
|
|
||||||
Note this is only meant as a backup method for Xorg users,
|
|
||||||
ideally you can use a real vnc client and the `vnc_click_hack()`
|
|
||||||
impl!
|
|
||||||
|
|
||||||
'''
|
|
||||||
global _reset_tech
|
|
||||||
try:
|
|
||||||
i3ipc_xdotool_manual_click_hack()
|
|
||||||
_reset_tech = 'i3ipc_xdotool'
|
|
||||||
return True
|
|
||||||
except OSError:
|
|
||||||
vnc_sockaddr: str = client.conf.vnc_addrs
|
|
||||||
log.exception(
|
|
||||||
no_setup_msg.format(vnc_sockaddr=vnc_sockaddr)
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
async def data_reset_hack(
|
async def data_reset_hack(
|
||||||
|
# vnc_host: str,
|
||||||
client: Client,
|
client: Client,
|
||||||
reset_type: Literal['data', 'connection'],
|
reset_type: Literal['data', 'connection'],
|
||||||
|
|
||||||
|
|
@ -117,60 +81,65 @@ async def data_reset_hack(
|
||||||
that need to be wrangle.
|
that need to be wrangle.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
ib_client: IB = client.ib
|
||||||
|
|
||||||
# look up any user defined vnc socket address mapped from
|
# look up any user defined vnc socket address mapped from
|
||||||
# a particular API socket port.
|
# a particular API socket port.
|
||||||
vnc_addrs: tuple[str]|None = client.conf.get('vnc_addrs')
|
api_port: str = str(ib_client.client.port)
|
||||||
if not vnc_addrs:
|
vnc_host: str
|
||||||
|
vnc_port: int
|
||||||
|
vnc_sockaddr: tuple[str] | None = client.conf.get('vnc_addrs')
|
||||||
|
|
||||||
|
no_setup_msg:str = (
|
||||||
|
f'No data reset hack test setup for {vnc_sockaddr}!\n'
|
||||||
|
'See config setup tips @\n'
|
||||||
|
'https://github.com/pikers/piker/tree/master/piker/brokers/ib'
|
||||||
|
)
|
||||||
|
|
||||||
|
if not vnc_sockaddr:
|
||||||
log.warning(
|
log.warning(
|
||||||
no_setup_msg.format(vnc_sockaddr=client.conf)
|
no_setup_msg
|
||||||
+
|
+
|
||||||
'REQUIRES A `vnc_addrs: array` ENTRY'
|
'REQUIRES A `vnc_addrs: array` ENTRY'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
vnc_host, vnc_port = vnc_sockaddr.get(
|
||||||
|
api_port,
|
||||||
|
('localhost', 3003)
|
||||||
|
)
|
||||||
global _reset_tech
|
global _reset_tech
|
||||||
|
|
||||||
match _reset_tech:
|
match _reset_tech:
|
||||||
case 'vnc':
|
case 'vnc':
|
||||||
try:
|
try:
|
||||||
await tractor.to_asyncio.run_task(
|
await tractor.to_asyncio.run_task(
|
||||||
partial(
|
partial(
|
||||||
vnc_click_hack,
|
vnc_click_hack,
|
||||||
client=client,
|
host=vnc_host,
|
||||||
|
port=vnc_port,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
except (
|
except OSError:
|
||||||
OSError, # no VNC server avail..
|
if vnc_host != 'localhost':
|
||||||
PermissionError, # asyncvnc pw fail..
|
log.warning(no_setup_msg)
|
||||||
):
|
return False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import i3ipc # noqa (since a deps dynamic check)
|
import i3ipc # noqa (since a deps dynamic check)
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
log.warning(
|
log.warning(no_setup_msg)
|
||||||
no_setup_msg.format(vnc_sockaddr=client.conf)
|
|
||||||
)
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# XXX, Xorg only workaround..
|
try:
|
||||||
# TODO? remove now that we have `pyvnc`?
|
i3ipc_xdotool_manual_click_hack()
|
||||||
# if vnc_host not in {
|
_reset_tech = 'i3ipc_xdotool'
|
||||||
# 'localhost',
|
return True
|
||||||
# '127.0.0.1',
|
except OSError:
|
||||||
# }:
|
log.exception(no_setup_msg)
|
||||||
# focussed, matches = i3ipc_fin_wins_titled()
|
return False
|
||||||
# if not matches:
|
|
||||||
# log.warning(
|
|
||||||
# no_setup_msg.format(vnc_sockaddr=vnc_sockaddr)
|
|
||||||
# )
|
|
||||||
# return False
|
|
||||||
# else:
|
|
||||||
# try_xdo_manual(vnc_sockaddr)
|
|
||||||
|
|
||||||
# localhost but no vnc-client or it borked..
|
|
||||||
else:
|
|
||||||
try_xdo_manual(client)
|
|
||||||
|
|
||||||
case 'i3ipc_xdotool':
|
case 'i3ipc_xdotool':
|
||||||
try_xdo_manual(client)
|
i3ipc_xdotool_manual_click_hack()
|
||||||
# i3ipc_xdotool_manual_click_hack()
|
|
||||||
|
|
||||||
case _ as tech:
|
case _ as tech:
|
||||||
raise RuntimeError(f'{tech} is not supported for reset tech!?')
|
raise RuntimeError(f'{tech} is not supported for reset tech!?')
|
||||||
|
|
@ -180,66 +149,21 @@ async def data_reset_hack(
|
||||||
|
|
||||||
|
|
||||||
async def vnc_click_hack(
|
async def vnc_click_hack(
|
||||||
client: Client,
|
host: str,
|
||||||
reset_type: str = 'data',
|
port: int,
|
||||||
pw: str|None = None,
|
reset_type: str = 'data'
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
Reset the data or network connection for the VNC attached
|
Reset the data or network connection for the VNC attached
|
||||||
ib-gateway using a (magic) keybinding combo.
|
ib gateway using magic combos.
|
||||||
|
|
||||||
A vnc-server password can be set either by an input `pw` param or
|
|
||||||
set in the client's config with the latter loaded from the user's
|
|
||||||
`brokers.toml` in a vnc-addrs-port-mapping section,
|
|
||||||
|
|
||||||
.. code:: toml
|
|
||||||
|
|
||||||
[ib.vnc_addrs]
|
|
||||||
4002 = {host = 'localhost', port = 5900, pw = 'doggy'}
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
api_port: str = str(client.ib.client.port)
|
|
||||||
conf: dict = client.conf
|
|
||||||
vnc_addrs: dict[int, tuple] = conf.get('vnc_addrs')
|
|
||||||
if not vnc_addrs:
|
|
||||||
return None
|
|
||||||
|
|
||||||
addr_entry: dict|tuple = vnc_addrs.get(
|
|
||||||
api_port,
|
|
||||||
('localhost', 5900) # a typical default
|
|
||||||
)
|
|
||||||
if pw is None:
|
|
||||||
match addr_entry:
|
|
||||||
case (
|
|
||||||
host,
|
|
||||||
port,
|
|
||||||
):
|
|
||||||
pass
|
|
||||||
|
|
||||||
case {
|
|
||||||
'host': host,
|
|
||||||
'port': port,
|
|
||||||
'pw': pw
|
|
||||||
}:
|
|
||||||
pass
|
|
||||||
|
|
||||||
case _:
|
|
||||||
raise ValueError(
|
|
||||||
f'Invalid `ib.vnc_addrs` entry ?\n'
|
|
||||||
f'{addr_entry!r}\n'
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
from pyvnc import (
|
import asyncvnc
|
||||||
AsyncVNCClient,
|
|
||||||
VNCConfig,
|
|
||||||
Point,
|
|
||||||
MOUSE_BUTTON_LEFT,
|
|
||||||
)
|
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
log.warning(
|
log.warning(
|
||||||
"In order to leverage `piker`'s built-in data reset hacks, install "
|
"In order to leverage `piker`'s built-in data reset hacks, install "
|
||||||
"the `pyvnc` project: https://github.com/regulad/pyvnc.git"
|
"the `asyncvnc` project: https://github.com/barneygale/asyncvnc"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -250,79 +174,24 @@ async def vnc_click_hack(
|
||||||
'connection': 'r'
|
'connection': 'r'
|
||||||
}[reset_type]
|
}[reset_type]
|
||||||
|
|
||||||
with tractor.devx.open_crash_handler():
|
async with asyncvnc.connect(
|
||||||
client = await AsyncVNCClient.connect(
|
host,
|
||||||
VNCConfig(
|
|
||||||
host=host,
|
|
||||||
port=port,
|
port=port,
|
||||||
password=pw,
|
|
||||||
)
|
# TODO: doesn't work see:
|
||||||
)
|
# https://github.com/barneygale/asyncvnc/issues/7
|
||||||
async with client:
|
# password='ibcansmbz',
|
||||||
|
|
||||||
|
) as client:
|
||||||
|
|
||||||
# move to middle of screen
|
# move to middle of screen
|
||||||
# 640x1800
|
# 640x1800
|
||||||
await client.move(
|
client.mouse.move(
|
||||||
Point(
|
x=500,
|
||||||
500,
|
y=500,
|
||||||
500,
|
|
||||||
)
|
)
|
||||||
)
|
client.mouse.click()
|
||||||
# ensure the ib-gw window is active
|
client.keyboard.press('Ctrl', 'Alt', key) # keys are stacked
|
||||||
await client.click(MOUSE_BUTTON_LEFT)
|
|
||||||
# send the hotkeys combo B)
|
|
||||||
await client.press('Ctrl', 'Alt', key) # keys are stacked
|
|
||||||
|
|
||||||
|
|
||||||
def i3ipc_fin_wins_titled(
|
|
||||||
titles: list[str] = [
|
|
||||||
'Interactive Brokers', # tws running in i3
|
|
||||||
'IB Gateway', # gw running in i3
|
|
||||||
# 'IB', # gw running in i3 (newer version?)
|
|
||||||
|
|
||||||
# !TODO, remote vnc instance
|
|
||||||
# -[ ] something in title (or other Con-props) that indicates
|
|
||||||
# this is explicitly for ibrk sw?
|
|
||||||
# |_[ ] !can use modden spawn eventually!
|
|
||||||
'TigerVNC',
|
|
||||||
# 'vncviewer', # the terminal..
|
|
||||||
],
|
|
||||||
) -> tuple[
|
|
||||||
i3ipc.Con, # orig focussed win
|
|
||||||
list[tuple[str, i3ipc.Con]], # matching wins by title
|
|
||||||
]:
|
|
||||||
'''
|
|
||||||
Attempt to find a local-DE window titled with an entry in
|
|
||||||
`titles`.
|
|
||||||
|
|
||||||
If found deliver the current focussed window and all matching
|
|
||||||
`i3ipc.Con`s in a list.
|
|
||||||
|
|
||||||
'''
|
|
||||||
import i3ipc
|
|
||||||
ipc = i3ipc.Connection()
|
|
||||||
|
|
||||||
# TODO: might be worth offering some kinda api for grabbing
|
|
||||||
# the window id from the pid?
|
|
||||||
# https://stackoverflow.com/a/2250879
|
|
||||||
tree = ipc.get_tree()
|
|
||||||
focussed: i3ipc.Con = tree.find_focused()
|
|
||||||
|
|
||||||
matches: list[i3ipc.Con] = []
|
|
||||||
for name in titles:
|
|
||||||
results = tree.find_titled(name)
|
|
||||||
print(f'results for {name}: {results}')
|
|
||||||
if results:
|
|
||||||
con = results[0]
|
|
||||||
matches.append((
|
|
||||||
name,
|
|
||||||
con,
|
|
||||||
))
|
|
||||||
|
|
||||||
return (
|
|
||||||
focussed,
|
|
||||||
matches,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def i3ipc_xdotool_manual_click_hack() -> None:
|
def i3ipc_xdotool_manual_click_hack() -> None:
|
||||||
|
|
@ -330,10 +199,29 @@ def i3ipc_xdotool_manual_click_hack() -> None:
|
||||||
Do the data reset hack but expecting a local X-window using `xdotool`.
|
Do the data reset hack but expecting a local X-window using `xdotool`.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
focussed, matches = i3ipc_fin_wins_titled()
|
import i3ipc
|
||||||
orig_win_id = focussed.window
|
i3 = i3ipc.Connection()
|
||||||
|
|
||||||
|
# TODO: might be worth offering some kinda api for grabbing
|
||||||
|
# the window id from the pid?
|
||||||
|
# https://stackoverflow.com/a/2250879
|
||||||
|
t = i3.get_tree()
|
||||||
|
|
||||||
|
orig_win_id = t.find_focused().window
|
||||||
|
|
||||||
|
# for tws
|
||||||
|
win_names: list[str] = [
|
||||||
|
'Interactive Brokers', # tws running in i3
|
||||||
|
'IB Gateway', # gw running in i3
|
||||||
|
# 'IB', # gw running in i3 (newer version?)
|
||||||
|
]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for name, con in matches:
|
for name in win_names:
|
||||||
|
results = t.find_titled(name)
|
||||||
|
print(f'results for {name}: {results}')
|
||||||
|
if results:
|
||||||
|
con = results[0]
|
||||||
print(f'Resetting data feed for {name}')
|
print(f'Resetting data feed for {name}')
|
||||||
win_id = str(con.window)
|
win_id = str(con.window)
|
||||||
w, h = con.rect.width, con.rect.height
|
w, h = con.rect.width, con.rect.height
|
||||||
|
|
@ -379,99 +267,3 @@ def i3ipc_xdotool_manual_click_hack() -> None:
|
||||||
])
|
])
|
||||||
except subprocess.TimeoutExpired:
|
except subprocess.TimeoutExpired:
|
||||||
log.exception('xdotool timed out?')
|
log.exception('xdotool timed out?')
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def is_current_time_in_range(
|
|
||||||
start_dt: datetime,
|
|
||||||
end_dt: datetime,
|
|
||||||
) -> bool:
|
|
||||||
'''
|
|
||||||
Check if current time is within the datetime range.
|
|
||||||
|
|
||||||
Use any/the-same timezone as provided by `start_dt.tzinfo` value
|
|
||||||
in the range.
|
|
||||||
|
|
||||||
'''
|
|
||||||
now: datetime = datetime.now(start_dt.tzinfo)
|
|
||||||
return start_dt <= now <= end_dt
|
|
||||||
|
|
||||||
|
|
||||||
# TODO, put this into `._util` and call it from here!
|
|
||||||
#
|
|
||||||
# NOTE, this was generated by @guille from a gpt5 prompt
|
|
||||||
# and was originally thot to be needed before learning about
|
|
||||||
# `ib_insync.contract.ContractDetails._parseSessions()` and
|
|
||||||
# it's downstream meths..
|
|
||||||
#
|
|
||||||
# This is still likely useful to keep for now to parse the
|
|
||||||
# `.tradingHours: str` value manually if we ever decide
|
|
||||||
# to move off `ib_async` and implement our own `trio`/`anyio`
|
|
||||||
# based version Bp
|
|
||||||
#
|
|
||||||
# >attempt to parse the retarted ib "time stampy thing" they
|
|
||||||
# >do for "venue hours" with this.. written by
|
|
||||||
# >gpt5-"thinking",
|
|
||||||
#
|
|
||||||
|
|
||||||
|
|
||||||
def parse_trading_hours(
|
|
||||||
spec: str,
|
|
||||||
tz: TzInfo|None = None
|
|
||||||
) -> dict[
|
|
||||||
date,
|
|
||||||
tuple[datetime, datetime]
|
|
||||||
]|None:
|
|
||||||
'''
|
|
||||||
Parse venue hours like:
|
|
||||||
'YYYYMMDD:HHMM-YYYYMMDD:HHMM;YYYYMMDD:CLOSED;...'
|
|
||||||
|
|
||||||
Returns `dict[date] = (open_dt, close_dt)` or `None` if
|
|
||||||
closed.
|
|
||||||
|
|
||||||
'''
|
|
||||||
if (
|
|
||||||
not isinstance(spec, str)
|
|
||||||
or
|
|
||||||
not spec
|
|
||||||
):
|
|
||||||
raise ValueError('spec must be a non-empty string')
|
|
||||||
|
|
||||||
out: dict[
|
|
||||||
date,
|
|
||||||
tuple[datetime, datetime]
|
|
||||||
]|None = {}
|
|
||||||
|
|
||||||
for part in (p.strip() for p in spec.split(';') if p.strip()):
|
|
||||||
if part.endswith(':CLOSED'):
|
|
||||||
day_s, _ = part.split(':', 1)
|
|
||||||
d = datetime.strptime(day_s, '%Y%m%d').date()
|
|
||||||
out[d] = None
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
|
||||||
start_s, end_s = part.split('-', 1)
|
|
||||||
start_dt = datetime.strptime(start_s, '%Y%m%d:%H%M')
|
|
||||||
end_dt = datetime.strptime(end_s, '%Y%m%d:%H%M')
|
|
||||||
except ValueError as exc:
|
|
||||||
raise ValueError(f'invalid segment: {part}') from exc
|
|
||||||
|
|
||||||
if tz is not None:
|
|
||||||
start_dt = start_dt.replace(tzinfo=tz)
|
|
||||||
end_dt = end_dt.replace(tzinfo=tz)
|
|
||||||
|
|
||||||
out[start_dt.date()] = (start_dt, end_dt)
|
|
||||||
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# ORIG desired usage,
|
|
||||||
#
|
|
||||||
# TODO, for non-drunk tomorrow,
|
|
||||||
# - call above fn and check that `output[today] is not None`
|
|
||||||
# trading_hrs: dict = parse_trading_hours(
|
|
||||||
# details.tradingHours
|
|
||||||
# )
|
|
||||||
# liq_hrs: dict = parse_trading_hours(
|
|
||||||
# details.liquidHours
|
|
||||||
# )
|
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,6 @@ from bidict import bidict
|
||||||
import trio
|
import trio
|
||||||
import tractor
|
import tractor
|
||||||
from tractor import to_asyncio
|
from tractor import to_asyncio
|
||||||
from tractor import trionics
|
|
||||||
from pendulum import (
|
from pendulum import (
|
||||||
from_timestamp,
|
from_timestamp,
|
||||||
DateTime,
|
DateTime,
|
||||||
|
|
@ -944,7 +943,6 @@ class Client:
|
||||||
)
|
)
|
||||||
if tkr:
|
if tkr:
|
||||||
break
|
break
|
||||||
|
|
||||||
except TimeoutError as err:
|
except TimeoutError as err:
|
||||||
timeouterr = err
|
timeouterr = err
|
||||||
await asyncio.sleep(0.01)
|
await asyncio.sleep(0.01)
|
||||||
|
|
@ -953,9 +951,7 @@ class Client:
|
||||||
else:
|
else:
|
||||||
if not warnset:
|
if not warnset:
|
||||||
log.warning(
|
log.warning(
|
||||||
f'Quote req timed out..\n'
|
f'Quote req timed out..maybe venue is closed?\n'
|
||||||
f'Maybe the venue is closed?\n'
|
|
||||||
f'\n'
|
|
||||||
f'{asdict(contract)}'
|
f'{asdict(contract)}'
|
||||||
)
|
)
|
||||||
warnset = True
|
warnset = True
|
||||||
|
|
@ -967,11 +963,9 @@ class Client:
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
if (
|
if timeouterr and raise_on_timeout:
|
||||||
timeouterr
|
import pdbp
|
||||||
and
|
pdbp.set_trace()
|
||||||
raise_on_timeout
|
|
||||||
):
|
|
||||||
raise timeouterr
|
raise timeouterr
|
||||||
|
|
||||||
if not warnset:
|
if not warnset:
|
||||||
|
|
@ -1256,12 +1250,6 @@ async def load_aio_clients(
|
||||||
|
|
||||||
for i in range(connect_retries):
|
for i in range(connect_retries):
|
||||||
try:
|
try:
|
||||||
log.info(
|
|
||||||
'Trying `ib_async` connect\n'
|
|
||||||
f'{host}: {port}\n'
|
|
||||||
f'clientId: {client_id}\n'
|
|
||||||
f'timeout: {connect_timeout}\n'
|
|
||||||
)
|
|
||||||
await ib.connectAsync(
|
await ib.connectAsync(
|
||||||
host,
|
host,
|
||||||
port,
|
port,
|
||||||
|
|
@ -1368,20 +1356,21 @@ async def load_aio_clients(
|
||||||
|
|
||||||
|
|
||||||
async def load_clients_for_trio(
|
async def load_clients_for_trio(
|
||||||
chan: tractor.to_asyncio.LinkedTaskChannel,
|
from_trio: asyncio.Queue,
|
||||||
|
to_trio: trio.abc.SendChannel,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
Pure async mngr proxy to ``load_aio_clients()``.
|
Pure async mngr proxy to ``load_aio_clients()``.
|
||||||
|
|
||||||
This is a bootstrap entrypoint to call from
|
This is a bootstrap entrypoing to call from
|
||||||
a `tractor.to_asyncio.open_channel_from()`.
|
a ``tractor.to_asyncio.open_channel_from()``.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
async with load_aio_clients(
|
async with load_aio_clients() as accts2clients:
|
||||||
disconnect_on_exit=False,
|
|
||||||
) as accts2clients:
|
to_trio.send_nowait(accts2clients)
|
||||||
|
|
||||||
chan.started_nowait(accts2clients)
|
|
||||||
# TODO: maybe a sync event to wait on instead?
|
# TODO: maybe a sync event to wait on instead?
|
||||||
await asyncio.sleep(float('inf'))
|
await asyncio.sleep(float('inf'))
|
||||||
|
|
||||||
|
|
@ -1394,10 +1383,7 @@ async def open_client_proxies() -> tuple[
|
||||||
async with (
|
async with (
|
||||||
tractor.trionics.maybe_open_context(
|
tractor.trionics.maybe_open_context(
|
||||||
acm_func=tractor.to_asyncio.open_channel_from,
|
acm_func=tractor.to_asyncio.open_channel_from,
|
||||||
kwargs={
|
kwargs={'target': load_clients_for_trio},
|
||||||
'target': load_clients_for_trio,
|
|
||||||
# ^XXX, kwarg to `open_channel_from()`
|
|
||||||
},
|
|
||||||
|
|
||||||
# lock around current actor task access
|
# lock around current actor task access
|
||||||
# TODO: maybe this should be the default in tractor?
|
# TODO: maybe this should be the default in tractor?
|
||||||
|
|
@ -1528,22 +1514,23 @@ class MethodProxy:
|
||||||
|
|
||||||
|
|
||||||
async def open_aio_client_method_relay(
|
async def open_aio_client_method_relay(
|
||||||
chan: tractor.to_asyncio.LinkedTaskChannel,
|
from_trio: asyncio.Queue,
|
||||||
|
to_trio: trio.abc.SendChannel,
|
||||||
client: Client,
|
client: Client,
|
||||||
event_consumers: dict[str, trio.Event],
|
event_consumers: dict[str, trio.Event],
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
# sync with `open_client_proxy()` caller
|
# sync with `open_client_proxy()` caller
|
||||||
chan.started_nowait(client)
|
to_trio.send_nowait(client)
|
||||||
|
|
||||||
# TODO: separate channel for error handling?
|
# TODO: separate channel for error handling?
|
||||||
client.inline_errors(chan)
|
client.inline_errors(to_trio)
|
||||||
|
|
||||||
# relay all method requests to ``asyncio``-side client and deliver
|
# relay all method requests to ``asyncio``-side client and deliver
|
||||||
# back results
|
# back results
|
||||||
while not chan._to_trio._closed: # <- TODO, better check like `._web_bs`?
|
while not to_trio._closed:
|
||||||
msg: tuple[str, dict]|dict|None = await chan.get()
|
msg: tuple[str, dict] | dict | None = await from_trio.get()
|
||||||
match msg:
|
match msg:
|
||||||
case None: # termination sentinel
|
case None: # termination sentinel
|
||||||
log.info('asyncio `Client` method-proxy SHUTDOWN!')
|
log.info('asyncio `Client` method-proxy SHUTDOWN!')
|
||||||
|
|
@ -1556,7 +1543,7 @@ async def open_aio_client_method_relay(
|
||||||
try:
|
try:
|
||||||
resp = await meth(**kwargs)
|
resp = await meth(**kwargs)
|
||||||
# echo the msg back
|
# echo the msg back
|
||||||
chan.send_nowait({'result': resp})
|
to_trio.send_nowait({'result': resp})
|
||||||
|
|
||||||
except (
|
except (
|
||||||
RequestError,
|
RequestError,
|
||||||
|
|
@ -1564,10 +1551,10 @@ async def open_aio_client_method_relay(
|
||||||
# TODO: relay all errors to trio?
|
# TODO: relay all errors to trio?
|
||||||
# BaseException,
|
# BaseException,
|
||||||
) as err:
|
) as err:
|
||||||
chan.send_nowait({'exception': err})
|
to_trio.send_nowait({'exception': err})
|
||||||
|
|
||||||
case {'error': content}:
|
case {'error': content}:
|
||||||
chan.send_nowait({'exception': content})
|
to_trio.send_nowait({'exception': content})
|
||||||
|
|
||||||
case _:
|
case _:
|
||||||
raise ValueError(f'Unhandled msg {msg}')
|
raise ValueError(f'Unhandled msg {msg}')
|
||||||
|
|
@ -1589,8 +1576,7 @@ async def open_client_proxy(
|
||||||
event_consumers=event_table,
|
event_consumers=event_table,
|
||||||
) as (first, chan),
|
) as (first, chan),
|
||||||
|
|
||||||
trionics.collapse_eg(), # loose-ify
|
trio.open_nursery() as relay_n,
|
||||||
trio.open_nursery() as relay_tn,
|
|
||||||
):
|
):
|
||||||
|
|
||||||
assert isinstance(first, Client)
|
assert isinstance(first, Client)
|
||||||
|
|
@ -1630,7 +1616,7 @@ async def open_client_proxy(
|
||||||
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
relay_tn.start_soon(relay_events)
|
relay_n.start_soon(relay_events)
|
||||||
|
|
||||||
yield proxy
|
yield proxy
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -34,7 +34,6 @@ import trio
|
||||||
from trio_typing import TaskStatus
|
from trio_typing import TaskStatus
|
||||||
import tractor
|
import tractor
|
||||||
from tractor.to_asyncio import LinkedTaskChannel
|
from tractor.to_asyncio import LinkedTaskChannel
|
||||||
from tractor import trionics
|
|
||||||
from ib_insync.contract import (
|
from ib_insync.contract import (
|
||||||
Contract,
|
Contract,
|
||||||
)
|
)
|
||||||
|
|
@ -117,11 +116,7 @@ def pack_position(
|
||||||
symbol=fqme,
|
symbol=fqme,
|
||||||
currency=con.currency,
|
currency=con.currency,
|
||||||
size=float(pos.position),
|
size=float(pos.position),
|
||||||
avg_price=(
|
avg_price=float(pos.avgCost) / float(con.multiplier or 1.0),
|
||||||
float(pos.avgCost)
|
|
||||||
/
|
|
||||||
float(con.multiplier or 1.0)
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -362,10 +357,6 @@ async def update_and_audit_pos_msg(
|
||||||
size=ibpos.position,
|
size=ibpos.position,
|
||||||
|
|
||||||
avg_price=pikerpos.ppu,
|
avg_price=pikerpos.ppu,
|
||||||
|
|
||||||
# XXX ensures matching even if multiple venue-names
|
|
||||||
# in `.bs_fqme`, likely from txn records..
|
|
||||||
bs_mktid=mkt.bs_mktid,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
ibfmtmsg: str = pformat(ibpos._asdict())
|
ibfmtmsg: str = pformat(ibpos._asdict())
|
||||||
|
|
@ -416,7 +407,7 @@ async def update_and_audit_pos_msg(
|
||||||
|
|
||||||
# TODO: make this a "propaganda" log level?
|
# TODO: make this a "propaganda" log level?
|
||||||
if ibpos.avgCost != msg.avg_price:
|
if ibpos.avgCost != msg.avg_price:
|
||||||
log.debug(
|
log.warning(
|
||||||
f'IB "FIFO" avg price for {msg.symbol} is DIFF:\n'
|
f'IB "FIFO" avg price for {msg.symbol} is DIFF:\n'
|
||||||
f'ib: {ibfmtmsg}\n'
|
f'ib: {ibfmtmsg}\n'
|
||||||
'---------------------------\n'
|
'---------------------------\n'
|
||||||
|
|
@ -434,8 +425,7 @@ async def aggr_open_orders(
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
Collect all open orders from client and fill in `order_msgs:
|
Collect all open orders from client and fill in `order_msgs: list`.
|
||||||
list`.
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
trades: list[Trade] = client.ib.openTrades()
|
trades: list[Trade] = client.ib.openTrades()
|
||||||
|
|
@ -556,10 +546,7 @@ async def open_trade_dialog(
|
||||||
),
|
),
|
||||||
|
|
||||||
# TODO: do this as part of `open_account()`!?
|
# TODO: do this as part of `open_account()`!?
|
||||||
open_symcache(
|
open_symcache('ib', only_from_memcache=True) as symcache,
|
||||||
'ib',
|
|
||||||
only_from_memcache=True,
|
|
||||||
) as symcache,
|
|
||||||
):
|
):
|
||||||
# Open a trade ledgers stack for appending trade records over
|
# Open a trade ledgers stack for appending trade records over
|
||||||
# multiple accounts.
|
# multiple accounts.
|
||||||
|
|
@ -567,10 +554,8 @@ async def open_trade_dialog(
|
||||||
ledgers: dict[str, TransactionLedger] = {}
|
ledgers: dict[str, TransactionLedger] = {}
|
||||||
tables: dict[str, Account] = {}
|
tables: dict[str, Account] = {}
|
||||||
order_msgs: list[Status] = []
|
order_msgs: list[Status] = []
|
||||||
conf: dict = get_config()
|
conf = get_config()
|
||||||
accounts_def_inv: bidict[str, str] = bidict(
|
accounts_def_inv: bidict[str, str] = bidict(conf['accounts']).inverse
|
||||||
conf['accounts']
|
|
||||||
).inverse
|
|
||||||
|
|
||||||
with (
|
with (
|
||||||
ExitStack() as lstack,
|
ExitStack() as lstack,
|
||||||
|
|
@ -720,11 +705,7 @@ async def open_trade_dialog(
|
||||||
# client-account and build out position msgs to deliver to
|
# client-account and build out position msgs to deliver to
|
||||||
# EMS.
|
# EMS.
|
||||||
for acctid, acnt in tables.items():
|
for acctid, acnt in tables.items():
|
||||||
active_pps: dict[str, Position]
|
active_pps, closed_pps = acnt.dump_active()
|
||||||
(
|
|
||||||
active_pps,
|
|
||||||
closed_pps,
|
|
||||||
) = acnt.dump_active()
|
|
||||||
|
|
||||||
for pps in [active_pps, closed_pps]:
|
for pps in [active_pps, closed_pps]:
|
||||||
piker_pps: list[Position] = list(pps.values())
|
piker_pps: list[Position] = list(pps.values())
|
||||||
|
|
@ -740,7 +721,6 @@ async def open_trade_dialog(
|
||||||
)
|
)
|
||||||
if ibpos:
|
if ibpos:
|
||||||
bs_mktid: str = str(ibpos.contract.conId)
|
bs_mktid: str = str(ibpos.contract.conId)
|
||||||
|
|
||||||
msg = await update_and_audit_pos_msg(
|
msg = await update_and_audit_pos_msg(
|
||||||
acctid,
|
acctid,
|
||||||
pikerpos,
|
pikerpos,
|
||||||
|
|
@ -758,7 +738,7 @@ async def open_trade_dialog(
|
||||||
f'UNEXPECTED POSITION says IB => {msg.symbol}\n'
|
f'UNEXPECTED POSITION says IB => {msg.symbol}\n'
|
||||||
'Maybe they LIQUIDATED YOU or your ledger is wrong?\n'
|
'Maybe they LIQUIDATED YOU or your ledger is wrong?\n'
|
||||||
)
|
)
|
||||||
log.debug(logmsg)
|
log.error(logmsg)
|
||||||
|
|
||||||
await ctx.started((
|
await ctx.started((
|
||||||
all_positions,
|
all_positions,
|
||||||
|
|
@ -767,22 +747,21 @@ async def open_trade_dialog(
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
ctx.open_stream() as ems_stream,
|
ctx.open_stream() as ems_stream,
|
||||||
trionics.collapse_eg(),
|
trio.open_nursery() as n,
|
||||||
trio.open_nursery() as tn,
|
|
||||||
):
|
):
|
||||||
# relay existing open orders to ems
|
# relay existing open orders to ems
|
||||||
for msg in order_msgs:
|
for msg in order_msgs:
|
||||||
await ems_stream.send(msg)
|
await ems_stream.send(msg)
|
||||||
|
|
||||||
for client in set(aioclients.values()):
|
for client in set(aioclients.values()):
|
||||||
trade_event_stream: LinkedTaskChannel = await tn.start(
|
trade_event_stream: LinkedTaskChannel = await n.start(
|
||||||
open_trade_event_stream,
|
open_trade_event_stream,
|
||||||
client,
|
client,
|
||||||
)
|
)
|
||||||
|
|
||||||
# start order request handler **before** local trades
|
# start order request handler **before** local trades
|
||||||
# event loop
|
# event loop
|
||||||
tn.start_soon(
|
n.start_soon(
|
||||||
handle_order_requests,
|
handle_order_requests,
|
||||||
ems_stream,
|
ems_stream,
|
||||||
accounts_def,
|
accounts_def,
|
||||||
|
|
@ -790,7 +769,7 @@ async def open_trade_dialog(
|
||||||
)
|
)
|
||||||
|
|
||||||
# allocate event relay tasks for each client connection
|
# allocate event relay tasks for each client connection
|
||||||
tn.start_soon(
|
n.start_soon(
|
||||||
deliver_trade_events,
|
deliver_trade_events,
|
||||||
|
|
||||||
trade_event_stream,
|
trade_event_stream,
|
||||||
|
|
@ -1262,47 +1241,32 @@ async def deliver_trade_events(
|
||||||
# never relay errors for non-broker related issues
|
# never relay errors for non-broker related issues
|
||||||
# https://interactivebrokers.github.io/tws-api/message_codes.html
|
# https://interactivebrokers.github.io/tws-api/message_codes.html
|
||||||
code: int = err['error_code']
|
code: int = err['error_code']
|
||||||
reason: str = err['reason']
|
if code in {
|
||||||
reqid: str = str(err['reqid'])
|
200, # uhh
|
||||||
|
|
||||||
# "Warning:" msg codes,
|
|
||||||
# https://interactivebrokers.github.io/tws-api/message_codes.html#warning_codes
|
|
||||||
# - 2109: 'Outside Regular Trading Hours'
|
|
||||||
if 'Warning:' in reason:
|
|
||||||
log.warning(
|
|
||||||
f'Order-API-warning: {code!r}\n'
|
|
||||||
f'reqid: {reqid!r}\n'
|
|
||||||
f'\n'
|
|
||||||
f'{pformat(err)}\n'
|
|
||||||
# ^TODO? should we just print the `reason`
|
|
||||||
# not the full `err`-dict?
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
# XXX known special (ignore) cases
|
|
||||||
elif code in {
|
|
||||||
200, # uhh.. ni idea
|
|
||||||
|
|
||||||
# hist pacing / connectivity
|
# hist pacing / connectivity
|
||||||
162,
|
162,
|
||||||
165,
|
165,
|
||||||
|
|
||||||
|
# WARNING codes:
|
||||||
|
# https://interactivebrokers.github.io/tws-api/message_codes.html#warning_codes
|
||||||
|
# Attribute 'Outside Regular Trading Hours' is
|
||||||
|
# " 'ignored based on the order type and
|
||||||
|
# destination. PlaceOrder is now ' 'being
|
||||||
|
# processed.',
|
||||||
|
2109,
|
||||||
|
|
||||||
# XXX: lol this isn't even documented..
|
# XXX: lol this isn't even documented..
|
||||||
# 'No market data during competing live session'
|
# 'No market data during competing live session'
|
||||||
1669,
|
1669,
|
||||||
}:
|
}:
|
||||||
log.error(
|
|
||||||
f'Order-API-error which is non-cancel-causing ?!\n'
|
|
||||||
f'\n'
|
|
||||||
f'{pformat(err)}\n'
|
|
||||||
)
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
reqid: str = str(err['reqid'])
|
||||||
|
reason: str = err['reason']
|
||||||
|
|
||||||
if err['reqid'] == -1:
|
if err['reqid'] == -1:
|
||||||
log.error(
|
log.error(f'TWS external order error:\n{pformat(err)}')
|
||||||
f'TWS external order error ??\n'
|
|
||||||
f'{pformat(err)}\n'
|
|
||||||
)
|
|
||||||
|
|
||||||
flow: dict = dict(
|
flow: dict = dict(
|
||||||
flows.get(reqid)
|
flows.get(reqid)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
# piker: trading gear for hackers
|
# piker: trading gear for hackers
|
||||||
# Copyright (C) 2018-forever Tyler Goodlet (in stewardship for pikers)
|
# Copyright (C) Tyler Goodlet (in stewardship for pikers)
|
||||||
|
|
||||||
# This program is free software: you can redistribute it and/or modify
|
# This program is free software: you can redistribute it and/or modify
|
||||||
# it under the terms of the GNU Affero General Public License as published by
|
# it under the terms of the GNU Affero General Public License as published by
|
||||||
|
|
@ -13,12 +13,10 @@
|
||||||
|
|
||||||
# You should have received a copy of the GNU Affero General Public License
|
# You should have received a copy of the GNU Affero General Public License
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
Data feed endpoints pre-wrapped and ready for use with ``tractor``/``trio``.
|
||||||
|
|
||||||
'''
|
"""
|
||||||
Data feed endpoints pre-wrapped and ready for use with `tractor`/`trio`
|
|
||||||
via "infected-asyncio-mode".
|
|
||||||
|
|
||||||
'''
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import asyncio
|
import asyncio
|
||||||
from contextlib import (
|
from contextlib import (
|
||||||
|
|
@ -28,6 +26,7 @@ from dataclasses import asdict
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from pprint import pformat
|
from pprint import pformat
|
||||||
|
from math import isnan
|
||||||
import time
|
import time
|
||||||
from typing import (
|
from typing import (
|
||||||
Any,
|
Any,
|
||||||
|
|
@ -41,6 +40,7 @@ import numpy as np
|
||||||
from pendulum import (
|
from pendulum import (
|
||||||
now,
|
now,
|
||||||
from_timestamp,
|
from_timestamp,
|
||||||
|
# DateTime,
|
||||||
Duration,
|
Duration,
|
||||||
duration as mk_duration,
|
duration as mk_duration,
|
||||||
)
|
)
|
||||||
|
|
@ -69,10 +69,7 @@ from .api import (
|
||||||
Contract,
|
Contract,
|
||||||
RequestError,
|
RequestError,
|
||||||
)
|
)
|
||||||
from ._util import (
|
from ._util import data_reset_hack
|
||||||
data_reset_hack,
|
|
||||||
is_current_time_in_range,
|
|
||||||
)
|
|
||||||
from .symbols import get_mkt_info
|
from .symbols import get_mkt_info
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
|
@ -187,8 +184,7 @@ async def open_history_client(
|
||||||
|
|
||||||
if (
|
if (
|
||||||
start_dt
|
start_dt
|
||||||
and
|
and start_dt.timestamp() == 0
|
||||||
start_dt.timestamp() == 0
|
|
||||||
):
|
):
|
||||||
await tractor.pause()
|
await tractor.pause()
|
||||||
|
|
||||||
|
|
@ -207,16 +203,14 @@ async def open_history_client(
|
||||||
):
|
):
|
||||||
count += 1
|
count += 1
|
||||||
mean += latency / count
|
mean += latency / count
|
||||||
log.debug(
|
print(
|
||||||
f'HISTORY FRAME QUERY LATENCY: {latency}\n'
|
f'HISTORY FRAME QUERY LATENCY: {latency}\n'
|
||||||
f'mean: {mean}'
|
f'mean: {mean}'
|
||||||
)
|
)
|
||||||
|
|
||||||
# could be trying to retreive bars over weekend
|
# could be trying to retreive bars over weekend
|
||||||
if out is None:
|
if out is None:
|
||||||
log.error(
|
log.error(f"Can't grab bars starting at {end_dt}!?!?")
|
||||||
f"No bars starting at {end_dt!r} !?!?"
|
|
||||||
)
|
|
||||||
if (
|
if (
|
||||||
end_dt
|
end_dt
|
||||||
and head_dt
|
and head_dt
|
||||||
|
|
@ -291,9 +285,8 @@ _pacing: str = (
|
||||||
|
|
||||||
async def wait_on_data_reset(
|
async def wait_on_data_reset(
|
||||||
proxy: MethodProxy,
|
proxy: MethodProxy,
|
||||||
|
|
||||||
reset_type: str = 'data',
|
reset_type: str = 'data',
|
||||||
timeout: float = 16,
|
timeout: float = 16, # float('inf'),
|
||||||
|
|
||||||
task_status: TaskStatus[
|
task_status: TaskStatus[
|
||||||
tuple[
|
tuple[
|
||||||
|
|
@ -302,47 +295,29 @@ async def wait_on_data_reset(
|
||||||
]
|
]
|
||||||
] = trio.TASK_STATUS_IGNORED,
|
] = trio.TASK_STATUS_IGNORED,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
'''
|
|
||||||
Wait on a (global-ish) "data-farm" event to be emitted
|
|
||||||
by the IB api server.
|
|
||||||
|
|
||||||
Allows syncing to reconnect event-messages emitted on the API
|
# TODO: we might have to put a task lock around this
|
||||||
console, such as:
|
# method..
|
||||||
|
hist_ev = proxy.status_event(
|
||||||
- 'HMDS data farm connection is OK:ushmds'
|
|
||||||
- 'Market data farm is connecting:usfuture'
|
|
||||||
- 'Market data farm connection is OK:usfuture'
|
|
||||||
|
|
||||||
Deliver a `(cs, done: Event)` pair to the caller to support it
|
|
||||||
waiting or cancelling the associated "data-reset-request";
|
|
||||||
normally a manual data-reset-req is expected to be the cause and
|
|
||||||
thus trigger such events (such as our click-hack-magic from
|
|
||||||
`.ib._util`).
|
|
||||||
|
|
||||||
'''
|
|
||||||
# ?TODO, do we need a task-lock around this method?
|
|
||||||
#
|
|
||||||
# register for an API "status event" wrapped for `trio`-sync.
|
|
||||||
hist_ev: trio.Event = proxy.status_event(
|
|
||||||
'HMDS data farm connection is OK:ushmds'
|
'HMDS data farm connection is OK:ushmds'
|
||||||
)
|
)
|
||||||
#
|
|
||||||
# ^TODO: other event-messages we might want to support waiting-for
|
# TODO: other event messages we might want to try and
|
||||||
# but i wasn't able to get reliable..
|
# wait for but i wasn't able to get any of this
|
||||||
#
|
# reliable..
|
||||||
# reconnect_start = proxy.status_event(
|
# reconnect_start = proxy.status_event(
|
||||||
# 'Market data farm is connecting:usfuture'
|
# 'Market data farm is connecting:usfuture'
|
||||||
# )
|
# )
|
||||||
# live_ev = proxy.status_event(
|
# live_ev = proxy.status_event(
|
||||||
# 'Market data farm connection is OK:usfuture'
|
# 'Market data farm connection is OK:usfuture'
|
||||||
# )
|
# )
|
||||||
|
|
||||||
# try to wait on the reset event(s) to arrive, a timeout
|
# try to wait on the reset event(s) to arrive, a timeout
|
||||||
# will trigger a retry up to 6 times (for now).
|
# will trigger a retry up to 6 times (for now).
|
||||||
client: Client = proxy._aio_ns
|
client: Client = proxy._aio_ns
|
||||||
|
|
||||||
done = trio.Event()
|
done = trio.Event()
|
||||||
with trio.move_on_after(timeout) as cs:
|
with trio.move_on_after(timeout) as cs:
|
||||||
|
|
||||||
task_status.started((cs, done))
|
task_status.started((cs, done))
|
||||||
|
|
||||||
log.warning(
|
log.warning(
|
||||||
|
|
@ -421,9 +396,8 @@ async def get_bars(
|
||||||
bool, # timed out hint
|
bool, # timed out hint
|
||||||
]:
|
]:
|
||||||
'''
|
'''
|
||||||
Request-n-retrieve historical data frames from a `trio.Task`
|
Retrieve historical data from a ``trio``-side task using
|
||||||
using a `MethoProxy` to query the `asyncio`-side's
|
a ``MethoProxy``.
|
||||||
`.ib.api.Client` methods.
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
global _data_resetter_task, _failed_resets
|
global _data_resetter_task, _failed_resets
|
||||||
|
|
@ -613,7 +587,7 @@ async def get_bars(
|
||||||
data_cs.cancel()
|
data_cs.cancel()
|
||||||
|
|
||||||
# spawn new data reset task
|
# spawn new data reset task
|
||||||
data_cs, reset_done = await tn.start(
|
data_cs, reset_done = await nurse.start(
|
||||||
partial(
|
partial(
|
||||||
wait_on_data_reset,
|
wait_on_data_reset,
|
||||||
proxy,
|
proxy,
|
||||||
|
|
@ -633,14 +607,11 @@ async def get_bars(
|
||||||
# such that simultaneous symbol queries don't try data resettingn
|
# such that simultaneous symbol queries don't try data resettingn
|
||||||
# too fast..
|
# too fast..
|
||||||
unset_resetter: bool = False
|
unset_resetter: bool = False
|
||||||
async with (
|
async with trio.open_nursery() as nurse:
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn
|
|
||||||
):
|
|
||||||
|
|
||||||
# start history request that we allow
|
# start history request that we allow
|
||||||
# to run indefinitely until a result is acquired
|
# to run indefinitely until a result is acquired
|
||||||
tn.start_soon(query)
|
nurse.start_soon(query)
|
||||||
|
|
||||||
# start history reset loop which waits up to the timeout
|
# start history reset loop which waits up to the timeout
|
||||||
# for a result before triggering a data feed reset.
|
# for a result before triggering a data feed reset.
|
||||||
|
|
@ -660,7 +631,7 @@ async def get_bars(
|
||||||
unset_resetter: bool = True
|
unset_resetter: bool = True
|
||||||
|
|
||||||
# spawn new data reset task
|
# spawn new data reset task
|
||||||
data_cs, reset_done = await tn.start(
|
data_cs, reset_done = await nurse.start(
|
||||||
partial(
|
partial(
|
||||||
wait_on_data_reset,
|
wait_on_data_reset,
|
||||||
proxy,
|
proxy,
|
||||||
|
|
@ -682,12 +653,14 @@ async def get_bars(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# per-actor cache of inter-eventloop-chans
|
|
||||||
_quote_streams: dict[str, trio.abc.ReceiveStream] = {}
|
_quote_streams: dict[str, trio.abc.ReceiveStream] = {}
|
||||||
|
|
||||||
|
|
||||||
async def _setup_quote_stream(
|
async def _setup_quote_stream(
|
||||||
chan: tractor.to_asyncio.LinkedTaskChannel,
|
|
||||||
|
from_trio: asyncio.Queue,
|
||||||
|
to_trio: trio.abc.SendChannel,
|
||||||
|
|
||||||
symbol: str,
|
symbol: str,
|
||||||
opts: tuple[int] = (
|
opts: tuple[int] = (
|
||||||
'375', # RT trade volume (excludes utrades)
|
'375', # RT trade volume (excludes utrades)
|
||||||
|
|
@ -705,13 +678,10 @@ async def _setup_quote_stream(
|
||||||
|
|
||||||
) -> trio.abc.ReceiveChannel:
|
) -> trio.abc.ReceiveChannel:
|
||||||
'''
|
'''
|
||||||
Stream L1 quotes via the `Ticker.updateEvent.connect(push)`
|
Stream a ticker using the std L1 api.
|
||||||
callback API by registering a `push` callback which simply
|
|
||||||
`chan.send_nowait()`s quote msgs back to the calling
|
|
||||||
parent-`trio.Task`-side.
|
|
||||||
|
|
||||||
NOTE, that this task-fn is run on the `asyncio.Task`-side ONLY
|
This task is ``asyncio``-side and must be called from
|
||||||
and is thus run via `tractor.to_asyncio.open_channel_from()`.
|
``tractor.to_asyncio.open_channel_from()``.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
global _quote_streams
|
global _quote_streams
|
||||||
|
|
@ -719,79 +689,37 @@ async def _setup_quote_stream(
|
||||||
async with load_aio_clients(
|
async with load_aio_clients(
|
||||||
disconnect_on_exit=False,
|
disconnect_on_exit=False,
|
||||||
) as accts2clients:
|
) as accts2clients:
|
||||||
|
|
||||||
# XXX since this is an `asyncio.Task`, we must use
|
|
||||||
# tractor.pause_from_sync()
|
|
||||||
|
|
||||||
caccount_name, client = get_preferred_data_client(accts2clients)
|
caccount_name, client = get_preferred_data_client(accts2clients)
|
||||||
contract = (
|
contract = contract or (await client.find_contract(symbol))
|
||||||
contract
|
to_trio.send_nowait(contract) # cuz why not
|
||||||
or
|
ticker: Ticker = client.ib.reqMktData(contract, ','.join(opts))
|
||||||
(await client.find_contract(symbol))
|
|
||||||
)
|
|
||||||
chan.started_nowait(contract) # cuz why not
|
|
||||||
ticker: Ticker = client.ib.reqMktData(
|
|
||||||
contract,
|
|
||||||
','.join(opts),
|
|
||||||
)
|
|
||||||
maybe_exc: BaseException|None = None
|
|
||||||
handler_tries: int = 0
|
|
||||||
aio_task: asyncio.Task = asyncio.current_task()
|
|
||||||
|
|
||||||
# ?TODO? this API is batch-wise and quite slow-af but,
|
# NOTE: it's batch-wise and slow af but I guess could
|
||||||
# - seems to be 5s updates?
|
# be good for backchecking? Seems to be every 5s maybe?
|
||||||
# - maybe we could use it for backchecking?
|
|
||||||
#
|
|
||||||
# ticker: Ticker = client.ib.reqTickByTickData(
|
# ticker: Ticker = client.ib.reqTickByTickData(
|
||||||
# contract, 'Last',
|
# contract, 'Last',
|
||||||
# )
|
# )
|
||||||
|
|
||||||
# define a very naive queue-pushing callback that relays
|
# # define a simple queue push routine that streams quote packets
|
||||||
# quote-packets directly the calling (parent) `trio.Task`.
|
# # to trio over the ``to_trio`` memory channel.
|
||||||
# Ensure on teardown we cancel the feed via their cancel API.
|
# to_trio, from_aio = trio.open_memory_channel(2**8) # type: ignore
|
||||||
#
|
|
||||||
def teardown():
|
def teardown():
|
||||||
'''
|
|
||||||
Disconnect our `push`-er callback and cancel the data-feed
|
|
||||||
for `contract`.
|
|
||||||
|
|
||||||
'''
|
|
||||||
nonlocal maybe_exc
|
|
||||||
ticker.updateEvent.disconnect(push)
|
ticker.updateEvent.disconnect(push)
|
||||||
report: str = f'Disconnected mkt-data for {symbol!r} due to '
|
log.error(f"Disconnected stream for `{symbol}`")
|
||||||
if maybe_exc is not None:
|
|
||||||
report += (
|
|
||||||
'error,\n'
|
|
||||||
f'{maybe_exc!r}\n'
|
|
||||||
)
|
|
||||||
log.error(report)
|
|
||||||
else:
|
|
||||||
report += (
|
|
||||||
'cancellation.\n'
|
|
||||||
)
|
|
||||||
log.cancel(report)
|
|
||||||
|
|
||||||
client.ib.cancelMktData(contract)
|
client.ib.cancelMktData(contract)
|
||||||
|
|
||||||
# decouple broadcast mem chan
|
# decouple broadcast mem chan
|
||||||
_quote_streams.pop(symbol, None)
|
_quote_streams.pop(symbol, None)
|
||||||
|
|
||||||
def push(
|
def push(t: Ticker) -> None:
|
||||||
t: Ticker,
|
"""
|
||||||
tries_before_raise: int = 6,
|
Push quotes to trio task.
|
||||||
) -> None:
|
|
||||||
'''
|
|
||||||
Push quotes verbatim to parent-side `trio.Task`.
|
|
||||||
|
|
||||||
'''
|
"""
|
||||||
nonlocal maybe_exc, handler_tries
|
# log.debug(t)
|
||||||
# log.debug(f'new IB quote: {t}\n')
|
|
||||||
try:
|
try:
|
||||||
chan.send_nowait(t)
|
to_trio.send_nowait(t)
|
||||||
|
|
||||||
# XXX TODO XXX replicate in `tractor` tests
|
|
||||||
# as per `CancelledError`-handler notes below!
|
|
||||||
# assert 0
|
|
||||||
except (
|
except (
|
||||||
trio.BrokenResourceError,
|
trio.BrokenResourceError,
|
||||||
|
|
||||||
|
|
@ -806,107 +734,35 @@ async def _setup_quote_stream(
|
||||||
# resulting in tracebacks spammed to console..
|
# resulting in tracebacks spammed to console..
|
||||||
# Manually do the dereg ourselves.
|
# Manually do the dereg ourselves.
|
||||||
teardown()
|
teardown()
|
||||||
|
|
||||||
# for slow debugging purposes to avoid clobbering prompt
|
|
||||||
# with log msgs
|
|
||||||
except trio.WouldBlock:
|
except trio.WouldBlock:
|
||||||
log.exception(
|
# log.warning(
|
||||||
f'Asyncio->Trio `chan.send_nowait()` blocked !?\n'
|
# f'channel is blocking symbol feed for {symbol}?'
|
||||||
f'\n'
|
# f'\n{to_trio.statistics}'
|
||||||
f'{chan._to_trio.statistics()}\n'
|
# )
|
||||||
)
|
pass
|
||||||
|
|
||||||
# ?TODO, handle re-connection attempts?
|
|
||||||
except BaseException as _berr:
|
|
||||||
berr = _berr
|
|
||||||
if handler_tries >= tries_before_raise:
|
|
||||||
# breakpoint()
|
|
||||||
maybe_exc = _berr
|
|
||||||
# task.set_exception(berr)
|
|
||||||
aio_task.cancel(msg=berr.args)
|
|
||||||
raise berr
|
|
||||||
else:
|
|
||||||
handler_tries += 1
|
|
||||||
|
|
||||||
log.exception(
|
|
||||||
f'Failed to push ticker quote !?\n'
|
|
||||||
f'handler_tries={handler_tries!r}\n'
|
|
||||||
f'ticker: {t!r}\n'
|
|
||||||
f'\n'
|
|
||||||
f'{chan._to_trio.statistics()}\n'
|
|
||||||
f'\n'
|
|
||||||
f'CAUSE: {berr}\n'
|
|
||||||
)
|
|
||||||
|
|
||||||
|
# except trio.WouldBlock:
|
||||||
|
# # for slow debugging purposes to avoid clobbering prompt
|
||||||
|
# # with log msgs
|
||||||
|
# pass
|
||||||
|
|
||||||
ticker.updateEvent.connect(push)
|
ticker.updateEvent.connect(push)
|
||||||
try:
|
try:
|
||||||
await asyncio.sleep(float('inf'))
|
await asyncio.sleep(float('inf'))
|
||||||
|
|
||||||
# XXX, for debug.. TODO? can we rm again?
|
|
||||||
#
|
|
||||||
# tractor.pause_from_sync()
|
|
||||||
# while True:
|
|
||||||
# await asyncio.sleep(1.6)
|
|
||||||
# if ticker.ticks:
|
|
||||||
# log.debug(
|
|
||||||
# f'ticker.ticks = \n'
|
|
||||||
# f'{ticker.ticks}\n'
|
|
||||||
# )
|
|
||||||
# else:
|
|
||||||
# log.warning(
|
|
||||||
# 'UHH no ticker.ticks ??'
|
|
||||||
# )
|
|
||||||
|
|
||||||
# XXX TODO XXX !?!?
|
|
||||||
# apparently **without this handler** and the subsequent
|
|
||||||
# re-raising of `maybe_exc from _taskc` cancelling the
|
|
||||||
# `aio_task` from the `push()`-callback will cause a very
|
|
||||||
# strange chain of exc raising that breaks alll sorts of
|
|
||||||
# downstream callers, tasks and remote-actor tasks!?
|
|
||||||
#
|
|
||||||
# -[ ] we need some lowlevel reproducting tests to replicate
|
|
||||||
# those worst-case scenarios in `tractor` core!!
|
|
||||||
# -[ ] likely we should factor-out the `tractor.to_asyncio`
|
|
||||||
# attempts at workarounds in `.translate_aio_errors()`
|
|
||||||
# for failed `asyncio.Task.set_exception()` to either
|
|
||||||
# call `aio_task.cancel()` and/or
|
|
||||||
# `aio_task._fut_waiter.set_exception()` to a re-useable
|
|
||||||
# toolset in something like a `.to_asyncio._utils`??
|
|
||||||
#
|
|
||||||
except asyncio.CancelledError as _taskc:
|
|
||||||
if maybe_exc is not None:
|
|
||||||
raise maybe_exc from _taskc
|
|
||||||
|
|
||||||
raise _taskc
|
|
||||||
|
|
||||||
except BaseException as _berr:
|
|
||||||
# stash any crash cause for reporting in `teardown()`
|
|
||||||
maybe_exc = _berr
|
|
||||||
raise _berr
|
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
# always disconnect our `push()` and cancel the
|
|
||||||
# ib-"mkt-data-feed".
|
|
||||||
teardown()
|
teardown()
|
||||||
|
|
||||||
|
# return from_aio
|
||||||
|
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def open_aio_quote_stream(
|
async def open_aio_quote_stream(
|
||||||
|
|
||||||
symbol: str,
|
symbol: str,
|
||||||
contract: Contract | None = None,
|
contract: Contract | None = None,
|
||||||
|
|
||||||
) -> (
|
) -> trio.abc.ReceiveStream:
|
||||||
trio.abc.Channel| # iface
|
|
||||||
tractor.to_asyncio.LinkedTaskChannel # actually
|
|
||||||
):
|
|
||||||
'''
|
|
||||||
Open a real-time `Ticker` quote stream from an `asyncio.Task`
|
|
||||||
spawned via `tractor.to_asyncio.open_channel_from()`, deliver the
|
|
||||||
inter-event-loop channel to the `trio.Task` caller and cache it
|
|
||||||
globally for re-use.
|
|
||||||
|
|
||||||
'''
|
|
||||||
from tractor.trionics import broadcast_receiver
|
from tractor.trionics import broadcast_receiver
|
||||||
global _quote_streams
|
global _quote_streams
|
||||||
|
|
||||||
|
|
@ -922,7 +778,6 @@ async def open_aio_quote_stream(
|
||||||
yield from_aio
|
yield from_aio
|
||||||
return
|
return
|
||||||
|
|
||||||
from_aio: tractor.to_asyncio.LinkedTaskChannel
|
|
||||||
async with tractor.to_asyncio.open_channel_from(
|
async with tractor.to_asyncio.open_channel_from(
|
||||||
_setup_quote_stream,
|
_setup_quote_stream,
|
||||||
symbol=symbol,
|
symbol=symbol,
|
||||||
|
|
@ -932,10 +787,6 @@ async def open_aio_quote_stream(
|
||||||
|
|
||||||
assert contract
|
assert contract
|
||||||
|
|
||||||
# TODO? de-reg on teardown of last consumer task?
|
|
||||||
# -> why aren't we using `.trionics.maybe_open_context()`
|
|
||||||
# here again?? (we are in `open_client_proxies()` tho?)
|
|
||||||
#
|
|
||||||
# cache feed for later consumers
|
# cache feed for later consumers
|
||||||
_quote_streams[symbol] = from_aio
|
_quote_streams[symbol] = from_aio
|
||||||
|
|
||||||
|
|
@ -950,12 +801,7 @@ def normalize(
|
||||||
calc_price: bool = False
|
calc_price: bool = False
|
||||||
|
|
||||||
) -> dict:
|
) -> dict:
|
||||||
'''
|
|
||||||
Translate `ib_async`'s `Ticker.ticks` values to a `piker`
|
|
||||||
normalized `dict` form for transmit to downstream `.data` layer
|
|
||||||
consumers.
|
|
||||||
|
|
||||||
'''
|
|
||||||
# check for special contract types
|
# check for special contract types
|
||||||
con = ticker.contract
|
con = ticker.contract
|
||||||
fqme, calc_price = con2fqme(con)
|
fqme, calc_price = con2fqme(con)
|
||||||
|
|
@ -974,7 +820,7 @@ def normalize(
|
||||||
|
|
||||||
tbt = ticker.tickByTicks
|
tbt = ticker.tickByTicks
|
||||||
if tbt:
|
if tbt:
|
||||||
log.info(f'tickbyticks:\n {ticker.tickByTicks}')
|
print(f'tickbyticks:\n {ticker.tickByTicks}')
|
||||||
|
|
||||||
ticker.ticks = new_ticks
|
ticker.ticks = new_ticks
|
||||||
|
|
||||||
|
|
@ -1010,39 +856,27 @@ def normalize(
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
# ?TODO? feels like this task-fn could be factored to reduce some
|
|
||||||
# indentation levels?
|
|
||||||
# -[ ] the reconnect while loop on ib-gw "data farm connection.."s
|
|
||||||
# -[ ] everything embedded under the `async with aclosing(stream):`
|
|
||||||
# as the "meat" of the quote delivery once the connection is
|
|
||||||
# stable.
|
|
||||||
#
|
|
||||||
async def stream_quotes(
|
async def stream_quotes(
|
||||||
|
|
||||||
send_chan: trio.abc.SendChannel,
|
send_chan: trio.abc.SendChannel,
|
||||||
symbols: list[str],
|
symbols: list[str],
|
||||||
feed_is_live: trio.Event,
|
feed_is_live: trio.Event,
|
||||||
|
loglevel: str = None,
|
||||||
# TODO? we need to hook into the `ib_async` logger like
|
|
||||||
# we can with i3ipc from modden!
|
|
||||||
# loglevel: str|None = None,
|
|
||||||
|
|
||||||
# startup sync
|
# startup sync
|
||||||
task_status: TaskStatus[tuple[dict, dict]] = trio.TASK_STATUS_IGNORED,
|
task_status: TaskStatus[tuple[dict, dict]] = trio.TASK_STATUS_IGNORED,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
Stream `symbols[0]` quotes back via `send_chan`.
|
Stream symbol quotes.
|
||||||
|
|
||||||
The `feed_is_live: Event` is set to signal the caller that it can
|
This is a ``trio`` callable routine meant to be invoked
|
||||||
begin processing msgs from the mem-chan.
|
once the brokerd is up.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# TODO: support multiple subscriptions
|
# TODO: support multiple subscriptions
|
||||||
sym: str = symbols[0]
|
sym = symbols[0]
|
||||||
log.info(
|
log.info(f'request for real-time quotes: {sym}')
|
||||||
f'request for real-time quotes\n'
|
|
||||||
f'sym: {sym!r}\n'
|
|
||||||
)
|
|
||||||
|
|
||||||
init_msgs: list[FeedInit] = []
|
init_msgs: list[FeedInit] = []
|
||||||
|
|
||||||
|
|
@ -1051,30 +885,21 @@ async def stream_quotes(
|
||||||
details: ibis.ContractDetails
|
details: ibis.ContractDetails
|
||||||
async with (
|
async with (
|
||||||
open_data_client() as proxy,
|
open_data_client() as proxy,
|
||||||
|
# trio.open_nursery() as tn,
|
||||||
):
|
):
|
||||||
mkt, details = await get_mkt_info(
|
mkt, details = await get_mkt_info(
|
||||||
sym,
|
sym,
|
||||||
proxy=proxy, # passed to avoid implicit client load
|
proxy=proxy, # passed to avoid implicit client load
|
||||||
)
|
)
|
||||||
|
|
||||||
# is venue active rn?
|
|
||||||
venue_is_open: bool = any(
|
|
||||||
is_current_time_in_range(
|
|
||||||
start_dt=sesh.start,
|
|
||||||
end_dt=sesh.end,
|
|
||||||
)
|
|
||||||
for sesh in details.tradingSessions()
|
|
||||||
)
|
|
||||||
|
|
||||||
init_msg = FeedInit(mkt_info=mkt)
|
init_msg = FeedInit(mkt_info=mkt)
|
||||||
|
|
||||||
# NOTE, tell sampler (via config) to skip vlm summing for dst
|
|
||||||
# assets which provide no vlm data..
|
|
||||||
if mkt.dst.atype in {
|
if mkt.dst.atype in {
|
||||||
'fiat',
|
'fiat',
|
||||||
'index',
|
'index',
|
||||||
'commodity',
|
'commodity',
|
||||||
}:
|
}:
|
||||||
|
# tell sampler config that it shouldn't do vlm summing.
|
||||||
init_msg.shm_write_opts['sum_tick_vlm'] = False
|
init_msg.shm_write_opts['sum_tick_vlm'] = False
|
||||||
init_msg.shm_write_opts['has_vlm'] = False
|
init_msg.shm_write_opts['has_vlm'] = False
|
||||||
|
|
||||||
|
|
@ -1082,21 +907,12 @@ async def stream_quotes(
|
||||||
|
|
||||||
con: Contract = details.contract
|
con: Contract = details.contract
|
||||||
first_ticker: Ticker | None = None
|
first_ticker: Ticker | None = None
|
||||||
|
with trio.move_on_after(1):
|
||||||
timeout: float = 1.6
|
|
||||||
with trio.move_on_after(timeout) as quote_cs:
|
|
||||||
first_ticker: Ticker = await proxy.get_quote(
|
first_ticker: Ticker = await proxy.get_quote(
|
||||||
contract=con,
|
contract=con,
|
||||||
raise_on_timeout=False,
|
raise_on_timeout=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
# XXX should never happen with this ep right?
|
|
||||||
# but if so then, more then likely mkt is closed?
|
|
||||||
if quote_cs.cancelled_caught:
|
|
||||||
log.warning(
|
|
||||||
f'First quote req timed out after {timeout!r}s'
|
|
||||||
)
|
|
||||||
|
|
||||||
if first_ticker:
|
if first_ticker:
|
||||||
first_quote: dict = normalize(first_ticker)
|
first_quote: dict = normalize(first_ticker)
|
||||||
|
|
||||||
|
|
@ -1108,27 +924,28 @@ async def stream_quotes(
|
||||||
f'{pformat(first_quote)}\n'
|
f'{pformat(first_quote)}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
# XXX NOTE: whenever we're "outside regular trading hours"
|
# NOTE: it might be outside regular trading hours for
|
||||||
# (only relevant for assets coming from the "legacy markets"
|
# assets with "standard venue operating hours" so we
|
||||||
# space) so we basically (from an API/runtime-operational
|
# only "pretend the feed is live" when the dst asset
|
||||||
# perspective) "pretend the feed is live" even if it's
|
# type is NOT within the NON-NORMAL-venue set: aka not
|
||||||
# actually closed.
|
# commodities, forex or crypto currencies which CAN
|
||||||
#
|
# always return a NaN on a snap quote request during
|
||||||
# IOW, we signal to the effective caller (task) that the live
|
# normal venue hours. In the case of a closed venue
|
||||||
# feed is "already up" but really we're just indicating that
|
# (equitiies, futes, bonds etc.) we at least try to
|
||||||
# the OHLCV history can start being loaded immediately by the
|
# grab the OHLC history.
|
||||||
# `piker.data`/`.tsp` layers.
|
if (
|
||||||
#
|
first_ticker
|
||||||
# XXX, deats: the "pretend we're live" is just done by
|
and
|
||||||
# a `feed_is_live.set()` even though nothing is actually live
|
isnan(first_ticker.last)
|
||||||
# Bp
|
# SO, if the last quote price value is NaN we ONLY
|
||||||
if not venue_is_open:
|
# "pretend to do" `feed_is_live.set()` if it's a known
|
||||||
log.warning(
|
# dst asset venue with a lot of closed operating hours.
|
||||||
f'Venue is closed, unable to establish real-time feed.\n'
|
and mkt.dst.atype not in {
|
||||||
f'mkt: {mkt!r}\n'
|
'commodity',
|
||||||
f'\n'
|
'fiat',
|
||||||
f'first_ticker: {first_ticker}\n'
|
'crypto',
|
||||||
)
|
}
|
||||||
|
):
|
||||||
task_status.started((
|
task_status.started((
|
||||||
init_msgs,
|
init_msgs,
|
||||||
first_quote,
|
first_quote,
|
||||||
|
|
@ -1139,12 +956,10 @@ async def stream_quotes(
|
||||||
feed_is_live.set()
|
feed_is_live.set()
|
||||||
|
|
||||||
# block and let data history backfill code run.
|
# block and let data history backfill code run.
|
||||||
# XXX obvi given the venue is closed, we never expect feed
|
|
||||||
# to come up; a taskc should be the only way to
|
|
||||||
# terminate this task.
|
|
||||||
await trio.sleep_forever()
|
await trio.sleep_forever()
|
||||||
|
return # we never expect feed to come up?
|
||||||
|
|
||||||
# ?TODO, we could instead spawn a task that waits on a feed
|
# TODO: we should instead spawn a task that waits on a feed
|
||||||
# to start and let it wait indefinitely..instead of this
|
# to start and let it wait indefinitely..instead of this
|
||||||
# hard coded stuff.
|
# hard coded stuff.
|
||||||
# async def wait_for_first_quote():
|
# async def wait_for_first_quote():
|
||||||
|
|
@ -1168,25 +983,21 @@ async def stream_quotes(
|
||||||
)
|
)
|
||||||
cs: trio.CancelScope | None = None
|
cs: trio.CancelScope | None = None
|
||||||
startup: bool = True
|
startup: bool = True
|
||||||
iter_quotes: trio.abc.Channel
|
|
||||||
while (
|
while (
|
||||||
startup
|
startup
|
||||||
or
|
or cs.cancel_called
|
||||||
cs.cancel_called
|
|
||||||
):
|
):
|
||||||
with trio.CancelScope() as cs:
|
with trio.CancelScope() as cs:
|
||||||
async with (
|
async with (
|
||||||
tractor.trionics.collapse_eg(),
|
trio.open_nursery() as nurse,
|
||||||
trio.open_nursery() as tn,
|
|
||||||
open_aio_quote_stream(
|
open_aio_quote_stream(
|
||||||
symbol=sym,
|
symbol=sym,
|
||||||
contract=con,
|
contract=con,
|
||||||
) as iter_quotes,
|
) as stream,
|
||||||
):
|
):
|
||||||
# ?TODO? can we rm this - particularly for `ib_async`?
|
|
||||||
# ugh, clear ticks since we've consumed them
|
# ugh, clear ticks since we've consumed them
|
||||||
# (ahem, ib_insync is stateful trash)
|
# (ahem, ib_insync is stateful trash)
|
||||||
# first_ticker.ticks = []
|
first_ticker.ticks = []
|
||||||
|
|
||||||
# only on first entry at feed boot up
|
# only on first entry at feed boot up
|
||||||
if startup:
|
if startup:
|
||||||
|
|
@ -1200,8 +1011,8 @@ async def stream_quotes(
|
||||||
# data feed event.
|
# data feed event.
|
||||||
async def reset_on_feed():
|
async def reset_on_feed():
|
||||||
|
|
||||||
# ??TODO? this seems to be surpressed from the
|
# TODO: this seems to be surpressed from the
|
||||||
# traceback in `tractor`?
|
# traceback in ``tractor``?
|
||||||
# assert 0
|
# assert 0
|
||||||
|
|
||||||
rt_ev = proxy.status_event(
|
rt_ev = proxy.status_event(
|
||||||
|
|
@ -1210,9 +1021,9 @@ async def stream_quotes(
|
||||||
await rt_ev.wait()
|
await rt_ev.wait()
|
||||||
cs.cancel() # cancel called should now be set
|
cs.cancel() # cancel called should now be set
|
||||||
|
|
||||||
tn.start_soon(reset_on_feed)
|
nurse.start_soon(reset_on_feed)
|
||||||
|
|
||||||
async with aclosing(iter_quotes):
|
async with aclosing(stream):
|
||||||
# if syminfo.get('no_vlm', False):
|
# if syminfo.get('no_vlm', False):
|
||||||
if not init_msg.shm_write_opts['has_vlm']:
|
if not init_msg.shm_write_opts['has_vlm']:
|
||||||
|
|
||||||
|
|
@ -1227,27 +1038,25 @@ async def stream_quotes(
|
||||||
# wait for real volume on feed (trading might be
|
# wait for real volume on feed (trading might be
|
||||||
# closed)
|
# closed)
|
||||||
while True:
|
while True:
|
||||||
ticker = await iter_quotes.receive()
|
ticker = await stream.receive()
|
||||||
|
|
||||||
# for a real volume contract we rait for
|
# for a real volume contract we rait for
|
||||||
# the first "real" trade to take place
|
# the first "real" trade to take place
|
||||||
if (
|
if (
|
||||||
# not calc_price
|
# not calc_price
|
||||||
# and not ticker.rtTime
|
# and not ticker.rtTime
|
||||||
False
|
not ticker.rtTime
|
||||||
# not ticker.rtTime
|
|
||||||
):
|
):
|
||||||
# spin consuming tickers until we
|
# spin consuming tickers until we
|
||||||
# get a real market datum
|
# get a real market datum
|
||||||
log.debug(f"New unsent ticker: {ticker}")
|
log.debug(f"New unsent ticker: {ticker}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
else:
|
else:
|
||||||
log.debug("Received first volume tick")
|
log.debug("Received first volume tick")
|
||||||
# ugh, clear ticks since we've
|
# ugh, clear ticks since we've
|
||||||
# consumed them (ahem, ib_insync is
|
# consumed them (ahem, ib_insync is
|
||||||
# truly stateful trash)
|
# truly stateful trash)
|
||||||
# ticker.ticks = []
|
ticker.ticks = []
|
||||||
|
|
||||||
# XXX: this works because we don't use
|
# XXX: this works because we don't use
|
||||||
# ``aclosing()`` above?
|
# ``aclosing()`` above?
|
||||||
|
|
@ -1257,24 +1066,15 @@ async def stream_quotes(
|
||||||
log.debug(f"First ticker received {quote}")
|
log.debug(f"First ticker received {quote}")
|
||||||
|
|
||||||
# tell data-layer spawner-caller that live
|
# tell data-layer spawner-caller that live
|
||||||
# quotes are now active desptie not having
|
# quotes are now streaming.
|
||||||
# necessarily received a first vlm/clearing
|
|
||||||
# tick.
|
|
||||||
ticker = await iter_quotes.receive()
|
|
||||||
feed_is_live.set()
|
feed_is_live.set()
|
||||||
fqme: str = quote['fqme']
|
|
||||||
await send_chan.send({fqme: quote})
|
|
||||||
|
|
||||||
# last = time.time()
|
# last = time.time()
|
||||||
async for ticker in iter_quotes:
|
async for ticker in stream:
|
||||||
quote = normalize(ticker)
|
quote = normalize(ticker)
|
||||||
fqme: str = quote['fqme']
|
fqme = quote['fqme']
|
||||||
log.debug(
|
|
||||||
f'Sending quote\n'
|
|
||||||
f'{quote}'
|
|
||||||
)
|
|
||||||
await send_chan.send({fqme: quote})
|
await send_chan.send({fqme: quote})
|
||||||
|
|
||||||
# ugh, clear ticks since we've consumed them
|
# ugh, clear ticks since we've consumed them
|
||||||
# ticker.ticks = []
|
ticker.ticks = []
|
||||||
# last = time.time()
|
# last = time.time()
|
||||||
|
|
|
||||||
|
|
@ -34,7 +34,6 @@ import urllib.parse
|
||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import base64
|
import base64
|
||||||
import tractor
|
|
||||||
import trio
|
import trio
|
||||||
|
|
||||||
from piker import config
|
from piker import config
|
||||||
|
|
@ -373,7 +372,8 @@ class Client:
|
||||||
# 1658347714, 'status': 'Success'}]}
|
# 1658347714, 'status': 'Success'}]}
|
||||||
|
|
||||||
if xfers:
|
if xfers:
|
||||||
await tractor.pause()
|
import tractor
|
||||||
|
await tractor.pp()
|
||||||
|
|
||||||
trans: dict[str, Transaction] = {}
|
trans: dict[str, Transaction] = {}
|
||||||
for entry in xfers:
|
for entry in xfers:
|
||||||
|
|
@ -501,7 +501,6 @@ class Client:
|
||||||
for xkey, data in resp['result'].items():
|
for xkey, data in resp['result'].items():
|
||||||
|
|
||||||
# NOTE: always cache in pairs tables for faster lookup
|
# NOTE: always cache in pairs tables for faster lookup
|
||||||
with tractor.devx.maybe_open_crash_handler(): # as bxerr:
|
|
||||||
pair = Pair(xname=xkey, **data)
|
pair = Pair(xname=xkey, **data)
|
||||||
|
|
||||||
# register the above `Pair` structs for all
|
# register the above `Pair` structs for all
|
||||||
|
|
|
||||||
|
|
@ -175,8 +175,9 @@ async def handle_order_requests(
|
||||||
|
|
||||||
case {
|
case {
|
||||||
'account': 'kraken.spot' as account,
|
'account': 'kraken.spot' as account,
|
||||||
'action': 'buy'|'sell',
|
'action': action,
|
||||||
}:
|
} if action in {'buy', 'sell'}:
|
||||||
|
|
||||||
# validate
|
# validate
|
||||||
order = BrokerdOrder(**msg)
|
order = BrokerdOrder(**msg)
|
||||||
|
|
||||||
|
|
@ -261,12 +262,6 @@ async def handle_order_requests(
|
||||||
} | extra
|
} | extra
|
||||||
|
|
||||||
log.info(f'Submitting WS order request:\n{pformat(req)}')
|
log.info(f'Submitting WS order request:\n{pformat(req)}')
|
||||||
|
|
||||||
# NOTE HOWTO, debug order requests
|
|
||||||
#
|
|
||||||
# if 'XRP' in pair:
|
|
||||||
# await tractor.pause()
|
|
||||||
|
|
||||||
await ws.send_msg(req)
|
await ws.send_msg(req)
|
||||||
|
|
||||||
# placehold for sanity checking in relay loop
|
# placehold for sanity checking in relay loop
|
||||||
|
|
@ -549,7 +544,7 @@ async def open_trade_dialog(
|
||||||
# to be reloaded.
|
# to be reloaded.
|
||||||
balances: dict[str, float] = await client.get_balances()
|
balances: dict[str, float] = await client.get_balances()
|
||||||
|
|
||||||
await verify_balances(
|
verify_balances(
|
||||||
acnt,
|
acnt,
|
||||||
src_fiat,
|
src_fiat,
|
||||||
balances,
|
balances,
|
||||||
|
|
@ -1090,8 +1085,6 @@ async def handle_order_updates(
|
||||||
f'Failed to {action} order {reqid}:\n'
|
f'Failed to {action} order {reqid}:\n'
|
||||||
f'{errmsg}'
|
f'{errmsg}'
|
||||||
)
|
)
|
||||||
# if tractor._state.debug_mode():
|
|
||||||
# await tractor.pause()
|
|
||||||
|
|
||||||
symbol: str = 'N/A'
|
symbol: str = 'N/A'
|
||||||
if chain := apiflows.get(reqid):
|
if chain := apiflows.get(reqid):
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ Symbology defs and search.
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
import tractor
|
import tractor
|
||||||
|
from rapidfuzz import process as fuzzy
|
||||||
|
|
||||||
from piker._cacheables import (
|
from piker._cacheables import (
|
||||||
async_lifo_cache,
|
async_lifo_cache,
|
||||||
|
|
@ -40,13 +41,8 @@ from piker.accounting._mktinfo import (
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# https://www.kraken.com/features/api#get-tradable-pairs
|
||||||
class Pair(Struct):
|
class Pair(Struct):
|
||||||
'''
|
|
||||||
A tradable asset pair as schema-defined by,
|
|
||||||
|
|
||||||
https://docs.kraken.com/api/docs/rest-api/get-tradable-asset-pairs
|
|
||||||
|
|
||||||
'''
|
|
||||||
xname: str # idiotic bs_mktid equiv i guess?
|
xname: str # idiotic bs_mktid equiv i guess?
|
||||||
altname: str # alternate pair name
|
altname: str # alternate pair name
|
||||||
wsname: str # WebSocket pair name (if available)
|
wsname: str # WebSocket pair name (if available)
|
||||||
|
|
@ -57,6 +53,7 @@ class Pair(Struct):
|
||||||
lot: str # volume lot size
|
lot: str # volume lot size
|
||||||
|
|
||||||
cost_decimals: int
|
cost_decimals: int
|
||||||
|
costmin: float
|
||||||
pair_decimals: int # scaling decimal places for pair
|
pair_decimals: int # scaling decimal places for pair
|
||||||
lot_decimals: int # scaling decimal places for volume
|
lot_decimals: int # scaling decimal places for volume
|
||||||
|
|
||||||
|
|
@ -82,7 +79,6 @@ class Pair(Struct):
|
||||||
tick_size: float # min price step size
|
tick_size: float # min price step size
|
||||||
status: str
|
status: str
|
||||||
|
|
||||||
costmin: str|None = None # XXX, only some mktpairs?
|
|
||||||
short_position_limit: float = 0
|
short_position_limit: float = 0
|
||||||
long_position_limit: float = float('inf')
|
long_position_limit: float = float('inf')
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -62,7 +62,7 @@ from piker._cacheables import (
|
||||||
)
|
)
|
||||||
from piker.log import get_logger
|
from piker.log import get_logger
|
||||||
from piker.data.validate import FeedInit
|
from piker.data.validate import FeedInit
|
||||||
from piker.types import Struct # NOTE, this is already a `tractor.msg.Struct`
|
from piker.types import Struct
|
||||||
from piker.data import (
|
from piker.data import (
|
||||||
def_iohlcv_fields,
|
def_iohlcv_fields,
|
||||||
match_from_pairs,
|
match_from_pairs,
|
||||||
|
|
@ -98,18 +98,9 @@ class KucoinMktPair(Struct, frozen=True):
|
||||||
def size_tick(self) -> Decimal:
|
def size_tick(self) -> Decimal:
|
||||||
return Decimal(str(self.quoteMinSize))
|
return Decimal(str(self.quoteMinSize))
|
||||||
|
|
||||||
callauctionFirstStageStartTime: None|float
|
|
||||||
callauctionIsEnabled: bool
|
|
||||||
callauctionPriceCeiling: float|None
|
|
||||||
callauctionPriceFloor: float|None
|
|
||||||
callauctionSecondStageStartTime: float|None
|
|
||||||
callauctionThirdStageStartTime: float|None
|
|
||||||
|
|
||||||
enableTrading: bool
|
enableTrading: bool
|
||||||
feeCategory: int
|
|
||||||
feeCurrency: str
|
feeCurrency: str
|
||||||
isMarginEnabled: bool
|
isMarginEnabled: bool
|
||||||
makerFeeCoefficient: float
|
|
||||||
market: str
|
market: str
|
||||||
minFunds: float
|
minFunds: float
|
||||||
name: str
|
name: str
|
||||||
|
|
@ -119,10 +110,11 @@ class KucoinMktPair(Struct, frozen=True):
|
||||||
quoteIncrement: float
|
quoteIncrement: float
|
||||||
quoteMaxSize: float
|
quoteMaxSize: float
|
||||||
quoteMinSize: float
|
quoteMinSize: float
|
||||||
st: bool
|
|
||||||
symbol: str # our bs_mktid, kucoin's internal id
|
symbol: str # our bs_mktid, kucoin's internal id
|
||||||
|
feeCategory: int
|
||||||
|
makerFeeCoefficient: float
|
||||||
takerFeeCoefficient: float
|
takerFeeCoefficient: float
|
||||||
tradingStartTime: float|None
|
st: bool
|
||||||
|
|
||||||
|
|
||||||
class AccountTrade(Struct, frozen=True):
|
class AccountTrade(Struct, frozen=True):
|
||||||
|
|
@ -404,13 +396,7 @@ class Client:
|
||||||
pairs: dict[str, KucoinMktPair] = {}
|
pairs: dict[str, KucoinMktPair] = {}
|
||||||
fqmes2mktids: bidict[str, str] = bidict()
|
fqmes2mktids: bidict[str, str] = bidict()
|
||||||
for item in entries:
|
for item in entries:
|
||||||
try:
|
|
||||||
pair = pairs[item['name']] = KucoinMktPair(**item)
|
pair = pairs[item['name']] = KucoinMktPair(**item)
|
||||||
except TypeError as te:
|
|
||||||
raise TypeError(
|
|
||||||
'`KucoinMktPair` and reponse fields do not match ??\n'
|
|
||||||
f'{KucoinMktPair.fields_diff(item)}\n'
|
|
||||||
) from te
|
|
||||||
fqmes2mktids[
|
fqmes2mktids[
|
||||||
item['name'].lower().replace('-', '')
|
item['name'].lower().replace('-', '')
|
||||||
] = pair.name
|
] = pair.name
|
||||||
|
|
|
||||||
|
|
@ -37,12 +37,6 @@ import tractor
|
||||||
from async_generator import asynccontextmanager
|
from async_generator import asynccontextmanager
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import wrapt
|
import wrapt
|
||||||
|
|
||||||
# TODO, port to `httpx`/`trio-websocket` whenver i get back to
|
|
||||||
# writing a proper ws-api streamer for this backend (since the data
|
|
||||||
# feeds are free now) as per GH feat-req:
|
|
||||||
# https://github.com/pikers/piker/issues/509
|
|
||||||
#
|
|
||||||
import asks
|
import asks
|
||||||
|
|
||||||
from ..calc import humanize, percent_change
|
from ..calc import humanize, percent_change
|
||||||
|
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
piker.clearing
|
|
||||||
______________
|
|
||||||
trade execution-n-control subsys for both live and paper trading as
|
|
||||||
well as algo-trading manual override/interaction across any backend
|
|
||||||
broker and data provider.
|
|
||||||
|
|
||||||
avail UIs
|
|
||||||
*********
|
|
||||||
|
|
||||||
order ctl
|
|
||||||
---------
|
|
||||||
the `piker.clearing` subsys is exposed mainly though
|
|
||||||
the `piker chart` GUI as a "chart trader" style UX and
|
|
||||||
is automatically enabled whenever a chart is opened.
|
|
||||||
|
|
||||||
.. ^TODO, more prose here!
|
|
||||||
|
|
||||||
the "manual" order control features are exposed via the
|
|
||||||
`piker.ui.order_mode` API and can pretty much always be
|
|
||||||
used (at least) in simulated-trading mode, aka "paper"-mode, and
|
|
||||||
the micro-manual is as follows:
|
|
||||||
|
|
||||||
``order_mode`` (
|
|
||||||
edge triggered activation by any of the following keys,
|
|
||||||
``mouse-click`` on y-level to submit at that price
|
|
||||||
):
|
|
||||||
|
|
||||||
- ``f``/ ``ctl-f`` to stage buy
|
|
||||||
- ``d``/ ``ctl-d`` to stage sell
|
|
||||||
- ``a`` to stage alert
|
|
||||||
|
|
||||||
|
|
||||||
``search_mode`` (
|
|
||||||
``ctl-l`` or ``ctl-space`` to open,
|
|
||||||
``ctl-c`` or ``ctl-space`` to close
|
|
||||||
) :
|
|
||||||
|
|
||||||
- begin typing to have symbol search automatically lookup
|
|
||||||
symbols from all loaded backend (broker) providers
|
|
||||||
- arrow keys and mouse click to navigate selection
|
|
||||||
- vi-like ``ctl-[hjkl]`` for navigation
|
|
||||||
|
|
||||||
|
|
||||||
position (pp) mgmt
|
|
||||||
------------------
|
|
||||||
you can also configure your position allocation limits from the
|
|
||||||
sidepane.
|
|
||||||
|
|
||||||
.. ^TODO, explain and provide tut once more refined!
|
|
||||||
|
|
@ -25,10 +25,7 @@ from typing import TYPE_CHECKING
|
||||||
|
|
||||||
import trio
|
import trio
|
||||||
import tractor
|
import tractor
|
||||||
from tractor.trionics import (
|
from tractor.trionics import broadcast_receiver
|
||||||
broadcast_receiver,
|
|
||||||
collapse_eg,
|
|
||||||
)
|
|
||||||
|
|
||||||
from ._util import (
|
from ._util import (
|
||||||
log, # sub-sys logger
|
log, # sub-sys logger
|
||||||
|
|
@ -171,6 +168,7 @@ class OrderClient(Struct):
|
||||||
|
|
||||||
|
|
||||||
async def relay_orders_from_sync_code(
|
async def relay_orders_from_sync_code(
|
||||||
|
|
||||||
client: OrderClient,
|
client: OrderClient,
|
||||||
symbol_key: str,
|
symbol_key: str,
|
||||||
to_ems_stream: tractor.MsgStream,
|
to_ems_stream: tractor.MsgStream,
|
||||||
|
|
@ -244,11 +242,6 @@ async def open_ems(
|
||||||
|
|
||||||
async with maybe_open_emsd(
|
async with maybe_open_emsd(
|
||||||
broker,
|
broker,
|
||||||
# XXX NOTE, LOL so this determines the daemon `emsd` loglevel
|
|
||||||
# then FYI.. that's kinda wrong no?
|
|
||||||
# -[ ] shouldn't it be set by `pikerd -l` or no?
|
|
||||||
# -[ ] would make a lot more sense to have a subsys ctl for
|
|
||||||
# levels.. like `-l emsd.info` or something?
|
|
||||||
loglevel=loglevel,
|
loglevel=loglevel,
|
||||||
) as portal:
|
) as portal:
|
||||||
|
|
||||||
|
|
@ -288,11 +281,8 @@ async def open_ems(
|
||||||
client._ems_stream = trades_stream
|
client._ems_stream = trades_stream
|
||||||
|
|
||||||
# start sync code order msg delivery task
|
# start sync code order msg delivery task
|
||||||
async with (
|
async with trio.open_nursery() as n:
|
||||||
collapse_eg(),
|
n.start_soon(
|
||||||
trio.open_nursery() as tn,
|
|
||||||
):
|
|
||||||
tn.start_soon(
|
|
||||||
relay_orders_from_sync_code,
|
relay_orders_from_sync_code,
|
||||||
client,
|
client,
|
||||||
fqme,
|
fqme,
|
||||||
|
|
@ -308,4 +298,4 @@ async def open_ems(
|
||||||
)
|
)
|
||||||
|
|
||||||
# stop the sync-msg-relay task on exit.
|
# stop the sync-msg-relay task on exit.
|
||||||
tn.cancel_scope.cancel()
|
n.cancel_scope.cancel()
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,6 @@ from bidict import bidict
|
||||||
import trio
|
import trio
|
||||||
from trio_typing import TaskStatus
|
from trio_typing import TaskStatus
|
||||||
import tractor
|
import tractor
|
||||||
from tractor import trionics
|
|
||||||
|
|
||||||
from ._util import (
|
from ._util import (
|
||||||
log, # sub-sys logger
|
log, # sub-sys logger
|
||||||
|
|
@ -77,6 +76,7 @@ if TYPE_CHECKING:
|
||||||
|
|
||||||
# TODO: numba all of this
|
# TODO: numba all of this
|
||||||
def mk_check(
|
def mk_check(
|
||||||
|
|
||||||
trigger_price: float,
|
trigger_price: float,
|
||||||
known_last: float,
|
known_last: float,
|
||||||
action: str,
|
action: str,
|
||||||
|
|
@ -162,7 +162,7 @@ async def clear_dark_triggers(
|
||||||
|
|
||||||
router: Router,
|
router: Router,
|
||||||
brokerd_orders_stream: tractor.MsgStream,
|
brokerd_orders_stream: tractor.MsgStream,
|
||||||
quote_stream: tractor.MsgStream,
|
quote_stream: tractor.ReceiveMsgStream, # noqa
|
||||||
broker: str,
|
broker: str,
|
||||||
fqme: str,
|
fqme: str,
|
||||||
|
|
||||||
|
|
@ -178,7 +178,6 @@ async def clear_dark_triggers(
|
||||||
'''
|
'''
|
||||||
# XXX: optimize this for speed!
|
# XXX: optimize this for speed!
|
||||||
# TODO:
|
# TODO:
|
||||||
# - port to the new ringbuf stuff in `tractor.ipc`!
|
|
||||||
# - numba all this!
|
# - numba all this!
|
||||||
# - this stream may eventually contain multiple symbols
|
# - this stream may eventually contain multiple symbols
|
||||||
quote_stream._raise_on_lag = False
|
quote_stream._raise_on_lag = False
|
||||||
|
|
@ -388,7 +387,6 @@ async def open_brokerd_dialog(
|
||||||
for ep_name in [
|
for ep_name in [
|
||||||
'open_trade_dialog', # probably final name?
|
'open_trade_dialog', # probably final name?
|
||||||
'trades_dialogue', # legacy
|
'trades_dialogue', # legacy
|
||||||
# ^!TODO, rm this since all backends ported no ?!?
|
|
||||||
]:
|
]:
|
||||||
trades_endpoint = getattr(
|
trades_endpoint = getattr(
|
||||||
brokermod,
|
brokermod,
|
||||||
|
|
@ -502,7 +500,7 @@ class Router(Struct):
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# setup at actor spawn time
|
# setup at actor spawn time
|
||||||
_tn: trio.Nursery
|
nursery: trio.Nursery
|
||||||
|
|
||||||
# broker to book map
|
# broker to book map
|
||||||
books: dict[str, DarkBook] = {}
|
books: dict[str, DarkBook] = {}
|
||||||
|
|
@ -672,7 +670,7 @@ class Router(Struct):
|
||||||
# dark book clearing loop, also lives with parent
|
# dark book clearing loop, also lives with parent
|
||||||
# daemon to allow dark order clearing while no
|
# daemon to allow dark order clearing while no
|
||||||
# client is connected.
|
# client is connected.
|
||||||
self._tn.start_soon(
|
self.nursery.start_soon(
|
||||||
clear_dark_triggers,
|
clear_dark_triggers,
|
||||||
self,
|
self,
|
||||||
relay.brokerd_stream,
|
relay.brokerd_stream,
|
||||||
|
|
@ -695,7 +693,7 @@ class Router(Struct):
|
||||||
|
|
||||||
# spawn a ``brokerd`` order control dialog stream
|
# spawn a ``brokerd`` order control dialog stream
|
||||||
# that syncs lifetime with the parent `emsd` daemon.
|
# that syncs lifetime with the parent `emsd` daemon.
|
||||||
self._tn.start_soon(
|
self.nursery.start_soon(
|
||||||
translate_and_relay_brokerd_events,
|
translate_and_relay_brokerd_events,
|
||||||
broker,
|
broker,
|
||||||
relay.brokerd_stream,
|
relay.brokerd_stream,
|
||||||
|
|
@ -769,12 +767,10 @@ async def _setup_persistent_emsd(
|
||||||
|
|
||||||
global _router
|
global _router
|
||||||
|
|
||||||
# open a root "service task-nursery" for the `emsd`-actor
|
# open a root "service nursery" for the ``emsd`` actor
|
||||||
async with (
|
async with trio.open_nursery() as service_nursery:
|
||||||
trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn
|
_router = Router(nursery=service_nursery)
|
||||||
):
|
|
||||||
_router = Router(_tn=tn)
|
|
||||||
|
|
||||||
# TODO: send back the full set of persistent
|
# TODO: send back the full set of persistent
|
||||||
# orders/execs?
|
# orders/execs?
|
||||||
|
|
@ -1028,18 +1024,8 @@ async def translate_and_relay_brokerd_events(
|
||||||
)
|
)
|
||||||
|
|
||||||
if status == 'closed':
|
if status == 'closed':
|
||||||
log.info(
|
log.info(f'Execution for {oid} is complete!')
|
||||||
f'Execution is complete!\n'
|
status_msg = book._active.pop(oid)
|
||||||
f'oid: {oid!r}\n'
|
|
||||||
)
|
|
||||||
status_msg = book._active.pop(oid, None)
|
|
||||||
if status_msg is None:
|
|
||||||
log.warning(
|
|
||||||
f'Order was already cleared from book ??\n'
|
|
||||||
f'oid: {oid!r}\n'
|
|
||||||
f'\n'
|
|
||||||
f'Maybe the order cancelled before submitted ??\n'
|
|
||||||
)
|
|
||||||
|
|
||||||
elif status == 'canceled':
|
elif status == 'canceled':
|
||||||
log.cancel(f'Cancellation for {oid} is complete!')
|
log.cancel(f'Cancellation for {oid} is complete!')
|
||||||
|
|
@ -1204,16 +1190,12 @@ async def process_client_order_cmds(
|
||||||
submitting live orders immediately if requested by the client.
|
submitting live orders immediately if requested by the client.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# TODO, only allow `msgspec.Struct` form!
|
# cmd: dict
|
||||||
cmd: dict
|
|
||||||
async for cmd in client_order_stream:
|
async for cmd in client_order_stream:
|
||||||
log.info(
|
log.info(f'Received order cmd:\n{pformat(cmd)}')
|
||||||
f'Received order cmd:\n'
|
|
||||||
f'{pformat(cmd)}\n'
|
|
||||||
)
|
|
||||||
|
|
||||||
# CAWT DAMN we need struct support!
|
# CAWT DAMN we need struct support!
|
||||||
oid: str = str(cmd['oid'])
|
oid = str(cmd['oid'])
|
||||||
|
|
||||||
# register this stream as an active order dialog (msg flow) for
|
# register this stream as an active order dialog (msg flow) for
|
||||||
# this order id such that translated message from the brokerd
|
# this order id such that translated message from the brokerd
|
||||||
|
|
@ -1319,7 +1301,7 @@ async def process_client_order_cmds(
|
||||||
case {
|
case {
|
||||||
'oid': oid,
|
'oid': oid,
|
||||||
'symbol': fqme,
|
'symbol': fqme,
|
||||||
'price': price,
|
'price': trigger_price,
|
||||||
'size': size,
|
'size': size,
|
||||||
'action': ('buy' | 'sell') as action,
|
'action': ('buy' | 'sell') as action,
|
||||||
'exec_mode': ('live' | 'paper'),
|
'exec_mode': ('live' | 'paper'),
|
||||||
|
|
@ -1351,7 +1333,7 @@ async def process_client_order_cmds(
|
||||||
|
|
||||||
symbol=sym,
|
symbol=sym,
|
||||||
action=action,
|
action=action,
|
||||||
price=price,
|
price=trigger_price,
|
||||||
size=size,
|
size=size,
|
||||||
account=req.account,
|
account=req.account,
|
||||||
)
|
)
|
||||||
|
|
@ -1373,11 +1355,7 @@ async def process_client_order_cmds(
|
||||||
# (``translate_and_relay_brokerd_events()`` above) will
|
# (``translate_and_relay_brokerd_events()`` above) will
|
||||||
# handle relaying the ems side responses back to
|
# handle relaying the ems side responses back to
|
||||||
# the client/cmd sender from this request
|
# the client/cmd sender from this request
|
||||||
log.info(
|
log.info(f'Sending live order to {broker}:\n{pformat(msg)}')
|
||||||
f'Sending live order to {broker}:\n'
|
|
||||||
f'{pformat(msg)}'
|
|
||||||
)
|
|
||||||
|
|
||||||
await brokerd_order_stream.send(msg)
|
await brokerd_order_stream.send(msg)
|
||||||
|
|
||||||
# an immediate response should be ``BrokerdOrderAck``
|
# an immediate response should be ``BrokerdOrderAck``
|
||||||
|
|
@ -1393,7 +1371,7 @@ async def process_client_order_cmds(
|
||||||
case {
|
case {
|
||||||
'oid': oid,
|
'oid': oid,
|
||||||
'symbol': fqme,
|
'symbol': fqme,
|
||||||
'price': price,
|
'price': trigger_price,
|
||||||
'size': size,
|
'size': size,
|
||||||
'exec_mode': exec_mode,
|
'exec_mode': exec_mode,
|
||||||
'action': action,
|
'action': action,
|
||||||
|
|
@ -1421,12 +1399,7 @@ async def process_client_order_cmds(
|
||||||
if isnan(last):
|
if isnan(last):
|
||||||
last = flume.rt_shm.array[-1]['close']
|
last = flume.rt_shm.array[-1]['close']
|
||||||
|
|
||||||
trigger_price: float = float(price)
|
pred = mk_check(trigger_price, last, action)
|
||||||
pred = mk_check(
|
|
||||||
trigger_price,
|
|
||||||
last,
|
|
||||||
action,
|
|
||||||
)
|
|
||||||
|
|
||||||
# NOTE: for dark orders currently we submit
|
# NOTE: for dark orders currently we submit
|
||||||
# the triggered live order at a price 5 ticks
|
# the triggered live order at a price 5 ticks
|
||||||
|
|
@ -1533,7 +1506,7 @@ async def maybe_open_trade_relays(
|
||||||
loglevel: str = 'info',
|
loglevel: str = 'info',
|
||||||
):
|
):
|
||||||
|
|
||||||
fqme, relay, feed, client_ready = await _router._tn.start(
|
fqme, relay, feed, client_ready = await _router.nursery.start(
|
||||||
_router.open_trade_relays,
|
_router.open_trade_relays,
|
||||||
fqme,
|
fqme,
|
||||||
exec_mode,
|
exec_mode,
|
||||||
|
|
@ -1563,18 +1536,19 @@ async def maybe_open_trade_relays(
|
||||||
|
|
||||||
@tractor.context
|
@tractor.context
|
||||||
async def _emsd_main(
|
async def _emsd_main(
|
||||||
ctx: tractor.Context, # becomes `ems_ctx` below
|
ctx: tractor.Context,
|
||||||
fqme: str,
|
fqme: str,
|
||||||
exec_mode: str, # ('paper', 'live')
|
exec_mode: str, # ('paper', 'live')
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
|
|
||||||
) -> tuple[ # `ctx.started()` value!
|
) -> tuple[
|
||||||
dict[ # positions
|
dict[
|
||||||
tuple[str, str], # brokername, acctid
|
# brokername, acctid
|
||||||
|
tuple[str, str],
|
||||||
list[BrokerdPosition],
|
list[BrokerdPosition],
|
||||||
],
|
],
|
||||||
list[str], # accounts
|
list[str],
|
||||||
dict[str, Status], # dialogs
|
dict[str, Status],
|
||||||
]:
|
]:
|
||||||
'''
|
'''
|
||||||
EMS (sub)actor entrypoint providing the execution management
|
EMS (sub)actor entrypoint providing the execution management
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,6 @@ Clearing sub-system message and protocols.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from decimal import Decimal
|
|
||||||
from typing import (
|
from typing import (
|
||||||
Literal,
|
Literal,
|
||||||
)
|
)
|
||||||
|
|
@ -72,15 +71,7 @@ class Order(Struct):
|
||||||
symbol: str # | MktPair
|
symbol: str # | MktPair
|
||||||
account: str # should we set a default as '' ?
|
account: str # should we set a default as '' ?
|
||||||
|
|
||||||
# https://docs.python.org/3/library/decimal.html#decimal-objects
|
price: float
|
||||||
#
|
|
||||||
# ?TODO? decimal usage throughout?
|
|
||||||
# -[ ] possibly leverage the `Encoder(decimal_format='number')`
|
|
||||||
# bit?
|
|
||||||
# |_https://jcristharif.com/msgspec/supported-types.html#decimal
|
|
||||||
# -[ ] should we also use it for .size?
|
|
||||||
#
|
|
||||||
price: Decimal
|
|
||||||
size: float # -ve is "sell", +ve is "buy"
|
size: float # -ve is "sell", +ve is "buy"
|
||||||
|
|
||||||
brokers: list[str] = []
|
brokers: list[str] = []
|
||||||
|
|
@ -187,7 +178,7 @@ class BrokerdOrder(Struct):
|
||||||
time_ns: int
|
time_ns: int
|
||||||
|
|
||||||
symbol: str # fqme
|
symbol: str # fqme
|
||||||
price: Decimal
|
price: float
|
||||||
size: float
|
size: float
|
||||||
|
|
||||||
# TODO: if we instead rely on a +ve/-ve size to determine
|
# TODO: if we instead rely on a +ve/-ve size to determine
|
||||||
|
|
@ -301,9 +292,6 @@ class BrokerdError(Struct):
|
||||||
|
|
||||||
# TODO: yeah, so we REALLY need to completely deprecate
|
# TODO: yeah, so we REALLY need to completely deprecate
|
||||||
# this and use the `.accounting.Position` msg-type instead..
|
# this and use the `.accounting.Position` msg-type instead..
|
||||||
# -[ ] an alternative might be to add a `Position.summary() ->
|
|
||||||
# `PositionSummary`-msg that we generate since `Position` has a lot
|
|
||||||
# of fields by default we likely don't want to send over the wire?
|
|
||||||
class BrokerdPosition(Struct):
|
class BrokerdPosition(Struct):
|
||||||
'''
|
'''
|
||||||
Position update event from brokerd.
|
Position update event from brokerd.
|
||||||
|
|
@ -316,4 +304,3 @@ class BrokerdPosition(Struct):
|
||||||
avg_price: float
|
avg_price: float
|
||||||
currency: str = ''
|
currency: str = ''
|
||||||
name: str = 'position'
|
name: str = 'position'
|
||||||
bs_mktid: str|int|None = None
|
|
||||||
|
|
|
||||||
|
|
@ -297,8 +297,6 @@ class PaperBoi(Struct):
|
||||||
|
|
||||||
# transmit pp msg to ems
|
# transmit pp msg to ems
|
||||||
pp: Position = self.acnt.pps[bs_mktid]
|
pp: Position = self.acnt.pps[bs_mktid]
|
||||||
# TODO, this will break if `require_only=True` was passed to
|
|
||||||
# `.update_from_ledger()`
|
|
||||||
|
|
||||||
pp_msg = BrokerdPosition(
|
pp_msg = BrokerdPosition(
|
||||||
broker=self.broker,
|
broker=self.broker,
|
||||||
|
|
@ -510,7 +508,7 @@ async def handle_order_requests(
|
||||||
reqid = await client.submit_limit(
|
reqid = await client.submit_limit(
|
||||||
oid=order.oid,
|
oid=order.oid,
|
||||||
symbol=f'{order.symbol}.{client.broker}',
|
symbol=f'{order.symbol}.{client.broker}',
|
||||||
price=float(order.price),
|
price=order.price,
|
||||||
action=order.action,
|
action=order.action,
|
||||||
size=order.size,
|
size=order.size,
|
||||||
# XXX: by default 0 tells ``ib_insync`` methods that
|
# XXX: by default 0 tells ``ib_insync`` methods that
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,6 @@ subsys: str = 'piker.clearing'
|
||||||
|
|
||||||
log = get_logger(subsys)
|
log = get_logger(subsys)
|
||||||
|
|
||||||
# TODO, oof doesn't this ignore the `loglevel` then???
|
|
||||||
get_console_log = partial(
|
get_console_log = partial(
|
||||||
get_console_log,
|
get_console_log,
|
||||||
name=subsys,
|
name=subsys,
|
||||||
|
|
|
||||||
|
|
@ -134,8 +134,8 @@ def pikerd(
|
||||||
Spawn the piker broker-daemon.
|
Spawn the piker broker-daemon.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# from tractor.devx import maybe_open_crash_handler
|
from tractor.devx import maybe_open_crash_handler
|
||||||
# with maybe_open_crash_handler(pdb=False):
|
with maybe_open_crash_handler(pdb=pdb):
|
||||||
log = get_console_log(loglevel, name='cli')
|
log = get_console_log(loglevel, name='cli')
|
||||||
|
|
||||||
if pdb:
|
if pdb:
|
||||||
|
|
@ -178,18 +178,39 @@ def pikerd(
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
service_mngr: service.Services
|
service_mngr: service.Services
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
service.open_pikerd(
|
service.open_pikerd(
|
||||||
registry_addrs=regaddrs,
|
registry_addrs=regaddrs,
|
||||||
loglevel=loglevel,
|
loglevel=loglevel,
|
||||||
debug_mode=pdb,
|
debug_mode=pdb,
|
||||||
# enable_transports=['uds'],
|
|
||||||
enable_transports=['tcp'],
|
) as service_mngr, # normally delivers a ``Services`` handle
|
||||||
) as service_mngr,
|
|
||||||
|
# AsyncExitStack() as stack,
|
||||||
):
|
):
|
||||||
assert service_mngr
|
# TODO: spawn all other sub-actor daemons according to
|
||||||
# ?TODO? spawn all other sub-actor daemons according to
|
|
||||||
# multiaddress endpoint spec defined by user config
|
# multiaddress endpoint spec defined by user config
|
||||||
|
assert service_mngr
|
||||||
|
|
||||||
|
# if tsdb:
|
||||||
|
# dname, conf = await stack.enter_async_context(
|
||||||
|
# service.marketstore.start_ahab_daemon(
|
||||||
|
# service_mngr,
|
||||||
|
# loglevel=loglevel,
|
||||||
|
# )
|
||||||
|
# )
|
||||||
|
# log.info(f'TSDB `{dname}` up with conf:\n{conf}')
|
||||||
|
|
||||||
|
# if es:
|
||||||
|
# dname, conf = await stack.enter_async_context(
|
||||||
|
# service.elastic.start_ahab_daemon(
|
||||||
|
# service_mngr,
|
||||||
|
# loglevel=loglevel,
|
||||||
|
# )
|
||||||
|
# )
|
||||||
|
# log.info(f'DB `{dname}` up with conf:\n{conf}')
|
||||||
|
|
||||||
await trio.sleep_forever()
|
await trio.sleep_forever()
|
||||||
|
|
||||||
trio.run(main)
|
trio.run(main)
|
||||||
|
|
@ -307,10 +328,6 @@ def services(config, tl, ports):
|
||||||
if not ports:
|
if not ports:
|
||||||
ports = [_default_registry_port]
|
ports = [_default_registry_port]
|
||||||
|
|
||||||
addr = tractor._addr.wrap_address(
|
|
||||||
addr=(host, ports[0])
|
|
||||||
)
|
|
||||||
|
|
||||||
async def list_services():
|
async def list_services():
|
||||||
nonlocal host
|
nonlocal host
|
||||||
async with (
|
async with (
|
||||||
|
|
@ -319,17 +336,15 @@ def services(config, tl, ports):
|
||||||
loglevel=config['loglevel'] if tl else None,
|
loglevel=config['loglevel'] if tl else None,
|
||||||
),
|
),
|
||||||
tractor.get_registry(
|
tractor.get_registry(
|
||||||
addr=addr,
|
host=host,
|
||||||
|
port=ports[0]
|
||||||
) as portal
|
) as portal
|
||||||
):
|
):
|
||||||
registry = await portal.run_from_ns(
|
registry = await portal.run_from_ns('self', 'get_registry')
|
||||||
'self',
|
|
||||||
'get_registry',
|
|
||||||
)
|
|
||||||
json_d = {}
|
json_d = {}
|
||||||
for key, socket in registry.items():
|
for key, socket in registry.items():
|
||||||
json_d[key] = f'{socket}'
|
host, port = socket
|
||||||
|
json_d[key] = f'{host}:{port}'
|
||||||
click.echo(f"{colorize_json(json_d)}")
|
click.echo(f"{colorize_json(json_d)}")
|
||||||
|
|
||||||
trio.run(list_services)
|
trio.run(list_services)
|
||||||
|
|
|
||||||
|
|
@ -41,13 +41,10 @@ from .log import get_logger
|
||||||
log = get_logger('broker-config')
|
log = get_logger('broker-config')
|
||||||
|
|
||||||
|
|
||||||
# XXX NOTE: taken from `click`
|
# XXX NOTE: taken from ``click`` since apparently they have some
|
||||||
# |_https://github.com/pallets/click/blob/main/src/click/utils.py#L449
|
# super weirdness with sigint and sudo..no clue
|
||||||
#
|
# we're probably going to slowly just modify it to our own version over
|
||||||
# (since apparently they have some super weirdness with SIGINT and
|
# time..
|
||||||
# sudo.. no clue we're probably going to slowly just modify it to our
|
|
||||||
# own version over time..)
|
|
||||||
#
|
|
||||||
def get_app_dir(
|
def get_app_dir(
|
||||||
app_name: str,
|
app_name: str,
|
||||||
roaming: bool = True,
|
roaming: bool = True,
|
||||||
|
|
@ -107,15 +104,14 @@ def get_app_dir(
|
||||||
# `tractor`) with the testing dir and check for it whenever we
|
# `tractor`) with the testing dir and check for it whenever we
|
||||||
# detect `pytest` is being used (which it isn't under normal
|
# detect `pytest` is being used (which it isn't under normal
|
||||||
# operation).
|
# operation).
|
||||||
# if "pytest" in sys.modules:
|
if "pytest" in sys.modules:
|
||||||
# import tractor
|
import tractor
|
||||||
# actor = tractor.current_actor(err_on_no_runtime=False)
|
actor = tractor.current_actor(err_on_no_runtime=False)
|
||||||
# if actor: # runtime is up
|
if actor: # runtime is up
|
||||||
# rvs = tractor._state._runtime_vars
|
rvs = tractor._state._runtime_vars
|
||||||
# import pdbp; pdbp.set_trace()
|
testdirpath = Path(rvs['piker_vars']['piker_test_dir'])
|
||||||
# testdirpath = Path(rvs['piker_vars']['piker_test_dir'])
|
assert testdirpath.exists(), 'piker test harness might be borked!?'
|
||||||
# assert testdirpath.exists(), 'piker test harness might be borked!?'
|
app_name = str(testdirpath)
|
||||||
# app_name = str(testdirpath)
|
|
||||||
|
|
||||||
if platform.system() == 'Windows':
|
if platform.system() == 'Windows':
|
||||||
key = "APPDATA" if roaming else "LOCALAPPDATA"
|
key = "APPDATA" if roaming else "LOCALAPPDATA"
|
||||||
|
|
@ -264,7 +260,7 @@ def load(
|
||||||
MutableMapping,
|
MutableMapping,
|
||||||
] = tomllib.loads,
|
] = tomllib.loads,
|
||||||
|
|
||||||
touch_if_dne: bool = True,
|
touch_if_dne: bool = False,
|
||||||
|
|
||||||
**tomlkws,
|
**tomlkws,
|
||||||
|
|
||||||
|
|
@ -273,7 +269,7 @@ def load(
|
||||||
Load config file by name.
|
Load config file by name.
|
||||||
|
|
||||||
If desired config is not in the top level piker-user config path then
|
If desired config is not in the top level piker-user config path then
|
||||||
pass the `path: Path` explicitly.
|
pass the ``path: Path`` explicitly.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# create the $HOME/.config/piker dir if dne
|
# create the $HOME/.config/piker dir if dne
|
||||||
|
|
@ -288,8 +284,7 @@ def load(
|
||||||
|
|
||||||
if (
|
if (
|
||||||
not path.is_file()
|
not path.is_file()
|
||||||
and
|
and touch_if_dne
|
||||||
touch_if_dne
|
|
||||||
):
|
):
|
||||||
# only do a template if no path provided,
|
# only do a template if no path provided,
|
||||||
# just touch an empty file with same name.
|
# just touch an empty file with same name.
|
||||||
|
|
|
||||||
|
|
@ -25,10 +25,12 @@ from collections import (
|
||||||
defaultdict,
|
defaultdict,
|
||||||
)
|
)
|
||||||
from contextlib import asynccontextmanager as acm
|
from contextlib import asynccontextmanager as acm
|
||||||
|
from functools import partial
|
||||||
import time
|
import time
|
||||||
from typing import (
|
from typing import (
|
||||||
Any,
|
Any,
|
||||||
AsyncIterator,
|
AsyncIterator,
|
||||||
|
Callable,
|
||||||
TYPE_CHECKING,
|
TYPE_CHECKING,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -42,7 +44,7 @@ from tractor.trionics import (
|
||||||
maybe_open_nursery,
|
maybe_open_nursery,
|
||||||
)
|
)
|
||||||
import trio
|
import trio
|
||||||
from trio_typing import TaskStatus
|
from trio import TaskStatus
|
||||||
|
|
||||||
from .ticktools import (
|
from .ticktools import (
|
||||||
frame_ticks,
|
frame_ticks,
|
||||||
|
|
@ -53,6 +55,9 @@ from ._util import (
|
||||||
get_console_log,
|
get_console_log,
|
||||||
)
|
)
|
||||||
from ..service import maybe_spawn_daemon
|
from ..service import maybe_spawn_daemon
|
||||||
|
from piker.log import (
|
||||||
|
mk_repr,
|
||||||
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from ._sharedmem import (
|
from ._sharedmem import (
|
||||||
|
|
@ -70,6 +75,7 @@ if TYPE_CHECKING:
|
||||||
_default_delay_s: float = 1.0
|
_default_delay_s: float = 1.0
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: use new `tractor.singleton_acm` API for this!
|
||||||
class Sampler:
|
class Sampler:
|
||||||
'''
|
'''
|
||||||
Global sampling engine registry.
|
Global sampling engine registry.
|
||||||
|
|
@ -79,9 +85,9 @@ class Sampler:
|
||||||
|
|
||||||
This non-instantiated type is meant to be a singleton within
|
This non-instantiated type is meant to be a singleton within
|
||||||
a `samplerd` actor-service spawned once by the user wishing to
|
a `samplerd` actor-service spawned once by the user wishing to
|
||||||
time-step-sample (real-time) quote feeds, see
|
time-step-sample a (real-time) quote feeds, see
|
||||||
``.service.maybe_open_samplerd()`` and the below
|
`.service.maybe_open_samplerd()` and the below
|
||||||
``register_with_sampler()``.
|
`register_with_sampler()`.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
service_nursery: None | trio.Nursery = None
|
service_nursery: None | trio.Nursery = None
|
||||||
|
|
@ -95,12 +101,6 @@ class Sampler:
|
||||||
# history loading.
|
# history loading.
|
||||||
incr_task_cs: trio.CancelScope | None = None
|
incr_task_cs: trio.CancelScope | None = None
|
||||||
|
|
||||||
bcast_errors: tuple[Exception] = (
|
|
||||||
trio.BrokenResourceError,
|
|
||||||
trio.ClosedResourceError,
|
|
||||||
trio.EndOfChannel,
|
|
||||||
)
|
|
||||||
|
|
||||||
# holds all the ``tractor.Context`` remote subscriptions for
|
# holds all the ``tractor.Context`` remote subscriptions for
|
||||||
# a particular sample period increment event: all subscribers are
|
# a particular sample period increment event: all subscribers are
|
||||||
# notified on a step.
|
# notified on a step.
|
||||||
|
|
@ -264,15 +264,14 @@ class Sampler:
|
||||||
subs: set
|
subs: set
|
||||||
last_ts, subs = pair
|
last_ts, subs = pair
|
||||||
|
|
||||||
# NOTE, for debugging pub-sub issues
|
task = trio.lowlevel.current_task()
|
||||||
# task = trio.lowlevel.current_task()
|
log.debug(
|
||||||
# log.debug(
|
f'SUBS {self.subscribers}\n'
|
||||||
# f'AlL-SUBS@{period_s!r}: {self.subscribers}\n'
|
f'PAIR {pair}\n'
|
||||||
# f'PAIR: {pair}\n'
|
f'TASK: {task}: {id(task)}\n'
|
||||||
# f'TASK: {task}: {id(task)}\n'
|
f'broadcasting {period_s} -> {last_ts}\n'
|
||||||
# f'broadcasting {period_s} -> {last_ts}\n'
|
|
||||||
# f'consumers: {subs}'
|
# f'consumers: {subs}'
|
||||||
# )
|
)
|
||||||
borked: set[MsgStream] = set()
|
borked: set[MsgStream] = set()
|
||||||
sent: set[MsgStream] = set()
|
sent: set[MsgStream] = set()
|
||||||
while True:
|
while True:
|
||||||
|
|
@ -289,11 +288,12 @@ class Sampler:
|
||||||
await stream.send(msg)
|
await stream.send(msg)
|
||||||
sent.add(stream)
|
sent.add(stream)
|
||||||
|
|
||||||
except self.bcast_errors as err:
|
except (
|
||||||
|
trio.BrokenResourceError,
|
||||||
|
trio.ClosedResourceError
|
||||||
|
):
|
||||||
log.error(
|
log.error(
|
||||||
f'Connection dropped for IPC ctx\n'
|
f'{stream._ctx.chan.uid} dropped connection'
|
||||||
f'{stream._ctx}\n\n'
|
|
||||||
f'Due to {type(err)}'
|
|
||||||
)
|
)
|
||||||
borked.add(stream)
|
borked.add(stream)
|
||||||
else:
|
else:
|
||||||
|
|
@ -381,7 +381,10 @@ async def register_with_sampler(
|
||||||
assert Sampler.ohlcv_shms
|
assert Sampler.ohlcv_shms
|
||||||
|
|
||||||
# unblock caller
|
# unblock caller
|
||||||
await ctx.started(set(Sampler.ohlcv_shms.keys()))
|
await ctx.started(
|
||||||
|
# XXX bc msgpack only allows one array type!
|
||||||
|
list(Sampler.ohlcv_shms.keys())
|
||||||
|
)
|
||||||
|
|
||||||
if open_index_stream:
|
if open_index_stream:
|
||||||
try:
|
try:
|
||||||
|
|
@ -400,8 +403,7 @@ async def register_with_sampler(
|
||||||
finally:
|
finally:
|
||||||
if (
|
if (
|
||||||
sub_for_broadcasts
|
sub_for_broadcasts
|
||||||
and
|
and subs
|
||||||
subs
|
|
||||||
):
|
):
|
||||||
try:
|
try:
|
||||||
subs.remove(stream)
|
subs.remove(stream)
|
||||||
|
|
@ -426,7 +428,6 @@ async def register_with_sampler(
|
||||||
|
|
||||||
|
|
||||||
async def spawn_samplerd(
|
async def spawn_samplerd(
|
||||||
|
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
**extra_tractor_kwargs
|
**extra_tractor_kwargs
|
||||||
|
|
||||||
|
|
@ -436,7 +437,10 @@ async def spawn_samplerd(
|
||||||
update and increment count write and stream broadcasting.
|
update and increment count write and stream broadcasting.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from piker.service import Services
|
from piker.service import (
|
||||||
|
get_service_mngr,
|
||||||
|
ServiceMngr,
|
||||||
|
)
|
||||||
|
|
||||||
dname = 'samplerd'
|
dname = 'samplerd'
|
||||||
log.info(f'Spawning `{dname}`')
|
log.info(f'Spawning `{dname}`')
|
||||||
|
|
@ -444,26 +448,33 @@ async def spawn_samplerd(
|
||||||
# singleton lock creation of ``samplerd`` since we only ever want
|
# singleton lock creation of ``samplerd`` since we only ever want
|
||||||
# one daemon per ``pikerd`` proc tree.
|
# one daemon per ``pikerd`` proc tree.
|
||||||
# TODO: make this built-into the service api?
|
# TODO: make this built-into the service api?
|
||||||
async with Services.locks[dname + '_singleton']:
|
mngr: ServiceMngr = get_service_mngr()
|
||||||
|
already_started: bool = dname in mngr.service_tasks
|
||||||
|
|
||||||
if dname not in Services.service_tasks:
|
async with mngr._locks[dname + '_singleton']:
|
||||||
|
ctx: Context = await mngr.start_service(
|
||||||
|
daemon_name=dname,
|
||||||
|
ctx_ep=partial(
|
||||||
|
register_with_sampler,
|
||||||
|
period_s=1,
|
||||||
|
sub_for_broadcasts=False,
|
||||||
|
),
|
||||||
|
debug_mode=mngr.debug_mode, # set by pikerd flag
|
||||||
|
|
||||||
portal = await Services.actor_n.start_actor(
|
# proxy-through to tractor
|
||||||
dname,
|
|
||||||
enable_modules=[
|
enable_modules=[
|
||||||
'piker.data._sampling',
|
'piker.data._sampling',
|
||||||
],
|
],
|
||||||
loglevel=loglevel,
|
loglevel=loglevel,
|
||||||
debug_mode=Services.debug_mode, # set by pikerd flag
|
|
||||||
**extra_tractor_kwargs
|
**extra_tractor_kwargs
|
||||||
)
|
)
|
||||||
|
if not already_started:
|
||||||
await Services.start_service_task(
|
assert (
|
||||||
dname,
|
ctx
|
||||||
portal,
|
and
|
||||||
register_with_sampler,
|
ctx.portal
|
||||||
period_s=1,
|
and
|
||||||
sub_for_broadcasts=False,
|
not ctx.cancel_called
|
||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
@ -568,7 +579,7 @@ async def open_sample_stream(
|
||||||
|
|
||||||
|
|
||||||
async def sample_and_broadcast(
|
async def sample_and_broadcast(
|
||||||
bus: _FeedsBus,
|
bus: _FeedsBus, # noqa
|
||||||
rt_shm: ShmArray,
|
rt_shm: ShmArray,
|
||||||
hist_shm: ShmArray,
|
hist_shm: ShmArray,
|
||||||
quote_stream: trio.abc.ReceiveChannel,
|
quote_stream: trio.abc.ReceiveChannel,
|
||||||
|
|
@ -588,17 +599,12 @@ async def sample_and_broadcast(
|
||||||
|
|
||||||
overruns = Counter()
|
overruns = Counter()
|
||||||
|
|
||||||
# NOTE, only used for debugging live-data-feed issues, though
|
# multiline nested `dict` formatter (since rn quote-msgs are
|
||||||
# this should be resolved more correctly in the future using the
|
# just that).
|
||||||
# new typed-msgspec feats of `tractor`!
|
pfmt: Callable[[str], str] = mk_repr()
|
||||||
#
|
|
||||||
# XXX, a multiline nested `dict` formatter (since rn quote-msgs
|
|
||||||
# are just that).
|
|
||||||
# pfmt: Callable[[str], str] = mk_repr()
|
|
||||||
|
|
||||||
# iterate stream delivered by broker
|
# iterate stream delivered by broker
|
||||||
async for quotes in quote_stream:
|
async for quotes in quote_stream:
|
||||||
# print(quotes)
|
|
||||||
|
|
||||||
# XXX WARNING XXX only enable for debugging bc ow can cost
|
# XXX WARNING XXX only enable for debugging bc ow can cost
|
||||||
# ALOT of perf with HF-feedz!!!
|
# ALOT of perf with HF-feedz!!!
|
||||||
|
|
@ -608,13 +614,7 @@ async def sample_and_broadcast(
|
||||||
# f'{pfmt(quotes)}'
|
# f'{pfmt(quotes)}'
|
||||||
# )
|
# )
|
||||||
|
|
||||||
# TODO,
|
# TODO: `numba` this!
|
||||||
# -[ ] `numba` or `cython`-nize this loop possibly?
|
|
||||||
# |_alternatively could we do it in rust somehow by upacking
|
|
||||||
# arrow msgs instead of using `msgspec`?
|
|
||||||
# -[ ] use `msgspec.Struct` support in new typed-msging from
|
|
||||||
# `tractor` to ensure only allowed msgs are transmitted?
|
|
||||||
#
|
|
||||||
for broker_symbol, quote in quotes.items():
|
for broker_symbol, quote in quotes.items():
|
||||||
# TODO: in theory you can send the IPC msg *before* writing
|
# TODO: in theory you can send the IPC msg *before* writing
|
||||||
# to the sharedmem array to decrease latency, however, that
|
# to the sharedmem array to decrease latency, however, that
|
||||||
|
|
@ -687,20 +687,17 @@ async def sample_and_broadcast(
|
||||||
sub_key: str = broker_symbol.lower()
|
sub_key: str = broker_symbol.lower()
|
||||||
subs: set[Sub] = bus.get_subs(sub_key)
|
subs: set[Sub] = bus.get_subs(sub_key)
|
||||||
|
|
||||||
# TODO, figure out how to make this useful whilst
|
if not subs:
|
||||||
# incoporating feed "pausing" ..
|
all_bs_fqmes: list[str] = list(
|
||||||
#
|
bus._subscribers.keys()
|
||||||
# if not subs:
|
)
|
||||||
# all_bs_fqmes: list[str] = list(
|
log.warning(
|
||||||
# bus._subscribers.keys()
|
f'No subscribers for {brokername!r} live-quote ??\n'
|
||||||
# )
|
f'broker_symbol: {broker_symbol}\n\n'
|
||||||
# log.warning(
|
|
||||||
# f'No subscribers for {brokername!r} live-quote ??\n'
|
|
||||||
# f'broker_symbol: {broker_symbol}\n\n'
|
|
||||||
|
|
||||||
# f'Maybe the backend-sys symbol does not match one of,\n'
|
f'Maybe the backend-sys symbol does not match one of,\n'
|
||||||
# f'{pfmt(all_bs_fqmes)}\n'
|
f'{pfmt(all_bs_fqmes)}\n'
|
||||||
# )
|
)
|
||||||
|
|
||||||
# NOTE: by default the broker backend doesn't append
|
# NOTE: by default the broker backend doesn't append
|
||||||
# it's own "name" into the fqme schema (but maybe it
|
# it's own "name" into the fqme schema (but maybe it
|
||||||
|
|
@ -740,7 +737,7 @@ async def sample_and_broadcast(
|
||||||
|
|
||||||
log.warning(
|
log.warning(
|
||||||
f'Feed OVERRUN {sub_key}'
|
f'Feed OVERRUN {sub_key}'
|
||||||
f'@{bus.brokername} -> \n'
|
'@{bus.brokername} -> \n'
|
||||||
f'feed @ {chan.uid}\n'
|
f'feed @ {chan.uid}\n'
|
||||||
f'throttle = {throttle} Hz'
|
f'throttle = {throttle} Hz'
|
||||||
)
|
)
|
||||||
|
|
@ -771,14 +768,18 @@ async def sample_and_broadcast(
|
||||||
if lags > 10:
|
if lags > 10:
|
||||||
await tractor.pause()
|
await tractor.pause()
|
||||||
|
|
||||||
except Sampler.bcast_errors as ipc_err:
|
except (
|
||||||
|
trio.BrokenResourceError,
|
||||||
|
trio.ClosedResourceError,
|
||||||
|
trio.EndOfChannel,
|
||||||
|
):
|
||||||
ctx: Context = ipc._ctx
|
ctx: Context = ipc._ctx
|
||||||
chan: Channel = ctx.chan
|
chan: Channel = ctx.chan
|
||||||
if ctx:
|
if ctx:
|
||||||
log.warning(
|
log.warning(
|
||||||
f'Dropped `brokerd`-feed for {broker_symbol!r} due to,\n'
|
'Dropped `brokerd`-quotes-feed connection:\n'
|
||||||
f'x>) {ctx.cid}@{chan.uid}'
|
f'{broker_symbol}:'
|
||||||
f'|_{ipc_err!r}\n\n'
|
f'{ctx.cid}@{chan.uid}'
|
||||||
)
|
)
|
||||||
if sub.throttle_rate:
|
if sub.throttle_rate:
|
||||||
assert ipc._closed
|
assert ipc._closed
|
||||||
|
|
@ -795,11 +796,12 @@ async def sample_and_broadcast(
|
||||||
|
|
||||||
|
|
||||||
async def uniform_rate_send(
|
async def uniform_rate_send(
|
||||||
|
|
||||||
rate: float,
|
rate: float,
|
||||||
quote_stream: trio.abc.ReceiveChannel,
|
quote_stream: trio.abc.ReceiveChannel,
|
||||||
stream: MsgStream,
|
stream: MsgStream,
|
||||||
|
|
||||||
task_status: TaskStatus[None] = trio.TASK_STATUS_IGNORED,
|
task_status: TaskStatus = trio.TASK_STATUS_IGNORED,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
|
|
@ -817,16 +819,13 @@ async def uniform_rate_send(
|
||||||
https://gist.github.com/njsmith/7ea44ec07e901cb78ebe1dd8dd846cb9
|
https://gist.github.com/njsmith/7ea44ec07e901cb78ebe1dd8dd846cb9
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# ?TODO? dynamically compute the **actual** approx overhead latency per cycle
|
# TODO: compute the approx overhead latency per cycle
|
||||||
# instead of this magic # bidinezz?
|
left_to_sleep = throttle_period = 1/rate - 0.000616
|
||||||
throttle_period: float = 1/rate - 0.000616
|
|
||||||
left_to_sleep: float = throttle_period
|
|
||||||
|
|
||||||
# send cycle state
|
# send cycle state
|
||||||
first_quote: dict|None
|
|
||||||
first_quote = last_quote = None
|
first_quote = last_quote = None
|
||||||
last_send: float = time.time()
|
last_send = time.time()
|
||||||
diff: float = 0
|
diff = 0
|
||||||
|
|
||||||
task_status.started()
|
task_status.started()
|
||||||
ticks_by_type: dict[
|
ticks_by_type: dict[
|
||||||
|
|
@ -837,28 +836,22 @@ async def uniform_rate_send(
|
||||||
clear_types = _tick_groups['clears']
|
clear_types = _tick_groups['clears']
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
|
|
||||||
# compute the remaining time to sleep for this throttled cycle
|
# compute the remaining time to sleep for this throttled cycle
|
||||||
left_to_sleep: float = throttle_period - diff
|
left_to_sleep = throttle_period - diff
|
||||||
|
|
||||||
if left_to_sleep > 0:
|
if left_to_sleep > 0:
|
||||||
cs: trio.CancelScope
|
|
||||||
with trio.move_on_after(left_to_sleep) as cs:
|
with trio.move_on_after(left_to_sleep) as cs:
|
||||||
sym: str
|
|
||||||
last_quote: dict
|
|
||||||
try:
|
try:
|
||||||
sym, last_quote = await quote_stream.receive()
|
sym, last_quote = await quote_stream.receive()
|
||||||
except trio.EndOfChannel:
|
except trio.EndOfChannel:
|
||||||
log.exception(
|
log.exception(f"feed for {stream} ended?")
|
||||||
f'Live stream for feed for ended?\n'
|
|
||||||
f'<=c\n'
|
|
||||||
f' |_[{stream!r}\n'
|
|
||||||
)
|
|
||||||
break
|
break
|
||||||
|
|
||||||
diff: float = time.time() - last_send
|
diff = time.time() - last_send
|
||||||
|
|
||||||
if not first_quote:
|
if not first_quote:
|
||||||
first_quote: float = last_quote
|
first_quote = last_quote
|
||||||
# first_quote['tbt'] = ticks_by_type
|
# first_quote['tbt'] = ticks_by_type
|
||||||
|
|
||||||
if (throttle_period - diff) > 0:
|
if (throttle_period - diff) > 0:
|
||||||
|
|
@ -919,9 +912,7 @@ async def uniform_rate_send(
|
||||||
# TODO: now if only we could sync this to the display
|
# TODO: now if only we could sync this to the display
|
||||||
# rate timing exactly lul
|
# rate timing exactly lul
|
||||||
try:
|
try:
|
||||||
await stream.send({
|
await stream.send({sym: first_quote})
|
||||||
sym: first_quote
|
|
||||||
})
|
|
||||||
except tractor.RemoteActorError as rme:
|
except tractor.RemoteActorError as rme:
|
||||||
if rme.type is not tractor._exceptions.StreamOverrun:
|
if rme.type is not tractor._exceptions.StreamOverrun:
|
||||||
raise
|
raise
|
||||||
|
|
@ -932,28 +923,20 @@ async def uniform_rate_send(
|
||||||
f'{sym}:{ctx.cid}@{chan.uid}'
|
f'{sym}:{ctx.cid}@{chan.uid}'
|
||||||
)
|
)
|
||||||
|
|
||||||
# NOTE: any of these can be raised by `tractor`'s IPC
|
except (
|
||||||
|
# NOTE: any of these can be raised by ``tractor``'s IPC
|
||||||
# transport-layer and we want to be highly resilient
|
# transport-layer and we want to be highly resilient
|
||||||
# to consumers which crash or lose network connection.
|
# to consumers which crash or lose network connection.
|
||||||
# I.e. we **DO NOT** want to crash and propagate up to
|
# I.e. we **DO NOT** want to crash and propagate up to
|
||||||
# ``pikerd`` these kinds of errors!
|
# ``pikerd`` these kinds of errors!
|
||||||
except (
|
trio.EndOfChannel,
|
||||||
|
trio.ClosedResourceError,
|
||||||
|
trio.BrokenResourceError,
|
||||||
ConnectionResetError,
|
ConnectionResetError,
|
||||||
) + Sampler.bcast_errors as ipc_err:
|
):
|
||||||
match ipc_err:
|
|
||||||
case trio.EndOfChannel():
|
|
||||||
log.info(
|
|
||||||
f'{stream} terminated by peer,\n'
|
|
||||||
f'{ipc_err!r}'
|
|
||||||
)
|
|
||||||
case _:
|
|
||||||
# if the feed consumer goes down then drop
|
# if the feed consumer goes down then drop
|
||||||
# out of this rate limiter
|
# out of this rate limiter
|
||||||
log.warning(
|
log.warning(f'{stream} closed')
|
||||||
f'{stream} closed due to,\n'
|
|
||||||
f'{ipc_err!r}'
|
|
||||||
)
|
|
||||||
|
|
||||||
await stream.aclose()
|
await stream.aclose()
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,6 @@ from pathlib import Path
|
||||||
from pprint import pformat
|
from pprint import pformat
|
||||||
from typing import (
|
from typing import (
|
||||||
Any,
|
Any,
|
||||||
Callable,
|
|
||||||
Sequence,
|
Sequence,
|
||||||
Hashable,
|
Hashable,
|
||||||
TYPE_CHECKING,
|
TYPE_CHECKING,
|
||||||
|
|
@ -57,7 +56,7 @@ from piker.brokers import (
|
||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from piker.accounting import (
|
from ..accounting import (
|
||||||
Asset,
|
Asset,
|
||||||
MktPair,
|
MktPair,
|
||||||
)
|
)
|
||||||
|
|
@ -91,18 +90,6 @@ class SymbologyCache(Struct):
|
||||||
# provided by the backend pkg.
|
# provided by the backend pkg.
|
||||||
mktmaps: dict[str, MktPair] = field(default_factory=dict)
|
mktmaps: dict[str, MktPair] = field(default_factory=dict)
|
||||||
|
|
||||||
def pformat(self) -> str:
|
|
||||||
return (
|
|
||||||
f'<{type(self).__name__}(\n'
|
|
||||||
f' .mod: {self.mod!r}\n'
|
|
||||||
f' .assets: {len(self.assets)!r}\n'
|
|
||||||
f' .pairs: {len(self.pairs)!r}\n'
|
|
||||||
f' .mktmaps: {len(self.mktmaps)!r}\n'
|
|
||||||
f')>'
|
|
||||||
)
|
|
||||||
|
|
||||||
__repr__ = pformat
|
|
||||||
|
|
||||||
def write_config(self) -> None:
|
def write_config(self) -> None:
|
||||||
|
|
||||||
# put the backend's pair-struct type ref at the top
|
# put the backend's pair-struct type ref at the top
|
||||||
|
|
@ -162,36 +149,19 @@ class SymbologyCache(Struct):
|
||||||
'Implement `Client.get_assets()`!'
|
'Implement `Client.get_assets()`!'
|
||||||
)
|
)
|
||||||
|
|
||||||
get_mkt_pairs: Callable|None = getattr(
|
if get_mkt_pairs := getattr(client, 'get_mkt_pairs', None):
|
||||||
client,
|
|
||||||
'get_mkt_pairs',
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
if not get_mkt_pairs:
|
|
||||||
log.warning(
|
|
||||||
'No symbology cache `Pair` support for `{provider}`..\n'
|
|
||||||
'Implement `Client.get_mkt_pairs()`!'
|
|
||||||
)
|
|
||||||
return self
|
|
||||||
|
|
||||||
pairs: dict[str, Struct] = await get_mkt_pairs()
|
pairs: dict[str, Struct] = await get_mkt_pairs()
|
||||||
if not pairs:
|
|
||||||
log.warning(
|
|
||||||
'No pairs from intial {provider!r} sym-cache request?\n\n'
|
|
||||||
'`Client.get_mkt_pairs()` -> {pairs!r} ?'
|
|
||||||
)
|
|
||||||
return self
|
|
||||||
|
|
||||||
for bs_fqme, pair in pairs.items():
|
for bs_fqme, pair in pairs.items():
|
||||||
|
|
||||||
|
# NOTE: every backend defined pair should
|
||||||
|
# declare it's ns path for roundtrip
|
||||||
|
# serialization lookup.
|
||||||
if not getattr(pair, 'ns_path', None):
|
if not getattr(pair, 'ns_path', None):
|
||||||
# XXX: every backend defined pair must declare
|
|
||||||
# a `.ns_path: tractor.NamespacePath` to enable
|
|
||||||
# roundtrip serialization lookup from a local
|
|
||||||
# cache file.
|
|
||||||
raise TypeError(
|
raise TypeError(
|
||||||
f'Pair-struct for {self.mod.name} MUST define a '
|
f'Pair-struct for {self.mod.name} MUST define a '
|
||||||
'`.ns_path: str`!\n\n'
|
'`.ns_path: str`!\n'
|
||||||
f'{pair!r}'
|
f'{pair}'
|
||||||
)
|
)
|
||||||
|
|
||||||
entry = await self.mod.get_mkt_info(pair.bs_fqme)
|
entry = await self.mod.get_mkt_info(pair.bs_fqme)
|
||||||
|
|
@ -225,6 +195,12 @@ class SymbologyCache(Struct):
|
||||||
pair,
|
pair,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
else:
|
||||||
|
log.warning(
|
||||||
|
'No symbology cache `Pair` support for `{provider}`..\n'
|
||||||
|
'Implement `Client.get_mkt_pairs()`!'
|
||||||
|
)
|
||||||
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ from functools import partial
|
||||||
from types import ModuleType
|
from types import ModuleType
|
||||||
from typing import (
|
from typing import (
|
||||||
Any,
|
Any,
|
||||||
|
Optional,
|
||||||
Callable,
|
Callable,
|
||||||
AsyncContextManager,
|
AsyncContextManager,
|
||||||
AsyncGenerator,
|
AsyncGenerator,
|
||||||
|
|
@ -34,7 +35,6 @@ from typing import (
|
||||||
)
|
)
|
||||||
import json
|
import json
|
||||||
|
|
||||||
import tractor
|
|
||||||
import trio
|
import trio
|
||||||
from trio_typing import TaskStatus
|
from trio_typing import TaskStatus
|
||||||
from trio_websocket import (
|
from trio_websocket import (
|
||||||
|
|
@ -167,7 +167,7 @@ async def _reconnect_forever(
|
||||||
|
|
||||||
async def proxy_msgs(
|
async def proxy_msgs(
|
||||||
ws: WebSocketConnection,
|
ws: WebSocketConnection,
|
||||||
rent_cs: trio.CancelScope, # parent cancel scope
|
pcs: trio.CancelScope, # parent cancel scope
|
||||||
):
|
):
|
||||||
'''
|
'''
|
||||||
Receive (under `timeout` deadline) all msgs from from underlying
|
Receive (under `timeout` deadline) all msgs from from underlying
|
||||||
|
|
@ -192,7 +192,7 @@ async def _reconnect_forever(
|
||||||
f'{url} connection bail with:'
|
f'{url} connection bail with:'
|
||||||
)
|
)
|
||||||
await trio.sleep(0.5)
|
await trio.sleep(0.5)
|
||||||
rent_cs.cancel()
|
pcs.cancel()
|
||||||
|
|
||||||
# go back to reonnect loop in parent task
|
# go back to reonnect loop in parent task
|
||||||
return
|
return
|
||||||
|
|
@ -204,7 +204,7 @@ async def _reconnect_forever(
|
||||||
f'{src_mod}\n'
|
f'{src_mod}\n'
|
||||||
'WS feed seems down and slow af.. reconnecting\n'
|
'WS feed seems down and slow af.. reconnecting\n'
|
||||||
)
|
)
|
||||||
rent_cs.cancel()
|
pcs.cancel()
|
||||||
|
|
||||||
# go back to reonnect loop in parent task
|
# go back to reonnect loop in parent task
|
||||||
return
|
return
|
||||||
|
|
@ -228,12 +228,7 @@ async def _reconnect_forever(
|
||||||
nobsws._connected = trio.Event()
|
nobsws._connected = trio.Event()
|
||||||
task_status.started()
|
task_status.started()
|
||||||
|
|
||||||
mc_state: trio._channel.MemoryChannelState = snd._state
|
while not snd._closed:
|
||||||
while (
|
|
||||||
mc_state.open_receive_channels > 0
|
|
||||||
and
|
|
||||||
mc_state.open_send_channels > 0
|
|
||||||
):
|
|
||||||
log.info(
|
log.info(
|
||||||
f'{src_mod}\n'
|
f'{src_mod}\n'
|
||||||
f'{url} trying (RE)CONNECT'
|
f'{url} trying (RE)CONNECT'
|
||||||
|
|
@ -242,11 +237,10 @@ async def _reconnect_forever(
|
||||||
ws: WebSocketConnection
|
ws: WebSocketConnection
|
||||||
try:
|
try:
|
||||||
async with (
|
async with (
|
||||||
|
trio.open_nursery() as n,
|
||||||
open_websocket_url(url) as ws,
|
open_websocket_url(url) as ws,
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn,
|
|
||||||
):
|
):
|
||||||
cs = nobsws._cs = tn.cancel_scope
|
cs = nobsws._cs = n.cancel_scope
|
||||||
nobsws._ws = ws
|
nobsws._ws = ws
|
||||||
log.info(
|
log.info(
|
||||||
f'{src_mod}\n'
|
f'{src_mod}\n'
|
||||||
|
|
@ -254,7 +248,7 @@ async def _reconnect_forever(
|
||||||
)
|
)
|
||||||
|
|
||||||
# begin relay loop to forward msgs
|
# begin relay loop to forward msgs
|
||||||
tn.start_soon(
|
n.start_soon(
|
||||||
proxy_msgs,
|
proxy_msgs,
|
||||||
ws,
|
ws,
|
||||||
cs,
|
cs,
|
||||||
|
|
@ -268,7 +262,7 @@ async def _reconnect_forever(
|
||||||
|
|
||||||
# TODO: should we return an explicit sub-cs
|
# TODO: should we return an explicit sub-cs
|
||||||
# from this fixture task?
|
# from this fixture task?
|
||||||
await tn.start(
|
await n.start(
|
||||||
open_fixture,
|
open_fixture,
|
||||||
fixture,
|
fixture,
|
||||||
nobsws,
|
nobsws,
|
||||||
|
|
@ -278,23 +272,11 @@ async def _reconnect_forever(
|
||||||
# to let tasks run **inside** the ws open block above.
|
# to let tasks run **inside** the ws open block above.
|
||||||
nobsws._connected.set()
|
nobsws._connected.set()
|
||||||
await trio.sleep_forever()
|
await trio.sleep_forever()
|
||||||
|
except HandshakeError:
|
||||||
except (
|
|
||||||
HandshakeError,
|
|
||||||
ConnectionRejected,
|
|
||||||
):
|
|
||||||
log.exception('Retrying connection')
|
log.exception('Retrying connection')
|
||||||
await trio.sleep(0.5) # throttle
|
|
||||||
|
|
||||||
except BaseException as _berr:
|
# ws & nursery block ends
|
||||||
berr = _berr
|
|
||||||
log.exception(
|
|
||||||
'Reconnect-attempt failed ??\n'
|
|
||||||
)
|
|
||||||
await trio.sleep(0.2) # throttle
|
|
||||||
raise berr
|
|
||||||
|
|
||||||
#|_ws & nursery block ends
|
|
||||||
nobsws._connected = trio.Event()
|
nobsws._connected = trio.Event()
|
||||||
if cs.cancelled_caught:
|
if cs.cancelled_caught:
|
||||||
log.cancel(
|
log.cancel(
|
||||||
|
|
@ -342,25 +324,21 @@ async def open_autorecon_ws(
|
||||||
connetivity errors, or some user defined recv timeout.
|
connetivity errors, or some user defined recv timeout.
|
||||||
|
|
||||||
You can provide a ``fixture`` async-context-manager which will be
|
You can provide a ``fixture`` async-context-manager which will be
|
||||||
entered/exitted around each connection reset; eg. for
|
entered/exitted around each connection reset; eg. for (re)requesting
|
||||||
(re)requesting subscriptions without requiring streaming setup
|
subscriptions without requiring streaming setup code to rerun.
|
||||||
code to rerun.
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
snd: trio.MemorySendChannel
|
snd: trio.MemorySendChannel
|
||||||
rcv: trio.MemoryReceiveChannel
|
rcv: trio.MemoryReceiveChannel
|
||||||
snd, rcv = trio.open_memory_channel(616)
|
snd, rcv = trio.open_memory_channel(616)
|
||||||
|
|
||||||
async with (
|
async with trio.open_nursery() as n:
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn
|
|
||||||
):
|
|
||||||
nobsws = NoBsWs(
|
nobsws = NoBsWs(
|
||||||
url,
|
url,
|
||||||
rcv,
|
rcv,
|
||||||
msg_recv_timeout=msg_recv_timeout,
|
msg_recv_timeout=msg_recv_timeout,
|
||||||
)
|
)
|
||||||
await tn.start(
|
await n.start(
|
||||||
partial(
|
partial(
|
||||||
_reconnect_forever,
|
_reconnect_forever,
|
||||||
url,
|
url,
|
||||||
|
|
@ -373,10 +351,11 @@ async def open_autorecon_ws(
|
||||||
await nobsws._connected.wait()
|
await nobsws._connected.wait()
|
||||||
assert nobsws._cs
|
assert nobsws._cs
|
||||||
assert nobsws.connected()
|
assert nobsws.connected()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
yield nobsws
|
yield nobsws
|
||||||
finally:
|
finally:
|
||||||
tn.cancel_scope.cancel()
|
n.cancel_scope.cancel()
|
||||||
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
|
@ -389,8 +368,8 @@ of msgs over a `NoBsWs`.
|
||||||
class JSONRPCResult(Struct):
|
class JSONRPCResult(Struct):
|
||||||
id: int
|
id: int
|
||||||
jsonrpc: str = '2.0'
|
jsonrpc: str = '2.0'
|
||||||
result: dict|None = None
|
result: Optional[dict] = None
|
||||||
error: dict|None = None
|
error: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
|
|
@ -408,22 +387,17 @@ async def open_jsonrpc_session(
|
||||||
# broken and never restored with wtv init sequence is required to
|
# broken and never restored with wtv init sequence is required to
|
||||||
# re-establish a working req-resp session.
|
# re-establish a working req-resp session.
|
||||||
|
|
||||||
|
# request_type: Optional[type] = None,
|
||||||
|
# request_hook: Optional[Callable] = None,
|
||||||
|
# error_hook: Optional[Callable] = None,
|
||||||
) -> Callable[[str, dict], dict]:
|
) -> Callable[[str, dict], dict]:
|
||||||
'''
|
|
||||||
Init a json-RPC-over-websocket connection to the provided `url`.
|
|
||||||
|
|
||||||
A `json_rpc: Callable[[str, dict], dict` is delivered to the
|
|
||||||
caller for sending requests and a bg-`trio.Task` handles
|
|
||||||
processing of response msgs including error reporting/raising in
|
|
||||||
the parent/caller task.
|
|
||||||
|
|
||||||
'''
|
|
||||||
# NOTE, store all request msgs so we can raise errors on the
|
# NOTE, store all request msgs so we can raise errors on the
|
||||||
# caller side!
|
# caller side!
|
||||||
req_msgs: dict[int, dict] = {}
|
req_msgs: dict[int, dict] = {}
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as n,
|
||||||
open_autorecon_ws(
|
open_autorecon_ws(
|
||||||
url=url,
|
url=url,
|
||||||
msg_recv_timeout=msg_recv_timeout,
|
msg_recv_timeout=msg_recv_timeout,
|
||||||
|
|
@ -512,10 +486,15 @@ async def open_jsonrpc_session(
|
||||||
'params': _,
|
'params': _,
|
||||||
}:
|
}:
|
||||||
log.debug(f'Recieved\n{msg}')
|
log.debug(f'Recieved\n{msg}')
|
||||||
|
# if request_hook:
|
||||||
|
# await request_hook(request_type(**msg))
|
||||||
|
|
||||||
case {
|
case {
|
||||||
'error': error
|
'error': error
|
||||||
}:
|
}:
|
||||||
|
# if error_hook:
|
||||||
|
# await error_hook(response_type(**msg))
|
||||||
|
|
||||||
# retreive orig request msg, set error
|
# retreive orig request msg, set error
|
||||||
# response in original "result" msg,
|
# response in original "result" msg,
|
||||||
# THEN FINALLY set the event to signal caller
|
# THEN FINALLY set the event to signal caller
|
||||||
|
|
@ -534,6 +513,6 @@ async def open_jsonrpc_session(
|
||||||
case _:
|
case _:
|
||||||
log.warning(f'Unhandled JSON-RPC msg!?\n{msg}')
|
log.warning(f'Unhandled JSON-RPC msg!?\n{msg}')
|
||||||
|
|
||||||
tn.start_soon(recv_task)
|
n.start_soon(recv_task)
|
||||||
yield json_rpc
|
yield json_rpc
|
||||||
tn.cancel_scope.cancel()
|
n.cancel_scope.cancel()
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,6 @@ from typing import (
|
||||||
AsyncContextManager,
|
AsyncContextManager,
|
||||||
Awaitable,
|
Awaitable,
|
||||||
Sequence,
|
Sequence,
|
||||||
TYPE_CHECKING,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
import trio
|
import trio
|
||||||
|
|
@ -76,10 +75,6 @@ from ._sampling import (
|
||||||
uniform_rate_send,
|
uniform_rate_send,
|
||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from tractor._addr import Address
|
|
||||||
from tractor.msg.types import Aid
|
|
||||||
|
|
||||||
|
|
||||||
class Sub(Struct, frozen=True):
|
class Sub(Struct, frozen=True):
|
||||||
'''
|
'''
|
||||||
|
|
@ -357,9 +352,7 @@ async def allocate_persistent_feed(
|
||||||
|
|
||||||
# yield back control to starting nursery once we receive either
|
# yield back control to starting nursery once we receive either
|
||||||
# some history or a real-time quote.
|
# some history or a real-time quote.
|
||||||
log.info(
|
log.info(f'loading OHLCV history: {fqme}')
|
||||||
f'loading OHLCV history: {fqme!r}\n'
|
|
||||||
)
|
|
||||||
await some_data_ready.wait()
|
await some_data_ready.wait()
|
||||||
|
|
||||||
flume = Flume(
|
flume = Flume(
|
||||||
|
|
@ -547,7 +540,10 @@ async def open_feed_bus(
|
||||||
# subscription since the backend isn't (yet) expected to
|
# subscription since the backend isn't (yet) expected to
|
||||||
# append it's own name to the fqme, so we filter on keys
|
# append it's own name to the fqme, so we filter on keys
|
||||||
# which *do not* include that name (e.g .ib) .
|
# which *do not* include that name (e.g .ib) .
|
||||||
bus._subscribers.setdefault(bs_fqme, set())
|
bus._subscribers.setdefault(
|
||||||
|
bs_fqme,
|
||||||
|
set(),
|
||||||
|
)
|
||||||
|
|
||||||
# sync feed subscribers with flume handles
|
# sync feed subscribers with flume handles
|
||||||
await ctx.started(
|
await ctx.started(
|
||||||
|
|
@ -730,10 +726,7 @@ class Feed(Struct):
|
||||||
async for msg in stream:
|
async for msg in stream:
|
||||||
await tx.send(msg)
|
await tx.send(msg)
|
||||||
|
|
||||||
async with (
|
async with trio.open_nursery() as nurse:
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as nurse
|
|
||||||
):
|
|
||||||
# spawn a relay task for each stream so that they all
|
# spawn a relay task for each stream so that they all
|
||||||
# multiplex to a common channel.
|
# multiplex to a common channel.
|
||||||
for brokername in mods:
|
for brokername in mods:
|
||||||
|
|
@ -796,6 +789,7 @@ async def install_brokerd_search(
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def maybe_open_feed(
|
async def maybe_open_feed(
|
||||||
|
|
||||||
fqmes: list[str],
|
fqmes: list[str],
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
|
|
||||||
|
|
@ -849,6 +843,7 @@ async def maybe_open_feed(
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def open_feed(
|
async def open_feed(
|
||||||
|
|
||||||
fqmes: list[str],
|
fqmes: list[str],
|
||||||
|
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
|
|
@ -907,19 +902,19 @@ async def open_feed(
|
||||||
feed.portals[brokermod] = portal
|
feed.portals[brokermod] = portal
|
||||||
|
|
||||||
# fill out "status info" that the UI can show
|
# fill out "status info" that the UI can show
|
||||||
chan: tractor.Channel = portal.chan
|
host, port = portal.channel.raddr
|
||||||
raddr: Address = chan.raddr
|
if host == '127.0.0.1':
|
||||||
aid: Aid = chan.aid
|
host = 'localhost'
|
||||||
# TAG_feed_status_update
|
|
||||||
feed.status.update({
|
feed.status.update({
|
||||||
'actor_id': aid,
|
'actor_name': portal.channel.uid[0],
|
||||||
'actor_short_id': f'{aid.name}@{aid.pid}',
|
'host': host,
|
||||||
'ipc': chan.raddr.proto_key,
|
'port': port,
|
||||||
'ipc_addr': raddr,
|
|
||||||
'hist_shm': 'NA',
|
'hist_shm': 'NA',
|
||||||
'rt_shm': 'NA',
|
'rt_shm': 'NA',
|
||||||
'throttle_hz': tick_throttle,
|
'throttle_rate': tick_throttle,
|
||||||
})
|
})
|
||||||
|
# feed.status.update(init_msg.pop('status', {}))
|
||||||
|
|
||||||
# (allocate and) connect to any feed bus for this broker
|
# (allocate and) connect to any feed bus for this broker
|
||||||
bus_ctxs.append(
|
bus_ctxs.append(
|
||||||
|
|
|
||||||
|
|
@ -36,10 +36,10 @@ from ._sharedmem import (
|
||||||
ShmArray,
|
ShmArray,
|
||||||
_Token,
|
_Token,
|
||||||
)
|
)
|
||||||
from piker.accounting import MktPair
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from piker.data.feed import Feed
|
from ..accounting import MktPair
|
||||||
|
from .feed import Feed
|
||||||
|
|
||||||
|
|
||||||
class Flume(Struct):
|
class Flume(Struct):
|
||||||
|
|
|
||||||
|
|
@ -113,9 +113,9 @@ def validate_backend(
|
||||||
)
|
)
|
||||||
if ep is None:
|
if ep is None:
|
||||||
log.warning(
|
log.warning(
|
||||||
f'Provider backend {mod.name!r} is missing '
|
f'Provider backend {mod.name} is missing '
|
||||||
f'{daemon_name!r} support?\n'
|
f'{daemon_name} support :(\n'
|
||||||
f'|_module endpoint-func missing: {name!r}\n'
|
f'The following endpoint is missing: {name}'
|
||||||
)
|
)
|
||||||
|
|
||||||
inits: list[
|
inits: list[
|
||||||
|
|
|
||||||
|
|
@ -498,7 +498,6 @@ async def cascade(
|
||||||
|
|
||||||
func_name: str = func.__name__
|
func_name: str = func.__name__
|
||||||
async with (
|
async with (
|
||||||
tractor.trionics.collapse_eg(), # avoid multi-taskc tb in console
|
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
):
|
):
|
||||||
# TODO: might be better to just make a "restart" method where
|
# TODO: might be better to just make a "restart" method where
|
||||||
|
|
|
||||||
|
|
@ -18,8 +18,8 @@
|
||||||
Log like a forester!
|
Log like a forester!
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import json
|
|
||||||
import reprlib
|
import reprlib
|
||||||
|
import json
|
||||||
from typing import (
|
from typing import (
|
||||||
Callable,
|
Callable,
|
||||||
)
|
)
|
||||||
|
|
@ -90,8 +90,6 @@ def colorize_json(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# TODO, eventually defer to the version in `modden` once
|
|
||||||
# it becomes a dep!
|
|
||||||
def mk_repr(
|
def mk_repr(
|
||||||
**repr_kws,
|
**repr_kws,
|
||||||
) -> Callable[[str], str]:
|
) -> Callable[[str], str]:
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,11 @@ Actor runtime primtives and (distributed) service APIs for,
|
||||||
=> TODO: maybe to (re)move elsewhere?
|
=> TODO: maybe to (re)move elsewhere?
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from ._mngr import Services as Services
|
from ._mngr import (
|
||||||
|
get_service_mngr as get_service_mngr,
|
||||||
|
open_service_mngr as open_service_mngr,
|
||||||
|
ServiceMngr as ServiceMngr,
|
||||||
|
)
|
||||||
from ._registry import (
|
from ._registry import (
|
||||||
_tractor_kwargs as _tractor_kwargs,
|
_tractor_kwargs as _tractor_kwargs,
|
||||||
_default_reg_addr as _default_reg_addr,
|
_default_reg_addr as _default_reg_addr,
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,6 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
from typing import (
|
from typing import (
|
||||||
Optional,
|
|
||||||
Any,
|
Any,
|
||||||
ClassVar,
|
ClassVar,
|
||||||
)
|
)
|
||||||
|
|
@ -30,13 +29,13 @@ from contextlib import (
|
||||||
)
|
)
|
||||||
|
|
||||||
import tractor
|
import tractor
|
||||||
import trio
|
|
||||||
|
|
||||||
from ._util import (
|
from ._util import (
|
||||||
get_console_log,
|
get_console_log,
|
||||||
)
|
)
|
||||||
from ._mngr import (
|
from ._mngr import (
|
||||||
Services,
|
open_service_mngr,
|
||||||
|
ServiceMngr,
|
||||||
)
|
)
|
||||||
from ._registry import ( # noqa
|
from ._registry import ( # noqa
|
||||||
_tractor_kwargs,
|
_tractor_kwargs,
|
||||||
|
|
@ -59,7 +58,7 @@ async def open_piker_runtime(
|
||||||
registry_addrs: list[tuple[str, int]] = [],
|
registry_addrs: list[tuple[str, int]] = [],
|
||||||
|
|
||||||
enable_modules: list[str] = [],
|
enable_modules: list[str] = [],
|
||||||
loglevel: Optional[str] = None,
|
loglevel: str|None = None,
|
||||||
|
|
||||||
# XXX NOTE XXX: you should pretty much never want debug mode
|
# XXX NOTE XXX: you should pretty much never want debug mode
|
||||||
# for data daemons when running in production.
|
# for data daemons when running in production.
|
||||||
|
|
@ -107,22 +106,21 @@ async def open_piker_runtime(
|
||||||
async with (
|
async with (
|
||||||
tractor.open_root_actor(
|
tractor.open_root_actor(
|
||||||
|
|
||||||
# passed through to `open_root_actor`
|
# passed through to ``open_root_actor``
|
||||||
registry_addrs=registry_addrs,
|
registry_addrs=registry_addrs,
|
||||||
name=name,
|
name=name,
|
||||||
start_method=start_method,
|
|
||||||
loglevel=loglevel,
|
loglevel=loglevel,
|
||||||
debug_mode=debug_mode,
|
debug_mode=debug_mode,
|
||||||
|
start_method=start_method,
|
||||||
# XXX NOTE MEMBER DAT der's a perf hit yo!!
|
|
||||||
# https://greenback.readthedocs.io/en/latest/principle.html#performance
|
|
||||||
maybe_enable_greenback=True,
|
|
||||||
|
|
||||||
# TODO: eventually we should be able to avoid
|
# TODO: eventually we should be able to avoid
|
||||||
# having the root have more then permissions to
|
# having the root have more then permissions to
|
||||||
# spawn other specialized daemons I think?
|
# spawn other specialized daemons I think?
|
||||||
enable_modules=enable_modules,
|
enable_modules=enable_modules,
|
||||||
hide_tb=False,
|
|
||||||
|
# TODO: how to configure this?
|
||||||
|
# keep it on by default if debug mode is set?
|
||||||
|
# maybe_enable_greenback=debug_mode,
|
||||||
|
|
||||||
**tractor_kwargs,
|
**tractor_kwargs,
|
||||||
) as actor,
|
) as actor,
|
||||||
|
|
@ -172,12 +170,13 @@ async def open_pikerd(
|
||||||
|
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
|
||||||
) -> Services:
|
) -> ServiceMngr:
|
||||||
'''
|
'''
|
||||||
Start a root piker daemon with an indefinite lifetime.
|
Start a root piker daemon actor (aka `pikerd`) with an indefinite
|
||||||
|
lifetime.
|
||||||
|
|
||||||
A root actor nursery is created which can be used to create and keep
|
A root actor-nursery is created which can be used to spawn and
|
||||||
alive underling services (see below).
|
supervise underling service sub-actors (see below).
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# NOTE: for the root daemon we always enable the root
|
# NOTE: for the root daemon we always enable the root
|
||||||
|
|
@ -204,9 +203,6 @@ async def open_pikerd(
|
||||||
root_actor,
|
root_actor,
|
||||||
reg_addrs,
|
reg_addrs,
|
||||||
),
|
),
|
||||||
tractor.open_nursery() as actor_nursery,
|
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as service_tn,
|
|
||||||
):
|
):
|
||||||
for addr in reg_addrs:
|
for addr in reg_addrs:
|
||||||
if addr not in root_actor.accept_addrs:
|
if addr not in root_actor.accept_addrs:
|
||||||
|
|
@ -215,25 +211,17 @@ async def open_pikerd(
|
||||||
'Maybe you have another daemon already running?'
|
'Maybe you have another daemon already running?'
|
||||||
)
|
)
|
||||||
|
|
||||||
# assign globally for future daemon/task creation
|
mngr: ServiceMngr
|
||||||
Services.actor_n = actor_nursery
|
async with open_service_mngr(
|
||||||
Services.service_n = service_tn
|
debug_mode=debug_mode,
|
||||||
Services.debug_mode = debug_mode
|
) as mngr:
|
||||||
|
yield mngr
|
||||||
try:
|
|
||||||
yield Services
|
|
||||||
|
|
||||||
finally:
|
|
||||||
# TODO: is this more clever/efficient?
|
|
||||||
# if 'samplerd' in Services.service_tasks:
|
|
||||||
# await Services.cancel_service('samplerd')
|
|
||||||
service_tn.cancel_scope.cancel()
|
|
||||||
|
|
||||||
|
|
||||||
# TODO: do we even need this?
|
# TODO: do we even need this?
|
||||||
# @acm
|
# @acm
|
||||||
# async def maybe_open_runtime(
|
# async def maybe_open_runtime(
|
||||||
# loglevel: Optional[str] = None,
|
# loglevel: str|None = None,
|
||||||
# **kwargs,
|
# **kwargs,
|
||||||
|
|
||||||
# ) -> None:
|
# ) -> None:
|
||||||
|
|
@ -262,10 +250,7 @@ async def maybe_open_pikerd(
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
|
||||||
) -> (
|
) -> tractor._portal.Portal | ClassVar[ServiceMngr]:
|
||||||
tractor._portal.Portal
|
|
||||||
|ClassVar[Services]
|
|
||||||
):
|
|
||||||
'''
|
'''
|
||||||
If no ``pikerd`` daemon-root-actor can be found start it and
|
If no ``pikerd`` daemon-root-actor can be found start it and
|
||||||
yield up (we should probably figure out returning a portal to self
|
yield up (we should probably figure out returning a portal to self
|
||||||
|
|
@ -290,8 +275,7 @@ async def maybe_open_pikerd(
|
||||||
|
|
||||||
registry_addrs: list[tuple[str, int]] = (
|
registry_addrs: list[tuple[str, int]] = (
|
||||||
registry_addrs
|
registry_addrs
|
||||||
or
|
or [_default_reg_addr]
|
||||||
[_default_reg_addr]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
pikerd_portal: tractor.Portal | None
|
pikerd_portal: tractor.Portal | None
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,7 @@ from requests.exceptions import (
|
||||||
ReadTimeout,
|
ReadTimeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
from ._mngr import Services
|
from ._mngr import ServiceMngr
|
||||||
from ._util import (
|
from ._util import (
|
||||||
log, # sub-sys logger
|
log, # sub-sys logger
|
||||||
get_console_log,
|
get_console_log,
|
||||||
|
|
@ -453,7 +453,7 @@ async def open_ahabd(
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def start_ahab_service(
|
async def start_ahab_service(
|
||||||
services: Services,
|
services: ServiceMngr,
|
||||||
service_name: str,
|
service_name: str,
|
||||||
|
|
||||||
# endpoint config passed as **kwargs
|
# endpoint config passed as **kwargs
|
||||||
|
|
@ -549,7 +549,8 @@ async def start_ahab_service(
|
||||||
log.warning('Failed to cancel root permsed container')
|
log.warning('Failed to cancel root permsed container')
|
||||||
|
|
||||||
except (
|
except (
|
||||||
trio.MultiError,
|
# trio.MultiError,
|
||||||
|
ExceptionGroup,
|
||||||
) as err:
|
) as err:
|
||||||
for subexc in err.exceptions:
|
for subexc in err.exceptions:
|
||||||
if isinstance(subexc, PermissionError):
|
if isinstance(subexc, PermissionError):
|
||||||
|
|
|
||||||
|
|
@ -26,15 +26,17 @@ from typing import (
|
||||||
from contextlib import (
|
from contextlib import (
|
||||||
asynccontextmanager as acm,
|
asynccontextmanager as acm,
|
||||||
)
|
)
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
import tractor
|
import tractor
|
||||||
from trio.lowlevel import current_task
|
import trio
|
||||||
|
|
||||||
from ._util import (
|
from ._util import (
|
||||||
log, # sub-sys logger
|
log, # sub-sys logger
|
||||||
)
|
)
|
||||||
from ._mngr import (
|
from ._mngr import (
|
||||||
Services,
|
get_service_mngr,
|
||||||
|
ServiceMngr,
|
||||||
)
|
)
|
||||||
from ._actor_runtime import maybe_open_pikerd
|
from ._actor_runtime import maybe_open_pikerd
|
||||||
from ._registry import find_service
|
from ._registry import find_service
|
||||||
|
|
@ -42,15 +44,14 @@ from ._registry import find_service
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def maybe_spawn_daemon(
|
async def maybe_spawn_daemon(
|
||||||
|
|
||||||
service_name: str,
|
service_name: str,
|
||||||
service_task_target: Callable,
|
service_task_target: Callable,
|
||||||
|
|
||||||
spawn_args: dict[str, Any],
|
spawn_args: dict[str, Any],
|
||||||
|
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
singleton: bool = False,
|
singleton: bool = False,
|
||||||
|
|
||||||
|
_locks = defaultdict(trio.Lock),
|
||||||
**pikerd_kwargs,
|
**pikerd_kwargs,
|
||||||
|
|
||||||
) -> tractor.Portal:
|
) -> tractor.Portal:
|
||||||
|
|
@ -68,10 +69,9 @@ async def maybe_spawn_daemon(
|
||||||
'''
|
'''
|
||||||
# serialize access to this section to avoid
|
# serialize access to this section to avoid
|
||||||
# 2 or more tasks racing to create a daemon
|
# 2 or more tasks racing to create a daemon
|
||||||
lock = Services.locks[service_name]
|
lock = _locks[service_name]
|
||||||
await lock.acquire()
|
await lock.acquire()
|
||||||
|
|
||||||
try:
|
|
||||||
async with find_service(
|
async with find_service(
|
||||||
service_name,
|
service_name,
|
||||||
registry_addrs=[('127.0.0.1', 6116)],
|
registry_addrs=[('127.0.0.1', 6116)],
|
||||||
|
|
@ -134,21 +134,65 @@ async def maybe_spawn_daemon(
|
||||||
async with tractor.wait_for_actor(service_name) as portal:
|
async with tractor.wait_for_actor(service_name) as portal:
|
||||||
lock.release()
|
lock.release()
|
||||||
yield portal
|
yield portal
|
||||||
await portal.cancel_actor()
|
# --- ---- ---
|
||||||
|
# XXX NOTE XXX
|
||||||
except BaseException as _err:
|
# --- ---- ---
|
||||||
err = _err
|
# DO NOT PUT A `portal.cancel_actor()` here (as was prior)!
|
||||||
if (
|
#
|
||||||
lock.locked()
|
# Doing so will cause an "out-of-band" ctxc
|
||||||
and
|
# (`tractor.ContextCancelled`) to be raised inside the
|
||||||
lock.statistics().owner is current_task()
|
# `ServiceMngr.open_context_in_task()`'s call to
|
||||||
):
|
# `ctx.wait_for_result()` AND the internal self-ctxc
|
||||||
log.exception(
|
# "graceful capture" WILL NOT CATCH IT!
|
||||||
f'Releasing stale lock after crash..?'
|
#
|
||||||
f'{err!r}\n'
|
# This can cause certain types of operations to raise
|
||||||
)
|
# that ctxc BEFORE THEY `return`, resulting in
|
||||||
lock.release()
|
# a "false-negative" ctxc being raised when really
|
||||||
raise err
|
# nothing actually failed, other then our semantic
|
||||||
|
# "failure" to suppress an expected, graceful,
|
||||||
|
# self-cancel scenario..
|
||||||
|
#
|
||||||
|
# bUt wHy duZ It WorK lIKe dis..
|
||||||
|
# ------------------------------
|
||||||
|
# from the perspective of the `tractor.Context` this
|
||||||
|
# cancel request was conducted "out of band" since
|
||||||
|
# `Context.cancel()` was never called and thus the
|
||||||
|
# `._cancel_called: bool` was never set. Despite the
|
||||||
|
# remote `.canceller` being set to `pikerd` (i.e. the
|
||||||
|
# same `Actor.uid` of the raising service-mngr task) the
|
||||||
|
# service-task's ctx itself was never marked as having
|
||||||
|
# requested cancellation and thus still raises the ctxc
|
||||||
|
# bc it was unaware of any such request.
|
||||||
|
#
|
||||||
|
# How to make grokin these cases easier tho?
|
||||||
|
# ------------------------------------------
|
||||||
|
# Because `Portal.cancel_actor()` was called it requests
|
||||||
|
# "full-`Actor`-runtime-cancellation" of it's peer
|
||||||
|
# process which IS NOT THE SAME as a single inter-actor
|
||||||
|
# RPC task cancelling its local context with a remote
|
||||||
|
# peer `Task` in that same peer process.
|
||||||
|
#
|
||||||
|
# ?TODO? It might be better if we do one (or all) of the
|
||||||
|
# following:
|
||||||
|
#
|
||||||
|
# -[ ] at least set a special message for the
|
||||||
|
# `ContextCancelled` when raised locally by the
|
||||||
|
# unaware ctx task such that we check for the
|
||||||
|
# `.canceller` being *our `Actor`* and in the case
|
||||||
|
# where `Context._cancel_called == False` we specially
|
||||||
|
# note that this is likely an "out-of-band"
|
||||||
|
# runtime-cancel request triggered by some call to
|
||||||
|
# `Portal.cancel_actor()`, possibly even reporting the
|
||||||
|
# exact LOC of that caller by tracking it inside our
|
||||||
|
# portal-type?
|
||||||
|
# -[ ] possibly add another field `ContextCancelled` like
|
||||||
|
# maybe a,
|
||||||
|
# `.request_type: Literal['os', 'proc', 'actor',
|
||||||
|
# 'ctx']` type thing which would allow immediately
|
||||||
|
# being able to tell what kind of cancellation caused
|
||||||
|
# the unexpected ctxc?
|
||||||
|
# -[ ] REMOVE THIS COMMENT, once we've settled on how to
|
||||||
|
# better augment `tractor` to be more explicit on this!
|
||||||
|
|
||||||
|
|
||||||
async def spawn_emsd(
|
async def spawn_emsd(
|
||||||
|
|
@ -163,21 +207,22 @@ async def spawn_emsd(
|
||||||
"""
|
"""
|
||||||
log.info('Spawning emsd')
|
log.info('Spawning emsd')
|
||||||
|
|
||||||
portal = await Services.actor_n.start_actor(
|
smngr: ServiceMngr = get_service_mngr()
|
||||||
|
portal = await smngr.actor_n.start_actor(
|
||||||
'emsd',
|
'emsd',
|
||||||
enable_modules=[
|
enable_modules=[
|
||||||
'piker.clearing._ems',
|
'piker.clearing._ems',
|
||||||
'piker.clearing._client',
|
'piker.clearing._client',
|
||||||
],
|
],
|
||||||
loglevel=loglevel,
|
loglevel=loglevel,
|
||||||
debug_mode=Services.debug_mode, # set by pikerd flag
|
debug_mode=smngr.debug_mode, # set by pikerd flag
|
||||||
**extra_tractor_kwargs
|
**extra_tractor_kwargs
|
||||||
)
|
)
|
||||||
|
|
||||||
# non-blocking setup of clearing service
|
# non-blocking setup of clearing service
|
||||||
from ..clearing._ems import _setup_persistent_emsd
|
from ..clearing._ems import _setup_persistent_emsd
|
||||||
|
|
||||||
await Services.start_service_task(
|
await smngr.start_service_task(
|
||||||
'emsd',
|
'emsd',
|
||||||
portal,
|
portal,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,16 +18,29 @@
|
||||||
daemon-service management API.
|
daemon-service management API.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
from contextlib import (
|
||||||
|
asynccontextmanager as acm,
|
||||||
|
# contextmanager as cm,
|
||||||
|
)
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
from dataclasses import (
|
||||||
|
dataclass,
|
||||||
|
field,
|
||||||
|
)
|
||||||
|
import functools
|
||||||
|
import inspect
|
||||||
from typing import (
|
from typing import (
|
||||||
Callable,
|
Callable,
|
||||||
Any,
|
Any,
|
||||||
)
|
)
|
||||||
|
|
||||||
import trio
|
import msgspec
|
||||||
from trio_typing import TaskStatus
|
|
||||||
import tractor
|
import tractor
|
||||||
|
import trio
|
||||||
|
from trio import TaskStatus
|
||||||
from tractor import (
|
from tractor import (
|
||||||
|
ActorNursery,
|
||||||
current_actor,
|
current_actor,
|
||||||
ContextCancelled,
|
ContextCancelled,
|
||||||
Context,
|
Context,
|
||||||
|
|
@ -39,6 +52,130 @@ from ._util import (
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: implement a singleton deco-API for wrapping the below
|
||||||
|
# factory's impl for general actor-singleton use?
|
||||||
|
#
|
||||||
|
# @singleton
|
||||||
|
# async def open_service_mngr(
|
||||||
|
# **init_kwargs,
|
||||||
|
# ) -> ServiceMngr:
|
||||||
|
# '''
|
||||||
|
# Note this function body is invoke IFF no existing singleton instance already
|
||||||
|
# exists in this proc's memory.
|
||||||
|
|
||||||
|
# '''
|
||||||
|
# # setup
|
||||||
|
# yield ServiceMngr(**init_kwargs)
|
||||||
|
# # teardown
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: singleton factory API instead of a class API
|
||||||
|
@acm
|
||||||
|
async def open_service_mngr(
|
||||||
|
*,
|
||||||
|
debug_mode: bool = False,
|
||||||
|
|
||||||
|
# impl deat which ensures a single global instance
|
||||||
|
_singleton: list[ServiceMngr|None] = [None],
|
||||||
|
**init_kwargs,
|
||||||
|
|
||||||
|
) -> ServiceMngr:
|
||||||
|
'''
|
||||||
|
Open a multi-subactor-as-service-daemon tree supervisor.
|
||||||
|
|
||||||
|
The delivered `ServiceMngr` is a singleton instance for each
|
||||||
|
actor-process and is allocated on first open and never
|
||||||
|
de-allocated unless explicitly deleted by al call to
|
||||||
|
`del_service_mngr()`.
|
||||||
|
|
||||||
|
'''
|
||||||
|
# TODO: factor this an allocation into
|
||||||
|
# a `._mngr.open_service_mngr()` and put in the
|
||||||
|
# once-n-only-once setup/`.__aenter__()` part!
|
||||||
|
# -[ ] how to make this only happen on the `mngr == None` case?
|
||||||
|
# |_ use `.trionics.maybe_open_context()` (for generic
|
||||||
|
# async-with-style-only-once of the factory impl, though
|
||||||
|
# what do we do for the allocation case?
|
||||||
|
# / `.maybe_open_nursery()` (since for this specific case
|
||||||
|
# it's simpler?) to activate
|
||||||
|
async with (
|
||||||
|
tractor.open_nursery() as an,
|
||||||
|
trio.open_nursery() as tn,
|
||||||
|
):
|
||||||
|
# impl specific obvi..
|
||||||
|
init_kwargs.update({
|
||||||
|
'actor_n': an,
|
||||||
|
'service_n': tn,
|
||||||
|
})
|
||||||
|
|
||||||
|
mngr: ServiceMngr|None
|
||||||
|
if (mngr := _singleton[0]) is None:
|
||||||
|
|
||||||
|
log.info('Allocating a new service mngr!')
|
||||||
|
mngr = _singleton[0] = ServiceMngr(**init_kwargs)
|
||||||
|
|
||||||
|
# TODO: put into `.__aenter__()` section of
|
||||||
|
# eventual `@singleton_acm` API wrapper.
|
||||||
|
#
|
||||||
|
# assign globally for future daemon/task creation
|
||||||
|
mngr.actor_n = an
|
||||||
|
mngr.service_n = tn
|
||||||
|
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
mngr.actor_n
|
||||||
|
and
|
||||||
|
mngr.service_tn
|
||||||
|
)
|
||||||
|
log.info(
|
||||||
|
'Using extant service mngr!\n\n'
|
||||||
|
f'{mngr!r}\n' # it has a nice `.__repr__()` of services state
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# NOTE: this is a singleton factory impl specific detail
|
||||||
|
# which should be supported in the condensed
|
||||||
|
# `@singleton_acm` API?
|
||||||
|
mngr.debug_mode = debug_mode
|
||||||
|
|
||||||
|
yield mngr
|
||||||
|
finally:
|
||||||
|
# TODO: is this more clever/efficient?
|
||||||
|
# if 'samplerd' in mngr.service_tasks:
|
||||||
|
# await mngr.cancel_service('samplerd')
|
||||||
|
tn.cancel_scope.cancel()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def get_service_mngr() -> ServiceMngr:
|
||||||
|
'''
|
||||||
|
Try to get the singleton service-mngr for this actor presuming it
|
||||||
|
has already been allocated using,
|
||||||
|
|
||||||
|
.. code:: python
|
||||||
|
|
||||||
|
async with open_<@singleton_acm(func)>() as mngr`
|
||||||
|
... this block kept open ...
|
||||||
|
|
||||||
|
If not yet allocated raise a `ServiceError`.
|
||||||
|
|
||||||
|
'''
|
||||||
|
# https://stackoverflow.com/a/12627202
|
||||||
|
# https://docs.python.org/3/library/inspect.html#inspect.Signature
|
||||||
|
maybe_mngr: ServiceMngr|None = inspect.signature(
|
||||||
|
open_service_mngr
|
||||||
|
).parameters['_singleton'].default[0]
|
||||||
|
|
||||||
|
if maybe_mngr is None:
|
||||||
|
raise RuntimeError(
|
||||||
|
'Someone must allocate a `ServiceMngr` using\n\n'
|
||||||
|
'`async with open_service_mngr()` beforehand!!\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
return maybe_mngr
|
||||||
|
|
||||||
|
|
||||||
# TODO: we need remote wrapping and a general soln:
|
# TODO: we need remote wrapping and a general soln:
|
||||||
# - factor this into a ``tractor.highlevel`` extension # pack for the
|
# - factor this into a ``tractor.highlevel`` extension # pack for the
|
||||||
# library.
|
# library.
|
||||||
|
|
@ -46,31 +183,46 @@ from ._util import (
|
||||||
# to the pikerd actor for starting services remotely!
|
# to the pikerd actor for starting services remotely!
|
||||||
# - prolly rename this to ActorServicesNursery since it spawns
|
# - prolly rename this to ActorServicesNursery since it spawns
|
||||||
# new actors and supervises them to completion?
|
# new actors and supervises them to completion?
|
||||||
class Services:
|
@dataclass
|
||||||
|
class ServiceMngr:
|
||||||
|
# class ServiceMngr(msgspec.Struct):
|
||||||
|
'''
|
||||||
|
A multi-subactor-as-service manager.
|
||||||
|
|
||||||
actor_n: tractor._supervise.ActorNursery
|
Spawn, supervise and monitor service/daemon subactors in a SC
|
||||||
|
process tree.
|
||||||
|
|
||||||
|
'''
|
||||||
|
actor_n: ActorNursery
|
||||||
service_n: trio.Nursery
|
service_n: trio.Nursery
|
||||||
debug_mode: bool # tractor sub-actor debug mode flag
|
debug_mode: bool = False # tractor sub-actor debug mode flag
|
||||||
|
|
||||||
service_tasks: dict[
|
service_tasks: dict[
|
||||||
str,
|
str,
|
||||||
tuple[
|
tuple[
|
||||||
trio.CancelScope,
|
trio.CancelScope,
|
||||||
|
Context,
|
||||||
Portal,
|
Portal,
|
||||||
trio.Event,
|
trio.Event,
|
||||||
]
|
]
|
||||||
] = {}
|
] = field(default_factory=dict)
|
||||||
locks = defaultdict(trio.Lock)
|
|
||||||
|
# internal per-service task mutexs
|
||||||
|
_locks = defaultdict(trio.Lock)
|
||||||
|
|
||||||
@classmethod
|
|
||||||
async def start_service_task(
|
async def start_service_task(
|
||||||
self,
|
self,
|
||||||
name: str,
|
name: str,
|
||||||
portal: Portal,
|
portal: Portal,
|
||||||
|
|
||||||
|
# TODO: typevar for the return type of the target and then
|
||||||
|
# use it below for `ctx_res`?
|
||||||
target: Callable,
|
target: Callable,
|
||||||
|
|
||||||
allow_overruns: bool = False,
|
allow_overruns: bool = False,
|
||||||
**ctx_kwargs,
|
**ctx_kwargs,
|
||||||
|
|
||||||
) -> (trio.CancelScope, Context):
|
) -> (trio.CancelScope, Context, Any):
|
||||||
'''
|
'''
|
||||||
Open a context in a service sub-actor, add to a stack
|
Open a context in a service sub-actor, add to a stack
|
||||||
that gets unwound at ``pikerd`` teardown.
|
that gets unwound at ``pikerd`` teardown.
|
||||||
|
|
@ -83,6 +235,7 @@ class Services:
|
||||||
task_status: TaskStatus[
|
task_status: TaskStatus[
|
||||||
tuple[
|
tuple[
|
||||||
trio.CancelScope,
|
trio.CancelScope,
|
||||||
|
Context,
|
||||||
trio.Event,
|
trio.Event,
|
||||||
Any,
|
Any,
|
||||||
]
|
]
|
||||||
|
|
@ -90,22 +243,29 @@ class Services:
|
||||||
|
|
||||||
) -> Any:
|
) -> Any:
|
||||||
|
|
||||||
|
# TODO: use the ctx._scope directly here instead?
|
||||||
|
# -[ ] actually what semantics do we expect for this
|
||||||
|
# usage!?
|
||||||
with trio.CancelScope() as cs:
|
with trio.CancelScope() as cs:
|
||||||
|
try:
|
||||||
async with portal.open_context(
|
async with portal.open_context(
|
||||||
target,
|
target,
|
||||||
allow_overruns=allow_overruns,
|
allow_overruns=allow_overruns,
|
||||||
**ctx_kwargs,
|
**ctx_kwargs,
|
||||||
|
|
||||||
) as (ctx, first):
|
) as (ctx, started):
|
||||||
|
|
||||||
# unblock once the remote context has started
|
# unblock once the remote context has started
|
||||||
complete = trio.Event()
|
complete = trio.Event()
|
||||||
task_status.started((cs, complete, first))
|
task_status.started((
|
||||||
|
cs,
|
||||||
|
ctx,
|
||||||
|
complete,
|
||||||
|
started,
|
||||||
|
))
|
||||||
log.info(
|
log.info(
|
||||||
f'`pikerd` service {name} started with value {first}'
|
f'`pikerd` service {name} started with value {started}'
|
||||||
)
|
)
|
||||||
try:
|
|
||||||
# wait on any context's return value
|
# wait on any context's return value
|
||||||
# and any final portal result from the
|
# and any final portal result from the
|
||||||
# sub-actor.
|
# sub-actor.
|
||||||
|
|
@ -115,39 +275,55 @@ class Services:
|
||||||
# either by error from the target context
|
# either by error from the target context
|
||||||
# function or by being cancelled here by the
|
# function or by being cancelled here by the
|
||||||
# surrounding cancel scope.
|
# surrounding cancel scope.
|
||||||
return (await portal.result(), ctx_res)
|
return (
|
||||||
|
await portal.wait_for_result(),
|
||||||
|
ctx_res,
|
||||||
|
)
|
||||||
|
|
||||||
except ContextCancelled as ctxe:
|
except ContextCancelled as ctxe:
|
||||||
canceller: tuple[str, str] = ctxe.canceller
|
canceller: tuple[str, str] = ctxe.canceller
|
||||||
our_uid: tuple[str, str] = current_actor().uid
|
our_uid: tuple[str, str] = current_actor().uid
|
||||||
if (
|
if (
|
||||||
canceller != portal.channel.uid
|
canceller != portal.chan.uid
|
||||||
and
|
and
|
||||||
canceller != our_uid
|
canceller != our_uid
|
||||||
):
|
):
|
||||||
log.cancel(
|
log.cancel(
|
||||||
f'Actor-service {name} was remotely cancelled?\n'
|
f'Actor-service `{name}` was remotely cancelled by a peer?\n'
|
||||||
f'remote canceller: {canceller}\n'
|
|
||||||
f'Keeping {our_uid} alive, ignoring sub-actor cancel..\n'
|
# TODO: this would be a good spot to use
|
||||||
|
# a respawn feature Bo
|
||||||
|
f'-> Keeping `pikerd` service manager alive despite this inter-peer cancel\n\n'
|
||||||
|
|
||||||
|
f'cancellee: {portal.chan.uid}\n'
|
||||||
|
f'canceller: {canceller}\n'
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
|
# NOTE: the ctx MUST be cancelled first if we
|
||||||
|
# don't want the above `ctx.wait_for_result()` to
|
||||||
|
# raise a self-ctxc. WHY, well since from the ctx's
|
||||||
|
# perspective the cancel request will have
|
||||||
|
# arrived out-out-of-band at the `Actor.cancel()`
|
||||||
|
# level, thus `Context.cancel_called == False`,
|
||||||
|
# meaning `ctx._is_self_cancelled() == False`.
|
||||||
|
# with trio.CancelScope(shield=True):
|
||||||
|
# await ctx.cancel()
|
||||||
await portal.cancel_actor()
|
await portal.cancel_actor()
|
||||||
complete.set()
|
complete.set()
|
||||||
self.service_tasks.pop(name)
|
self.service_tasks.pop(name)
|
||||||
|
|
||||||
cs, complete, first = await self.service_n.start(open_context_in_task)
|
cs, sub_ctx, complete, started = await self.service_n.start(
|
||||||
|
open_context_in_task
|
||||||
|
)
|
||||||
|
|
||||||
# store the cancel scope and portal for later cancellation or
|
# store the cancel scope and portal for later cancellation or
|
||||||
# retstart if needed.
|
# retstart if needed.
|
||||||
self.service_tasks[name] = (cs, portal, complete)
|
self.service_tasks[name] = (cs, sub_ctx, portal, complete)
|
||||||
|
return cs, sub_ctx, started
|
||||||
|
|
||||||
return cs, first
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
async def cancel_service(
|
async def cancel_service(
|
||||||
self,
|
self,
|
||||||
name: str,
|
name: str,
|
||||||
|
|
@ -158,8 +334,80 @@ class Services:
|
||||||
|
|
||||||
'''
|
'''
|
||||||
log.info(f'Cancelling `pikerd` service {name}')
|
log.info(f'Cancelling `pikerd` service {name}')
|
||||||
cs, portal, complete = self.service_tasks[name]
|
cs, sub_ctx, portal, complete = self.service_tasks[name]
|
||||||
cs.cancel()
|
|
||||||
|
# cs.cancel()
|
||||||
|
await sub_ctx.cancel()
|
||||||
await complete.wait()
|
await complete.wait()
|
||||||
assert name not in self.service_tasks, \
|
|
||||||
|
if name in self.service_tasks:
|
||||||
|
# TODO: custom err?
|
||||||
|
# raise ServiceError(
|
||||||
|
raise RuntimeError(
|
||||||
f'Serice task for {name} not terminated?'
|
f'Serice task for {name} not terminated?'
|
||||||
|
)
|
||||||
|
|
||||||
|
# assert name not in self.service_tasks, \
|
||||||
|
# f'Serice task for {name} not terminated?'
|
||||||
|
|
||||||
|
async def start_service(
|
||||||
|
self,
|
||||||
|
daemon_name: str,
|
||||||
|
ctx_ep: Callable, # kwargs must `partial`-ed in!
|
||||||
|
|
||||||
|
debug_mode: bool = False,
|
||||||
|
**tractor_actor_kwargs,
|
||||||
|
|
||||||
|
) -> Context:
|
||||||
|
'''
|
||||||
|
Start a "service" task in a new sub-actor (daemon) and manage it's lifetime
|
||||||
|
indefinitely.
|
||||||
|
|
||||||
|
Services can be cancelled/shutdown using `.cancel_service()`.
|
||||||
|
|
||||||
|
'''
|
||||||
|
entry: tuple|None = self.service_tasks.get(daemon_name)
|
||||||
|
if entry:
|
||||||
|
(cs, sub_ctx, portal, complete) = entry
|
||||||
|
return sub_ctx
|
||||||
|
|
||||||
|
if daemon_name not in self.service_tasks:
|
||||||
|
portal = await self.actor_n.start_actor(
|
||||||
|
daemon_name,
|
||||||
|
debug_mode=( # maybe set globally during allocate
|
||||||
|
debug_mode
|
||||||
|
or
|
||||||
|
self.debug_mode
|
||||||
|
),
|
||||||
|
**tractor_actor_kwargs,
|
||||||
|
)
|
||||||
|
ctx_kwargs: dict[str, Any] = {}
|
||||||
|
if isinstance(ctx_ep, functools.partial):
|
||||||
|
ctx_kwargs: dict[str, Any] = ctx_ep.keywords
|
||||||
|
ctx_ep: Callable = ctx_ep.func
|
||||||
|
|
||||||
|
(cs, sub_ctx, started) = await self.start_service_task(
|
||||||
|
daemon_name,
|
||||||
|
portal,
|
||||||
|
ctx_ep,
|
||||||
|
**ctx_kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
return sub_ctx
|
||||||
|
|
||||||
|
|
||||||
|
# TODO:
|
||||||
|
# -[ ] factor all the common shit from `.data._sampling`
|
||||||
|
# and `.brokers._daemon` into here / `ServiceMngr`
|
||||||
|
# in terms of allocating the `Portal` as part of the
|
||||||
|
# "service-in-subactor" starting!
|
||||||
|
# -[ ] move to `tractor.hilevel._service`, import and use here!
|
||||||
|
# NOTE: purposely leaks the ref to the mod-scope Bo
|
||||||
|
# import tractor
|
||||||
|
# from tractor.hilevel import (
|
||||||
|
# open_service_mngr,
|
||||||
|
# ServiceMngr,
|
||||||
|
# )
|
||||||
|
# mngr: ServiceMngr|None = None
|
||||||
|
# with tractor.hilevel.open_service_mngr() as mngr:
|
||||||
|
# Services = proxy(mngr)
|
||||||
|
|
|
||||||
|
|
@ -101,15 +101,13 @@ async def open_registry(
|
||||||
|
|
||||||
if (
|
if (
|
||||||
not tractor.is_root_process()
|
not tractor.is_root_process()
|
||||||
and
|
and not Registry.addrs
|
||||||
not Registry.addrs
|
|
||||||
):
|
):
|
||||||
Registry.addrs.extend(actor.reg_addrs)
|
Registry.addrs.extend(actor.reg_addrs)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
ensure_exists
|
ensure_exists
|
||||||
and
|
and not Registry.addrs
|
||||||
not Registry.addrs
|
|
||||||
):
|
):
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f"`{uid}` registry should already exist but doesn't?"
|
f"`{uid}` registry should already exist but doesn't?"
|
||||||
|
|
@ -148,7 +146,7 @@ async def find_service(
|
||||||
| list[Portal]
|
| list[Portal]
|
||||||
| None
|
| None
|
||||||
):
|
):
|
||||||
# try:
|
|
||||||
reg_addrs: list[tuple[str, int]]
|
reg_addrs: list[tuple[str, int]]
|
||||||
async with open_registry(
|
async with open_registry(
|
||||||
addrs=(
|
addrs=(
|
||||||
|
|
@ -159,39 +157,22 @@ async def find_service(
|
||||||
or Registry.addrs
|
or Registry.addrs
|
||||||
),
|
),
|
||||||
) as reg_addrs:
|
) as reg_addrs:
|
||||||
|
log.info(f'Scanning for service `{service_name}`')
|
||||||
|
|
||||||
log.info(
|
maybe_portals: list[Portal] | Portal | None
|
||||||
f'Scanning for service {service_name!r}'
|
|
||||||
)
|
|
||||||
|
|
||||||
# attach to existing daemon by name if possible
|
# attach to existing daemon by name if possible
|
||||||
maybe_portals: list[Portal]|Portal|None
|
|
||||||
async with tractor.find_actor(
|
async with tractor.find_actor(
|
||||||
service_name,
|
service_name,
|
||||||
registry_addrs=reg_addrs,
|
registry_addrs=reg_addrs,
|
||||||
only_first=first_only, # if set only returns single ref
|
only_first=first_only, # if set only returns single ref
|
||||||
) as maybe_portals:
|
) as maybe_portals:
|
||||||
if not maybe_portals:
|
if not maybe_portals:
|
||||||
# log.info(
|
|
||||||
print(
|
|
||||||
f'Could NOT find service {service_name!r} -> {maybe_portals!r}'
|
|
||||||
)
|
|
||||||
yield None
|
yield None
|
||||||
return
|
return
|
||||||
|
|
||||||
# log.info(
|
|
||||||
print(
|
|
||||||
f'Found service {service_name!r} -> {maybe_portals}'
|
|
||||||
)
|
|
||||||
yield maybe_portals
|
yield maybe_portals
|
||||||
|
|
||||||
# except BaseException as _berr:
|
|
||||||
# berr = _berr
|
|
||||||
# log.exception(
|
|
||||||
# 'tractor.find_actor() failed with,\n'
|
|
||||||
# )
|
|
||||||
# raise berr
|
|
||||||
|
|
||||||
|
|
||||||
async def check_for_service(
|
async def check_for_service(
|
||||||
service_name: str,
|
service_name: str,
|
||||||
|
|
|
||||||
|
|
@ -21,11 +21,13 @@ from typing import (
|
||||||
TYPE_CHECKING,
|
TYPE_CHECKING,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# TODO: oof, needs to be changed to `httpx`!
|
||||||
import asks
|
import asks
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
import docker
|
import docker
|
||||||
from ._ahab import DockerContainer
|
from ._ahab import DockerContainer
|
||||||
|
from . import ServiceMngr
|
||||||
|
|
||||||
from ._util import log # sub-sys logger
|
from ._util import log # sub-sys logger
|
||||||
from ._util import (
|
from ._util import (
|
||||||
|
|
@ -127,7 +129,7 @@ def start_elasticsearch(
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def start_ahab_daemon(
|
async def start_ahab_daemon(
|
||||||
service_mngr: Services,
|
service_mngr: ServiceMngr,
|
||||||
user_config: dict | None = None,
|
user_config: dict | None = None,
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -53,7 +53,7 @@ import pendulum
|
||||||
# import purerpc
|
# import purerpc
|
||||||
|
|
||||||
from ..data.feed import maybe_open_feed
|
from ..data.feed import maybe_open_feed
|
||||||
from . import Services
|
from . import ServiceMngr
|
||||||
from ._util import (
|
from ._util import (
|
||||||
log, # sub-sys logger
|
log, # sub-sys logger
|
||||||
get_console_log,
|
get_console_log,
|
||||||
|
|
@ -233,7 +233,7 @@ def start_marketstore(
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def start_ahab_daemon(
|
async def start_ahab_daemon(
|
||||||
service_mngr: Services,
|
service_mngr: ServiceMngr,
|
||||||
user_config: dict | None = None,
|
user_config: dict | None = None,
|
||||||
loglevel: str | None = None,
|
loglevel: str | None = None,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -386,8 +386,6 @@ def ldshm(
|
||||||
open_annot_ctl() as actl,
|
open_annot_ctl() as actl,
|
||||||
):
|
):
|
||||||
shm_df: pl.DataFrame | None = None
|
shm_df: pl.DataFrame | None = None
|
||||||
tf2aids: dict[float, dict] = {}
|
|
||||||
|
|
||||||
for (
|
for (
|
||||||
shmfile,
|
shmfile,
|
||||||
shm,
|
shm,
|
||||||
|
|
@ -528,17 +526,16 @@ def ldshm(
|
||||||
new_df,
|
new_df,
|
||||||
step_gaps,
|
step_gaps,
|
||||||
)
|
)
|
||||||
|
|
||||||
# last chance manual overwrites in REPL
|
# last chance manual overwrites in REPL
|
||||||
# await tractor.pause()
|
await tractor.pause()
|
||||||
assert aids
|
assert aids
|
||||||
tf2aids[period_s] = aids
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# allow interaction even when no ts problems.
|
# allow interaction even when no ts problems.
|
||||||
assert not diff
|
|
||||||
|
|
||||||
await tractor.pause()
|
await tractor.pause()
|
||||||
log.info('Exiting TSP shm anal-izer!')
|
# assert not diff
|
||||||
|
|
||||||
|
|
||||||
if shm_df is None:
|
if shm_df is None:
|
||||||
log.error(
|
log.error(
|
||||||
|
|
|
||||||
|
|
@ -162,12 +162,11 @@ class NativeStorageClient:
|
||||||
def index_files(self):
|
def index_files(self):
|
||||||
for path in self._datadir.iterdir():
|
for path in self._datadir.iterdir():
|
||||||
if (
|
if (
|
||||||
path.is_dir()
|
path.name in {'borked', 'expired',}
|
||||||
or
|
or
|
||||||
'.parquet' not in str(path)
|
'.parquet' not in str(path)
|
||||||
# or
|
|
||||||
# path.name in {'borked', 'expired',}
|
|
||||||
):
|
):
|
||||||
|
# ignore all non-apache files (for now)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
key: str = path.name.rstrip('.parquet')
|
key: str = path.name.rstrip('.parquet')
|
||||||
|
|
|
||||||
|
|
@ -620,19 +620,16 @@ async def start_backfill(
|
||||||
f'{next_start_dt} -> {last_start_dt}'
|
f'{next_start_dt} -> {last_start_dt}'
|
||||||
)
|
)
|
||||||
|
|
||||||
# NOTE, always drop the src asset token for
|
# always drop the src asset token for
|
||||||
# non-currency-pair like market types (for now)
|
# non-currency-pair like market types (for now)
|
||||||
#
|
|
||||||
# THAT IS, for now our table key schema is NOT
|
|
||||||
# including the dst[/src] source asset token. SO,
|
|
||||||
# 'tsla.nasdaq.ib' over 'tsla/usd.nasdaq.ib' for
|
|
||||||
# historical reasons ONLY.
|
|
||||||
if mkt.dst.atype not in {
|
if mkt.dst.atype not in {
|
||||||
'crypto',
|
'crypto',
|
||||||
'crypto_currency',
|
'crypto_currency',
|
||||||
'fiat', # a "forex pair"
|
'fiat', # a "forex pair"
|
||||||
'perpetual_future', # stupid "perps" from cex land
|
'perpetual_future', # stupid "perps" from cex land
|
||||||
}:
|
}:
|
||||||
|
# for now, our table key schema is not including
|
||||||
|
# the dst[/src] source asset token.
|
||||||
col_sym_key: str = mkt.get_fqme(
|
col_sym_key: str = mkt.get_fqme(
|
||||||
delim_char='',
|
delim_char='',
|
||||||
without_src=True,
|
without_src=True,
|
||||||
|
|
@ -963,10 +960,7 @@ async def tsdb_backfill(
|
||||||
# concurrently load the provider's most-recent-frame AND any
|
# concurrently load the provider's most-recent-frame AND any
|
||||||
# pre-existing tsdb history already saved in `piker` storage.
|
# pre-existing tsdb history already saved in `piker` storage.
|
||||||
dt_eps: list[DateTime, DateTime] = []
|
dt_eps: list[DateTime, DateTime] = []
|
||||||
async with (
|
async with trio.open_nursery() as tn:
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn
|
|
||||||
):
|
|
||||||
tn.start_soon(
|
tn.start_soon(
|
||||||
push_latest_frame,
|
push_latest_frame,
|
||||||
dt_eps,
|
dt_eps,
|
||||||
|
|
@ -1015,16 +1009,9 @@ async def tsdb_backfill(
|
||||||
int,
|
int,
|
||||||
Duration,
|
Duration,
|
||||||
]|None = config.get('frame_types', None)
|
]|None = config.get('frame_types', None)
|
||||||
|
|
||||||
if def_frame_durs:
|
if def_frame_durs:
|
||||||
def_frame_size: Duration = def_frame_durs[timeframe]
|
def_frame_size: Duration = def_frame_durs[timeframe]
|
||||||
|
assert def_frame_size == calced_frame_size
|
||||||
if def_frame_size != calced_frame_size:
|
|
||||||
log.warning(
|
|
||||||
f'Expected frame size {def_frame_size}\n'
|
|
||||||
f'Rxed frame {calced_frame_size}\n'
|
|
||||||
)
|
|
||||||
# await tractor.pause()
|
|
||||||
else:
|
else:
|
||||||
# use what we calced from first frame above.
|
# use what we calced from first frame above.
|
||||||
def_frame_size = calced_frame_size
|
def_frame_size = calced_frame_size
|
||||||
|
|
@ -1053,9 +1040,7 @@ async def tsdb_backfill(
|
||||||
# if there is a gap to backfill from the first
|
# if there is a gap to backfill from the first
|
||||||
# history frame until the last datum loaded from the tsdb
|
# history frame until the last datum loaded from the tsdb
|
||||||
# continue that now in the background
|
# continue that now in the background
|
||||||
async with trio.open_nursery(
|
async with trio.open_nursery() as tn:
|
||||||
strict_exception_groups=False,
|
|
||||||
) as tn:
|
|
||||||
|
|
||||||
bf_done = await tn.start(
|
bf_done = await tn.start(
|
||||||
partial(
|
partial(
|
||||||
|
|
@ -1320,7 +1305,6 @@ async def manage_history(
|
||||||
# sampling period) data set since normally differently
|
# sampling period) data set since normally differently
|
||||||
# sampled timeseries can be loaded / process independently
|
# sampled timeseries can be loaded / process independently
|
||||||
# ;)
|
# ;)
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
):
|
):
|
||||||
log.info(
|
log.info(
|
||||||
|
|
|
||||||
|
|
@ -517,7 +517,7 @@ def with_dts(
|
||||||
|
|
||||||
'''
|
'''
|
||||||
return df.with_columns([
|
return df.with_columns([
|
||||||
pl.col(time_col).shift(1).name.suffix('_prev'),
|
pl.col(time_col).shift(1).suffix('_prev'),
|
||||||
pl.col(time_col).diff().alias('s_diff'),
|
pl.col(time_col).diff().alias('s_diff'),
|
||||||
pl.from_epoch(pl.col(time_col)).alias('dt'),
|
pl.from_epoch(pl.col(time_col)).alias('dt'),
|
||||||
]).with_columns([
|
]).with_columns([
|
||||||
|
|
@ -616,18 +616,6 @@ def detect_price_gaps(
|
||||||
# ])
|
# ])
|
||||||
...
|
...
|
||||||
|
|
||||||
# TODO: probably just use the null_segs impl above?
|
|
||||||
def detect_vlm_gaps(
|
|
||||||
df: pl.DataFrame,
|
|
||||||
col: str = 'volume',
|
|
||||||
|
|
||||||
) -> pl.DataFrame:
|
|
||||||
|
|
||||||
vnull: pl.DataFrame = df.filter(
|
|
||||||
pl.col(col) == 0
|
|
||||||
)
|
|
||||||
return vnull
|
|
||||||
|
|
||||||
|
|
||||||
def dedupe(
|
def dedupe(
|
||||||
src_df: pl.DataFrame,
|
src_df: pl.DataFrame,
|
||||||
|
|
@ -638,6 +626,7 @@ def dedupe(
|
||||||
|
|
||||||
) -> tuple[
|
) -> tuple[
|
||||||
pl.DataFrame, # with dts
|
pl.DataFrame, # with dts
|
||||||
|
pl.DataFrame, # gaps
|
||||||
pl.DataFrame, # with deduplicated dts (aka gap/repeat removal)
|
pl.DataFrame, # with deduplicated dts (aka gap/repeat removal)
|
||||||
int, # len diff between input and deduped
|
int, # len diff between input and deduped
|
||||||
]:
|
]:
|
||||||
|
|
@ -650,22 +639,19 @@ def dedupe(
|
||||||
'''
|
'''
|
||||||
wdts: pl.DataFrame = with_dts(src_df)
|
wdts: pl.DataFrame = with_dts(src_df)
|
||||||
|
|
||||||
deduped = wdts
|
|
||||||
|
|
||||||
# remove duplicated datetime samples/sections
|
|
||||||
deduped: pl.DataFrame = wdts.unique(
|
|
||||||
# subset=['dt'],
|
|
||||||
subset=['time'],
|
|
||||||
maintain_order=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
# maybe sort on any time field
|
# maybe sort on any time field
|
||||||
if sort:
|
if sort:
|
||||||
deduped = deduped.sort(by='time')
|
wdts = wdts.sort(by='time')
|
||||||
# TODO: detect out-of-order segments which were corrected!
|
# TODO: detect out-of-order segments which were corrected!
|
||||||
# -[ ] report in log msg
|
# -[ ] report in log msg
|
||||||
# -[ ] possibly return segment sections which were moved?
|
# -[ ] possibly return segment sections which were moved?
|
||||||
|
|
||||||
|
# remove duplicated datetime samples/sections
|
||||||
|
deduped: pl.DataFrame = wdts.unique(
|
||||||
|
subset=['dt'],
|
||||||
|
maintain_order=True,
|
||||||
|
)
|
||||||
|
|
||||||
diff: int = (
|
diff: int = (
|
||||||
wdts.height
|
wdts.height
|
||||||
-
|
-
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,6 @@ Main app startup and run.
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from types import ModuleType
|
from types import ModuleType
|
||||||
|
|
||||||
import tractor
|
|
||||||
import trio
|
import trio
|
||||||
|
|
||||||
from piker.ui.qt import (
|
from piker.ui.qt import (
|
||||||
|
|
@ -117,7 +116,6 @@ async def _async_main(
|
||||||
needed_brokermods[brokername] = brokers[brokername]
|
needed_brokermods[brokername] = brokers[brokername]
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as root_n,
|
trio.open_nursery() as root_n,
|
||||||
):
|
):
|
||||||
# set root nursery and task stack for spawning other charts/feeds
|
# set root nursery and task stack for spawning other charts/feeds
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,7 @@ import trio
|
||||||
|
|
||||||
from piker.ui.qt import (
|
from piker.ui.qt import (
|
||||||
QtCore,
|
QtCore,
|
||||||
|
QtWidgets,
|
||||||
Qt,
|
Qt,
|
||||||
QLineF,
|
QLineF,
|
||||||
QFrame,
|
QFrame,
|
||||||
|
|
|
||||||
|
|
@ -1445,10 +1445,7 @@ async def display_symbol_data(
|
||||||
# for pause/resume on mouse interaction
|
# for pause/resume on mouse interaction
|
||||||
rt_chart.feed = feed
|
rt_chart.feed = feed
|
||||||
|
|
||||||
async with (
|
async with trio.open_nursery() as ln:
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as ln,
|
|
||||||
):
|
|
||||||
# if available load volume related built-in display(s)
|
# if available load volume related built-in display(s)
|
||||||
vlm_charts: dict[
|
vlm_charts: dict[
|
||||||
str,
|
str,
|
||||||
|
|
|
||||||
|
|
@ -22,10 +22,7 @@ from contextlib import asynccontextmanager as acm
|
||||||
from typing import Callable
|
from typing import Callable
|
||||||
|
|
||||||
import trio
|
import trio
|
||||||
from tractor.trionics import (
|
from tractor.trionics import gather_contexts
|
||||||
gather_contexts,
|
|
||||||
collapse_eg,
|
|
||||||
)
|
|
||||||
|
|
||||||
from piker.ui.qt import (
|
from piker.ui.qt import (
|
||||||
QtCore,
|
QtCore,
|
||||||
|
|
@ -210,10 +207,7 @@ async def open_signal_handler(
|
||||||
async for args in recv:
|
async for args in recv:
|
||||||
await async_handler(*args)
|
await async_handler(*args)
|
||||||
|
|
||||||
async with (
|
async with trio.open_nursery() as tn:
|
||||||
collapse_eg(),
|
|
||||||
trio.open_nursery() as tn
|
|
||||||
):
|
|
||||||
tn.start_soon(proxy_to_handler)
|
tn.start_soon(proxy_to_handler)
|
||||||
async with send:
|
async with send:
|
||||||
yield
|
yield
|
||||||
|
|
@ -248,7 +242,6 @@ async def open_handlers(
|
||||||
widget: QWidget
|
widget: QWidget
|
||||||
streams: list[trio.abc.ReceiveChannel]
|
streams: list[trio.abc.ReceiveChannel]
|
||||||
async with (
|
async with (
|
||||||
collapse_eg(),
|
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
gather_contexts([
|
gather_contexts([
|
||||||
open_event_stream(
|
open_event_stream(
|
||||||
|
|
|
||||||
|
|
@ -18,11 +18,10 @@
|
||||||
Feed status and controls widget(s) for embedding in a UI-pane.
|
Feed status and controls widget(s) for embedding in a UI-pane.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from typing import (
|
from textwrap import dedent
|
||||||
Any,
|
from typing import TYPE_CHECKING
|
||||||
TYPE_CHECKING,
|
|
||||||
)
|
|
||||||
|
|
||||||
# from PyQt5.QtCore import Qt
|
# from PyQt5.QtCore import Qt
|
||||||
|
|
||||||
|
|
@ -50,55 +49,35 @@ def mk_feed_label(
|
||||||
a feed control protocol.
|
a feed control protocol.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
status: dict[str, Any] = feed.status
|
status = feed.status
|
||||||
assert status
|
assert status
|
||||||
|
|
||||||
# SO tips on ws/nls,
|
msg = dedent("""
|
||||||
# https://stackoverflow.com/a/15721400
|
actor: **{actor_name}**\n
|
||||||
ws: str = ' '
|
|_ @**{host}:{port}**\n
|
||||||
# nl: str = '<br>' # dun work?
|
""")
|
||||||
actor_info_repr: str = (
|
|
||||||
f')> **{status["actor_short_id"]}**\n'
|
|
||||||
'\n' # bc md?
|
|
||||||
)
|
|
||||||
|
|
||||||
# fields to select *IN* for display
|
for key, val in status.items():
|
||||||
# (see `.data.feed.open_feed()` status
|
if key in ('host', 'port', 'actor_name'):
|
||||||
# update -> TAG_feed_status_update)
|
continue
|
||||||
for key in [
|
msg += f'\n|_ {key}: **{{{key}}}**\n'
|
||||||
'ipc',
|
|
||||||
'hist_shm',
|
|
||||||
'rt_shm',
|
|
||||||
'throttle_hz',
|
|
||||||
]:
|
|
||||||
# NOTE, the 2nd key is filled via `.format()` updates.
|
|
||||||
actor_info_repr += (
|
|
||||||
f'\n' # bc md?
|
|
||||||
f'{ws}|_{key}: **{{{key}}}**\n'
|
|
||||||
)
|
|
||||||
# ^TODO? formatting and content..
|
|
||||||
# -[ ] showing which fqme is "forward" on the
|
|
||||||
# chart/fsp/order-mode?
|
|
||||||
# '|_ flows: **{symbols}**\n'
|
|
||||||
#
|
|
||||||
# -[x] why isn't the indent working?
|
|
||||||
# => markdown, now solved..
|
|
||||||
|
|
||||||
feed_label = FormatLabel(
|
feed_label = FormatLabel(
|
||||||
fmt_str=actor_info_repr,
|
fmt_str=msg,
|
||||||
|
# |_ streams: **{symbols}**\n
|
||||||
font=_font.font,
|
font=_font.font,
|
||||||
font_size=_font_small.px_size,
|
font_size=_font_small.px_size,
|
||||||
font_color='default_lightest',
|
font_color='default_lightest',
|
||||||
)
|
)
|
||||||
|
|
||||||
# ?TODO, remove this?
|
|
||||||
# form.vbox.setAlignment(feed_label, Qt.AlignBottom)
|
# form.vbox.setAlignment(feed_label, Qt.AlignBottom)
|
||||||
# form.vbox.setAlignment(Qt.AlignBottom)
|
# form.vbox.setAlignment(Qt.AlignBottom)
|
||||||
# _ = chart.height() - (
|
_ = chart.height() - (
|
||||||
# form.height() +
|
form.height() +
|
||||||
# form.fill_bar.height()
|
form.fill_bar.height()
|
||||||
# # feed_label.height()
|
# feed_label.height()
|
||||||
# )
|
)
|
||||||
|
|
||||||
feed_label.format(**feed.status)
|
feed_label.format(**feed.status)
|
||||||
|
|
||||||
return feed_label
|
return feed_label
|
||||||
|
|
|
||||||
|
|
@ -600,7 +600,6 @@ async def open_fsp_admin(
|
||||||
kwargs=kwargs,
|
kwargs=kwargs,
|
||||||
) as (cache_hit, cluster_map),
|
) as (cache_hit, cluster_map),
|
||||||
|
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
):
|
):
|
||||||
if cache_hit:
|
if cache_hit:
|
||||||
|
|
@ -614,8 +613,6 @@ async def open_fsp_admin(
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
yield admin
|
yield admin
|
||||||
|
|
||||||
# ??TODO, does this *need* to be inside a finally?
|
|
||||||
finally:
|
finally:
|
||||||
# terminate all tasks via signals
|
# terminate all tasks via signals
|
||||||
for key, entry in admin._registry.items():
|
for key, entry in admin._registry.items():
|
||||||
|
|
|
||||||
|
|
@ -285,20 +285,18 @@ class FormatLabel(QLabel):
|
||||||
font_size: int,
|
font_size: int,
|
||||||
font_color: str,
|
font_color: str,
|
||||||
|
|
||||||
use_md: bool = True,
|
|
||||||
|
|
||||||
parent=None,
|
parent=None,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
|
|
||||||
# by default set the format string verbatim and expect user
|
# by default set the format string verbatim and expect user to
|
||||||
# to call ``.format()`` later (presumably they'll notice the
|
# call ``.format()`` later (presumably they'll notice the
|
||||||
# unformatted content if ``fmt_str`` isn't meant to be
|
# unformatted content if ``fmt_str`` isn't meant to be
|
||||||
# unformatted).
|
# unformatted).
|
||||||
self.fmt_str = fmt_str
|
self.fmt_str = fmt_str
|
||||||
# self.setText(fmt_str) # ?TODO, why here?
|
self.setText(fmt_str)
|
||||||
|
|
||||||
self.setStyleSheet(
|
self.setStyleSheet(
|
||||||
f"""QLabel {{
|
f"""QLabel {{
|
||||||
|
|
@ -308,7 +306,6 @@ class FormatLabel(QLabel):
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
self.setFont(_font.font)
|
self.setFont(_font.font)
|
||||||
if use_md:
|
|
||||||
self.setTextFormat(
|
self.setTextFormat(
|
||||||
Qt.TextFormat.MarkdownText
|
Qt.TextFormat.MarkdownText
|
||||||
)
|
)
|
||||||
|
|
@ -319,10 +316,7 @@ class FormatLabel(QLabel):
|
||||||
size_policy.Expanding,
|
size_policy.Expanding,
|
||||||
)
|
)
|
||||||
self.setAlignment(
|
self.setAlignment(
|
||||||
Qt.AlignLeft
|
Qt.AlignVCenter | Qt.AlignLeft
|
||||||
|
|
|
||||||
Qt.AlignBottom
|
|
||||||
# Qt.AlignVCenter
|
|
||||||
)
|
)
|
||||||
self.setText(self.fmt_str)
|
self.setText(self.fmt_str)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,8 @@
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
Remote control tasks for sending annotations (and maybe more cmds) to
|
Remote control tasks for sending annotations (and maybe more cmds)
|
||||||
a chart from some other actor.
|
to a chart from some other actor.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
@ -32,7 +32,6 @@ from typing import (
|
||||||
)
|
)
|
||||||
|
|
||||||
import tractor
|
import tractor
|
||||||
import trio
|
|
||||||
from tractor import trionics
|
from tractor import trionics
|
||||||
from tractor import (
|
from tractor import (
|
||||||
Portal,
|
Portal,
|
||||||
|
|
@ -317,8 +316,6 @@ class AnnotCtl(Struct):
|
||||||
)
|
)
|
||||||
yield aid
|
yield aid
|
||||||
finally:
|
finally:
|
||||||
# async ipc send op
|
|
||||||
with trio.CancelScope(shield=True):
|
|
||||||
await self.remove(aid)
|
await self.remove(aid)
|
||||||
|
|
||||||
async def redraw(
|
async def redraw(
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,7 @@
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
qompleterz: embeddable search and complete using trio, Qt and
|
qompleterz: embeddable search and complete using trio, Qt and rapidfuzz.
|
||||||
rapidfuzz.
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
@ -47,7 +46,6 @@ import time
|
||||||
from pprint import pformat
|
from pprint import pformat
|
||||||
|
|
||||||
from rapidfuzz import process as fuzzy
|
from rapidfuzz import process as fuzzy
|
||||||
import tractor
|
|
||||||
import trio
|
import trio
|
||||||
from trio_typing import TaskStatus
|
from trio_typing import TaskStatus
|
||||||
|
|
||||||
|
|
@ -55,7 +53,7 @@ from piker.ui.qt import (
|
||||||
size_policy,
|
size_policy,
|
||||||
align_flag,
|
align_flag,
|
||||||
Qt,
|
Qt,
|
||||||
# QtCore,
|
QtCore,
|
||||||
QtWidgets,
|
QtWidgets,
|
||||||
QModelIndex,
|
QModelIndex,
|
||||||
QItemSelectionModel,
|
QItemSelectionModel,
|
||||||
|
|
@ -922,10 +920,7 @@ async def fill_results(
|
||||||
|
|
||||||
# issue multi-provider fan-out search request and place
|
# issue multi-provider fan-out search request and place
|
||||||
# "searching.." statuses on outstanding results providers
|
# "searching.." statuses on outstanding results providers
|
||||||
async with (
|
async with trio.open_nursery() as n:
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn
|
|
||||||
):
|
|
||||||
|
|
||||||
for provider, (search, pause) in (
|
for provider, (search, pause) in (
|
||||||
_searcher_cache.copy().items()
|
_searcher_cache.copy().items()
|
||||||
|
|
@ -949,7 +944,7 @@ async def fill_results(
|
||||||
status_field='-> searchin..',
|
status_field='-> searchin..',
|
||||||
)
|
)
|
||||||
|
|
||||||
await tn.start(
|
await n.start(
|
||||||
pack_matches,
|
pack_matches,
|
||||||
view,
|
view,
|
||||||
has_results,
|
has_results,
|
||||||
|
|
@ -1009,14 +1004,12 @@ async def handle_keyboard_input(
|
||||||
view.set_font_size(searchbar.dpi_font.px_size)
|
view.set_font_size(searchbar.dpi_font.px_size)
|
||||||
send, recv = trio.open_memory_channel(616)
|
send, recv = trio.open_memory_channel(616)
|
||||||
|
|
||||||
async with (
|
async with trio.open_nursery() as n:
|
||||||
tractor.trionics.collapse_eg(), # needed?
|
|
||||||
trio.open_nursery() as tn
|
|
||||||
):
|
|
||||||
# start a background multi-searcher task which receives
|
# start a background multi-searcher task which receives
|
||||||
# patterns relayed from this keyboard input handler and
|
# patterns relayed from this keyboard input handler and
|
||||||
# async updates the completer view's results.
|
# async updates the completer view's results.
|
||||||
tn.start_soon(
|
n.start_soon(
|
||||||
partial(
|
partial(
|
||||||
fill_results,
|
fill_results,
|
||||||
searchw,
|
searchw,
|
||||||
|
|
|
||||||
|
|
@ -269,8 +269,6 @@ def hcolor(name: str) -> str:
|
||||||
|
|
||||||
# default ohlc-bars/curve gray
|
# default ohlc-bars/curve gray
|
||||||
'bracket': '#666666', # like the logo
|
'bracket': '#666666', # like the logo
|
||||||
'pikers': '#616161', # a trader shade of..
|
|
||||||
'beast': '#161616', # in the dark alone.
|
|
||||||
|
|
||||||
# bluish
|
# bluish
|
||||||
'charcoal': '#36454F',
|
'charcoal': '#36454F',
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,6 @@ Chart trading, the only way to scalp.
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from decimal import Decimal
|
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from pprint import pformat
|
from pprint import pformat
|
||||||
import time
|
import time
|
||||||
|
|
@ -42,6 +41,7 @@ from piker.accounting import (
|
||||||
Position,
|
Position,
|
||||||
mk_allocator,
|
mk_allocator,
|
||||||
MktPair,
|
MktPair,
|
||||||
|
Symbol,
|
||||||
)
|
)
|
||||||
from piker.clearing import (
|
from piker.clearing import (
|
||||||
open_ems,
|
open_ems,
|
||||||
|
|
@ -143,15 +143,6 @@ class OrderMode:
|
||||||
}
|
}
|
||||||
_staged_order: Order | None = None
|
_staged_order: Order | None = None
|
||||||
|
|
||||||
@property
|
|
||||||
def curr_mkt(self) -> MktPair:
|
|
||||||
'''
|
|
||||||
Deliver the currently selected `MktPair` according
|
|
||||||
chart state.
|
|
||||||
|
|
||||||
'''
|
|
||||||
return self.chart.linked.mkt
|
|
||||||
|
|
||||||
def on_level_change_update_next_order_info(
|
def on_level_change_update_next_order_info(
|
||||||
self,
|
self,
|
||||||
level: float,
|
level: float,
|
||||||
|
|
@ -181,11 +172,7 @@ class OrderMode:
|
||||||
line.update_labels(order_info)
|
line.update_labels(order_info)
|
||||||
|
|
||||||
# update bound-in staged order
|
# update bound-in staged order
|
||||||
mkt: MktPair = self.curr_mkt
|
order.price = level
|
||||||
order.price: Decimal = mkt.quantize(
|
|
||||||
size=level,
|
|
||||||
quantity_type='price',
|
|
||||||
)
|
|
||||||
order.size = order_info['size']
|
order.size = order_info['size']
|
||||||
|
|
||||||
# when an order is changed we flip the settings side-pane to
|
# when an order is changed we flip the settings side-pane to
|
||||||
|
|
@ -200,9 +187,7 @@ class OrderMode:
|
||||||
|
|
||||||
) -> LevelLine:
|
) -> LevelLine:
|
||||||
|
|
||||||
# TODO, if we instead just always decimalize at the ems layer
|
level = order.price
|
||||||
# we can avoid this back-n-forth casting?
|
|
||||||
level = float(order.price)
|
|
||||||
|
|
||||||
line = order_line(
|
line = order_line(
|
||||||
chart or self.chart,
|
chart or self.chart,
|
||||||
|
|
@ -239,11 +224,7 @@ class OrderMode:
|
||||||
# the order mode allocator but we still need to update the
|
# the order mode allocator but we still need to update the
|
||||||
# "staged" order message we'll send to the ems
|
# "staged" order message we'll send to the ems
|
||||||
def update_order_price(y: float) -> None:
|
def update_order_price(y: float) -> None:
|
||||||
mkt: MktPair = self.curr_mkt
|
order.price = y
|
||||||
order.price: Decimal = mkt.quantize(
|
|
||||||
size=y,
|
|
||||||
quantity_type='price',
|
|
||||||
)
|
|
||||||
|
|
||||||
line._on_level_change = update_order_price
|
line._on_level_change = update_order_price
|
||||||
|
|
||||||
|
|
@ -294,31 +275,34 @@ class OrderMode:
|
||||||
chart = cursor.linked.chart
|
chart = cursor.linked.chart
|
||||||
if (
|
if (
|
||||||
not chart
|
not chart
|
||||||
and
|
and cursor
|
||||||
cursor
|
and cursor.active_plot
|
||||||
and
|
|
||||||
cursor.active_plot
|
|
||||||
):
|
):
|
||||||
return
|
return
|
||||||
|
|
||||||
chart = cursor.active_plot
|
chart = cursor.active_plot
|
||||||
price: float = cursor._datum_xy[1]
|
price = cursor._datum_xy[1]
|
||||||
if not price:
|
if not price:
|
||||||
# zero prices are not supported by any means
|
# zero prices are not supported by any means
|
||||||
# since that's illogical / a no-op.
|
# since that's illogical / a no-op.
|
||||||
return
|
return
|
||||||
|
|
||||||
|
mkt: MktPair = self.chart.linked.mkt
|
||||||
|
|
||||||
|
# NOTE : we could also use instead,
|
||||||
|
# mkt.quantize(price, quantity_type='price')
|
||||||
|
# but it returns a Decimal and it's probably gonna
|
||||||
|
# be slower?
|
||||||
# TODO: should we be enforcing this precision
|
# TODO: should we be enforcing this precision
|
||||||
# at a different layer in the stack?
|
# at a different layer in the stack? right now
|
||||||
# |_ might require `MktPair` tracking in the EMS?
|
# any precision error will literally be relayed
|
||||||
# |_ right now any precision error will be relayed
|
# all the way back from the backend.
|
||||||
# all the way back from the backend and vice-versa..
|
|
||||||
#
|
price = round(
|
||||||
mkt: MktPair = self.curr_mkt
|
price,
|
||||||
price: Decimal = mkt.quantize(
|
ndigits=mkt.price_tick_digits,
|
||||||
size=price,
|
|
||||||
quantity_type='price',
|
|
||||||
)
|
)
|
||||||
|
|
||||||
order = self._staged_order = Order(
|
order = self._staged_order = Order(
|
||||||
action=action,
|
action=action,
|
||||||
price=price,
|
price=price,
|
||||||
|
|
@ -394,7 +378,7 @@ class OrderMode:
|
||||||
'oid': oid,
|
'oid': oid,
|
||||||
})
|
})
|
||||||
|
|
||||||
if float(order.price) <= 0:
|
if order.price <= 0:
|
||||||
log.error(
|
log.error(
|
||||||
'*!? Invalid `Order.price <= 0` ?!*\n'
|
'*!? Invalid `Order.price <= 0` ?!*\n'
|
||||||
# TODO: make this present multi-line in object form
|
# TODO: make this present multi-line in object form
|
||||||
|
|
@ -531,15 +515,14 @@ class OrderMode:
|
||||||
# if an order msg is provided update the line
|
# if an order msg is provided update the line
|
||||||
# **from** that msg.
|
# **from** that msg.
|
||||||
if order:
|
if order:
|
||||||
price: float = float(order.price)
|
if order.price <= 0:
|
||||||
if price <= 0:
|
|
||||||
log.error(f'Order has 0 price, cancelling..\n{order}')
|
log.error(f'Order has 0 price, cancelling..\n{order}')
|
||||||
self.cancel_orders([order.oid])
|
self.cancel_orders([order.oid])
|
||||||
return None
|
return None
|
||||||
|
|
||||||
line.set_level(price)
|
line.set_level(order.price)
|
||||||
self.on_level_change_update_next_order_info(
|
self.on_level_change_update_next_order_info(
|
||||||
level=price,
|
level=order.price,
|
||||||
line=line,
|
line=line,
|
||||||
order=order,
|
order=order,
|
||||||
# use the corresponding position tracker for the
|
# use the corresponding position tracker for the
|
||||||
|
|
@ -555,13 +538,14 @@ class OrderMode:
|
||||||
|
|
||||||
def on_fill(
|
def on_fill(
|
||||||
self,
|
self,
|
||||||
|
|
||||||
uuid: str,
|
uuid: str,
|
||||||
price: float,
|
price: float,
|
||||||
time_s: float,
|
time_s: float,
|
||||||
|
|
||||||
pointing: str | None = None,
|
pointing: str | None = None,
|
||||||
|
|
||||||
) -> bool:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
Fill msg handler.
|
Fill msg handler.
|
||||||
|
|
||||||
|
|
@ -574,33 +558,13 @@ class OrderMode:
|
||||||
- update fill bar size
|
- update fill bar size
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# XXX WARNING XXX
|
dialog = self.dialogs[uuid]
|
||||||
# if a `Status(resp='error')` arrives *before* this
|
|
||||||
# fill-status, the `.dialogs` entry may have already been
|
|
||||||
# popped and thus the below will skipped.
|
|
||||||
#
|
|
||||||
# NOTE, to avoid this confusing scenario ensure that any
|
|
||||||
# errors delivered thru from the broker-backend are not just
|
|
||||||
# "noisy reporting" (like is very common from IB..) and are
|
|
||||||
# instead ONLY errors-causing-order-dialog-cancellation!
|
|
||||||
if not (dialog := self.dialogs.get(uuid)):
|
|
||||||
log.warning(
|
|
||||||
f'Order was already cleared from `.dialogs` ??\n'
|
|
||||||
f'uuid: {uuid!r}\n'
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
|
|
||||||
lines = dialog.lines
|
lines = dialog.lines
|
||||||
chart = self.chart
|
chart = self.chart
|
||||||
|
|
||||||
if not lines:
|
# XXX: seems to fail on certain types of races?
|
||||||
log.warn("No line(s) for order {uuid}!?")
|
|
||||||
return False
|
|
||||||
|
|
||||||
# update line state(s)
|
|
||||||
#
|
|
||||||
# ?XXX this fails on certain types of races?
|
|
||||||
# assert len(lines) == 2
|
# assert len(lines) == 2
|
||||||
|
if lines:
|
||||||
flume: Flume = self.feed.flumes[chart.linked.mkt.fqme]
|
flume: Flume = self.feed.flumes[chart.linked.mkt.fqme]
|
||||||
_, _, ratio = flume.get_ds_info()
|
_, _, ratio = flume.get_ds_info()
|
||||||
|
|
||||||
|
|
@ -626,31 +590,28 @@ class OrderMode:
|
||||||
pointing=pointing,
|
pointing=pointing,
|
||||||
color=lines[0].color
|
color=lines[0].color
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
log.warn("No line(s) for order {uuid}!?")
|
||||||
|
|
||||||
def on_cancel(
|
def on_cancel(
|
||||||
self,
|
self,
|
||||||
uuid: str,
|
uuid: str
|
||||||
|
|
||||||
) -> bool:
|
) -> None:
|
||||||
|
|
||||||
msg: Order|None = self.client._sent_orders.pop(uuid, None)
|
msg: Order = self.client._sent_orders.pop(uuid, None)
|
||||||
if msg is None:
|
|
||||||
log.warning(
|
|
||||||
f'Received cancel for unsubmitted order {pformat(msg)}'
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
|
|
||||||
# remove GUI line, show cursor.
|
if msg is not None:
|
||||||
self.lines.remove_line(uuid=uuid)
|
self.lines.remove_line(uuid=uuid)
|
||||||
self.chart.linked.cursor.show_xhair()
|
self.chart.linked.cursor.show_xhair()
|
||||||
|
|
||||||
# remove msg dialog (history)
|
dialog = self.dialogs.pop(uuid, None)
|
||||||
dialog: Dialog|None = self.dialogs.pop(uuid, None)
|
|
||||||
if dialog:
|
if dialog:
|
||||||
dialog.last_status_close()
|
dialog.last_status_close()
|
||||||
|
else:
|
||||||
return True
|
log.warning(
|
||||||
|
f'Received cancel for unsubmitted order {pformat(msg)}'
|
||||||
|
)
|
||||||
|
|
||||||
def cancel_orders_under_cursor(self) -> list[str]:
|
def cancel_orders_under_cursor(self) -> list[str]:
|
||||||
return self.cancel_orders(
|
return self.cancel_orders(
|
||||||
|
|
@ -720,9 +681,9 @@ class OrderMode:
|
||||||
) -> Dialog | None:
|
) -> Dialog | None:
|
||||||
# NOTE: the `.order` attr **must** be set with the
|
# NOTE: the `.order` attr **must** be set with the
|
||||||
# equivalent order msg in order to be loaded.
|
# equivalent order msg in order to be loaded.
|
||||||
order: Order = msg.req
|
order = msg.req
|
||||||
oid = str(msg.oid)
|
oid = str(msg.oid)
|
||||||
symbol: str = order.symbol
|
symbol = order.symbol
|
||||||
|
|
||||||
# TODO: MEGA UGGG ZONEEEE!
|
# TODO: MEGA UGGG ZONEEEE!
|
||||||
src = msg.src
|
src = msg.src
|
||||||
|
|
@ -741,22 +702,13 @@ class OrderMode:
|
||||||
order.oid = str(order.oid)
|
order.oid = str(order.oid)
|
||||||
order.brokers = [brokername]
|
order.brokers = [brokername]
|
||||||
|
|
||||||
# ?TODO? change this over to `MktPair`, but it's gonna be
|
# TODO: change this over to `MktPair`, but it's
|
||||||
# tough since we don't have any such data really in our
|
# gonna be tough since we don't have any such data
|
||||||
# clearing msg schema..
|
# really in our clearing msg schema..
|
||||||
# BUT WAIT! WHY do we even want/need this!?
|
order.symbol = Symbol.from_fqme(
|
||||||
#
|
fqsn=fqme,
|
||||||
# order.symbol = self.curr_mkt
|
info={},
|
||||||
#
|
)
|
||||||
# XXX, the old approach.. which i don't quire member why..
|
|
||||||
# -[ ] verify we for sure don't require this any more!
|
|
||||||
# |_https://github.com/pikers/piker/issues/517
|
|
||||||
#
|
|
||||||
# order.symbol = Symbol.from_fqme(
|
|
||||||
# fqsn=fqme,
|
|
||||||
# info={},
|
|
||||||
# )
|
|
||||||
|
|
||||||
maybe_dialog: Dialog | None = self.submit_order(
|
maybe_dialog: Dialog | None = self.submit_order(
|
||||||
send_msg=False,
|
send_msg=False,
|
||||||
order=order,
|
order=order,
|
||||||
|
|
@ -814,7 +766,6 @@ async def open_order_mode(
|
||||||
brokerd_accounts,
|
brokerd_accounts,
|
||||||
ems_dialog_msgs,
|
ems_dialog_msgs,
|
||||||
),
|
),
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
|
|
||||||
):
|
):
|
||||||
|
|
@ -1079,23 +1030,13 @@ async def process_trade_msg(
|
||||||
if name in (
|
if name in (
|
||||||
'position',
|
'position',
|
||||||
):
|
):
|
||||||
mkt: MktPair = mode.chart.linked.mkt
|
sym: MktPair = mode.chart.linked.mkt
|
||||||
pp_msg_symbol = msg['symbol'].lower()
|
pp_msg_symbol = msg['symbol'].lower()
|
||||||
pp_msg_bsmktid = msg['bs_mktid']
|
fqme = sym.fqme
|
||||||
fqme = mkt.fqme
|
broker = sym.broker
|
||||||
broker = mkt.broker
|
|
||||||
if (
|
if (
|
||||||
# match on any backed-specific(-unique)-ID first!
|
|
||||||
(
|
|
||||||
pp_msg_bsmktid
|
|
||||||
and
|
|
||||||
mkt.bs_mktid == pp_msg_bsmktid
|
|
||||||
)
|
|
||||||
or
|
|
||||||
# OW try against what's provided as an FQME..
|
|
||||||
pp_msg_symbol == fqme
|
pp_msg_symbol == fqme
|
||||||
or
|
or pp_msg_symbol == fqme.removesuffix(f'.{broker}')
|
||||||
pp_msg_symbol == fqme.removesuffix(f'.{broker}')
|
|
||||||
):
|
):
|
||||||
log.info(
|
log.info(
|
||||||
f'Loading position for `{fqme}`:\n'
|
f'Loading position for `{fqme}`:\n'
|
||||||
|
|
@ -1118,7 +1059,7 @@ async def process_trade_msg(
|
||||||
return
|
return
|
||||||
|
|
||||||
msg = Status(**msg)
|
msg = Status(**msg)
|
||||||
# resp: str = msg.resp
|
resp = msg.resp
|
||||||
oid = msg.oid
|
oid = msg.oid
|
||||||
dialog: Dialog = mode.dialogs.get(oid)
|
dialog: Dialog = mode.dialogs.get(oid)
|
||||||
|
|
||||||
|
|
@ -1160,7 +1101,7 @@ async def process_trade_msg(
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
):
|
):
|
||||||
msg.req: Order = order
|
msg.req = order
|
||||||
dialog: (
|
dialog: (
|
||||||
Dialog
|
Dialog
|
||||||
# NOTE: on an invalid order submission (eg.
|
# NOTE: on an invalid order submission (eg.
|
||||||
|
|
@ -1182,33 +1123,20 @@ async def process_trade_msg(
|
||||||
mode.on_submit(oid)
|
mode.on_submit(oid)
|
||||||
|
|
||||||
case Status(resp='error'):
|
case Status(resp='error'):
|
||||||
# TODO: parse into broker-side msg, or should we
|
|
||||||
# expect it to just be **that** msg verbatim (since
|
|
||||||
# we'd presumably have only 1 `Error` msg-struct)
|
|
||||||
broker_msg: dict = msg.brokerd_msg
|
|
||||||
|
|
||||||
# XXX NOTE, this presumes the rxed "error" is
|
|
||||||
# order-dialog-cancel-causing, THUS backends much ONLY
|
|
||||||
# relay errors of this "severity"!!
|
|
||||||
log.error(
|
|
||||||
f'Order errored ??\n'
|
|
||||||
f'oid: {oid!r}\n'
|
|
||||||
f'\n'
|
|
||||||
f'{pformat(broker_msg)}\n'
|
|
||||||
f'\n'
|
|
||||||
f'=> CANCELLING ORDER DIALOG <=\n'
|
|
||||||
|
|
||||||
# from tractor.devx.pformat import ppfmt
|
|
||||||
# !TODO LOL, wtf the msg is causing
|
|
||||||
# a recursion bug!
|
|
||||||
# -[ ] get this shit on msgspec stat!
|
|
||||||
# f'{ppfmt(broker_msg)}'
|
|
||||||
)
|
|
||||||
# do all the things for a cancel:
|
# do all the things for a cancel:
|
||||||
# - drop order-msg dialog from client table
|
# - drop order-msg dialog from client table
|
||||||
# - delete level line from view
|
# - delete level line from view
|
||||||
mode.on_cancel(oid)
|
mode.on_cancel(oid)
|
||||||
|
|
||||||
|
# TODO: parse into broker-side msg, or should we
|
||||||
|
# expect it to just be **that** msg verbatim (since
|
||||||
|
# we'd presumably have only 1 `Error` msg-struct)
|
||||||
|
broker_msg: dict = msg.brokerd_msg
|
||||||
|
log.error(
|
||||||
|
f'Order {oid}->{resp} with:\n{pformat(broker_msg)}'
|
||||||
|
)
|
||||||
|
|
||||||
case Status(resp='canceled'):
|
case Status(resp='canceled'):
|
||||||
# delete level line from view
|
# delete level line from view
|
||||||
mode.on_cancel(oid)
|
mode.on_cancel(oid)
|
||||||
|
|
@ -1223,10 +1151,10 @@ async def process_trade_msg(
|
||||||
# TODO: UX for a "pending" clear/live order
|
# TODO: UX for a "pending" clear/live order
|
||||||
log.info(f'Dark order triggered for {fmtmsg}')
|
log.info(f'Dark order triggered for {fmtmsg}')
|
||||||
|
|
||||||
# TODO: do the struct-msg version, blah blah..
|
|
||||||
# req=Order(exec_mode='live', action='alert') as req,
|
|
||||||
case Status(
|
case Status(
|
||||||
resp='triggered',
|
resp='triggered',
|
||||||
|
# TODO: do the struct-msg version, blah blah..
|
||||||
|
# req=Order(exec_mode='live', action='alert') as req,
|
||||||
req={
|
req={
|
||||||
'exec_mode': 'live',
|
'exec_mode': 'live',
|
||||||
'action': 'alert',
|
'action': 'alert',
|
||||||
|
|
@ -1238,7 +1166,7 @@ async def process_trade_msg(
|
||||||
tm = time.time()
|
tm = time.time()
|
||||||
mode.on_fill(
|
mode.on_fill(
|
||||||
oid,
|
oid,
|
||||||
price=float(req.price),
|
price=req.price,
|
||||||
time_s=tm,
|
time_s=tm,
|
||||||
)
|
)
|
||||||
mode.lines.remove_line(uuid=oid)
|
mode.lines.remove_line(uuid=oid)
|
||||||
|
|
@ -1293,7 +1221,7 @@ async def process_trade_msg(
|
||||||
tm = details['broker_time']
|
tm = details['broker_time']
|
||||||
mode.on_fill(
|
mode.on_fill(
|
||||||
oid,
|
oid,
|
||||||
price=float(details['price']),
|
price=details['price'],
|
||||||
time_s=tm,
|
time_s=tm,
|
||||||
pointing='up' if action == 'buy' else 'down',
|
pointing='up' if action == 'buy' else 'down',
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -2,13 +2,13 @@
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "anyio"
|
name = "anyio"
|
||||||
version = "3.7.1"
|
version = "4.6.2.post1"
|
||||||
description = "High level compatibility layer for multiple asynchronous event loop implementations"
|
description = "High level compatibility layer for multiple asynchronous event loop implementations"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.9"
|
||||||
files = [
|
files = [
|
||||||
{file = "anyio-3.7.1-py3-none-any.whl", hash = "sha256:91dee416e570e92c64041bd18b900d1d6fa78dff7048769ce5ac5ddad004fbb5"},
|
{file = "anyio-4.6.2.post1-py3-none-any.whl", hash = "sha256:6d170c36fba3bdd840c73d3868c1e777e33676a69c3a72cf0a0d5d6d8009b61d"},
|
||||||
{file = "anyio-3.7.1.tar.gz", hash = "sha256:44a3c9aba0f5defa43261a8b3efb97891f2bd7d804e0e1f56419befa1adfc780"},
|
{file = "anyio-4.6.2.post1.tar.gz", hash = "sha256:4c8bc31ccdb51c7f7bd251f51c609e038d63e34219b44aa86e47576389880b4c"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
|
|
@ -50,7 +50,7 @@ files = [
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "asyncvnc"
|
name = "asyncvnc"
|
||||||
version = "1.1.0"
|
version = "1.1.0"
|
||||||
description = ""
|
description = "Asynchronous VNC for Python"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">= 3.7"
|
python-versions = ">= 3.7"
|
||||||
files = []
|
files = []
|
||||||
|
|
@ -69,21 +69,22 @@ resolved_reference = "825447564e3af6b0d4a0996793f1ca7fb360c48f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "attrs"
|
name = "attrs"
|
||||||
version = "23.1.0"
|
version = "23.2.0"
|
||||||
description = "Classes Without Boilerplate"
|
description = "Classes Without Boilerplate"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.7"
|
||||||
files = [
|
files = [
|
||||||
{file = "attrs-23.1.0-py3-none-any.whl", hash = "sha256:1f28b4522cdc2fb4256ac1a020c78acf9cba2c6b461ccd2c126f3aa8e8335d04"},
|
{file = "attrs-23.2.0-py3-none-any.whl", hash = "sha256:99b87a485a5820b23b879f04c2305b44b951b502fd64be915879d77a7e8fc6f1"},
|
||||||
{file = "attrs-23.1.0.tar.gz", hash = "sha256:6279836d581513a26f1bf235f9acd333bc9115683f14f7e8fae46c98fc50e015"},
|
{file = "attrs-23.2.0.tar.gz", hash = "sha256:935dc3b529c262f6cf76e50877d35a4bd3c1de194fd41f47a2b7ae8f19971f30"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.extras]
|
[package.extras]
|
||||||
cov = ["attrs[tests]", "coverage[toml] (>=5.3)"]
|
cov = ["attrs[tests]", "coverage[toml] (>=5.3)"]
|
||||||
dev = ["attrs[docs,tests]", "pre-commit"]
|
dev = ["attrs[tests]", "pre-commit"]
|
||||||
docs = ["furo", "myst-parser", "sphinx", "sphinx-notfound-page", "sphinxcontrib-towncrier", "towncrier", "zope-interface"]
|
docs = ["furo", "myst-parser", "sphinx", "sphinx-notfound-page", "sphinxcontrib-towncrier", "towncrier", "zope-interface"]
|
||||||
tests = ["attrs[tests-no-zope]", "zope-interface"]
|
tests = ["attrs[tests-no-zope]", "zope-interface"]
|
||||||
tests-no-zope = ["cloudpickle", "hypothesis", "mypy (>=1.1.1)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "pytest-xdist[psutil]"]
|
tests-mypy = ["mypy (>=1.6)", "pytest-mypy-plugins"]
|
||||||
|
tests-no-zope = ["attrs[tests-mypy]", "cloudpickle", "hypothesis", "pympler", "pytest (>=4.3.0)", "pytest-xdist[psutil]"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bidict"
|
name = "bidict"
|
||||||
|
|
@ -103,75 +104,78 @@ test = ["hypothesis", "pytest", "pytest-benchmark[histogram]", "pytest-cov", "py
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cffi"
|
name = "cffi"
|
||||||
version = "1.15.1"
|
version = "1.17.1"
|
||||||
description = "Foreign Function Interface for Python calling C code."
|
description = "Foreign Function Interface for Python calling C code."
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = "*"
|
python-versions = ">=3.8"
|
||||||
files = [
|
files = [
|
||||||
{file = "cffi-1.15.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:a66d3508133af6e8548451b25058d5812812ec3798c886bf38ed24a98216fab2"},
|
{file = "cffi-1.17.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:df8b1c11f177bc2313ec4b2d46baec87a5f3e71fc8b45dab2ee7cae86d9aba14"},
|
||||||
{file = "cffi-1.15.1-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:470c103ae716238bbe698d67ad020e1db9d9dba34fa5a899b5e21577e6d52ed2"},
|
{file = "cffi-1.17.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8f2cdc858323644ab277e9bb925ad72ae0e67f69e804f4898c070998d50b1a67"},
|
||||||
{file = "cffi-1.15.1-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:9ad5db27f9cabae298d151c85cf2bad1d359a1b9c686a275df03385758e2f914"},
|
{file = "cffi-1.17.1-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:edae79245293e15384b51f88b00613ba9f7198016a5948b5dddf4917d4d26382"},
|
||||||
{file = "cffi-1.15.1-cp27-cp27m-win32.whl", hash = "sha256:b3bbeb01c2b273cca1e1e0c5df57f12dce9a4dd331b4fa1635b8bec26350bde3"},
|
{file = "cffi-1.17.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:45398b671ac6d70e67da8e4224a065cec6a93541bb7aebe1b198a61b58c7b702"},
|
||||||
{file = "cffi-1.15.1-cp27-cp27m-win_amd64.whl", hash = "sha256:e00b098126fd45523dd056d2efba6c5a63b71ffe9f2bbe1a4fe1716e1d0c331e"},
|
{file = "cffi-1.17.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ad9413ccdeda48c5afdae7e4fa2192157e991ff761e7ab8fdd8926f40b160cc3"},
|
||||||
{file = "cffi-1.15.1-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:d61f4695e6c866a23a21acab0509af1cdfd2c013cf256bbf5b6b5e2695827162"},
|
{file = "cffi-1.17.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5da5719280082ac6bd9aa7becb3938dc9f9cbd57fac7d2871717b1feb0902ab6"},
|
||||||
{file = "cffi-1.15.1-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:ed9cb427ba5504c1dc15ede7d516b84757c3e3d7868ccc85121d9310d27eed0b"},
|
{file = "cffi-1.17.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bb1a08b8008b281856e5971307cc386a8e9c5b625ac297e853d36da6efe9c17"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:39d39875251ca8f612b6f33e6b1195af86d1b3e60086068be9cc053aa4376e21"},
|
{file = "cffi-1.17.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:045d61c734659cc045141be4bae381a41d89b741f795af1dd018bfb532fd0df8"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:285d29981935eb726a4399badae8f0ffdff4f5050eaa6d0cfc3f64b857b77185"},
|
{file = "cffi-1.17.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:6883e737d7d9e4899a8a695e00ec36bd4e5e4f18fabe0aca0efe0a4b44cdb13e"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3eb6971dcff08619f8d91607cfc726518b6fa2a9eba42856be181c6d0d9515fd"},
|
{file = "cffi-1.17.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:6b8b4a92e1c65048ff98cfe1f735ef8f1ceb72e3d5f0c25fdb12087a23da22be"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:21157295583fe8943475029ed5abdcf71eb3911894724e360acff1d61c1d54bc"},
|
{file = "cffi-1.17.1-cp310-cp310-win32.whl", hash = "sha256:c9c3d058ebabb74db66e431095118094d06abf53284d9c81f27300d0e0d8bc7c"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5635bd9cb9731e6d4a1132a498dd34f764034a8ce60cef4f5319c0541159392f"},
|
{file = "cffi-1.17.1-cp310-cp310-win_amd64.whl", hash = "sha256:0f048dcf80db46f0098ccac01132761580d28e28bc0f78ae0d58048063317e15"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2012c72d854c2d03e45d06ae57f40d78e5770d252f195b93f581acf3ba44496e"},
|
{file = "cffi-1.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a45e3c6913c5b87b3ff120dcdc03f6131fa0065027d0ed7ee6190736a74cd401"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd86c085fae2efd48ac91dd7ccffcfc0571387fe1193d33b6394db7ef31fe2a4"},
|
{file = "cffi-1.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:30c5e0cb5ae493c04c8b42916e52ca38079f1b235c2f8ae5f4527b963c401caf"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:fa6693661a4c91757f4412306191b6dc88c1703f780c8234035eac011922bc01"},
|
{file = "cffi-1.17.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f75c7ab1f9e4aca5414ed4d8e5c0e303a34f4421f8a0d47a4d019ceff0ab6af4"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:59c0b02d0a6c384d453fece7566d1c7e6b7bae4fc5874ef2ef46d56776d61c9e"},
|
{file = "cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a1ed2dd2972641495a3ec98445e09766f077aee98a1c896dcb4ad0d303628e41"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-win32.whl", hash = "sha256:cba9d6b9a7d64d4bd46167096fc9d2f835e25d7e4c121fb2ddfc6528fb0413b2"},
|
{file = "cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:46bf43160c1a35f7ec506d254e5c890f3c03648a4dbac12d624e4490a7046cd1"},
|
||||||
{file = "cffi-1.15.1-cp310-cp310-win_amd64.whl", hash = "sha256:ce4bcc037df4fc5e3d184794f27bdaab018943698f4ca31630bc7f84a7b69c6d"},
|
{file = "cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a24ed04c8ffd54b0729c07cee15a81d964e6fee0e3d4d342a27b020d22959dc6"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3d08afd128ddaa624a48cf2b859afef385b720bb4b43df214f85616922e6a5ac"},
|
{file = "cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:610faea79c43e44c71e1ec53a554553fa22321b65fae24889706c0a84d4ad86d"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3799aecf2e17cf585d977b780ce79ff0dc9b78d799fc694221ce814c2c19db83"},
|
{file = "cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a9b15d491f3ad5d692e11f6b71f7857e7835eb677955c00cc0aefcd0669adaf6"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a591fe9e525846e4d154205572a029f653ada1a78b93697f3b5a8f1f2bc055b9"},
|
{file = "cffi-1.17.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:de2ea4b5833625383e464549fec1bc395c1bdeeb5f25c4a3a82b5a8c756ec22f"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3548db281cd7d2561c9ad9984681c95f7b0e38881201e157833a2342c30d5e8c"},
|
{file = "cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fc48c783f9c87e60831201f2cce7f3b2e4846bf4d8728eabe54d60700b318a0b"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:91fc98adde3d7881af9b59ed0294046f3806221863722ba7d8d120c575314325"},
|
{file = "cffi-1.17.1-cp311-cp311-win32.whl", hash = "sha256:85a950a4ac9c359340d5963966e3e0a94a676bd6245a4b55bc43949eee26a655"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:94411f22c3985acaec6f83c6df553f2dbe17b698cc7f8ae751ff2237d96b9e3c"},
|
{file = "cffi-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:caaf0640ef5f5517f49bc275eca1406b0ffa6aa184892812030f04c2abf589a0"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:03425bdae262c76aad70202debd780501fabeaca237cdfddc008987c0e0f59ef"},
|
{file = "cffi-1.17.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:805b4371bf7197c329fcb3ead37e710d1bca9da5d583f5073b799d5c5bd1eee4"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:cc4d65aeeaa04136a12677d3dd0b1c0c94dc43abac5860ab33cceb42b801c1e8"},
|
{file = "cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:733e99bc2df47476e3848417c5a4540522f234dfd4ef3ab7fafdf555b082ec0c"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-win32.whl", hash = "sha256:a0f100c8912c114ff53e1202d0078b425bee3649ae34d7b070e9697f93c5d52d"},
|
{file = "cffi-1.17.1-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1257bdabf294dceb59f5e70c64a3e2f462c30c7ad68092d01bbbfb1c16b1ba36"},
|
||||||
{file = "cffi-1.15.1-cp311-cp311-win_amd64.whl", hash = "sha256:04ed324bda3cda42b9b695d51bb7d54b680b9719cfab04227cdd1e04e5de3104"},
|
{file = "cffi-1.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da95af8214998d77a98cc14e3a3bd00aa191526343078b530ceb0bd710fb48a5"},
|
||||||
{file = "cffi-1.15.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50a74364d85fd319352182ef59c5c790484a336f6db772c1a9231f1c3ed0cbd7"},
|
{file = "cffi-1.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d63afe322132c194cf832bfec0dc69a99fb9bb6bbd550f161a49e9e855cc78ff"},
|
||||||
{file = "cffi-1.15.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e263d77ee3dd201c3a142934a086a4450861778baaeeb45db4591ef65550b0a6"},
|
{file = "cffi-1.17.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f79fc4fc25f1c8698ff97788206bb3c2598949bfe0fef03d299eb1b5356ada99"},
|
||||||
{file = "cffi-1.15.1-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cec7d9412a9102bdc577382c3929b337320c4c4c4849f2c5cdd14d7368c5562d"},
|
{file = "cffi-1.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b62ce867176a75d03a665bad002af8e6d54644fad99a3c70905c543130e39d93"},
|
||||||
{file = "cffi-1.15.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4289fc34b2f5316fbb762d75362931e351941fa95fa18789191b33fc4cf9504a"},
|
{file = "cffi-1.17.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:386c8bf53c502fff58903061338ce4f4950cbdcb23e2902d86c0f722b786bbe3"},
|
||||||
{file = "cffi-1.15.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:173379135477dc8cac4bc58f45db08ab45d228b3363adb7af79436135d028405"},
|
{file = "cffi-1.17.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4ceb10419a9adf4460ea14cfd6bc43d08701f0835e979bf821052f1805850fe8"},
|
||||||
{file = "cffi-1.15.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:6975a3fac6bc83c4a65c9f9fcab9e47019a11d3d2cf7f3c0d03431bf145a941e"},
|
{file = "cffi-1.17.1-cp312-cp312-win32.whl", hash = "sha256:a08d7e755f8ed21095a310a693525137cfe756ce62d066e53f502a83dc550f65"},
|
||||||
{file = "cffi-1.15.1-cp36-cp36m-win32.whl", hash = "sha256:2470043b93ff09bf8fb1d46d1cb756ce6132c54826661a32d4e4d132e1977adf"},
|
{file = "cffi-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903"},
|
||||||
{file = "cffi-1.15.1-cp36-cp36m-win_amd64.whl", hash = "sha256:30d78fbc8ebf9c92c9b7823ee18eb92f2e6ef79b45ac84db507f52fbe3ec4497"},
|
{file = "cffi-1.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f3a2b4222ce6b60e2e8b337bb9596923045681d71e5a082783484d845390938e"},
|
||||||
{file = "cffi-1.15.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:198caafb44239b60e252492445da556afafc7d1e3ab7a1fb3f0584ef6d742375"},
|
{file = "cffi-1.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0984a4925a435b1da406122d4d7968dd861c1385afe3b45ba82b750f229811e2"},
|
||||||
{file = "cffi-1.15.1-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5ef34d190326c3b1f822a5b7a45f6c4535e2f47ed06fec77d3d799c450b2651e"},
|
{file = "cffi-1.17.1-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d01b12eeeb4427d3110de311e1774046ad344f5b1a7403101878976ecd7a10f3"},
|
||||||
{file = "cffi-1.15.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8102eaf27e1e448db915d08afa8b41d6c7ca7a04b7d73af6514df10a3e74bd82"},
|
{file = "cffi-1.17.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:706510fe141c86a69c8ddc029c7910003a17353970cff3b904ff0686a5927683"},
|
||||||
{file = "cffi-1.15.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5df2768244d19ab7f60546d0c7c63ce1581f7af8b5de3eb3004b9b6fc8a9f84b"},
|
{file = "cffi-1.17.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de55b766c7aa2e2a3092c51e0483d700341182f08e67c63630d5b6f200bb28e5"},
|
||||||
{file = "cffi-1.15.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a8c4917bd7ad33e8eb21e9a5bbba979b49d9a97acb3a803092cbc1133e20343c"},
|
{file = "cffi-1.17.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c59d6e989d07460165cc5ad3c61f9fd8f1b4796eacbd81cee78957842b834af4"},
|
||||||
{file = "cffi-1.15.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e2642fe3142e4cc4af0799748233ad6da94c62a8bec3a6648bf8ee68b1c7426"},
|
{file = "cffi-1.17.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd398dbc6773384a17fe0d3e7eeb8d1a21c2200473ee6806bb5e6a8e62bb73dd"},
|
||||||
{file = "cffi-1.15.1-cp37-cp37m-win32.whl", hash = "sha256:e229a521186c75c8ad9490854fd8bbdd9a0c9aa3a524326b55be83b54d4e0ad9"},
|
{file = "cffi-1.17.1-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3edc8d958eb099c634dace3c7e16560ae474aa3803a5df240542b305d14e14ed"},
|
||||||
{file = "cffi-1.15.1-cp37-cp37m-win_amd64.whl", hash = "sha256:a0b71b1b8fbf2b96e41c4d990244165e2c9be83d54962a9a1d118fd8657d2045"},
|
{file = "cffi-1.17.1-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:72e72408cad3d5419375fc87d289076ee319835bdfa2caad331e377589aebba9"},
|
||||||
{file = "cffi-1.15.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:320dab6e7cb2eacdf0e658569d2575c4dad258c0fcc794f46215e1e39f90f2c3"},
|
{file = "cffi-1.17.1-cp313-cp313-win32.whl", hash = "sha256:e03eab0a8677fa80d646b5ddece1cbeaf556c313dcfac435ba11f107ba117b5d"},
|
||||||
{file = "cffi-1.15.1-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e74c6b51a9ed6589199c787bf5f9875612ca4a8a0785fb2d4a84429badaf22a"},
|
{file = "cffi-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:f6a16c31041f09ead72d69f583767292f750d24913dadacf5756b966aacb3f1a"},
|
||||||
{file = "cffi-1.15.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5c84c68147988265e60416b57fc83425a78058853509c1b0629c180094904a5"},
|
{file = "cffi-1.17.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:636062ea65bd0195bc012fea9321aca499c0504409f413dc88af450b57ffd03b"},
|
||||||
{file = "cffi-1.15.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3b926aa83d1edb5aa5b427b4053dc420ec295a08e40911296b9eb1b6170f6cca"},
|
{file = "cffi-1.17.1-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7eac2ef9b63c79431bc4b25f1cd649d7f061a28808cbc6c47b534bd789ef964"},
|
||||||
{file = "cffi-1.15.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:87c450779d0914f2861b8526e035c5e6da0a3199d8f1add1a665e1cbc6fc6d02"},
|
{file = "cffi-1.17.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e221cf152cff04059d011ee126477f0d9588303eb57e88923578ace7baad17f9"},
|
||||||
{file = "cffi-1.15.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4f2c9f67e9821cad2e5f480bc8d83b8742896f1242dba247911072d4fa94c192"},
|
{file = "cffi-1.17.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:31000ec67d4221a71bd3f67df918b1f88f676f1c3b535a7eb473255fdc0b83fc"},
|
||||||
{file = "cffi-1.15.1-cp38-cp38-win32.whl", hash = "sha256:8b7ee99e510d7b66cdb6c593f21c043c248537a32e0bedf02e01e9553a172314"},
|
{file = "cffi-1.17.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6f17be4345073b0a7b8ea599688f692ac3ef23ce28e5df79c04de519dbc4912c"},
|
||||||
{file = "cffi-1.15.1-cp38-cp38-win_amd64.whl", hash = "sha256:00a9ed42e88df81ffae7a8ab6d9356b371399b91dbdf0c3cb1e84c03a13aceb5"},
|
{file = "cffi-1.17.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e2b1fac190ae3ebfe37b979cc1ce69c81f4e4fe5746bb401dca63a9062cdaf1"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:54a2db7b78338edd780e7ef7f9f6c442500fb0d41a5a4ea24fff1c929d5af585"},
|
{file = "cffi-1.17.1-cp38-cp38-win32.whl", hash = "sha256:7596d6620d3fa590f677e9ee430df2958d2d6d6de2feeae5b20e82c00b76fbf8"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:fcd131dd944808b5bdb38e6f5b53013c5aa4f334c5cad0c72742f6eba4b73db0"},
|
{file = "cffi-1.17.1-cp38-cp38-win_amd64.whl", hash = "sha256:78122be759c3f8a014ce010908ae03364d00a1f81ab5c7f4a7a5120607ea56e1"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7473e861101c9e72452f9bf8acb984947aa1661a7704553a9f6e4baa5ba64415"},
|
{file = "cffi-1.17.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b2ab587605f4ba0bf81dc0cb08a41bd1c0a5906bd59243d56bad7668a6fc6c16"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6c9a799e985904922a4d207a94eae35c78ebae90e128f0c4e521ce339396be9d"},
|
{file = "cffi-1.17.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:28b16024becceed8c6dfbc75629e27788d8a3f9030691a1dbf9821a128b22c36"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3bcde07039e586f91b45c88f8583ea7cf7a0770df3a1649627bf598332cb6984"},
|
{file = "cffi-1.17.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1d599671f396c4723d016dbddb72fe8e0397082b0a77a4fab8028923bec050e8"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:33ab79603146aace82c2427da5ca6e58f2b3f2fb5da893ceac0c42218a40be35"},
|
{file = "cffi-1.17.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca74b8dbe6e8e8263c0ffd60277de77dcee6c837a3d0881d8c1ead7268c9e576"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d598b938678ebf3c67377cdd45e09d431369c3b1a5b331058c338e201f12b27"},
|
{file = "cffi-1.17.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f7f5baafcc48261359e14bcd6d9bff6d4b28d9103847c9e136694cb0501aef87"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:db0fbb9c62743ce59a9ff687eb5f4afbe77e5e8403d6697f7446e5f609976f76"},
|
{file = "cffi-1.17.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98e3969bcff97cae1b2def8ba499ea3d6f31ddfdb7635374834cf89a1a08ecf0"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:98d85c6a2bef81588d9227dde12db8a7f47f639f4a17c9ae08e773aa9c697bf3"},
|
{file = "cffi-1.17.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdf5ce3acdfd1661132f2a9c19cac174758dc2352bfe37d98aa7512c6b7178b3"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-win32.whl", hash = "sha256:40f4774f5a9d4f5e344f31a32b5096977b5d48560c5592e2f3d2c4374bd543ee"},
|
{file = "cffi-1.17.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:9755e4345d1ec879e3849e62222a18c7174d65a6a92d5b346b1863912168b595"},
|
||||||
{file = "cffi-1.15.1-cp39-cp39-win_amd64.whl", hash = "sha256:70df4e3b545a17496c9b3f41f5115e69a4f2e77e94e1d2a8e1070bc0c38c8a3c"},
|
{file = "cffi-1.17.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:f1e22e8c4419538cb197e4dd60acc919d7696e5ef98ee4da4e01d3f8cfa4cc5a"},
|
||||||
{file = "cffi-1.15.1.tar.gz", hash = "sha256:d400bfb9a37b1351253cb402671cea7e89bdecc294e8016a707f6d1d8ac934f9"},
|
{file = "cffi-1.17.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:c03e868a0b3bc35839ba98e74211ed2b05d2119be4e8a0f224fba9384f1fe02e"},
|
||||||
|
{file = "cffi-1.17.1-cp39-cp39-win32.whl", hash = "sha256:e31ae45bc2e29f6b2abd0de1cc3b9d5205aa847cafaecb8af1476a609a2f6eb7"},
|
||||||
|
{file = "cffi-1.17.1-cp39-cp39-win_amd64.whl", hash = "sha256:d016c76bdd850f3c626af19b0542c9677ba156e4ee4fccfdd7848803533ef662"},
|
||||||
|
{file = "cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
|
|
@ -221,47 +225,51 @@ development = ["black", "flake8", "mypy", "pytest", "types-colorama"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cryptography"
|
name = "cryptography"
|
||||||
version = "41.0.3"
|
version = "43.0.3"
|
||||||
description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers."
|
description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers."
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.7"
|
||||||
files = [
|
files = [
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-macosx_10_12_universal2.whl", hash = "sha256:652627a055cb52a84f8c448185922241dd5217443ca194d5739b44612c5e6507"},
|
{file = "cryptography-43.0.3-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:bf7a1932ac4176486eab36a19ed4c0492da5d97123f1406cf15e41b05e787d2e"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-macosx_10_12_x86_64.whl", hash = "sha256:8f09daa483aedea50d249ef98ed500569841d6498aa9c9f4b0531b9964658922"},
|
{file = "cryptography-43.0.3-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:63efa177ff54aec6e1c0aefaa1a241232dcd37413835a9b674b6e3f0ae2bfd3e"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4fd871184321100fb400d759ad0cddddf284c4b696568204d281c902fc7b0d81"},
|
{file = "cryptography-43.0.3-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e1ce50266f4f70bf41a2c6dc4358afadae90e2a1e5342d3c08883df1675374f"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:84537453d57f55a50a5b6835622ee405816999a7113267739a1b4581f83535bd"},
|
{file = "cryptography-43.0.3-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:443c4a81bb10daed9a8f334365fe52542771f25aedaf889fd323a853ce7377d6"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:3fb248989b6363906827284cd20cca63bb1a757e0a2864d4c1682a985e3dca47"},
|
{file = "cryptography-43.0.3-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:74f57f24754fe349223792466a709f8e0c093205ff0dca557af51072ff47ab18"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:42cb413e01a5d36da9929baa9d70ca90d90b969269e5a12d39c1e0d475010116"},
|
{file = "cryptography-43.0.3-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:9762ea51a8fc2a88b70cf2995e5675b38d93bf36bd67d91721c309df184f49bd"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:aeb57c421b34af8f9fe830e1955bf493a86a7996cc1338fe41b30047d16e962c"},
|
{file = "cryptography-43.0.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:81ef806b1fef6b06dcebad789f988d3b37ccaee225695cf3e07648eee0fc6b73"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:6af1c6387c531cd364b72c28daa29232162010d952ceb7e5ca8e2827526aceae"},
|
{file = "cryptography-43.0.3-cp37-abi3-win32.whl", hash = "sha256:cbeb489927bd7af4aa98d4b261af9a5bc025bd87f0e3547e11584be9e9427be2"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-win32.whl", hash = "sha256:0d09fb5356f975974dbcb595ad2d178305e5050656affb7890a1583f5e02a306"},
|
{file = "cryptography-43.0.3-cp37-abi3-win_amd64.whl", hash = "sha256:f46304d6f0c6ab8e52770addfa2fc41e6629495548862279641972b6215451cd"},
|
||||||
{file = "cryptography-41.0.3-cp37-abi3-win_amd64.whl", hash = "sha256:a983e441a00a9d57a4d7c91b3116a37ae602907a7618b882c8013b5762e80574"},
|
{file = "cryptography-43.0.3-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:8ac43ae87929a5982f5948ceda07001ee5e83227fd69cf55b109144938d96984"},
|
||||||
{file = "cryptography-41.0.3-pp310-pypy310_pp73-macosx_10_12_x86_64.whl", hash = "sha256:5259cb659aa43005eb55a0e4ff2c825ca111a0da1814202c64d28a985d33b087"},
|
{file = "cryptography-43.0.3-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:846da004a5804145a5f441b8530b4bf35afbf7da70f82409f151695b127213d5"},
|
||||||
{file = "cryptography-41.0.3-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:67e120e9a577c64fe1f611e53b30b3e69744e5910ff3b6e97e935aeb96005858"},
|
{file = "cryptography-43.0.3-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f996e7268af62598f2fc1204afa98a3b5712313a55c4c9d434aef49cadc91d4"},
|
||||||
{file = "cryptography-41.0.3-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:7efe8041897fe7a50863e51b77789b657a133c75c3b094e51b5e4b5cec7bf906"},
|
{file = "cryptography-43.0.3-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f7b178f11ed3664fd0e995a47ed2b5ff0a12d893e41dd0494f406d1cf555cab7"},
|
||||||
{file = "cryptography-41.0.3-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:ce785cf81a7bdade534297ef9e490ddff800d956625020ab2ec2780a556c313e"},
|
{file = "cryptography-43.0.3-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c2e6fc39c4ab499049df3bdf567f768a723a5e8464816e8f009f121a5a9f4405"},
|
||||||
{file = "cryptography-41.0.3-pp38-pypy38_pp73-macosx_10_12_x86_64.whl", hash = "sha256:57a51b89f954f216a81c9d057bf1a24e2f36e764a1ca9a501a6964eb4a6800dd"},
|
{file = "cryptography-43.0.3-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:e1be4655c7ef6e1bbe6b5d0403526601323420bcf414598955968c9ef3eb7d16"},
|
||||||
{file = "cryptography-41.0.3-pp38-pypy38_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:4c2f0d35703d61002a2bbdcf15548ebb701cfdd83cdc12471d2bae80878a4207"},
|
{file = "cryptography-43.0.3-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:df6b6c6d742395dd77a23ea3728ab62f98379eff8fb61be2744d4679ab678f73"},
|
||||||
{file = "cryptography-41.0.3-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:23c2d778cf829f7d0ae180600b17e9fceea3c2ef8b31a99e3c694cbbf3a24b84"},
|
{file = "cryptography-43.0.3-cp39-abi3-win32.whl", hash = "sha256:d56e96520b1020449bbace2b78b603442e7e378a9b3bd68de65c782db1507995"},
|
||||||
{file = "cryptography-41.0.3-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:95dd7f261bb76948b52a5330ba5202b91a26fbac13ad0e9fc8a3ac04752058c7"},
|
{file = "cryptography-43.0.3-cp39-abi3-win_amd64.whl", hash = "sha256:0c580952eef9bf68c4747774cde7ec1d85a6e61de97281f2dba83c7d2c806362"},
|
||||||
{file = "cryptography-41.0.3-pp39-pypy39_pp73-macosx_10_12_x86_64.whl", hash = "sha256:41d7aa7cdfded09b3d73a47f429c298e80796c8e825ddfadc84c8a7f12df212d"},
|
{file = "cryptography-43.0.3-pp310-pypy310_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d03b5621a135bffecad2c73e9f4deb1a0f977b9a8ffe6f8e002bf6c9d07b918c"},
|
||||||
{file = "cryptography-41.0.3-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:d0d651aa754ef58d75cec6edfbd21259d93810b73f6ec246436a21b7841908de"},
|
{file = "cryptography-43.0.3-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:a2a431ee15799d6db9fe80c82b055bae5a752bef645bba795e8e52687c69efe3"},
|
||||||
{file = "cryptography-41.0.3-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:ab8de0d091acbf778f74286f4989cf3d1528336af1b59f3e5d2ebca8b5fe49e1"},
|
{file = "cryptography-43.0.3-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:281c945d0e28c92ca5e5930664c1cefd85efe80e5c0d2bc58dd63383fda29f83"},
|
||||||
{file = "cryptography-41.0.3-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:a74fbcdb2a0d46fe00504f571a2a540532f4c188e6ccf26f1f178480117b33c4"},
|
{file = "cryptography-43.0.3-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:f18c716be16bc1fea8e95def49edf46b82fccaa88587a45f8dc0ff6ab5d8e0a7"},
|
||||||
{file = "cryptography-41.0.3.tar.gz", hash = "sha256:6d192741113ef5e30d89dcb5b956ef4e1578f304708701b8b73d38e3e1461f34"},
|
{file = "cryptography-43.0.3-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:4a02ded6cd4f0a5562a8887df8b3bd14e822a90f97ac5e544c162899bc467664"},
|
||||||
|
{file = "cryptography-43.0.3-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:53a583b6637ab4c4e3591a15bc9db855b8d9dee9a669b550f311480acab6eb08"},
|
||||||
|
{file = "cryptography-43.0.3-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:1ec0bcf7e17c0c5669d881b1cd38c4972fade441b27bda1051665faaa89bdcaa"},
|
||||||
|
{file = "cryptography-43.0.3-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:2ce6fae5bdad59577b44e4dfed356944fbf1d925269114c28be377692643b4ff"},
|
||||||
|
{file = "cryptography-43.0.3.tar.gz", hash = "sha256:315b9001266a492a6ff443b61238f956b214dbec9910a081ba5b6646a055a805"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
cffi = ">=1.12"
|
cffi = {version = ">=1.12", markers = "platform_python_implementation != \"PyPy\""}
|
||||||
|
|
||||||
[package.extras]
|
[package.extras]
|
||||||
docs = ["sphinx (>=5.3.0)", "sphinx-rtd-theme (>=1.1.1)"]
|
docs = ["sphinx (>=5.3.0)", "sphinx-rtd-theme (>=1.1.1)"]
|
||||||
docstest = ["pyenchant (>=1.6.11)", "sphinxcontrib-spelling (>=4.0.1)", "twine (>=1.12.0)"]
|
docstest = ["pyenchant (>=1.6.11)", "readme-renderer", "sphinxcontrib-spelling (>=4.0.1)"]
|
||||||
nox = ["nox"]
|
nox = ["nox"]
|
||||||
pep8test = ["black", "check-sdist", "mypy", "ruff"]
|
pep8test = ["check-sdist", "click", "mypy", "ruff"]
|
||||||
sdist = ["build"]
|
sdist = ["build"]
|
||||||
ssh = ["bcrypt (>=3.1.5)"]
|
ssh = ["bcrypt (>=3.1.5)"]
|
||||||
test = ["pretend", "pytest (>=6.2.0)", "pytest-benchmark", "pytest-cov", "pytest-xdist"]
|
test = ["certifi", "cryptography-vectors (==43.0.3)", "pretend", "pytest (>=6.2.0)", "pytest-benchmark", "pytest-cov", "pytest-xdist"]
|
||||||
test-randomorder = ["pytest-randomly"]
|
test-randomorder = ["pytest-randomly"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -333,13 +341,13 @@ files = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "eventkit"
|
name = "eventkit"
|
||||||
version = "1.0.1"
|
version = "1.0.3"
|
||||||
description = "Event-driven data pipelines"
|
description = "Event-driven data pipelines"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = "*"
|
python-versions = "*"
|
||||||
files = [
|
files = [
|
||||||
{file = "eventkit-1.0.1-py3-none-any.whl", hash = "sha256:6060a6aa04d5c5d20f2e55b7c17e2a22e8d31f88f2c2791d60eab3301aa040da"},
|
{file = "eventkit-1.0.3-py3-none-any.whl", hash = "sha256:0e199527a89aff9d195b9671ad45d2cc9f79ecda0900de8ecfb4c864d67ad6a2"},
|
||||||
{file = "eventkit-1.0.1.tar.gz", hash = "sha256:56b99a6205f61cd995aa5e0036e37bd61f052f7d32560e60b6fe45e319a7ef3a"},
|
{file = "eventkit-1.0.3.tar.gz", hash = "sha256:99497f6f3c638a50ff7616f2f8cd887b18bbff3765dc1bd8681554db1467c933"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
|
|
@ -347,13 +355,13 @@ numpy = "*"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "exceptiongroup"
|
name = "exceptiongroup"
|
||||||
version = "1.1.3"
|
version = "1.2.2"
|
||||||
description = "Backport of PEP 654 (exception groups)"
|
description = "Backport of PEP 654 (exception groups)"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.7"
|
||||||
files = [
|
files = [
|
||||||
{file = "exceptiongroup-1.1.3-py3-none-any.whl", hash = "sha256:343280667a4585d195ca1cf9cef84a4e178c4b6cf2274caef9859782b567d5e3"},
|
{file = "exceptiongroup-1.2.2-py3-none-any.whl", hash = "sha256:3111b9d131c238bec2f8f516e123e14ba243563fb135d3fe885990585aa7795b"},
|
||||||
{file = "exceptiongroup-1.1.3.tar.gz", hash = "sha256:097acd85d473d75af5bb98e41b61ff7fe35efe6675e4f9370ec6ec5126d160e9"},
|
{file = "exceptiongroup-1.2.2.tar.gz", hash = "sha256:47c2edf7c6738fafb49fd34290706d1a1a2f4d1c6df275526b62cbb4aa5393cc"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.extras]
|
[package.extras]
|
||||||
|
|
@ -480,31 +488,37 @@ nest-asyncio = "*"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "idna"
|
name = "idna"
|
||||||
version = "3.4"
|
version = "3.10"
|
||||||
description = "Internationalized Domain Names in Applications (IDNA)"
|
description = "Internationalized Domain Names in Applications (IDNA)"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.5"
|
python-versions = ">=3.6"
|
||||||
files = [
|
files = [
|
||||||
{file = "idna-3.4-py3-none-any.whl", hash = "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2"},
|
{file = "idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3"},
|
||||||
{file = "idna-3.4.tar.gz", hash = "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4"},
|
{file = "idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9"},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[package.extras]
|
||||||
|
all = ["flake8 (>=7.1.1)", "mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.6.2)"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "importlib-metadata"
|
name = "importlib-metadata"
|
||||||
version = "6.8.0"
|
version = "8.5.0"
|
||||||
description = "Read metadata from Python packages"
|
description = "Read metadata from Python packages"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.8"
|
python-versions = ">=3.8"
|
||||||
files = [
|
files = [
|
||||||
{file = "importlib_metadata-6.8.0-py3-none-any.whl", hash = "sha256:3ebb78df84a805d7698245025b975d9d67053cd94c79245ba4b3eb694abe68bb"},
|
{file = "importlib_metadata-8.5.0-py3-none-any.whl", hash = "sha256:45e54197d28b7a7f1559e60b95e7c567032b602131fbd588f1497f47880aa68b"},
|
||||||
{file = "importlib_metadata-6.8.0.tar.gz", hash = "sha256:dbace7892d8c0c4ac1ad096662232f831d4e64f4c4545bd53016a3e9d4654743"},
|
{file = "importlib_metadata-8.5.0.tar.gz", hash = "sha256:71522656f0abace1d072b9e5481a48f07c138e00f079c38c8f883823f9c26bd7"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
zipp = ">=0.5"
|
zipp = ">=3.20"
|
||||||
|
|
||||||
[package.extras]
|
[package.extras]
|
||||||
docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"]
|
check = ["pytest-checkdocs (>=2.4)", "pytest-ruff (>=0.2.1)"]
|
||||||
|
cover = ["pytest-cov"]
|
||||||
|
doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"]
|
||||||
|
enabler = ["pytest-enabler (>=2.2)"]
|
||||||
perf = ["ipython"]
|
perf = ["ipython"]
|
||||||
testing = ["flufl.flake8", "importlib-resources (>=1.3)", "packaging", "pyfakefs", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy (>=0.9.1)", "pytest-perf (>=0.9.2)", "pytest-ruff"]
|
testing = ["flufl.flake8", "importlib-resources (>=1.3)", "packaging", "pyfakefs", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy (>=0.9.1)", "pytest-perf (>=0.9.2)", "pytest-ruff"]
|
||||||
|
|
||||||
|
|
@ -644,13 +658,13 @@ files = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nest-asyncio"
|
name = "nest-asyncio"
|
||||||
version = "1.5.7"
|
version = "1.6.0"
|
||||||
description = "Patch asyncio to allow nested event loops"
|
description = "Patch asyncio to allow nested event loops"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.5"
|
python-versions = ">=3.5"
|
||||||
files = [
|
files = [
|
||||||
{file = "nest_asyncio-1.5.7-py3-none-any.whl", hash = "sha256:5301c82941b550b3123a1ea772ba9a1c80bad3a182be8c1a5ae6ad3be57a9657"},
|
{file = "nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c"},
|
||||||
{file = "nest_asyncio-1.5.7.tar.gz", hash = "sha256:6a80f7b98f24d9083ed24608977c09dd608d83f91cccc24c9d2cba6d10e01c10"},
|
{file = "nest_asyncio-1.6.0.tar.gz", hash = "sha256:6f172d5449aca15afd6c646851f4e31e02c598d553a667e38cafa997cfec55fe"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -729,13 +743,13 @@ files = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "outcome"
|
name = "outcome"
|
||||||
version = "1.2.0"
|
version = "1.3.0.post0"
|
||||||
description = "Capture the outcome of Python function calls."
|
description = "Capture the outcome of Python function calls."
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.7"
|
||||||
files = [
|
files = [
|
||||||
{file = "outcome-1.2.0-py2.py3-none-any.whl", hash = "sha256:c4ab89a56575d6d38a05aa16daeaa333109c1f96167aba8901ab18b6b5e0f7f5"},
|
{file = "outcome-1.3.0.post0-py2.py3-none-any.whl", hash = "sha256:e771c5ce06d1415e356078d3bdd68523f284b4ce5419828922b6871e65eda82b"},
|
||||||
{file = "outcome-1.2.0.tar.gz", hash = "sha256:6f82bd3de45da303cf1f771ecafa1633750a358436a8bb60e06a1ceb745d2672"},
|
{file = "outcome-1.3.0.post0.tar.gz", hash = "sha256:9dcf02e65f2971b80047b377468e72a268e15c0af3cf1238e6ff14f7f91143b8"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
|
|
@ -743,13 +757,13 @@ attrs = ">=19.2.0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "packaging"
|
name = "packaging"
|
||||||
version = "23.1"
|
version = "24.2"
|
||||||
description = "Core utilities for Python packages"
|
description = "Core utilities for Python packages"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.8"
|
||||||
files = [
|
files = [
|
||||||
{file = "packaging-23.1-py3-none-any.whl", hash = "sha256:994793af429502c4ea2ebf6bf664629d07c1a9fe974af92966e4b8d2df7edc61"},
|
{file = "packaging-24.2-py3-none-any.whl", hash = "sha256:09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759"},
|
||||||
{file = "packaging-23.1.tar.gz", hash = "sha256:a392980d2b6cffa644431898be54b0045151319d1e7ec34f0cfed48767dd334f"},
|
{file = "packaging-24.2.tar.gz", hash = "sha256:c228a6dc5e932d346bc5739379109d49e8853dd8223571c7c5b55260edc0b97f"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -836,24 +850,24 @@ xlsxwriter = ["xlsxwriter"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pycparser"
|
name = "pycparser"
|
||||||
version = "2.21"
|
version = "2.22"
|
||||||
description = "C parser in Python"
|
description = "C parser in Python"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
|
python-versions = ">=3.8"
|
||||||
files = [
|
files = [
|
||||||
{file = "pycparser-2.21-py2.py3-none-any.whl", hash = "sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9"},
|
{file = "pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc"},
|
||||||
{file = "pycparser-2.21.tar.gz", hash = "sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206"},
|
{file = "pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pygments"
|
name = "pygments"
|
||||||
version = "2.16.1"
|
version = "2.18.0"
|
||||||
description = "Pygments is a syntax highlighting package written in Python."
|
description = "Pygments is a syntax highlighting package written in Python."
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.8"
|
||||||
files = [
|
files = [
|
||||||
{file = "Pygments-2.16.1-py3-none-any.whl", hash = "sha256:13fc09fa63bc8d8671a6d247e1eb303c4b343eaee81d861f3404db2935653692"},
|
{file = "pygments-2.18.0-py3-none-any.whl", hash = "sha256:b8e6aca0523f3ab76fee51799c488e38782ac06eafcf95e7ba832985c8e7b13a"},
|
||||||
{file = "Pygments-2.16.1.tar.gz", hash = "sha256:1daff0494820c69bc8941e407aa20f577374ee88364ee10a98fdbe0aece96e29"},
|
{file = "pygments-2.18.0.tar.gz", hash = "sha256:786ff802f32e91311bff3889f6e9a86e81505fe99f2735bb6d60ae0c5004f199"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.extras]
|
[package.extras]
|
||||||
|
|
@ -861,24 +875,24 @@ plugins = ["importlib-metadata"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pyreadline3"
|
name = "pyreadline3"
|
||||||
version = "3.4.1"
|
version = "3.5.4"
|
||||||
description = "A python implementation of GNU readline."
|
description = "A python implementation of GNU readline."
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = "*"
|
python-versions = ">=3.8"
|
||||||
files = [
|
files = [
|
||||||
{file = "pyreadline3-3.4.1-py3-none-any.whl", hash = "sha256:b0efb6516fd4fb07b45949053826a62fa4cb353db5be2bbb4a7aa1fdd1e345fb"},
|
{file = "pyreadline3-3.5.4-py3-none-any.whl", hash = "sha256:eaf8e6cc3c49bcccf145fc6067ba8643d1df34d604a1ec0eccbf7a18e6d3fae6"},
|
||||||
{file = "pyreadline3-3.4.1.tar.gz", hash = "sha256:6f3d1f7b8a31ba32b73917cefc1f28cc660562f39aea8646d30bd6eff21f7bae"},
|
{file = "pyreadline3-3.5.4.tar.gz", hash = "sha256:8d57d53039a1c75adba8e50dd3d992b28143480816187ea5efbd5c78e6c885b7"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "python-dateutil"
|
name = "python-dateutil"
|
||||||
version = "2.8.2"
|
version = "2.9.0.post0"
|
||||||
description = "Extensions to the standard Python datetime module"
|
description = "Extensions to the standard Python datetime module"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7"
|
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7"
|
||||||
files = [
|
files = [
|
||||||
{file = "python-dateutil-2.8.2.tar.gz", hash = "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"},
|
{file = "python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3"},
|
||||||
{file = "python_dateutil-2.8.2-py2.py3-none-any.whl", hash = "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9"},
|
{file = "python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
|
|
@ -897,13 +911,13 @@ files = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rich"
|
name = "rich"
|
||||||
version = "13.5.2"
|
version = "13.9.4"
|
||||||
description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal"
|
description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7.0"
|
python-versions = ">=3.8.0"
|
||||||
files = [
|
files = [
|
||||||
{file = "rich-13.5.2-py3-none-any.whl", hash = "sha256:146a90b3b6b47cac4a73c12866a499e9817426423f57c5a66949c086191a8808"},
|
{file = "rich-13.9.4-py3-none-any.whl", hash = "sha256:6049d5e6ec054bf2779ab3358186963bac2ea89175919d699e378b99738c2a90"},
|
||||||
{file = "rich-13.5.2.tar.gz", hash = "sha256:fb9d6c0a0f643c99eed3875b5377a184132ba9be4d61516a55273d3554d75a39"},
|
{file = "rich-13.9.4.tar.gz", hash = "sha256:439594978a49a09530cff7ebc4b5c7103ef57baf48d5ea3184f21d9a2befa098"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
|
|
@ -926,13 +940,13 @@ files = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sniffio"
|
name = "sniffio"
|
||||||
version = "1.3.0"
|
version = "1.3.1"
|
||||||
description = "Sniff out which async library your code is running under"
|
description = "Sniff out which async library your code is running under"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.7"
|
||||||
files = [
|
files = [
|
||||||
{file = "sniffio-1.3.0-py3-none-any.whl", hash = "sha256:eecefdce1e5bbfb7ad2eeaabf7c1eeb404d7757c379bd1f7e5cce9d8bf425384"},
|
{file = "sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2"},
|
||||||
{file = "sniffio-1.3.0.tar.gz", hash = "sha256:e60305c5e5d314f5389259b7f22aaa33d8f7dee49763119234af3755c55b9101"},
|
{file = "sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -962,24 +976,24 @@ pyreadline3 = {version = "*", markers = "platform_system == \"Windows\""}
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tomli"
|
name = "tomli"
|
||||||
version = "2.0.1"
|
version = "2.1.0"
|
||||||
description = "A lil' TOML parser"
|
description = "A lil' TOML parser"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.8"
|
||||||
files = [
|
files = [
|
||||||
{file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"},
|
{file = "tomli-2.1.0-py3-none-any.whl", hash = "sha256:a5c57c3d1c56f5ccdf89f6523458f60ef716e210fc47c4cfb188c5ba473e0391"},
|
||||||
{file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"},
|
{file = "tomli-2.1.0.tar.gz", hash = "sha256:3f646cae2aec94e17d04973e4249548320197cfabdf130015d023de4b74d8ab8"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tomli-w"
|
name = "tomli-w"
|
||||||
version = "1.0.0"
|
version = "1.1.0"
|
||||||
description = "A lil' TOML writer"
|
description = "A lil' TOML writer"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.9"
|
||||||
files = [
|
files = [
|
||||||
{file = "tomli_w-1.0.0-py3-none-any.whl", hash = "sha256:9f2a07e8be30a0729e533ec968016807069991ae2fd921a78d42f429ae5f4463"},
|
{file = "tomli_w-1.1.0-py3-none-any.whl", hash = "sha256:1403179c78193e3184bfaade390ddbd071cba48a32a2e62ba11aae47490c63f7"},
|
||||||
{file = "tomli_w-1.0.0.tar.gz", hash = "sha256:f463434305e0336248cac9c2dc8076b707d8a12d019dd349f5c1e382dd1ae1b9"},
|
{file = "tomli_w-1.1.0.tar.gz", hash = "sha256:49e847a3a304d516a169a601184932ef0f6b61623fe680f836a2aa7128ed0d33"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1114,13 +1128,13 @@ wsproto = ">=0.14"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typer"
|
name = "typer"
|
||||||
version = "0.9.0"
|
version = "0.9.4"
|
||||||
description = "Typer, build great CLIs. Easy to code. Based on Python type hints."
|
description = "Typer, build great CLIs. Easy to code. Based on Python type hints."
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.6"
|
python-versions = ">=3.6"
|
||||||
files = [
|
files = [
|
||||||
{file = "typer-0.9.0-py3-none-any.whl", hash = "sha256:5d96d986a21493606a358cae4461bd8cdf83cbf33a5aa950ae629ca3b51467ee"},
|
{file = "typer-0.9.4-py3-none-any.whl", hash = "sha256:aa6c4a4e2329d868b80ecbaf16f807f2b54e192209d7ac9dd42691d63f7a54eb"},
|
||||||
{file = "typer-0.9.0.tar.gz", hash = "sha256:50922fd79aea2f4751a8e0408ff10d2662bd0c8bbfa84755a699f3bada2978b2"},
|
{file = "typer-0.9.4.tar.gz", hash = "sha256:f714c2d90afae3a7929fcd72a3abb08df305e1ff61719381384211c4070af57f"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
|
|
@ -1131,17 +1145,17 @@ typing-extensions = ">=3.7.4.3"
|
||||||
all = ["colorama (>=0.4.3,<0.5.0)", "rich (>=10.11.0,<14.0.0)", "shellingham (>=1.3.0,<2.0.0)"]
|
all = ["colorama (>=0.4.3,<0.5.0)", "rich (>=10.11.0,<14.0.0)", "shellingham (>=1.3.0,<2.0.0)"]
|
||||||
dev = ["autoflake (>=1.3.1,<2.0.0)", "flake8 (>=3.8.3,<4.0.0)", "pre-commit (>=2.17.0,<3.0.0)"]
|
dev = ["autoflake (>=1.3.1,<2.0.0)", "flake8 (>=3.8.3,<4.0.0)", "pre-commit (>=2.17.0,<3.0.0)"]
|
||||||
doc = ["cairosvg (>=2.5.2,<3.0.0)", "mdx-include (>=1.4.1,<2.0.0)", "mkdocs (>=1.1.2,<2.0.0)", "mkdocs-material (>=8.1.4,<9.0.0)", "pillow (>=9.3.0,<10.0.0)"]
|
doc = ["cairosvg (>=2.5.2,<3.0.0)", "mdx-include (>=1.4.1,<2.0.0)", "mkdocs (>=1.1.2,<2.0.0)", "mkdocs-material (>=8.1.4,<9.0.0)", "pillow (>=9.3.0,<10.0.0)"]
|
||||||
test = ["black (>=22.3.0,<23.0.0)", "coverage (>=6.2,<7.0)", "isort (>=5.0.6,<6.0.0)", "mypy (==0.910)", "pytest (>=4.4.0,<8.0.0)", "pytest-cov (>=2.10.0,<5.0.0)", "pytest-sugar (>=0.9.4,<0.10.0)", "pytest-xdist (>=1.32.0,<4.0.0)", "rich (>=10.11.0,<14.0.0)", "shellingham (>=1.3.0,<2.0.0)"]
|
test = ["black (>=22.3.0,<23.0.0)", "coverage (>=6.2,<7.0)", "isort (>=5.0.6,<6.0.0)", "mypy (==0.971)", "pytest (>=4.4.0,<8.0.0)", "pytest-cov (>=2.10.0,<5.0.0)", "pytest-sugar (>=0.9.4,<0.10.0)", "pytest-xdist (>=1.32.0,<4.0.0)", "rich (>=10.11.0,<14.0.0)", "shellingham (>=1.3.0,<2.0.0)"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typing-extensions"
|
name = "typing-extensions"
|
||||||
version = "4.7.1"
|
version = "4.12.2"
|
||||||
description = "Backported and Experimental Type Hints for Python 3.7+"
|
description = "Backported and Experimental Type Hints for Python 3.8+"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.8"
|
||||||
files = [
|
files = [
|
||||||
{file = "typing_extensions-4.7.1-py3-none-any.whl", hash = "sha256:440d5dd3af93b060174bf433bccd69b0babc3b15b1a8dca43789fd7f61514b36"},
|
{file = "typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d"},
|
||||||
{file = "typing_extensions-4.7.1.tar.gz", hash = "sha256:b75ddc264f0ba5615db7ba217daeb99701ad295353c45f9e95963337ceeeffb2"},
|
{file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1244,18 +1258,22 @@ h11 = ">=0.9.0,<1"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zipp"
|
name = "zipp"
|
||||||
version = "3.16.2"
|
version = "3.21.0"
|
||||||
description = "Backport of pathlib-compatible object wrapper for zip files"
|
description = "Backport of pathlib-compatible object wrapper for zip files"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.8"
|
python-versions = ">=3.9"
|
||||||
files = [
|
files = [
|
||||||
{file = "zipp-3.16.2-py3-none-any.whl", hash = "sha256:679e51dd4403591b2d6838a48de3d283f3d188412a9782faadf845f298736ba0"},
|
{file = "zipp-3.21.0-py3-none-any.whl", hash = "sha256:ac1bbe05fd2991f160ebce24ffbac5f6d11d83dc90891255885223d42b3cd931"},
|
||||||
{file = "zipp-3.16.2.tar.gz", hash = "sha256:ebc15946aa78bd63458992fc81ec3b6f7b1e92d51c35e6de1c3804e73b799147"},
|
{file = "zipp-3.21.0.tar.gz", hash = "sha256:2c9958f6430a2040341a52eb608ed6dd93ef4392e02ffe219417c1b28b5dd1f4"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.extras]
|
[package.extras]
|
||||||
docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"]
|
check = ["pytest-checkdocs (>=2.4)", "pytest-ruff (>=0.2.1)"]
|
||||||
testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-ignore-flaky", "pytest-mypy (>=0.9.1)", "pytest-ruff"]
|
cover = ["pytest-cov"]
|
||||||
|
doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"]
|
||||||
|
enabler = ["pytest-enabler (>=2.2)"]
|
||||||
|
test = ["big-O", "importlib-resources", "jaraco.functools", "jaraco.itertools", "jaraco.test", "more-itertools", "pytest (>=6,!=8.1.*)", "pytest-ignore-flaky"]
|
||||||
|
type = ["pytest-mypy"]
|
||||||
|
|
||||||
[metadata]
|
[metadata]
|
||||||
lock-version = "2.0"
|
lock-version = "2.0"
|
||||||
|
|
|
||||||
155
pyproject.toml
155
pyproject.toml
|
|
@ -18,12 +18,28 @@
|
||||||
requires = ["hatchling"]
|
requires = ["hatchling"]
|
||||||
build-backend = "hatchling.build"
|
build-backend = "hatchling.build"
|
||||||
|
|
||||||
|
# ------ - ------
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
# https://docs.astral.sh/ruff/settings/#lint_ignore
|
||||||
|
ignore = []
|
||||||
|
|
||||||
|
# https://docs.astral.sh/ruff/settings/#lint_per-file-ignores
|
||||||
|
# "piker/ui/qt.py" = [
|
||||||
|
# "E402",
|
||||||
|
# 'F401', # unused imports (without __all__ or blah as blah)
|
||||||
|
# # "F841", # unused variable rules
|
||||||
|
# ]
|
||||||
|
# ignore-init-module-imports = false
|
||||||
|
|
||||||
|
# ------ - ------
|
||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "piker"
|
name = "piker"
|
||||||
version = "0.1.0a0dev0"
|
version = "0.1.0a0dev0"
|
||||||
description = "trading gear for hackers"
|
description = "trading gear for hackers"
|
||||||
authors = [{ name = "Tyler Goodlet", email = "goodboy_foss@protonmail.com" }]
|
authors = [{ name = "Tyler Goodlet", email = "goodboy_foss@protonmail.com" }]
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12, <3.13"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
readme = "README.rst"
|
readme = "README.rst"
|
||||||
keywords = [
|
keywords = [
|
||||||
|
|
@ -39,8 +55,8 @@ classifiers = [
|
||||||
"Operating System :: POSIX :: Linux",
|
"Operating System :: POSIX :: Linux",
|
||||||
"Programming Language :: Python :: Implementation :: CPython",
|
"Programming Language :: Python :: Implementation :: CPython",
|
||||||
"Programming Language :: Python :: 3 :: Only",
|
"Programming Language :: Python :: 3 :: Only",
|
||||||
|
"Programming Language :: Python :: 3.11",
|
||||||
"Programming Language :: Python :: 3.12",
|
"Programming Language :: Python :: 3.12",
|
||||||
"Programming Language :: Python :: 3.13",
|
|
||||||
"Intended Audience :: Financial and Insurance Industry",
|
"Intended Audience :: Financial and Insurance Industry",
|
||||||
"Intended Audience :: Science/Research",
|
"Intended Audience :: Science/Research",
|
||||||
"Intended Audience :: Developers",
|
"Intended Audience :: Developers",
|
||||||
|
|
@ -49,13 +65,13 @@ classifiers = [
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-generator >=1.10, <2.0.0",
|
"async-generator >=1.10, <2.0.0",
|
||||||
"attrs >=23.1.0, <24.0.0",
|
"attrs >=23.1.0, <24.0.0",
|
||||||
"bidict >=0.23.1",
|
"bidict >=0.22.1, <0.23.0",
|
||||||
"colorama >=0.4.6, <0.5.0",
|
"colorama >=0.4.6, <0.5.0",
|
||||||
"colorlog >=6.7.0, <7.0.0",
|
"colorlog >=6.7.0, <7.0.0",
|
||||||
"ib-insync >=0.9.86, <0.10.0",
|
"ib-insync >=0.9.86, <0.10.0",
|
||||||
"numpy>=2.0",
|
"numba >=0.59.0, <0.60.0",
|
||||||
"polars >=0.20.6",
|
"numpy >=1.25, <2.0",
|
||||||
"polars-fuzzy-match>=0.1.5",
|
"polars >=0.18.13, <0.19.0",
|
||||||
"pygments >=2.16.1, <3.0.0",
|
"pygments >=2.16.1, <3.0.0",
|
||||||
"rich >=13.5.2, <14.0.0",
|
"rich >=13.5.2, <14.0.0",
|
||||||
"tomli >=2.0.1, <3.0.0",
|
"tomli >=2.0.1, <3.0.0",
|
||||||
|
|
@ -63,27 +79,21 @@ dependencies = [
|
||||||
"trio-util >=0.7.0, <0.8.0",
|
"trio-util >=0.7.0, <0.8.0",
|
||||||
"trio-websocket >=0.10.3, <0.11.0",
|
"trio-websocket >=0.10.3, <0.11.0",
|
||||||
"typer >=0.9.0, <1.0.0",
|
"typer >=0.9.0, <1.0.0",
|
||||||
"trio >=0.27",
|
"rapidfuzz >=3.5.2, <4.0.0",
|
||||||
"pendulum",
|
"pdbp >=1.5.0, <2.0.0",
|
||||||
|
"trio >=0.24, <0.25",
|
||||||
|
"pendulum >=3.0.0, <4.0.0",
|
||||||
"httpx >=0.27.0, <0.28.0",
|
"httpx >=0.27.0, <0.28.0",
|
||||||
"cryptofeed >=2.4.0, <3.0.0",
|
"cryptofeed >=2.4.0, <3.0.0",
|
||||||
"pyarrow>=18.0.0",
|
"pyarrow >=17.0.0, <18.0.0",
|
||||||
"websockets ==12.0",
|
"websockets ==12.0",
|
||||||
"msgspec>=0.19.0,<0.20",
|
"msgspec",
|
||||||
"tractor",
|
"tractor",
|
||||||
|
"asyncvnc",
|
||||||
"tomlkit",
|
"tomlkit",
|
||||||
"trio-typing>=0.10.0",
|
|
||||||
"numba>=0.61.0",
|
|
||||||
"pyvnc",
|
|
||||||
]
|
]
|
||||||
# ------ dependencies ------
|
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
# TODO: add an `--only daemon` group for running non-ui / pikerd
|
|
||||||
# service tree in distributed mode B)
|
|
||||||
# https://docs.astral.sh/uv/concepts/projects/dependencies/#optional-dependencies
|
|
||||||
|
|
||||||
[dependency-groups]
|
|
||||||
uis = [
|
uis = [
|
||||||
# https://docs.astral.sh/uv/concepts/projects/dependencies/#optional-dependencies
|
# https://docs.astral.sh/uv/concepts/projects/dependencies/#optional-dependencies
|
||||||
# TODO: make sure the levenshtein shit compiles on nix..
|
# TODO: make sure the levenshtein shit compiles on nix..
|
||||||
|
|
@ -93,108 +103,45 @@ uis = [
|
||||||
"pyqt6 >=6.7.0, <7.0.0",
|
"pyqt6 >=6.7.0, <7.0.0",
|
||||||
"pyqtgraph",
|
"pyqtgraph",
|
||||||
|
|
||||||
# for consideration,
|
# ------ - ------
|
||||||
# - 'visidata'
|
|
||||||
|
|
||||||
"qdarkstyle >=3.0.2, <4.0.0",
|
# TODO: add an `--only daemon` group for running non-ui / pikerd
|
||||||
"pyqt6 >=6.7.0, <7.0.0",
|
# service tree in distributed mode B)
|
||||||
"pyqtgraph",
|
# https://docs.astral.sh/uv/concepts/projects/dependencies/#optional-dependencies
|
||||||
|
# [project.optional-dependencies]
|
||||||
]
|
]
|
||||||
|
|
||||||
# TODO: a toolset that makes debugging a `pikerd` service (tree) easy
|
[dependency-groups]
|
||||||
# to hack on directly using more or less the local env:
|
dev = [
|
||||||
|
"pytest >=6.0.0, <7.0.0",
|
||||||
|
"elasticsearch >=8.9.0, <9.0.0",
|
||||||
|
"xonsh >=0.14.2, <0.15.0",
|
||||||
|
"prompt-toolkit ==3.0.40",
|
||||||
|
"cython >=3.0.0, <4.0.0",
|
||||||
|
"greenback >=1.1.1, <2.0.0",
|
||||||
|
# console ehancements and eventually remote debugging
|
||||||
|
# extras/helpers.
|
||||||
|
# TODO: add a toolset that makes debugging a `pikerd` service
|
||||||
|
# (tree) easy to hack on directly using more or less the local env:
|
||||||
# - xonsh + xxh
|
# - xonsh + xxh
|
||||||
# - rsyscall + pdbp
|
# - rsyscall + pdbp
|
||||||
# - actor runtime control console like BEAM/OTP
|
# - actor runtime control console like BEAM/OTP
|
||||||
#
|
|
||||||
# console ehancements and eventually remote debugging extras/helpers.
|
|
||||||
# use `uv --dev` to enable
|
|
||||||
repl = [
|
|
||||||
# debug
|
|
||||||
"pdbp >=1.5.0, <2.0.0",
|
|
||||||
"greenback >=1.1.1, <2.0.0",
|
|
||||||
"xonsh",
|
|
||||||
"prompt-toolkit ==3.0.40",
|
|
||||||
"pyperclip>=1.9.0",
|
|
||||||
|
|
||||||
]
|
]
|
||||||
testing = [
|
|
||||||
"pytest",
|
|
||||||
]
|
|
||||||
de = [
|
|
||||||
# DE-specific
|
|
||||||
"i3ipc>=2.2.1",
|
|
||||||
]
|
|
||||||
dev = [
|
|
||||||
# https://docs.astral.sh/uv/concepts/projects/dependencies/#development-dependencies
|
|
||||||
"cython >=3.0.0, <4.0.0",
|
|
||||||
|
|
||||||
# nested deps-groups
|
|
||||||
# https://docs.astral.sh/uv/concepts/projects/dependencies/#nesting-groups
|
|
||||||
{include-group = 'uis'},
|
|
||||||
{include-group = 'repl'},
|
|
||||||
{include-group = 'testing'},
|
|
||||||
{include-group = 'de'},
|
|
||||||
]
|
|
||||||
lint = [
|
|
||||||
# XXX, with flake.nix needs to be from nixpkgs
|
|
||||||
"ruff>=0.9.6"
|
|
||||||
#
|
|
||||||
# ^TODO? these markers don't work; use deps-flags for now?
|
|
||||||
# ; os_name != 'nixos' and platform_system != 'NixOS'",
|
|
||||||
# ; defined('IN_NIX_SHELL')",
|
|
||||||
]
|
|
||||||
dbs = [
|
|
||||||
"elasticsearch >=8.9.0, <9.0.0",
|
|
||||||
]
|
|
||||||
# ------ dependency-groups ------
|
|
||||||
|
|
||||||
|
|
||||||
[tool.pytest.ini_options]
|
|
||||||
# https://docs.pytest.org/en/stable/reference/reference.html#configuration-options
|
|
||||||
testpaths = [
|
|
||||||
"tests",
|
|
||||||
]
|
|
||||||
# https://docs.pytest.org/en/stable/reference/reference.html#confval-console_output_style
|
|
||||||
console_output_style = 'progress'
|
|
||||||
|
|
||||||
# https://docs.pytest.org/en/stable/how-to/plugins.html#disabling-plugins-from-autoloading
|
|
||||||
# https://docs.pytest.org/en/stable/how-to/plugins.html#deactivating-unregistering-a-plugin-by-name
|
|
||||||
addopts = '-p no:xonsh'
|
|
||||||
# ------ tool.pytest ------
|
|
||||||
|
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
piker = "piker.cli:cli"
|
piker = "piker.cli:cli"
|
||||||
pikerd = "piker.cli:pikerd"
|
pikerd = "piker.cli:pikerd"
|
||||||
ledger = "piker.accounting.cli:ledger"
|
ledger = "piker.accounting.cli:ledger"
|
||||||
# ------ project.scripts ------
|
|
||||||
|
|
||||||
[tool.hatch.build.targets.sdist]
|
[tool.hatch.build.targets.sdist]
|
||||||
include = ["piker"]
|
include = ["piker"]
|
||||||
|
|
||||||
[tool.hatch.build.targets.wheel]
|
[tool.hatch.build.targets.wheel]
|
||||||
include = ["piker"]
|
include = ["piker"]
|
||||||
# ------ tool.hatch ------
|
|
||||||
|
|
||||||
|
|
||||||
# TODO? move to a `uv.toml`?
|
|
||||||
[tool.uv]
|
|
||||||
python-preference = 'system'
|
|
||||||
python-downloads = 'manual'
|
|
||||||
# https://docs.astral.sh/uv/concepts/projects/dependencies/#default-groups
|
|
||||||
default-groups = ['uis', 'dev']
|
|
||||||
# ------ tool.uv ------
|
|
||||||
|
|
||||||
|
|
||||||
[tool.uv.sources]
|
[tool.uv.sources]
|
||||||
pyqtgraph = { git = "https://github.com/pikers/pyqtgraph.git" }
|
pyqtgraph = { git = "https://github.com/pikers/pyqtgraph.git" }
|
||||||
|
asyncvnc = { git = "https://github.com/pikers/asyncvnc.git", branch = "main" }
|
||||||
tomlkit = { git = "https://github.com/pikers/tomlkit.git", branch ="piker_pin" }
|
tomlkit = { git = "https://github.com/pikers/tomlkit.git", branch ="piker_pin" }
|
||||||
pyvnc = { git = "https://github.com/regulad/pyvnc.git" }
|
msgspec = { git = "https://github.com/jcrist/msgspec.git" }
|
||||||
|
tractor = { path = "../tractor" }
|
||||||
# XXX since, we're like, always hacking new shite all-the-time. Bp
|
|
||||||
tractor = { git = "https://github.com/goodboy/tractor.git", branch ="piker_pin" }
|
|
||||||
# tractor = { git = "https://pikers.dev/goodboy/tractor", branch = "piker_pin" }
|
|
||||||
# tractor = { git = "https://pikers.dev/goodboy/tractor", branch = "main" }
|
|
||||||
# ------ goodboy ------
|
|
||||||
# hackin dev-envs, usually there's something new he's hackin in..
|
|
||||||
# tractor = { path = "../tractor", editable = true }
|
|
||||||
|
|
|
||||||
94
ruff.toml
94
ruff.toml
|
|
@ -1,94 +0,0 @@
|
||||||
# from default `ruff.toml` @
|
|
||||||
# https://docs.astral.sh/ruff/configuration/
|
|
||||||
|
|
||||||
# Exclude a variety of commonly ignored directories.
|
|
||||||
exclude = [
|
|
||||||
".bzr",
|
|
||||||
".direnv",
|
|
||||||
".eggs",
|
|
||||||
".git",
|
|
||||||
".git-rewrite",
|
|
||||||
".hg",
|
|
||||||
".ipynb_checkpoints",
|
|
||||||
".mypy_cache",
|
|
||||||
".nox",
|
|
||||||
".pants.d",
|
|
||||||
".pyenv",
|
|
||||||
".pytest_cache",
|
|
||||||
".pytype",
|
|
||||||
".ruff_cache",
|
|
||||||
".svn",
|
|
||||||
".tox",
|
|
||||||
".venv",
|
|
||||||
".vscode",
|
|
||||||
"__pypackages__",
|
|
||||||
"_build",
|
|
||||||
"buck-out",
|
|
||||||
"build",
|
|
||||||
"dist",
|
|
||||||
"node_modules",
|
|
||||||
"site-packages",
|
|
||||||
"venv",
|
|
||||||
]
|
|
||||||
|
|
||||||
# Same as Black.
|
|
||||||
line-length = 88
|
|
||||||
indent-width = 4
|
|
||||||
|
|
||||||
# Assume Python 3.9
|
|
||||||
target-version = "py312"
|
|
||||||
|
|
||||||
# ------ - ------
|
|
||||||
# TODO, stop warnings around `anext()` builtin use?
|
|
||||||
# tool.ruff.target-version = "py310"
|
|
||||||
|
|
||||||
|
|
||||||
[lint]
|
|
||||||
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
|
|
||||||
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
|
|
||||||
# McCabe complexity (`C901`) by default.
|
|
||||||
select = ["E4", "E7", "E9", "F"]
|
|
||||||
ignore = []
|
|
||||||
ignore-init-module-imports = false
|
|
||||||
|
|
||||||
[lint.per-file-ignores]
|
|
||||||
"piker/ui/qt.py" = [
|
|
||||||
"E402",
|
|
||||||
'F401', # unused imports (without __all__ or blah as blah)
|
|
||||||
# "F841", # unused variable rules
|
|
||||||
]
|
|
||||||
|
|
||||||
# Allow fix for all enabled rules (when `--fix`) is provided.
|
|
||||||
fixable = ["ALL"]
|
|
||||||
unfixable = []
|
|
||||||
|
|
||||||
# TODO? uhh why no work!?
|
|
||||||
# Allow unused variables when underscore-prefixed.
|
|
||||||
# dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
|
||||||
|
|
||||||
[format]
|
|
||||||
# Use single quotes in `ruff format`.
|
|
||||||
quote-style = "single"
|
|
||||||
|
|
||||||
# Like Black, indent with spaces, rather than tabs.
|
|
||||||
indent-style = "space"
|
|
||||||
|
|
||||||
# Like Black, respect magic trailing commas.
|
|
||||||
skip-magic-trailing-comma = false
|
|
||||||
|
|
||||||
# Like Black, automatically detect the appropriate line ending.
|
|
||||||
line-ending = "auto"
|
|
||||||
|
|
||||||
# Enable auto-formatting of code examples in docstrings. Markdown,
|
|
||||||
# reStructuredText code/literal blocks and doctests are all supported.
|
|
||||||
#
|
|
||||||
# This is currently disabled by default, but it is planned for this
|
|
||||||
# to be opt-out in the future.
|
|
||||||
docstring-code-format = false
|
|
||||||
|
|
||||||
# Set the line length limit used when formatting code snippets in
|
|
||||||
# docstrings.
|
|
||||||
#
|
|
||||||
# This only has an effect when the `docstring-code-format` setting is
|
|
||||||
# enabled.
|
|
||||||
docstring-code-line-length = "dynamic"
|
|
||||||
|
|
@ -1,22 +1,4 @@
|
||||||
# piker: trading gear for hackers
|
"""
|
||||||
# Copyright (C) Tyler Goodlet (in stewardship for pikers)
|
|
||||||
|
|
||||||
# This program is free software: you can redistribute it and/or modify
|
|
||||||
# it under the terms of the GNU Affero General Public License as published by
|
|
||||||
# the Free Software Foundation, either version 3 of the License, or
|
|
||||||
# (at your option) any later version.
|
|
||||||
|
|
||||||
# This program is distributed in the hope that it will be useful,
|
|
||||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
# GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
# You should have received a copy of the GNU Affero General Public License
|
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
'''
|
|
||||||
A per-display, DPI (scaling) info dumper.
|
|
||||||
|
|
||||||
Resource list for mucking with DPIs on multiple screens:
|
Resource list for mucking with DPIs on multiple screens:
|
||||||
|
|
||||||
- https://stackoverflow.com/questions/42141354/convert-pixel-size-to-point-size-for-fonts-on-multiple-platforms
|
- https://stackoverflow.com/questions/42141354/convert-pixel-size-to-point-size-for-fonts-on-multiple-platforms
|
||||||
|
|
@ -30,86 +12,89 @@ Resource list for mucking with DPIs on multiple screens:
|
||||||
- https://stackoverflow.com/questions/16561879/what-is-the-difference-between-logicaldpix-and-physicaldpix-in-qt
|
- https://stackoverflow.com/questions/16561879/what-is-the-difference-between-logicaldpix-and-physicaldpix-in-qt
|
||||||
- https://doc.qt.io/qt-5/qguiapplication.html#screenAt
|
- https://doc.qt.io/qt-5/qguiapplication.html#screenAt
|
||||||
|
|
||||||
'''
|
"""
|
||||||
|
|
||||||
from pyqtgraph import QtGui
|
from pyqtgraph import QtGui
|
||||||
from PyQt6 import (
|
from PyQt5.QtCore import (
|
||||||
QtCore,
|
Qt, QCoreApplication
|
||||||
QtWidgets,
|
|
||||||
)
|
|
||||||
from PyQt6.QtCore import (
|
|
||||||
Qt,
|
|
||||||
QCoreApplication,
|
|
||||||
QSize,
|
|
||||||
QRect,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Proper high DPI scaling is available in Qt >= 5.6.0. This attibute
|
# Proper high DPI scaling is available in Qt >= 5.6.0. This attibute
|
||||||
# must be set before creating the application
|
# must be set before creating the application
|
||||||
if hasattr(Qt, 'AA_EnableHighDpiScaling'):
|
if hasattr(Qt, 'AA_EnableHighDpiScaling'):
|
||||||
QCoreApplication.setAttribute(
|
QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
|
||||||
Qt.AA_EnableHighDpiScaling,
|
|
||||||
True,
|
|
||||||
)
|
|
||||||
|
|
||||||
if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
|
if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
|
||||||
QCoreApplication.setAttribute(
|
QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
|
||||||
Qt.AA_UseHighDpiPixmaps,
|
|
||||||
True,
|
|
||||||
)
|
|
||||||
|
|
||||||
app = QtWidgets.QApplication([])
|
|
||||||
window = QtWidgets.QMainWindow()
|
app = QtGui.QApplication([])
|
||||||
main_widget = QtWidgets.QWidget()
|
window = QtGui.QMainWindow()
|
||||||
|
main_widget = QtGui.QWidget()
|
||||||
window.setCentralWidget(main_widget)
|
window.setCentralWidget(main_widget)
|
||||||
window.show()
|
window.show()
|
||||||
|
|
||||||
pxr: float = main_widget.devicePixelRatioF()
|
pxr = main_widget.devicePixelRatioF()
|
||||||
|
|
||||||
# explicitly get main widget and primary displays
|
# screen_num = app.desktop().screenNumber()
|
||||||
current_screen: QtGui.QScreen = app.screenAt(
|
# screen = app.screens()[screen_num]
|
||||||
main_widget.geometry().center()
|
|
||||||
)
|
|
||||||
primary_screen: QtGui.QScreen = app.primaryScreen()
|
|
||||||
|
|
||||||
screen: QtGui.QScreen
|
screen = app.screenAt(main_widget.geometry().center())
|
||||||
for screen in app.screens():
|
|
||||||
name: str = screen.name()
|
name = screen.name()
|
||||||
model: str = screen.model().rstrip()
|
size = screen.size()
|
||||||
size: QSize = screen.size()
|
geo = screen.availableGeometry()
|
||||||
geo: QRect = screen.availableGeometry()
|
phydpi = screen.physicalDotsPerInch()
|
||||||
phydpi: float = screen.physicalDotsPerInch()
|
logdpi = screen.logicalDotsPerInch()
|
||||||
logdpi: float = screen.logicalDotsPerInch()
|
|
||||||
is_primary: bool = screen is primary_screen
|
|
||||||
is_current: bool = screen is current_screen
|
|
||||||
|
|
||||||
print(
|
print(
|
||||||
f'------ screen name: {name} ------\n'
|
# f'screen number: {screen_num}\n',
|
||||||
f'|_primary: {is_primary}\n'
|
f'screen name: {name}\n'
|
||||||
f' _current: {is_current}\n'
|
f'screen size: {size}\n'
|
||||||
f' _model: {model}\n'
|
f'screen geometry: {geo}\n\n'
|
||||||
f' _screen size: {size}\n'
|
f'devicePixelRationF(): {pxr}\n'
|
||||||
f' _screen geometry: {geo}\n'
|
f'physical dpi: {phydpi}\n'
|
||||||
f' _devicePixelRationF(): {pxr}\n'
|
f'logical dpi: {logdpi}\n'
|
||||||
f' _physical dpi: {phydpi}\n'
|
|
||||||
f' _logical dpi: {logdpi}\n'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# app-wide font info
|
print('-'*50)
|
||||||
|
|
||||||
|
screen = app.primaryScreen()
|
||||||
|
|
||||||
|
name = screen.name()
|
||||||
|
size = screen.size()
|
||||||
|
geo = screen.availableGeometry()
|
||||||
|
phydpi = screen.physicalDotsPerInch()
|
||||||
|
logdpi = screen.logicalDotsPerInch()
|
||||||
|
|
||||||
|
print(
|
||||||
|
# f'screen number: {screen_num}\n',
|
||||||
|
f'screen name: {name}\n'
|
||||||
|
f'screen size: {size}\n'
|
||||||
|
f'screen geometry: {geo}\n\n'
|
||||||
|
f'devicePixelRationF(): {pxr}\n'
|
||||||
|
f'physical dpi: {phydpi}\n'
|
||||||
|
f'logical dpi: {logdpi}\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# app-wide font
|
||||||
font = QtGui.QFont("Hack")
|
font = QtGui.QFont("Hack")
|
||||||
# use pixel size to be cross-resolution compatible?
|
# use pixel size to be cross-resolution compatible?
|
||||||
font.setPixelSize(6)
|
font.setPixelSize(6)
|
||||||
|
|
||||||
fm = QtGui.QFontMetrics(font)
|
|
||||||
fontdpi: float = fm.fontDpi()
|
|
||||||
font_h: int = fm.height()
|
|
||||||
|
|
||||||
string: str = '10000'
|
fm = QtGui.QFontMetrics(font)
|
||||||
str_br: QtCore.QRect = fm.boundingRect(string)
|
fontdpi = fm.fontDpi()
|
||||||
str_w: int = str_br.width()
|
font_h = fm.height()
|
||||||
|
|
||||||
|
string = '10000'
|
||||||
|
str_br = fm.boundingRect(string)
|
||||||
|
str_w = str_br.width()
|
||||||
|
|
||||||
|
|
||||||
print(
|
print(
|
||||||
f'------ global font settings ------\n'
|
# f'screen number: {screen_num}\n',
|
||||||
f'font dpi: {fontdpi}\n'
|
f'font dpi: {fontdpi}\n'
|
||||||
f'font height: {font_h}\n'
|
f'font height: {font_h}\n'
|
||||||
f'string bounding rect: {str_br}\n'
|
f'string bounding rect: {str_br}\n'
|
||||||
|
|
|
||||||
|
|
@ -10,17 +10,11 @@ from piker import (
|
||||||
config,
|
config,
|
||||||
)
|
)
|
||||||
from piker.service import (
|
from piker.service import (
|
||||||
Services,
|
get_service_mngr,
|
||||||
)
|
)
|
||||||
from piker.log import get_console_log
|
from piker.log import get_console_log
|
||||||
|
|
||||||
|
|
||||||
# include `tractor`'s built-in fixtures!
|
|
||||||
pytest_plugins: tuple[str] = (
|
|
||||||
"tractor._testing.pytest",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def pytest_addoption(parser):
|
def pytest_addoption(parser):
|
||||||
parser.addoption("--ll", action="store", dest='loglevel',
|
parser.addoption("--ll", action="store", dest='loglevel',
|
||||||
default=None, help="logging level to set when testing")
|
default=None, help="logging level to set when testing")
|
||||||
|
|
@ -135,7 +129,7 @@ async def _open_test_pikerd(
|
||||||
) as service_manager,
|
) as service_manager,
|
||||||
):
|
):
|
||||||
# this proc/actor is the pikerd
|
# this proc/actor is the pikerd
|
||||||
assert service_manager is Services
|
assert service_manager is get_service_mngr()
|
||||||
|
|
||||||
async with tractor.wait_for_actor(
|
async with tractor.wait_for_actor(
|
||||||
'pikerd',
|
'pikerd',
|
||||||
|
|
|
||||||
|
|
@ -12,14 +12,12 @@ from piker import config
|
||||||
from piker.accounting import (
|
from piker.accounting import (
|
||||||
Account,
|
Account,
|
||||||
calc,
|
calc,
|
||||||
open_account,
|
|
||||||
load_account,
|
|
||||||
load_account_from_ledger,
|
|
||||||
open_trade_ledger,
|
|
||||||
Position,
|
Position,
|
||||||
TransactionLedger,
|
TransactionLedger,
|
||||||
|
open_trade_ledger,
|
||||||
|
load_account,
|
||||||
|
load_account_from_ledger,
|
||||||
)
|
)
|
||||||
import tractor
|
|
||||||
|
|
||||||
|
|
||||||
def test_root_conf_networking_section(
|
def test_root_conf_networking_section(
|
||||||
|
|
@ -55,17 +53,12 @@ def test_account_file_default_empty(
|
||||||
)
|
)
|
||||||
def test_paper_ledger_position_calcs(
|
def test_paper_ledger_position_calcs(
|
||||||
fq_acnt: tuple[str, str],
|
fq_acnt: tuple[str, str],
|
||||||
debug_mode: bool,
|
|
||||||
):
|
):
|
||||||
broker: str
|
broker: str
|
||||||
acnt_name: str
|
acnt_name: str
|
||||||
broker, acnt_name = fq_acnt
|
broker, acnt_name = fq_acnt
|
||||||
|
|
||||||
accounts_path: Path = (
|
accounts_path: Path = config.repodir() / 'tests' / '_inputs'
|
||||||
config.repodir()
|
|
||||||
/ 'tests'
|
|
||||||
/ '_inputs' # tests-local-subdir
|
|
||||||
)
|
|
||||||
|
|
||||||
ldr: TransactionLedger
|
ldr: TransactionLedger
|
||||||
with (
|
with (
|
||||||
|
|
@ -84,7 +77,6 @@ def test_paper_ledger_position_calcs(
|
||||||
ledger=ldr,
|
ledger=ldr,
|
||||||
|
|
||||||
_fp=accounts_path,
|
_fp=accounts_path,
|
||||||
debug_mode=debug_mode,
|
|
||||||
|
|
||||||
) as (dfs, ledger),
|
) as (dfs, ledger),
|
||||||
|
|
||||||
|
|
@ -110,87 +102,3 @@ def test_paper_ledger_position_calcs(
|
||||||
df = dfs[xrp]
|
df = dfs[xrp]
|
||||||
assert df['cumsize'][-1] == 0
|
assert df['cumsize'][-1] == 0
|
||||||
assert pos.cumsize == 0
|
assert pos.cumsize == 0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
'fq_acnt',
|
|
||||||
[
|
|
||||||
('ib', 'algopaper'),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_ib_account_with_duplicated_mktids(
|
|
||||||
fq_acnt: tuple[str, str],
|
|
||||||
debug_mode: bool,
|
|
||||||
):
|
|
||||||
# ?TODO, once we start symcache-incremental-update-support?
|
|
||||||
# from piker.data import (
|
|
||||||
# open_symcache,
|
|
||||||
# )
|
|
||||||
#
|
|
||||||
# async def main():
|
|
||||||
# async with (
|
|
||||||
# # TODO: do this as part of `open_account()`!?
|
|
||||||
# open_symcache(
|
|
||||||
# 'ib',
|
|
||||||
# only_from_memcache=True,
|
|
||||||
# ) as symcache,
|
|
||||||
# ):
|
|
||||||
|
|
||||||
|
|
||||||
from piker.brokers.ib.ledger import (
|
|
||||||
tx_sort,
|
|
||||||
|
|
||||||
# ?TODO, once we want to pull lowlevel txns and process them?
|
|
||||||
# norm_trade_records,
|
|
||||||
# update_ledger_from_api_trades,
|
|
||||||
)
|
|
||||||
|
|
||||||
broker: str
|
|
||||||
acnt_id: str = 'algopaper'
|
|
||||||
broker, acnt_id = fq_acnt
|
|
||||||
accounts_def = config.load_accounts([broker])
|
|
||||||
assert accounts_def[f'{broker}.{acnt_id}']
|
|
||||||
|
|
||||||
ledger: TransactionLedger
|
|
||||||
acnt: Account
|
|
||||||
with (
|
|
||||||
tractor.devx.maybe_open_crash_handler(pdb=debug_mode),
|
|
||||||
|
|
||||||
open_trade_ledger(
|
|
||||||
'ib',
|
|
||||||
acnt_id,
|
|
||||||
tx_sort=tx_sort,
|
|
||||||
|
|
||||||
# TODO, eventually incrementally updated for IB..
|
|
||||||
# symcache=symcache,
|
|
||||||
symcache=None,
|
|
||||||
allow_from_sync_code=True,
|
|
||||||
|
|
||||||
) as ledger,
|
|
||||||
|
|
||||||
open_account(
|
|
||||||
'ib',
|
|
||||||
acnt_id,
|
|
||||||
write_on_exit=True,
|
|
||||||
) as acnt,
|
|
||||||
):
|
|
||||||
# per input params
|
|
||||||
symcache = ledger.symcache
|
|
||||||
assert not (
|
|
||||||
symcache.pairs
|
|
||||||
or
|
|
||||||
symcache.pairs
|
|
||||||
or
|
|
||||||
symcache.mktmaps
|
|
||||||
)
|
|
||||||
# re-compute all positions that have changed state.
|
|
||||||
# TODO: likely we should change the API to return the
|
|
||||||
# position updates from `.update_from_ledger()`?
|
|
||||||
active, closed = acnt.dump_active()
|
|
||||||
|
|
||||||
# breakpoint()
|
|
||||||
|
|
||||||
# TODO, (see above imports as well) incremental update from
|
|
||||||
# (updated) ledger?
|
|
||||||
# -[ ] pull some code from `.ib.broker` content.
|
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ import pytest
|
||||||
import tractor
|
import tractor
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from piker.service import Services
|
from piker.service import ServiceMngr
|
||||||
from piker.log import get_logger
|
from piker.log import get_logger
|
||||||
from piker.clearing._messages import (
|
from piker.clearing._messages import (
|
||||||
Order,
|
Order,
|
||||||
|
|
@ -42,7 +42,7 @@ from piker.accounting import (
|
||||||
unpack_fqme,
|
unpack_fqme,
|
||||||
)
|
)
|
||||||
from piker.accounting import (
|
from piker.accounting import (
|
||||||
open_account,
|
open_pps,
|
||||||
Position,
|
Position,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -136,7 +136,7 @@ def load_and_check_pos(
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
with open_account(ppmsg.broker, ppmsg.account) as table:
|
with open_pps(ppmsg.broker, ppmsg.account) as table:
|
||||||
|
|
||||||
if ppmsg.size == 0:
|
if ppmsg.size == 0:
|
||||||
assert ppmsg.symbol not in table.pps
|
assert ppmsg.symbol not in table.pps
|
||||||
|
|
@ -158,7 +158,7 @@ def load_and_check_pos(
|
||||||
|
|
||||||
|
|
||||||
def test_ems_err_on_bad_broker(
|
def test_ems_err_on_bad_broker(
|
||||||
open_test_pikerd: Services,
|
open_test_pikerd: ServiceMngr,
|
||||||
loglevel: str,
|
loglevel: str,
|
||||||
):
|
):
|
||||||
async def load_bad_fqme():
|
async def load_bad_fqme():
|
||||||
|
|
@ -179,7 +179,7 @@ def test_ems_err_on_bad_broker(
|
||||||
# NOTE: emsd should error on the actor's enabled modules
|
# NOTE: emsd should error on the actor's enabled modules
|
||||||
# import phase, when looking for a backend named `doggy`.
|
# import phase, when looking for a backend named `doggy`.
|
||||||
except tractor.RemoteActorError as re:
|
except tractor.RemoteActorError as re:
|
||||||
assert re.type is ModuleNotFoundError
|
assert re.type == ModuleNotFoundError
|
||||||
|
|
||||||
run_and_tollerate_cancels(load_bad_fqme)
|
run_and_tollerate_cancels(load_bad_fqme)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -142,12 +142,7 @@ async def test_concurrent_tokens_refresh(us_symbols, loglevel):
|
||||||
# async with tractor.open_nursery() as n:
|
# async with tractor.open_nursery() as n:
|
||||||
# await n.run_in_actor('other', intermittently_refresh_tokens)
|
# await n.run_in_actor('other', intermittently_refresh_tokens)
|
||||||
|
|
||||||
async with (
|
async with trio.open_nursery() as n:
|
||||||
tractor.trionics.collapse_eg(),
|
|
||||||
trio.open_nursery(
|
|
||||||
# strict_exception_groups=False,
|
|
||||||
) as n
|
|
||||||
):
|
|
||||||
|
|
||||||
quoter = await qt.stock_quoter(client, us_symbols)
|
quoter = await qt.stock_quoter(client, us_symbols)
|
||||||
|
|
||||||
|
|
@ -388,9 +383,7 @@ async def test_quote_streaming(tmx_symbols, loglevel, stream_what):
|
||||||
else:
|
else:
|
||||||
symbols = [tmx_symbols]
|
symbols = [tmx_symbols]
|
||||||
|
|
||||||
async with trio.open_nursery(
|
async with trio.open_nursery() as n:
|
||||||
strict_exception_groups=False,
|
|
||||||
) as n:
|
|
||||||
for syms, func in zip(symbols, stream_what):
|
for syms, func in zip(symbols, stream_what):
|
||||||
n.start_soon(func, feed, syms)
|
n.start_soon(func, feed, syms)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ import tractor
|
||||||
|
|
||||||
from piker.service import (
|
from piker.service import (
|
||||||
find_service,
|
find_service,
|
||||||
Services,
|
ServiceMngr,
|
||||||
)
|
)
|
||||||
from piker.data import (
|
from piker.data import (
|
||||||
open_feed,
|
open_feed,
|
||||||
|
|
@ -44,7 +44,7 @@ def test_runtime_boot(
|
||||||
async def main():
|
async def main():
|
||||||
port = 6666
|
port = 6666
|
||||||
daemon_addr = ('127.0.0.1', port)
|
daemon_addr = ('127.0.0.1', port)
|
||||||
services: Services
|
services: ServiceMngr
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
open_test_pikerd(
|
open_test_pikerd(
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue