{"id":50996624,"url":"https://github.com/aabbtree77/cryptobot","last_synced_at":"2026-06-20T10:03:00.843Z","repository":{"id":357019110,"uuid":"1234058730","full_name":"aabbtree77/cryptobot","owner":"aabbtree77","description":"Cryptocurrency trading bot with resync, modulo actual trading.","archived":false,"fork":false,"pushed_at":"2026-05-19T20:41:00.000Z","size":89,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-20T00:05:01.533Z","etag":null,"topics":["distributed-computing","latency","reconnection","resilience","resync","trading","websocket"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aabbtree77.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-09T17:39:26.000Z","updated_at":"2026-05-19T20:42:09.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/aabbtree77/cryptobot","commit_stats":null,"previous_names":["aabbtree77/cryptobot"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/aabbtree77/cryptobot","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aabbtree77%2Fcryptobot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aabbtree77%2Fcryptobot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aabbtree77%2Fcryptobot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aabbtree77%2Fcryptobot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aabbtree77","download_url":"https://codeload.github.com/aabbtree77/cryptobot/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aabbtree77%2Fcryptobot/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34565244,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-20T02:00:06.407Z","response_time":98,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["distributed-computing","latency","reconnection","resilience","resync","trading","websocket"],"created_at":"2026-06-20T10:03:00.080Z","updated_at":"2026-06-20T10:03:00.830Z","avatar_url":"https://github.com/aabbtree77.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# spec.md\n\n```text\nBINANCE LOW-LATENCY TRADING BOT\nDeterministic Event-Loop Architecture\nGo / Single Process / Epoch-Based Resynchronization\n\n\n\n======================================================================\n0. CORE PHILOSOPHY\n======================================================================\n\nThe system is NOT fundamentally a websocket client.\n\nThe system is:\na continuously repaired local simulation of exchange reality.\n\nThe websocket connection is merely:\na transport mechanism feeding authoritative market state.\n\nThe core architectural objective is NOT:\n- socket survival\n- reconnect minimization\n- uptime maximization\n\nThe actual objective is:\n\nminimize duration of invalid local market state\n\nMeaning:\nthe system must rapidly detect when confidence in local state\nhas degraded, then restore trustworthy synchronized state.\n\nPrimary metric:\n\ntime-to-correct-resync\n\nNOT:\n- reconnect count\n- socket longevity\n- ping success rate\n\n\n\n======================================================================\n1. PROCESS MODEL\n======================================================================\n\nSingle binary.\nSingle process.\nSingle strategy loop.\n\nNo:\n- microservices\n- Kafka\n- ZooKeeper\n- actor framework\n- Erlang supervision tree emulation\n- distributed consensus\n- service mesh\n- Kubernetes orchestration complexity\n\nReasoning:\n\nThe system currently contains:\n- one exchange\n- one websocket stream\n- one strategy engine\n\nLocal memory inside one process provides:\n- strongest consistency model\n- lowest coordination overhead\n- deterministic debugging\n- lowest reconnect latency\n\nDistributed systems complexity is intentionally avoided.\n\n\n\n======================================================================\n2. EXECUTION MODEL\n======================================================================\n\nThe architecture intentionally separates:\n\n1. deterministic state mutation\n2. asynchronous network I/O\n\nTrading state mutates ONLY inside:\nthe strategy event loop.\n\nNetwork goroutines:\n- never mutate strategy state\n- never perform trading decisions\n- never reconnect themselves\n- never supervise themselves\n\nThis preserves:\n- deterministic reasoning\n- replayability\n- debuggability\n- absence of mutexes\n\n\n\n======================================================================\n3. GOROUTINE MODEL\n======================================================================\n\nExactly three long-lived goroutines:\n\n1. Strategy Loop\n2. Websocket Reader\n3. Websocket Writer\n\n\n----------------------------------------------------------------------\n3.1 Strategy Loop\n----------------------------------------------------------------------\n\nResponsibilities:\n- maintain authoritative local market state\n- maintain orderbook\n- maintain positions\n- maintain balances\n- maintain risk state\n- maintain session confidence metrics\n- detect degraded state\n- trigger resynchronization decisions\n- emit outbound exchange commands\n\nThe strategy loop is:\nsingle-threaded\nserialized\ndeterministic\n\nAll state mutation occurs here.\n\n\n----------------------------------------------------------------------\n3.2 Websocket Reader\n----------------------------------------------------------------------\n\nResponsibilities:\n- read websocket frames\n- decode Binance payloads\n- immediately timestamp local receive time\n- attach connection epoch\n- validate sequence continuity\n- emit market events\n- emit control events\n\nReader NEVER:\n- mutates strategy state\n- reconnects\n- decides trading actions\n\n\n----------------------------------------------------------------------\n3.3 Websocket Writer\n----------------------------------------------------------------------\n\nResponsibilities:\n- serialize outbound websocket writes\n- send subscriptions\n- send orders\n- optionally send websocket pings\n- detect outbound transport failures\n- emit write-failure control events\n\nWriter NEVER:\n- mutates strategy state\n- reconnects\n- supervises sessions\n\n\n\n======================================================================\n4. CHANNEL MODEL\n======================================================================\n\nThree channels exist:\n\n1. marketEvents\n2. controlEvents\n3. outboundCommands\n\n\n----------------------------------------------------------------------\n4.1 marketEvents\n----------------------------------------------------------------------\n\nPurpose:\nhigh-volume exchange market data stream\n\nExamples:\n- trades\n- orderbook deltas\n- ticker updates\n- liquidation updates\n\nCharacteristics:\n- bursty\n- high throughput\n- freshness-sensitive\n- lower priority than control plane\n\n\n----------------------------------------------------------------------\n4.2 controlEvents\n----------------------------------------------------------------------\n\nPurpose:\nsystem/session/control-plane events\n\nExamples:\n- GapDetected\n- Disconnected\n- WriteFailed\n- SubscriptionConfirmed\n- Resynchronized\n- LatencyDegraded\n- ShutdownRequested\n\nCharacteristics:\n- low volume\n- latency-sensitive\n- state-transition-critical\n\nControl events must NOT compete equally with market flood traffic.\n\n\n----------------------------------------------------------------------\n4.3 outboundCommands\n----------------------------------------------------------------------\n\nPurpose:\ncommands emitted by strategy toward Binance\n\nExamples:\n- PlaceOrder\n- CancelOrder\n- Subscribe\n- Unsubscribe\n- CloseConnection\n\nCharacteristics:\n- low volume\n- latency-sensitive\n- serialized by writer goroutine\n\n\n\n======================================================================\n5. DATA FLOW MODEL\n======================================================================\n\n\nMARKET DATA FLOW\n\nBinance\n    -\u003e\nWebsocket Reader\n    -\u003e\nmarketEvents\n    -\u003e\nStrategy Loop\n\n\n\nCONTROL FLOW\n\nReader/Writer/Main\n    -\u003e\ncontrolEvents\n    -\u003e\nStrategy Loop\n\n\n\nOUTBOUND FLOW\n\nStrategy Loop\n    -\u003e\noutboundCommands\n    -\u003e\nWebsocket Writer\n    -\u003e\nBinance\n\n\n\nIMPORTANT:\n\nThere is NO global event bus.\n\nThere is NO many-to-many actor mesh.\n\nThe Strategy Loop is the single authoritative consumer\nof all meaningful system events.\n\n\n\n======================================================================\n6. STRATEGY EVENT LOOP MODEL\n======================================================================\n\nThe architecture resembles a deterministic game simulation loop.\n\nConceptually:\n\nwhile running:\n    prioritize control signals\n    process market updates\n    mutate world state\n    emit actions\n\n\nThe Strategy Loop may internally prioritize:\n\n1. controlEvents\n2. marketEvents\n\nusing select-based priority handling.\n\n\nExample conceptual structure:\n\nselect {\n    case ctrl := \u003c-controlEvents:\n        handleControl(ctrl)\n\n    case market := \u003c-marketEvents:\n        handleMarket(market)\n}\n\n\nThis is intentionally:\n- centralized\n- deterministic\n- cooperative\n\nNOT actor-style distributed mutation.\n\n\n\n======================================================================\n7. GAME LOOP INTERPRETATION\n======================================================================\n\nThe system maps naturally onto a real-time simulation model.\n\n\nWorldState\n    =\nlocal market simulation\n\nNetworkSession\n    =\nexchange connectivity\n\nEntity\n    =\norders / positions / instruments\n\nTick\n    =\nevent processing iteration\n\nDesync\n    =\nlocal divergence from exchange reality\n\nResync\n    =\nauthoritative state correction\n\nEpoch\n    =\ngeneration counter\n\n\nThis framing is intentional because:\nreal-time games solved deterministic synchronization\nproblems decades ago.\n\nThe architecture resembles:\na deterministic simulation fed by asynchronous I/O.\n\n\n\n======================================================================\n8. CONNECTION EPOCH MODEL\n======================================================================\n\nEvery successful websocket connection increments:\n\nepoch++\n\n\nEach websocket session owns:\n- exactly one reader goroutine\n- exactly one writer goroutine\n- exactly one websocket connection\n\n\nEvery emitted event carries:\n\nEvent {\n    Epoch\n    ...\n}\n\n\nThe Strategy Loop stores:\n\ncurrentEpoch\n\n\nIf:\n\nevent.Epoch != currentEpoch\n\nthen:\ndiscard event immediately.\n\n\nPurpose:\nprevent stale transport artifacts from corrupting current state.\n\n\nThis prevents:\n- reconnect races\n- stale delayed sends\n- old goroutine emissions\n- duplicated subscriptions\n- zombie transport behavior\n\n\n\n======================================================================\n9. SESSION LIFECYCLE MODEL\n======================================================================\n\nReconnect is NOT crash recovery.\n\nReconnect is:\ntransport session replacement.\n\n\nLifecycle:\n\n1. increment epoch\n2. dial websocket\n3. spawn reader/writer pair\n4. process session\n5. detect degraded confidence\n6. terminate entire session\n7. create fresh session\n\n\nIMPORTANT:\n\nReader/writer NEVER reconnect themselves.\n\nNo goroutine supervises itself.\n\nNo recursive reconnect logic exists.\n\nTransport sessions are disposable.\n\n\n\n======================================================================\n10. TIME MODEL\n======================================================================\n\nThree different temporal observations exist.\n\n\n----------------------------------------------------------------------\n10.1 ExchangeTS\n----------------------------------------------------------------------\n\nTimestamp from Binance payload.\n\nPurpose:\nauthoritative market chronology.\n\n\nThis is the canonical market timeline.\n\n\n----------------------------------------------------------------------\n10.2 RecvTS\n----------------------------------------------------------------------\n\nLocal monotonic timestamp taken immediately after websocket\nframe decode inside Reader goroutine.\n\nPurpose:\nmeasure:\n- transport latency\n- freshness\n- stream silence\n- transport degradation\n\n\nRecvTS is NOT authoritative ordering.\n\n\n----------------------------------------------------------------------\n10.3 ProcessTS\n----------------------------------------------------------------------\n\nTimestamp taken when Strategy Loop actually processes event.\n\nPurpose:\nmeasure:\n- internal queue delay\n- local processing backlog\n- event-loop saturation\n\n\nThis is critical telemetry.\n\n\n\n======================================================================\n11. LATENCY TELEMETRY MODEL\n======================================================================\n\nThe system continuously computes:\n\n\ntransport_latency\n    =\nRecvTS - ExchangeTS\n\n\nqueue_delay\n    =\nProcessTS - RecvTS\n\n\nmarket_silence\n    =\nnow - lastRecvTS\n\n\n\nThese represent DIFFERENT failure classes.\n\n\n----------------------------------------------------------------------\n11.1 Example: Transport Collapse\n----------------------------------------------------------------------\n\nExchangeTS -\u003e RecvTS = 12s\nRecvTS -\u003e ProcessTS = 2ms\n\nInterpretation:\n- network/TCP degradation\n- retransmission swamp\n- stale arriving data\n- strategy loop healthy\n\n\n----------------------------------------------------------------------\n11.2 Example: Internal Saturation\n----------------------------------------------------------------------\n\nExchangeTS -\u003e RecvTS = 30ms\nRecvTS -\u003e ProcessTS = 4s\n\nInterpretation:\n- network healthy\n- local processing backlog\n- strategy loop overloaded\n\n\nThis distinction is essential for debugging.\n\n\n\n======================================================================\n12. HEARTBEAT MODEL\n======================================================================\n\nPrimary heartbeat:\narrival of useful market data.\n\n\nNOT:\nping/pong.\n\n\nPing/pong only assists:\n- dead TCP detection\n- NAT keepalive\n- idle socket handling\n\n\nPrimary liveness metric:\n\nmarket_silence\n    =\nnow - lastRecvTS\n\n\nThis avoids false confidence from sockets that remain technically\nopen while delivering stale or useless data.\n\n\n\n======================================================================\n13. CONFIDENCE MODEL\n======================================================================\n\nThe system continuously estimates:\n\nconfidence(local state ~= exchange reality)\n\n\nReconnect/resync triggers include:\n\n- no market flow\n- sequence gaps\n- ancient timestamps\n- excessive transport latency\n- write failures\n- subscription failures\n- invalid orderbook continuity\n- excessive queue delay\n- stale snapshots\n\n\nReconnect is therefore:\nconfidence-driven\n\nNOT:\nping-timeout-driven.\n\n\n\n======================================================================\n14. RESYNCHRONIZATION MODEL\n======================================================================\n\nThe primary system metric:\n\ntime-to-correct-resync\n\n\nDefinition:\n\ntime from degraded confidence\nto restored trustworthy synchronized state\n\n\nPipeline components:\n\ndetect stale stream      1-3s\ntcp reconnect            100-500ms\nresubscribe              50-200ms\nsnapshot fetch           100-500ms\nbook rebuild             10-50ms\nvalidation                \u003c10ms\n\n\nTarget total:\n~2-5 seconds\n\n\nThis is preferred over:\nmaintaining technically alive but stale sessions.\n\n\n\n======================================================================\n15. ORDERBOOK RESYNC MODEL\n======================================================================\n\nOrderbook correctness takes priority over stream continuity.\n\nIf:\n- sequence gaps occur\n- continuity invalidated\n- stale deltas detected\n\nthen:\n- local orderbook invalidated\n- snapshot refetched\n- deltas replayed\n- continuity revalidated\n\n\nThe system prefers:\nauthoritative correction\n\nover:\nspeculative continuity.\n\n\n\n======================================================================\n16. DEGRADED MODE MODEL\n======================================================================\n\nThe Strategy Loop may enter degraded trading modes.\n\nExamples:\n- disable opening positions\n- allow exits only\n- cancel maker orders\n- suspend strategy\n- force resync\n\n\nMode decisions depend on:\n- freshness\n- queue delay\n- transport latency\n- continuity confidence\n\n\n\n======================================================================\n17. FAILURE MODEL\n======================================================================\n\nTransport failures:\nrecoverable.\n\nState corruption:\nfatal.\n\n\nExamples of recoverable failures:\n- websocket disconnect\n- delayed packets\n- write failure\n- subscription timeout\n\n\nExamples of fatal failures:\n- inconsistent order state\n- impossible position state\n- invariant violations\n- corrupted local book state\n\n\nThe dangerous state is NOT disconnected socket.\n\nThe dangerous state is:\ncontinuing to trade using invalid local reality.\n\n\n\n======================================================================\n18. SCHEDULING MODEL\n======================================================================\n\nGo runtime scheduling:\npreemptive underneath.\n\nTrading architecture:\ncooperative and serialized.\n\n\nAll meaningful state mutation occurs:\ninside one deterministic event loop.\n\n\nThis avoids:\n- mutex-heavy concurrency\n- temporal races\n- distributed mutation\n- actor-style debugging complexity\n\n\n\n======================================================================\n19. DEBUGGING MODEL\n======================================================================\n\nStructured logs should include:\n\n- epoch\n- exchange timestamp\n- receive timestamp\n- process timestamp\n- queue delay\n- transport latency\n- sequence numbers\n- order IDs\n- reconnect cause\n- confidence degradation reason\n\n\nThe architecture intentionally preserves:\ncausal observability.\n\n\nThe system should support:\n- event replay\n- deterministic simulation\n- postmortem analysis\n- latency attribution\n- reconnect timeline reconstruction\n\n\n\n======================================================================\n20. DESIGN PRINCIPLE SUMMARY\n======================================================================\n\nThe architecture intentionally optimizes for:\n\n- deterministic reasoning\n- rapid resynchronization\n- explicit failure boundaries\n- transport disposability\n- freshness awareness\n- replayability\n- observability\n- low operational complexity\n\n\nThe architecture intentionally avoids:\n\n- distributed coordination\n- actor meshes\n- supervision forests\n- recursive reconnect logic\n- hidden goroutine ownership\n- shared mutable state\n- microservice decomposition\n- \"never disconnect\" thinking\n\n\nThe system behaves as:\na deterministic market-state simulation engine\ncontinuously repaired from asynchronous exchange input.\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faabbtree77%2Fcryptobot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faabbtree77%2Fcryptobot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faabbtree77%2Fcryptobot/lists"}