This commit is contained in:
wvr committed 2026-11-21 20:00:22 -06:00
1 parent 421050292d
commit ce36cba8e9
2978 files changed
+35317 -85

No files matched your search

File renamed without changes.
-72
View File
@@ -1,72 +0,0 @@
#!/usr/bin/env python3
"""Download NQ front-month 1-minute bars from Databento into a gzipped CSV.
Setup (one time):
1. Sign up at https://databento.com (new accounts get $125 in free data credits)
2. Copy your API key from the portal (API Keys page)
3. pip install -U databento pandas
Run:
export DATABENTO_API_KEY=db-xxxxxxxxxxxxxxxx # Windows: set DATABENTO_API_KEY=...
python get_nq_1m.py # 2018-01-01 -> latest available
python get_nq_1m.py --start 2020-01-01 --symbol MNQ.v.0
The script prints the estimated cost and asks before downloading anything.
Output columns: ts_et (US/Eastern, bar open time), open, high, low, close, volume, instrument_id.
instrument_id changes on roll days, so contract switches are visible in the data.
"""
import argparse
import os
import sys
import databento as db
import pandas as pd
DATASET = "GLBX.MDP3" # CME Globex
SCHEMA = "ohlcv-1m"
p = argparse.ArgumentParser()
p.add_argument("--start", default="2018-01-01")
p.add_argument("--end", default=None, help="exclusive end date; default = latest available")
p.add_argument("--symbol", default="NQ.v.0",
help="continuous front month, rolled by volume (default NQ.v.0; MNQ.v.0 for micros)")
p.add_argument("--out", default="nq_1m.csv.gz")
p.add_argument("--all-hours", action="store_true",
help="keep the full overnight session instead of trimming to 08:00-16:15 ET")
p.add_argument("-y", "--yes", action="store_true", help="skip the cost confirmation")
a = p.parse_args()
key = os.environ.get("DATABENTO_API_KEY")
if not key:
sys.exit("Set DATABENTO_API_KEY first (see the top of this file).")
client = db.Historical(key)
end = a.end
if end is None:
rng = client.metadata.get_dataset_range(dataset=DATASET)
end = (rng.get("schema", {}).get(SCHEMA, {}) or {}).get("end") or rng["end"]
params = dict(dataset=DATASET, schema=SCHEMA, stype_in="continuous",
symbols=[a.symbol], start=a.start, end=end)
cost = client.metadata.get_cost(**params)
print(f"{a.symbol} {SCHEMA} {a.start} -> {end}: estimated cost ${cost:.2f}")
if not a.yes and input("Download? [y/N] ").strip().lower() != "y":
sys.exit("Cancelled.")
print("Downloading...")
df = client.timeseries.get_range(**params).to_df(tz="America/New_York")
df = df[["open", "high", "low", "close", "volume", "instrument_id"]]
df.index.name = "ts_et"
if not a.all_hours:
t = df.index.strftime("%H:%M")
df = df[(t >= "08:00") & (t <= "16:15")]
df.to_csv(a.out, float_format="%.2f")
days = df.index.normalize().nunique()
rolls = int((df["instrument_id"].diff().fillna(0) != 0).sum())
print(f"Wrote {a.out}: {len(df):,} bars, {days} trading days, "
f"{df.index[0]} -> {df.index[-1]}, {rolls} contract rolls")
print("Attach that file in the chat.")
+15 -13
View File
@@ -23,8 +23,9 @@
// 4. Otherwise (9:33): the old rule. 9:30 close vs yesterday's 4:00 pm close: above -> SHORT, below -> LONG. // 4. Otherwise (9:33): the old rule. 9:30 close vs yesterday's 4:00 pm close: above -> SHORT, below -> LONG.
// Sizing: contracts = round(stop $ / ($ per point x 0.20 x daily ATR(14))), min 1, max 4; // Sizing: contracts = round(stop $ / ($ per point x 0.20 x daily ATR(14))), min 1, max 4;
// stop pts = (stop $ - $20 x contracts) / (contracts x $ per point); target pts = (target $ + commission x contracts) / (contracts x $ per point). // stop pts = (stop $ - $20 x contracts) / (contracts x $ per point); target pts = (target $ + commission x contracts) / (contracts x $ per point).
// Micros (MGC / MCL / MNQ / MNG, 1/10 size, max 40) when the stop $ is under 75% of one full contract's risk at // Small contracts when the stop $ is under 75% of one full contract's risk at the ATR stop distance:
// the ATR stop distance; then $3 allowance per micro and micro commissions. // MGC / MCL / MNQ (1/10 size, max 40); nat gas uses QG (E-mini, 1/4 size, tick 0.005, max 16) because Lucid has no micro NG.
// Then $3 allowance per small contract and its own commission.
// Evaluation endgame: type what the account still needs to pass. $500 or less -> stop = what's needed (1:1); // Evaluation endgame: type what the account still needs to pass. $500 or less -> stop = what's needed (1:1);
// more than $500 -> target = what's needed, stop = all the room (the Stop $ input). 0 = off (fresh account). // more than $500 -> target = what's needed, stop = all the room (the Stop $ input). 0 = off (fresh account).
// Works on any chart timeframe (1 min, 5 min, 1 hour...): every signal is computed from 1-minute data of each contract. // Works on any chart timeframe (1 min, 5 min, 1 hour...): every signal is computed from 1-minute data of each contract.
@@ -70,7 +71,7 @@ ngComm = input.float(4.00, "Natural gas", step = 0.1, group = grpF, display = di
gcCommM = input.float(1.60, "Micro gold (MGC)", step = 0.1, group = grpF, display = display.none) gcCommM = input.float(1.60, "Micro gold (MGC)", step = 0.1, group = grpF, display = display.none)
clCommM = input.float(1.00, "Micro crude (MCL)", step = 0.1, group = grpF, display = display.none) clCommM = input.float(1.00, "Micro crude (MCL)", step = 0.1, group = grpF, display = display.none)
nqCommM = input.float(1.00, "Micro NQ (MNQ)", step = 0.1, group = grpF, display = display.none) nqCommM = input.float(1.00, "Micro NQ (MNQ)", step = 0.1, group = grpF, display = display.none)
ngCommM = input.float(1.00, "Micro nat gas (MNG)", step = 0.1, group = grpF, display = display.none) ngCommM = input.float(2.60, "E-mini nat gas (QG)", step = 0.1, group = grpF, display = display.none)
// ---------- helpers (evaluated in each symbol's own context via request.security) ---------- // ---------- helpers (evaluated in each symbol's own context via request.security) ----------
endsAt(h, m) => hour(time_close, tz) == h and minute(time_close, tz) == m endsAt(h, m) => hour(time_close, tz) == h and minute(time_close, tz) == m
@@ -198,15 +199,16 @@ endOn = needUsd > 0
stopEff = endOn and needUsd <= endThr ? needUsd : stopUsd stopEff = endOn and needUsd <= endThr ? needUsd : stopUsd
tgtEff = endOn ? needUsd : targetUsd tgtEff = endOn ? needUsd : targetUsd
sizeFor(atrD, pv, mt, comm, commM) => sizeFor(atrD, pv, mt, comm, commM, ratio, mtM) =>
micro = stopEff < 0.75 * pv * atrFrac * atrD // stop too small for one full contract at the ATR stop distance micro = stopEff < 0.75 * pv * atrFrac * atrD // stop too small for one full contract at the ATR stop distance
p = micro ? pv / 10 : pv p = micro ? pv / ratio : pv
cap = micro ? maxC * 10 : maxC cap = micro ? maxC * ratio : maxC
tk = micro ? mtM : mt // QG ticks 0.005, NG 0.001
cst = micro ? costUsdM : costUsd cst = micro ? costUsdM : costUsd
cm = micro ? commM : comm cm = micro ? commM : comm
n = math.max(1, math.min(cap, math.round(stopEff / (p * atrFrac * atrD)))) n = math.max(1, math.min(cap, math.round(stopEff / (p * atrFrac * atrD))))
sp = math.floor(math.max(stopEff - cst * n, 0) / (n * p) / mt + 1e-6) * mt // 1e-6 guards against float error (1.18 / 0.01 = 117.999...) sp = math.floor(math.max(stopEff - cst * n, 0) / (n * p) / tk + 1e-6) * tk // 1e-6 guards against float error (1.18 / 0.01 = 117.999...)
tp = math.ceil((tgtEff + cm * n) / (n * p) / mt - 1e-6) * mt tp = math.ceil((tgtEff + cm * n) / (n * p) / tk - 1e-6) * tk
[n, sp, tp, sp * n * p, tp * n * p, micro] // Risk USD / Reward USD = whole position [n, sp, tp, sp * n * p, tp * n * p, micro] // Risk USD / Reward USD = whole position
// ---------- display helpers ---------- // ---------- display helpers ----------
@@ -291,10 +293,10 @@ nqBranch = pending ? (useNews ? "waiting for the 8:30 candle (news check at 8:3
nqEntry = pending ? (useNews ? "8:31 / 8:33 / 9:31 / 9:33" : "9:31 / 9:33") : newsWait ? "8:33 (or 9:31 / 9:33)" : newsTrade ? (aDisp != 0 ? "8:31" : "8:33") : hEntry nqEntry = pending ? (useNews ? "8:31 / 8:33 / 9:31 / 9:33" : "9:31 / 9:33") : newsWait ? "8:33 (or 9:31 / 9:33)" : newsTrade ? (aDisp != 0 ? "8:31" : "8:33") : hEntry
// ---------- sizing ---------- // ---------- sizing ----------
[gcN, gcSp, gcTp, gcRiskUsd, gcRewUsd, gcMicro] = sizeFor(gcAtr, gcPv, gcMt, gcComm, gcCommM) [gcN, gcSp, gcTp, gcRiskUsd, gcRewUsd, gcMicro] = sizeFor(gcAtr, gcPv, gcMt, gcComm, gcCommM, 10, gcMt)
[clN, clSp, clTp, clRiskUsd, clRewUsd, clMicro] = sizeFor(clAtr, clPv, clMt, clComm, clCommM) [clN, clSp, clTp, clRiskUsd, clRewUsd, clMicro] = sizeFor(clAtr, clPv, clMt, clComm, clCommM, 10, clMt)
[nqN, nqSp, nqTp, nqRiskUsd, nqRewUsd, nqMicro] = sizeFor(nqAtr, nqPv, nqMt, nqComm, nqCommM) [nqN, nqSp, nqTp, nqRiskUsd, nqRewUsd, nqMicro] = sizeFor(nqAtr, nqPv, nqMt, nqComm, nqCommM, 10, nqMt)
[ngN, ngSp, ngTp, ngRiskUsd, ngRewUsd, ngMicro] = sizeFor(ngAtr, ngPv, ngMt, ngComm, ngCommM) [ngN, ngSp, ngTp, ngRiskUsd, ngRewUsd, ngMicro] = sizeFor(ngAtr, ngPv, ngMt, ngComm, ngCommM, 4, 0.005)
// ---------- display ---------- // ---------- display ----------
@@ -331,7 +333,7 @@ if barstate.islast
table.cell(t, 2, 3, sideText(clDir), text_color = sideColor(clDir)) table.cell(t, 2, 3, sideText(clDir), text_color = sideColor(clDir))
table.cell(t, 3, 3, "crude's side for the trading day that opens at 6 pm (no hedging)", text_color = color.white) table.cell(t, 3, 3, "crude's side for the trading day that opens at 6 pm (no hedging)", text_color = color.white)
table.cell(t, 4, 3, num(ngAtr), text_color = color.white) table.cell(t, 4, 3, num(ngAtr), text_color = color.white)
table.cell(t, 5, 3, str.tostring(ngN) + (ngMicro ? " MNG" : ""), text_color = ngMicro ? color.yellow : color.white) table.cell(t, 5, 3, str.tostring(ngN) + (ngMicro ? " QG" : ""), text_color = ngMicro ? color.yellow : color.white)
table.cell(t, 6, 3, usd(ngRiskUsd), text_color = color.red) table.cell(t, 6, 3, usd(ngRiskUsd), text_color = color.red)
table.cell(t, 7, 3, usd(ngRewUsd), text_color = color.lime) table.cell(t, 7, 3, usd(ngRewUsd), text_color = color.lime)
table.cell(t, 8, 3, pts(ngSp), text_color = color.new(color.red, 40)) table.cell(t, 8, 3, pts(ngSp), text_color = color.new(color.red, 40))
+11
View File
@@ -0,0 +1,11 @@
VC - Venture Capital
-------------
* Most investments fail and a few pay off large, so returns depend far more
on the number of independent bets than on picking each one well.
* Lesson: the fleet is a VC portfolio. Independence matters most, and since
same-market accounts move together, you really have about 5 independent bets
a day. More independent bets (another firm, another uncorrelated market)
is the most valuable change available.
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Download NQ front-month trades (aggressor side) for a short window each weekday. One request per day,
saved under raw_of/ and skipped on re-run (safe to restart after a timeout). Then builds one CSV.
export DATABENTO_API_KEY=db-xxxxxxxx
python3 orderflow_get.py # NQ, 09:29-09:32 ET, 2010-06-07 -> 2015-01-01 (~$13)
python3 orderflow_get.py --start 2016-01-01 --end 2026-11-21 # later, only if the test passes
"""
import argparse, glob, os, sys, time
import databento as db
import pandas as pd
p = argparse.ArgumentParser()
p.add_argument("--symbol", default="NQ"); p.add_argument("--window", nargs=2, default=["09:29", "09:32"])
p.add_argument("--start", default="2010-06-07"); p.add_argument("--end", default="2015-01-01")
p.add_argument("--yes", action="store_true", help="skip the confirmation prompt")
a = p.parse_args()
key = os.environ.get("DATABENTO_API_KEY") or sys.exit("Set DATABENTO_API_KEY first.")
c = db.Historical(key); os.makedirs("raw_of", exist_ok=True)
days = [d for d in pd.bdate_range(a.start, a.end) if d < pd.Timestamp(a.end)]
todo = [d for d in days if not os.path.exists(f"raw_of/{a.symbol}_{d.date()}.dbn.zst")]
print(f"{len(days)} weekdays, {len(todo)} still to download, window {a.window[0]}-{a.window[1]} ET")
if todo and not a.yes and input("Download (billed by Databento)? [y/N] ").strip().lower() != "y": sys.exit("cancelled")
for k, d in enumerate(todo, 1):
s = pd.Timestamp(f"{d.date()} {a.window[0]}", tz="America/New_York").tz_convert("UTC")
e = pd.Timestamp(f"{d.date()} {a.window[1]}", tz="America/New_York").tz_convert("UTC")
out, tmp = f"raw_of/{a.symbol}_{d.date()}.dbn.zst", f"raw_of/{a.symbol}_{d.date()}.part"
for attempt in range(4):
try:
c.timeseries.get_range(dataset="GLBX.MDP3", schema="trades", stype_in="continuous", symbols=[f"{a.symbol}.v.0"],
start=s.isoformat(), end=e.isoformat(), path=tmp)
os.replace(tmp, out); break
except Exception as ex:
if os.path.exists(tmp): os.remove(tmp)
if attempt == 3: sys.exit(f"stopped at {d.date()} ({ex}); just run the command again to resume")
time.sleep(5 * (attempt + 1))
if k % 50 == 0 or k == len(todo): print(f" {k}/{len(todo)} done", flush=True)
frames = []
for f in sorted(glob.glob(f"raw_of/{a.symbol}_*.dbn.zst")):
if not (a.start <= f.split("_")[-1][:10] < a.end): continue
df = db.DBNStore.from_file(f).to_df()
if len(df): frames.append(df.reset_index()[["ts_event", "price", "size", "side", "instrument_id"]])
X = pd.concat(frames); X["ts_et"] = pd.to_datetime(X.pop("ts_event"), utc=True).dt.tz_convert("America/New_York")
name = f"{a.symbol}_trades_{a.window[0].replace(':','')}-{a.window[1].replace(':','')}_{a.start[:4]}-{str(int(a.end[:4]) - (1 if a.end[5:] == '01-01' else 0))}.csv.gz"
X.to_csv(name, index=False); print(f"wrote {name}: {len(X):,} trades, {X.ts_et.dt.date.nunique()} days")
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 2978 files, more files were not shown because too many files have changed in this diff. Show more