cointoss.app¶
app
¶
The cointoss namespace: the scheduled sweeps and backfill, and the read API.
CointossApp is a lythonic NamespaceFragment. woodglue mounts it from woodglue.yaml as one
entry of a namespace's entries, and fragment_entry builds that entry:
namespaces:
cointoss:
run_engine: true
entries:
- type: fragment
gref: "cointoss.app:CointossApp"
nsref: "data:"
configs:
sweep:
triggers: [{name: daily_sweep, schedule: "5 0 * * *"}]
backfill:
triggers: [{name: daily_backfill, schedule: "0 1 * * *"}]
stock_sweep:
triggers: [{name: weekday_stock_sweep, schedule: "30 22 * * 1-5"}]
The read nodes are tagged api, so woodglue serves them over JSON-RPC as cointoss.data:members
and so on. sweep and backfill are not: they write and call CoinGecko, so they run from
their triggers, from woodglue's system.fire_trigger, or from the CLI, never from an ordinary
API call.
backfill (cointoss.backfill) has its own trigger rather than running inside the sweep, so a
slow or failing backfill neither delays the day's sweep nor marks it failed, and each firing is
logged on its own. It fires an hour after the default sweep; the order is not load-bearing,
since neither overwrites a bar the other stored. It takes the sweep lock for each write rather
than for its whole run, which is long, so a sweep or backup waiting for the lock gets it within
one coin's write.
stock_sweep (cointoss.stocks) evaluates the reserved yahoo-industries universe from Yahoo's
industry lists, resolves their tickers through OpenFIGI and fetches the stocks' bars from Yahoo
(cointoss.stock_bars), on its own trigger on weekdays after the US close, 22:30 UTC by default. It is idempotent within a US session, and like the backfill
it fetches outside the sweep lock and takes it for its writes, since its OpenFIGI calls are
paced to minutes on a first run.
The portfolio writes, create_portfolio, add_trade and void_trade, are api nodes too, but
declare the Required Action WRITE_ACTION, write (woodglue ADR 0005). woodglue runs them over
JSON-RPC only for a Grant of write on the namespace, which no call Grant reaches, wildcards
such as call * included; the explorer's Grant and a reader's Role are call cointoss. The
portfolio Role (PORTFOLIO_ROLE, PORTFOLIO_GRANTS) holds write cointoss beside
call cointoss, and the built-in admin Role reaches every Action. A refused write is answered
before the node runs, which a JSON-RPC client receives as -32003. woodglue checks only requests
it serves: a node called in process, as the tests do, runs for any Caller.
The caller is the owner: create_portfolio records the Caller's User id, and add_trade and
void_trade act only on that User's Portfolios. Another User's Portfolio or Trade is reported
exactly as a missing one is, NotFound, so ids do not reveal what others hold. With auth
disabled every request is woodglue's anonymous Caller, and owns as anonymous.
Runtime settings come from the data directory (cointoss.config.Settings): init.data_dir if
given, else woodglue's instance data directory (current_mount), else $COINTOSS_HOME, else
~/.local/share/cointoss. A woodglue.yaml written by cointoss init carries no
init.data_dir, so a copied instance serves its own store; older files that carry one still
work. Settings are read once, when the fragment is built, so a bad cointoss.yaml stops
woodglue at startup rather than failing the next sweep silently. A config edit takes effect on
restart.
Each call opens the store and closes it before returning, rather than holding one connection
for the fragment's life. woodglue calls a sync node on the IOLoop thread while lythonic's
DagRunner runs one in an executor thread, and a sqlite3 connection refuses use from a thread
other than its creator's; the store's WAL journal lets these short readers run beside a sweep's
writes; and nothing is left holding a transaction or a replaced file. Opening costs the schema
and version check, a few small queries, which a local API at human rates does not notice.
A read never creates anything: against a data directory with no cointoss.db it raises
NotInitialized, naming cointoss init. Only init and the sweep create the store.
One sweep runs at a time per data directory. The sweep node takes an exclusive flock on
sweep.lock there, which cointoss backup also holds while it copies. A scheduled firing
waits for the lock, up to SWEEP_LOCK_WAIT: lythonic records a firing as the trigger's last run
even when it fails, so a firing skipped because a backup held the lock would not be retried
until the next day, losing that day's bars. It waits by retrying a non-blocking flock between
asyncio.sleeps, never with a blocking flock, which would stall woodglue's IOLoop and the
JSON-RPC API with it. A manual cointoss sweep passes wait=0, so one started while another
runs raises SweepInProgress at once and does nothing.
A request the store cannot answer -- an unknown universe or Instrument, a date before a
universe's first entry, a malformed date -- raises an ApiError carrying a JSON-RPC error code
and a message naming what was not found. ApiError is a woodglue RpcError, so a JSON-RPC
client receives that code and message, and woodglue logs it without a traceback.
DEFAULT_SWEEP_SCHEDULE = '5 0 * * *'
module-attribute
¶
Five past midnight UTC: after CoinGecko's 00:00 point exists, and early enough to be it.
SWEEP_NODE = 'sweep'
module-attribute
¶
The fragment's sweep node, as named in a namespace entry's configs.
DEFAULT_BACKFILL_SCHEDULE = '0 1 * * *'
module-attribute
¶
01:00 UTC: after the default sweep has written the day's bars and released the lock.
DEFAULT_STOCK_SWEEP_SCHEDULE = '30 22 * * 1-5'
module-attribute
¶
22:30 UTC on weekdays: after the US close at 16:00 New York, in summer and in winter.
NAMESPACE = 'cointoss'
module-attribute
¶
The woodglue namespace cointoss init mounts the fragment under.
WRITE_ACTION = 'write'
module-attribute
¶
The Required Action of the portfolio writes; only a write Grant on the namespace runs them.
PORTFOLIO_GRANTS = (f'call {NAMESPACE}', f'{WRITE_ACTION} {NAMESPACE}')
module-attribute
¶
The Grants of PORTFOLIO_ROLE: the read API and the portfolio writes.
SWEEP_LOCK_WAIT = 600.0
module-attribute
¶
Seconds a scheduled sweep or a backup waits for the sweep lock before giving up.
LOCK_POLL = 1.0
module-attribute
¶
Seconds between attempts to take a held sweep lock.
ApiError
¶
NotFound
¶
NotInitialized
¶
BadRequest
¶
Unauthorized
¶
Conflict
¶
SweepInProgress
¶
MemberView
¶
Bases: BaseModel
One member on a date and its bar for that date, if one is stored.
Close, volume and market cap are what a swept CoinGecko bar holds. Rank is not persisted, so it is not here.
Source code in src/cointoss/app.py
ChangeView
¶
Bases: BaseModel
What joined and what left a universe on one date.
Source code in src/cointoss/app.py
UniverseView
¶
Bases: BaseModel
A stored Universe Definition at its latest revision.
Source code in src/cointoss/app.py
SweepOutcome
¶
Bases: BaseModel
What one firing of the sweep did for the UTC day.
already_swept means every declared universe already had a Run for day, so nothing was
fetched and report is None.
Source code in src/cointoss/app.py
CointossApp
¶
Bases: NamespaceFragment
The scheduled sweeps and backfill, and the read API over one instance's store.
Source code in src/cointoss/app.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 | |
sweep(force=False, wait=SWEEP_LOCK_WAIT)
async
¶
Reconcile the declared universes, then sweep CoinGecko markets for today (UTC).
Idempotent within a UTC day. Once every declared universe has a Run for today, a further
firing fetches nothing and reports already_swept. Otherwise -- the first firing, a
retry after a failure, a universe newly declared, or force -- it sweeps at the current
time. ingest.sweep returns a universe's Run already recorded for the day rather than
evaluating it again, and keeps any bar already stored for the day, so a re-sweep only
fills in what is missing and never files a Restatement against the day's own bars.
The universes swept are the declared ones and, once a trade has created it,
portfolio-held.
Creates the data directory and store if absent. Waits up to wait seconds for the sweep
lock, since the trigger fires the node with no arguments, and raises SweepInProgress if
another sweep or a backup still holds it then.
Source code in src/cointoss/app.py
backfill(days=BACKFILL_DAYS, wait=SWEEP_LOCK_WAIT)
async
¶
Fill every date with no stored bar, from CoinGecko's last days days and from Yahoo.
See cointoss.backfill. Each write waits up to wait seconds for the sweep lock and
raises SweepInProgress if it is still held then. Refuses a data directory with no
store, since only a sweep has universes whose members it could fill.
Source code in src/cointoss/app.py
stock_sweep(force=False, wait=SWEEP_LOCK_WAIT)
async
¶
Evaluate yahoo-industries for the latest US session closed, and retry unresolved stocks.
See cointoss.stocks. Idempotent within a session unless force. Creates the data
directory and store if absent. Its writes wait up to wait seconds for the sweep lock,
and raise SweepInProgress if it is still held then.
Source code in src/cointoss/app.py
members(universe, date)
¶
The members of a universe on a date, each with that date's close, volume and market cap.
Bars are dated by the session they close (Session Offset), so on the latest swept date a CoinGecko-priced member has no close yet: its close is the next day's 00:00 price, and arrives with the next sweep.
Source code in src/cointoss/app.py
changes(universe, start, end)
¶
Joins and leaves by date, for each date in [start, end] the membership changed.
A universe's first entry reports every member as joining.
Source code in src/cointoss/app.py
bars(instrument_id, start, end)
¶
One Instrument's bars from start to end inclusive, through its Price Sources.
Each is dated by the session it closes, as Store.bars_for resolves them.
Source code in src/cointoss/app.py
universes_of(instrument_id, start, end)
¶
The universes an Instrument was a member of on any day of [start, end].
Source code in src/cointoss/app.py
runs(universe, limit=20)
¶
A universe's most recent Evaluation Runs, newest first: whether the sweep is alive.
Source code in src/cointoss/app.py
universes()
¶
Every stored Universe Definition with its current band, declared in config or not.
Source code in src/cointoss/app.py
datasets()
¶
frame(dataset, params=None)
¶
One Dataset as a long table, params validated against its model (see datasets).
An unknown Dataset is NotFound; params its model refuses, or a match over
cointoss.datasets.ROW_CAP rows, are BadRequest. Nothing matching is an empty frame.
An owned Dataset (trades, positions, portfolio_value) holds only the caller's own
Portfolios, and another User's Portfolio named in its params is NotFound, as one that
does not exist. Read in-process, with no Caller, it is Unauthorized, as a write is.
Source code in src/cointoss/app.py
create_portfolio(name, kind=PortfolioKind.REAL, custodian=None)
¶
Create a Portfolio owned by the caller. kind is real, paper or what_if.
A name is unique among the caller's own Portfolios; reusing one is a Conflict.
Source code in src/cointoss/app.py
add_trade(portfolio_id, instrument, quantity, cost=None, traded_at=None, kind=TradeKind.REAL, note=None, source=Source.COINGECKO, coingecko_id=None)
async
¶
Record a Trade in one of the caller's Portfolios, and hold its Instrument for pricing.
instrument is a stored Instrument Id (type.scope.symbol) or a symbol typed against
source, pinned as cointoss.ingest.resolve_typed_symbol pins one, with its mandatory
FIGI attempt; coingecko_id names the coin when a CoinGecko symbol is shared. A positive
quantity is a buy, a negative one a sale; cost is the Trade's total in USD.
traded_at is an ISO time, read as UTC when it has no offset, and now by default.
The Instrument is included in portfolio-held, created on first use, so the next
sweep writes a coin's bar even when it ranks outside every declared universe, and the
next stock sweep a stock's whole history, listed by Yahoo or not; a stock is typed
against yahoo.
The other arguments are checked before the Instrument is named, since pinning a symbol stores its Instrument. The Inclusion is written before the Trade, each in its own commit: should the Trade then fail, an Instrument held with no Trade only costs the sweep a bar, while a Trade whose Instrument is not held would go unpriced.
Source code in src/cointoss/app.py
void_trade(trade_id)
¶
Void one of the caller's Trades now. It stays recorded and counts toward nothing.
A Trade is voided once: voiding it again is a Conflict, and the first Void stands.
Source code in src/cointoss/app.py
utcnow()
¶
utc_today()
¶
fragment_entry(*, data_dir=None, schedule=DEFAULT_SWEEP_SCHEDULE, backfill_schedule=DEFAULT_BACKFILL_SCHEDULE, stock_schedule=DEFAULT_STOCK_SWEEP_SCHEDULE)
¶
The woodglue.yaml namespace entry mounting the fragment with its scheduled triggers.
lythonic reads triggers only from configuration, so the default schedule lives here and in
whatever cointoss init writes from it. Without data_dir the fragment resolves the data
directory itself when it is built, from woodglue's mount when there is one.
Source code in src/cointoss/app.py
fragment_schedule(entry, node=SWEEP_NODE, trigger=SWEEP_TRIGGER)
¶
A node's schedule in a namespace entry shaped like fragment_entry's, if any.
>>> fragment_schedule(fragment_entry(schedule="35 0 * * *"))
'35 0 * * *'
>>> fragment_schedule(fragment_entry(), BACKFILL_NODE, BACKFILL_TRIGGER)
'0 1 * * *'
>>> fragment_schedule({"type": "fragment"}) is None
True
Source code in src/cointoss/app.py
sweep_lock(data_dir, wait=0.0)
¶
Hold the data directory's sweep lock, waiting up to wait seconds for it.
Raises SweepInProgress if it is still held then; with no wait, at once. The wait sleeps
the calling thread, so the event loop uses sweep_lock_async. An flock is released by the
kernel when its holder exits, so a killed sweep leaves no stale lock behind.
Source code in src/cointoss/app.py
sweep_lock_async(data_dir, wait=0.0)
async
¶
sweep_lock, waiting with asyncio.sleep so the event loop keeps running meanwhile.
Source code in src/cointoss/app.py
one_line(exc, *, whole='')
¶
An error's message on one line: each validation error's field and reason, or the text.
A validation error of the whole model, with no field, is labelled whole when given.