Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incremental update paths #302

Merged
merged 113 commits into from
Jun 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
113 commits
Select commit Hold shift + click to select a range
c097016
Add new `ui._flows` module
goodboy Apr 14, 2022
599c77f
Port ui components to use flows, drop all late assignments of shm
goodboy Apr 14, 2022
d0af280
Port view downsampling handler to new update apis
goodboy Apr 14, 2022
5a9bab0
WIP incremental render apis
goodboy Apr 16, 2022
e0a72a2
WIP starting architecture doc str writeup..
goodboy Apr 18, 2022
f4dc0fb
Add `BarItems.draw_last()` and disable `.update_from_array()`
goodboy Apr 20, 2022
427a336
More WIP, implement `BarItems` rendering in `Flow.update_graphics()`
goodboy Apr 20, 2022
239c9d7
Don't require data input to constructor
goodboy Apr 20, 2022
3dbce6f
Add `FastAppendCurve.draw_last()`
goodboy Apr 20, 2022
7e1ec7b
Incrementally update flattend OHLC data
goodboy May 10, 2022
df78e9b
Delegate graphics cycle max/min to chart/flows
goodboy Apr 21, 2022
2af4050
Remove `._set_yrange()` handler from x-range-change signal
goodboy Apr 21, 2022
c94c532
`FastAppendCurve`: Only render in-view data if possible
goodboy Apr 22, 2022
af6aad4
If a sample stream is already ded, just warn
goodboy Apr 22, 2022
6420654
Put mxmn profile mapping at end of method
goodboy Apr 22, 2022
db72791
Always use coord cache, add naive view range diffing logic
goodboy Apr 22, 2022
aee44fe
Right, handle the case where the shm prepend history isn't full XD
goodboy Apr 23, 2022
69282a9
Handle null output case for vlm chart mxmn
goodboy Apr 23, 2022
64c6287
Always set coords cache on curves
goodboy Apr 23, 2022
b97ec38
Always maybe render graphics
goodboy Apr 23, 2022
b2b31b8
WIP incrementally update step array format
goodboy Apr 24, 2022
82b2d2e
Hipshot, use uppx to drive theoretical px w
goodboy Apr 5, 2022
ba0ba34
Drop log scaling support since uppx driven scaling seems way faster/b…
goodboy Apr 24, 2022
629ea8b
Downsample on every uppx inrement since it's way faster
goodboy Apr 24, 2022
c5beecf
Drop cursor debounce delay, decrease rate limit
goodboy Apr 24, 2022
12d60e6
WIP get incremental step curve updates working
goodboy Apr 26, 2022
186658a
Drop uppx guard around downsamples on interaction
goodboy Apr 26, 2022
b129216
Drop step routine import
goodboy Apr 26, 2022
859eaff
Drop vwap fsp for now; causes hangs..
goodboy Apr 26, 2022
2b60414
Startup up with 3k bars
goodboy Apr 26, 2022
0770a39
Only do curve appends on low uppx levels
goodboy Apr 26, 2022
0744dd0
Up the display throttle rate to 22Hz
goodboy Apr 27, 2022
7a34373
An absolute uppx diff of >= 1 seems more then fine
goodboy Apr 27, 2022
36a1015
Add profiler passthrough type annot, comments about appends vs. uppx
goodboy Apr 29, 2022
e163a7e
Drop `bar_wap` curve for now, seems to also be causing hangs?!
goodboy Apr 29, 2022
fb38265
Clean out legacy code from `Flow.update_graphics()`
goodboy May 1, 2022
1fcb923
Add back mx/mn updates for L1-in-view, lost during rebase
goodboy May 2, 2022
4f36743
Only udpate prepended graphics when actually in view
goodboy May 9, 2022
47cf4aa
Error log brokerd msgs that have `.reqid == None`
goodboy May 10, 2022
c455df7
Drop legacy step path gen, always slice full data
goodboy May 13, 2022
cfc4198
Use new profiler arg name, add more marks throughout flow update
goodboy May 13, 2022
5e60221
Use new flag, add more marks through display loop
goodboy May 13, 2022
09e988e
Use `ms_threshold` throughout remaining profilers
goodboy May 13, 2022
5d26609
Add "no-tsdb-found" history load length defaults
goodboy May 15, 2022
b609f46
Always delay interaction update profiling
goodboy May 15, 2022
f6909ae
Drop legacy step mode data formatter
goodboy May 15, 2022
e8e2623
Drop `BarItems.update_from_array()`; moved into `Flow`
goodboy May 15, 2022
bc50db5
Rename `._ohlc.gen_qpath()` -> `.gen_ohlc_qpath()`
goodboy May 15, 2022
9c5bc6d
Add `.ui._pathops` module
goodboy May 15, 2022
037300c
Move ohlc lines-curve generators into pathops mod
goodboy May 15, 2022
ca5a25f
Drop commented `numba` imports
goodboy May 15, 2022
537b725
Factor ohlc to line data conversion into `._pathops.ohlc_to_line()`
goodboy May 15, 2022
5d29403
Factor step format data gen into `to_step_format()`
goodboy May 15, 2022
27ee9fd
Drop old non-working flatten routine
goodboy May 15, 2022
b236dc7
Make vlm a float; discrete is so 80s
goodboy May 16, 2022
1dca776
Add notes about how to do mkts "trimming"
goodboy May 16, 2022
1f95ba4
Drop input xy from constructor, only keep state for cursor stuff..
goodboy May 16, 2022
f67fd11
Little formattito
goodboy May 16, 2022
df1c89e
Drop all "pixel width" refs (`px_width`) from m4 impl
goodboy May 17, 2022
81be0b4
Dont pass `px_width` to m4, add some commented path cap tracking
goodboy May 17, 2022
e258654
Just drop "line dot" updates for now..
goodboy May 17, 2022
4c7661f
Factor `.update_from_array()` into `Flow.update_graphics()`
goodboy May 18, 2022
1dab77c
Rect wont show on step curves unless we avoid `.draw_last()`
goodboy May 18, 2022
b5b9ecf
Treat paths like input/output vars
goodboy May 18, 2022
b3ae562
Fully drop `.update_from_array()`
goodboy May 18, 2022
72e849c
Drop commented cruft from update logic
goodboy May 18, 2022
876add4
Drop `.update()` call from `.draw_last()`
goodboy May 18, 2022
664a208
Drop path generation from `gen_ohlc_qpath()`
goodboy May 18, 2022
aa0efe1
Drop `BarItems.draw_from_data()`
goodboy May 18, 2022
167ae96
Move graphics update logic into `Renderer.render()`
goodboy May 18, 2022
17456d9
Drop tons of old cruft, move around some commented ideas
goodboy May 19, 2022
fa30df3
Simplify default xy formatter
goodboy May 19, 2022
432d454
Fix last values, must be pulled from source data in step mode
goodboy May 20, 2022
f5de361
Import directly from `tractor.trionics`
goodboy May 21, 2022
c256d3b
Type annot name in put to log routine
goodboy May 21, 2022
b985b48
Add `._last_bar_lines` guard to `.paint()`
goodboy May 21, 2022
5d91516
Drop step mode "last datum" graphics creation from `.draw_last()`
goodboy May 21, 2022
eca2401
Lul, well that heigh did not work..
goodboy May 24, 2022
bbe1ff1
Don't kill all containers on teardown XD
goodboy May 24, 2022
1b38628
Handle teardown race, add comment about shm subdirs
goodboy May 24, 2022
8ce7e99
Drop prints
goodboy May 24, 2022
42572d3
Add back linked plots/views y-range autoscaling
goodboy May 24, 2022
04897fd
Implement pre-graphics format incremental update
goodboy May 25, 2022
d4f31f2
Move update-state-vars defaults above step mode block
goodboy May 25, 2022
066b8df
Implement OHLC downsampled curve via renderer, drop old bypass code
goodboy May 25, 2022
08c83af
Rejig config helpers for arbitrary named files
goodboy May 26, 2022
88ac2fd
Aggretate cache resetting into a single ctx mngr method
goodboy May 28, 2022
d61b636
Auto-yrange overlays in interaction (downsampler) handler
goodboy May 29, 2022
a9ec1a9
Vlm "rate" fsps, change maxmin callback name to include `multi_`
goodboy May 30, 2022
ab0def2
Change flag name to `autoscale_overlays`
goodboy May 30, 2022
360643b
Fix optional input `bars_range` type to match `Flow.datums_range()`
goodboy May 30, 2022
2c2c453
Reset line graphics on downsample step..
goodboy May 30, 2022
6f00617
Only do new "datum append" when visible in pixels
goodboy May 31, 2022
3ab91de
Drop all (old) unused state instance vars
goodboy May 31, 2022
8f1faf9
Add todo for bars range reuse in interaction handler
goodboy May 31, 2022
57acc3b
Factor all per graphic `.draw_last()` methods into closures
goodboy May 31, 2022
a7ff471
Pass tsdb flag when db is up XD
goodboy May 31, 2022
fc24f5e
Iterate 1s and 1m from tsdb series
goodboy May 31, 2022
363ba8f
Only drop throttle feeds if channel disconnects?
goodboy Jun 1, 2022
064d185
Drop pointless geo call from `.pain()`
goodboy Jun 1, 2022
b71e8c5
Guard against empty source history slice output
goodboy Jun 1, 2022
e6d03ba
Add missing f-str prefix
goodboy Jun 1, 2022
80835d4
More detailed rt feed drop logging
goodboy Jun 1, 2022
0f4bfcd
Drop global pg settings
goodboy Jun 2, 2022
4138cef
Drop old state from `BarsItems`
goodboy Jun 2, 2022
c518553
Add new curve doc string
goodboy Jun 2, 2022
d770867
Drop width arg to bar lines factory
goodboy Jun 2, 2022
736178a
Rename `FastAppendCurve` -> `Curve`
goodboy Jun 2, 2022
55772ef
Bleh, try avoiding the too many files bug-thing..
goodboy Jun 3, 2022
a66934a
Add `Curve` sub-types with new custom graphics API
goodboy Jun 3, 2022
e5f9639
Return xy data from `Curve.draw_last_datum()` methods
goodboy Jun 3, 2022
99965e7
Only draw mx/mn line for last uppx's worth of datums
goodboy Jun 3, 2022
44c242a
Fill in label with pairs from `status` value of backend init msg
goodboy Jun 6, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion piker/brokers/kraken.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from contextlib import asynccontextmanager as acm
from dataclasses import asdict, field
from datetime import datetime
from pprint import pformat
from typing import Any, Optional, AsyncIterator, Callable, Union
import time

Expand Down Expand Up @@ -569,7 +570,10 @@ async def handle_order_requests(
order: BrokerdOrder

async for request_msg in ems_order_stream:
log.info(f'Received order request {request_msg}')
log.info(
'Received order request:\n'
f'{pformat(request_msg)}'
)

action = request_msg['action']

Expand Down Expand Up @@ -628,6 +632,7 @@ async def handle_order_requests(
# update the internal pairing of oid to krakens
# txid with the new txid that is returned on edit
reqid = resp['result']['txid']

# deliver ack that order has been submitted to broker routing
await ems_order_stream.send(
BrokerdOrderAck(
Expand Down Expand Up @@ -788,7 +793,10 @@ async def subscribe(ws: wsproto.WSConnection, token: str):
# Get websocket token for authenticated data stream
# Assert that a token was actually received.
resp = await client.endpoint('GetWebSocketsToken', {})

# lol wtf is this..
assert resp['error'] == []

token = resp['result']['token']

async with (
Expand Down
30 changes: 23 additions & 7 deletions piker/clearing/_ems.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ def check_lt(price: float) -> bool:

return check_lt

raise ValueError('trigger: {trigger_price}, last: {known_last}')
raise ValueError(
f'trigger: {trigger_price}, last: {known_last}'
)


@dataclass
Expand Down Expand Up @@ -561,7 +563,10 @@ async def translate_and_relay_brokerd_events(

name = brokerd_msg['name']

log.info(f'Received broker trade event:\n{pformat(brokerd_msg)}')
log.info(
f'Received broker trade event:\n'
f'{pformat(brokerd_msg)}'
)

if name == 'position':

Expand Down Expand Up @@ -613,19 +618,28 @@ async def translate_and_relay_brokerd_events(
# packed at submission since we already know it ahead of
# time
paper = brokerd_msg['broker_details'].get('paper_info')
ext = brokerd_msg['broker_details'].get('external')
if paper:
# paperboi keeps the ems id up front
oid = paper['oid']

else:
elif ext:
# may be an order msg specified as "external" to the
# piker ems flow (i.e. generated by some other
# external broker backend client (like tws for ib)
ext = brokerd_msg['broker_details'].get('external')
if ext:
log.error(f"External trade event {ext}")
log.error(f"External trade event {ext}")

continue

else:
# something is out of order, we don't have an oid for
# this broker-side message.
log.error(
'Unknown oid:{oid} for msg:\n'
f'{pformat(brokerd_msg)}'
'Unable to relay message to client side!?'
)

else:
# check for existing live flow entry
entry = book._ems_entries.get(oid)
Expand Down Expand Up @@ -823,7 +837,9 @@ async def process_client_order_cmds(
if reqid:

# send cancel to brokerd immediately!
log.info("Submitting cancel for live order {reqid}")
log.info(
f'Submitting cancel for live order {reqid}'
)

await brokerd_order_stream.send(msg.dict())

Expand Down
82 changes: 64 additions & 18 deletions piker/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# piker: trading gear for hackers
# Copyright (C) 2018-present Tyler Goodlet (in stewardship of piker0)
# Copyright (C) 2018-present 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
Expand All @@ -16,6 +16,7 @@

"""
Broker configuration mgmt.

"""
import platform
import sys
Expand Down Expand Up @@ -50,7 +51,7 @@ def get_app_dir(app_name, roaming=True, force_posix=False):
Unix (POSIX):
``~/.foo-bar``
Win XP (roaming):
``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``
``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo``
Win XP (not roaming):
``C:\Documents and Settings\<user>\Application Data\Foo Bar``
Win 7 (roaming):
Expand Down Expand Up @@ -81,7 +82,8 @@ def _posixify(name):
folder = os.path.expanduser("~")
return os.path.join(folder, app_name)
if force_posix:
return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name))))
return os.path.join(
os.path.expanduser("~/.{}".format(_posixify(app_name))))
if sys.platform == "darwin":
return os.path.join(
os.path.expanduser("~/Library/Application Support"), app_name
Expand All @@ -107,7 +109,12 @@ def _posixify(name):
]
)

_file_name = 'brokers.toml'
_conf_names: set[str] = {
'brokers',
'trades',
'watchlists',
}

_watchlists_data_path = os.path.join(_config_dir, 'watchlists.json')
_context_defaults = dict(
default_map={
Expand All @@ -129,23 +136,43 @@ def _override_config_dir(
_config_dir = path


def get_broker_conf_path():
def _conf_fn_w_ext(
name: str,
) -> str:
# change this if we ever change the config file format.
return f'{name}.toml'


def get_conf_path(
conf_name: str = 'brokers',

) -> str:
"""Return the default config path normally under
``~/.config/piker`` on linux.

Contains files such as:
- brokers.toml
- watchlists.toml
- trades.toml

# maybe coming soon ;)
- signals.toml
- strats.toml

"""
return os.path.join(_config_dir, _file_name)
assert conf_name in _conf_names
fn = _conf_fn_w_ext(conf_name)
return os.path.join(
_config_dir,
fn,
)


def repodir():
"""Return the abspath to the repo directory.
"""
'''
Return the abspath to the repo directory.

'''
dirpath = os.path.abspath(
# we're 3 levels down in **this** module file
dirname(dirname(os.path.realpath(__file__)))
Expand All @@ -154,16 +181,27 @@ def repodir():


def load(
conf_name: str = 'brokers',
path: str = None

) -> (dict, str):
"""Load broker config.
"""
path = path or get_broker_conf_path()
'''
Load config file by name.

'''
path = path or get_conf_path(conf_name)
if not os.path.isfile(path):
shutil.copyfile(
os.path.join(repodir(), 'config', 'brokers.toml'),
path,
fn = _conf_fn_w_ext(conf_name)

template = os.path.join(
repodir(),
'config',
fn
)
# try to copy in a template config to the user's directory
# if one exists.
if os.path.isfile(template):
shutil.copyfile(template, path)

config = toml.load(path)
log.debug(f"Read config file {path}")
Expand All @@ -172,13 +210,17 @@ def load(

def write(
config: dict, # toml config as dict
name: str = 'brokers',
path: str = None,

) -> None:
"""Write broker config to disk.
''''
Write broker config to disk.

Create a ``brokers.ini`` file if one does not exist.
"""
path = path or get_broker_conf_path()

'''
path = path or get_conf_path(name)
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
log.debug(f"Creating config dir {_config_dir}")
Expand All @@ -188,7 +230,10 @@ def write(
raise ValueError(
"Watch out you're trying to write a blank config!")

log.debug(f"Writing config file {path}")
log.debug(
f"Writing config `{name}` file to:\n"
f"{path}"
)
with open(path, 'w') as cf:
return toml.dump(config, cf)

Expand Down Expand Up @@ -218,4 +263,5 @@ def load_accounts(

# our default paper engine entry
accounts['paper'] = None

return accounts
2 changes: 0 additions & 2 deletions piker/data/_ahab.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,6 @@ def unpack_msg(err: Exception) -> str:
finally:
if client:
client.close()
for c in client.containers.list():
c.kill()


class Container:
Expand Down
Loading