如何用 Veriql Forecast 免費 API 和 Python 計算 Bitcoin 觸及任意價格的機率
What are the odds Bitcoin touches your price today? Touch odds at any price from a free API (Python)
Veriql Forecast API 教學示範如何用 Python 根據 `/v1/touch/{asset}/{h}` 的樣本,計算 Bitcoin 觸及任意指定價格的機率。API 免費使用,毋須 API key 或註冊;約 15 行 Python 的計算結果與 API 固定幅度報價完全一致。內容亦説明「觸及」與窗口結束時仍在價位之外的分別,以及使用數據時須留意的兩種情況。
The free Veriql Forecast API already lists touch odds at fixed steps: 1%, 2%, 3%, 5%, 8% and 13% above and below the window's start price. A real question is usually about one exact price, such as a round number, a stop or a liquidation price: "what is the chance Bitcoin trades at $62,500 before midnight UTC?" The endpoint /v1/touch/{asset}/{h} returns the sample behind those odds, and about 15 lines of Python turn it into a chance for any price. You need no key and no sign-up.
This tutorial shows the code and checks it against the API's own numbers, which it matches exactly. It also covers the two mistakes that are easy to make with this data: reading a window that has already ended, and asking about a price that has already been touched.
We run this API (Veriql Forecast), so read this as a tutorial from the people who built it. Forecast, not financial advice.
Touch or end beyond?
The API gives two chances for every price:
- Touch: the price trades at that level at least once before the window ends. A stop-loss, a take-profit or a liquidation cares about this one.
- Ends beyond: the price is still past that level when the window closes. A bet on the closing price cares about this one.
The touch chance is never smaller than the end-beyond chance: a price that ends beyond a level has touched it on the way, and a price can also reach a level and fall back. The first tutorial covers the ranges and the fixed-step odds.
One request
curl https://forecast.veriql.app/v1/touch/BTC/24h
This is the answer for the 24-hour Bitcoin window from 00:00 UTC on 28 Nov 2026 to 00:00 UTC on 29 Nov, with the sample lists cut short:
{
"asset": "BTC",
"horizon": "24h",
"t": 1795824000,
"ends_at": 1795910400,
"p0": 59872.5,
"sigma_now": 0.025536442289015814,
"n": 730,
"samples": {
"e_up": [0, 0, 0, 0],
"e_dn": [0, 0.0, 0.001, 0.002],
"z": [-3.764, -3.733, -3.533, -3.305]
},
"credits": ["Price data: Bitstamp"],
"disclaimer": "Forecast, not financial advice."
}
-
tandends_at: the window's start and end, in unix seconds (UTC). -
p0: the price at the start of the window. -
sigma_now: the forecast volatility for the whole window, as a log return. Here it is about 2.6%. -
samples: three lists ofnpast cases.e_upholds how far the price went up during each past window,e_dnhow far it went down, andzwhere it ended, each measured in units of that window's own volatility. In the answers we saw, each list came sorted from low to high, so the three lists are not lined up case by case. You only ever count within one list, so that does not matter.
The endpoint covers the crypto assets: BTC, ETH, XRP, SOL and NEAR. h is 24h (the UTC day) or 8h (windows starting at 00:00, 08:00 or 16:00 UTC).
The math
Because the past cases are measured in volatility units, you turn your price into the same unit and count how many past cases went at least that far:
m = ln(price / p0) / sigma_now
price above p0: touch = share of e_up >= m ends beyond = share of z >= m
price below p0: touch = share of e_dn >= -m ends beyond = share of z <= m
In Python:
import math
def chances(sample, price):
"""Touch and end-beyond chances for one price, from a /v1/touch sample."""
p0, sigma, n, s = sample["p0"], sample["sigma_now"], sample["n"], sample["samples"]
m = math.log(price / p0) / sigma # the move to this price, in units of the window's volatility
if m >= 0: # a price above the window's start
touch = sum(e >= m for e in s["e_up"]) / n
end = sum(z >= m for z in s["z"]) / n
else: # a price below the start
touch = sum(e >= -m for e in s["e_dn"]) / n
end = sum(z <= m for z in s["z"]) / n
return touch, end
Check it against the API
/v1/latest/BTC lists the API's own touch odds at the fixed steps. If you turn each step into a price and run it through chances(), you should get the same numbers:
import requests
API = "https://forecast.veriql.app/v1"
def check_against_api(asset, h):
sample = requests.get(f"{API}/touch/{asset}/{h}", timeout=10).json()
latest = requests.get(f"{API}/latest/{asset}", timeout=10).json()["horizons"][h]
assert abs(latest["start_price"] - sample["p0"]) < 1e-9, "different windows, try again"
worst = 0.0
for row in latest["touch"]:
lv = row["level"]
price = sample["p0"] * (1 + lv if row["side"] == "up" else 1 - lv)
touch, end = chances(sample, price)
worst = max(worst, abs(touch - row["chance"]), abs(end - row["beyond_end"]))
print(f"{asset} {h}: {len(latest['touch'])} levels checked, largest difference {worst}")
We ran it for Bitcoin and Ether on both windows at 01:08 UTC on 28 Nov 2026:
BTC 8h: 12 levels checked, largest difference 0.0
BTC 24h: 12 levels checked, largest difference 0.0
ETH 8h: 12 levels checked, largest difference 0.0
ETH 24h: 12 levels checked, largest difference 0.0
All 48 levels match exactly. The assert matters: the two requests can land on either side of a new forecast, and then you would compare two different windows.
Two mistakes to avoid
1. A window that has ended. Between one window's end and the next forecast, /v1/touch can still serve the last sample. Compare ends_at with the clock before you use it:
import time
if sample["ends_at"] <= time.time():
print("This window has ended and the next one is not out yet.")
2. A price that has already been touched. The chances describe the whole window as seen from its start. If the window has already traded at your price, the answer is "yes, it touched", not a chance. /v1/now gives the lowest and highest price of each open window so far:
now = requests.get(f"{API}/now", timeout=10).json()["assets"]["BTC"]
window = now["windows"]["24h"] # {origin, ends_at, low, high, until}, or None
if window and window["origin"] == sample["t"]:
hit = window["high"] >= price if price >= sample["p0"] else window["low"] <= price
Check that origin equals the sample's t, so that both describe the same window. Call /v1/now at most once a minute.
The whole script
touch_odds.py puts the pieces together. It needs only requests:
"""Touch odds at any price, from the free Veriql Forecast API (no key).
Usage: python touch_odds.py BTC 24h 61000 62500 58000
Forecast, not financial advice. Price data: Bitstamp.
"""
import math
import sys
import time
from datetime import datetime, timezone
import requests
API = "https://forecast.veriql.app/v1"
def utc(ts):
return datetime.fromtimestamp(ts, timezone.utc).strftime("%d %b %H:%M UTC")
def chances(sample, price):
"""Touch and end-beyond chances for one price, from a /v1/touch sample."""
p0, sigma, n, s = sample["p0"], sample["sigma_now"], sample["n"], sample["samples"]
m = math.log(price / p0) / sigma # the move to this price, in units of the window's volatility
if m >= 0: # a price above the window's start
touch = sum(e >= m for e in s["e_up"]) / n
end = sum(z >= m for z in s["z"]) / n
else: # a price below the start
touch = sum(e >= -m for e in s["e_dn"]) / n
end = sum(z <= m for z in s["z"]) / n
return touch, end
def main(asset, h, prices):
sample = requests.get(f"{API}/touch/{asset}/{h}", timeout=10).json()
now = requests.get(f"{API}/now", timeout=10).json()["assets"][asset]
window = now["windows"].get(h)
print(f"{asset} {h} window {utc(sample['t'])} to {utc(sample['ends_at'])}, "
f"start price {sample['p0']:,.2f}, {sample['n']} past cases")
if sample["ends_at"] <= time.time():
print(" This window has ended and the next one is not out yet: "
"the numbers below are that window's, for illustration only.")
if now["price"]:
print(f" Price now {now['price']['value']:,.2f}")
for price in prices:
pct = (price / sample["p0"] - 1) * 100
if window and window["origin"] == sample["t"]:
hit = window["high"] >= price if price >= sample["p0"] else window["low"] <= price
if hit:
print(f" {price:>12,.2f} ({pct:+.2f}%): already touched in this window")
continue
touch, end = chances(sample, price)
print(f" {price:>12,.2f} ({pct:+.2f}%): touch {touch:.0%}, ends beyond {end:.0%}")
print("Price data: Bitstamp. Forecast, not financial advice.")
if __name__ == "__main__":
main(sys.argv[1].upper(), sys.argv[2], [float(p) for p in sys.argv[3:]])
Run it with an asset, a window and any number of prices:
python touch_odds.py BTC 24h 61000 62500 58000 59800
Here is its output for the same 28 Nov window. We ran it at 01:08 UTC, about an hour into the window. Bitcoin had already traded down to 59,775 by then, so for 59,800 the script reports the touch instead of a chance:
BTC 24h window 28 Nov 00:00 UTC to 29 Nov 00:00 UTC, start price 59,872.50, 730 past cases
Price now 59,925.01
61,000.00 (+1.88%): touch 36%, ends beyond 18%
62,500.00 (+4.39%): touch 9%, ends beyond 5%
58,000.00 (-3.13%): touch 20%, ends beyond 8%
59,800.00 (-0.12%): already touched in this window
Price data: Bitstamp. Forecast, not financial advice.
How to read the numbers
- The sample is finite. The 24-hour sample has 730 past cases and the 8-hour sample has 2,190, so one case is worth about 0.14 and 0.05 percentage points. Far from the start price the chances move in coarse steps.
- 0% means none of the past cases went that far. It does not mean the move cannot happen.
-
The record is young. The live record started on 25 Nov 2026.
/v1/scorecardshows how often the ranges held so far, misses included, so check it instead of taking our word for it. - Credit the data. Show "Price data: Bitstamp" and "Forecast, not financial advice." next to any number you display.
For AI agents: exact prices in one paid call
An agent that does not want to fetch the sample can ask for up to 10 exact prices in one call over x402:
GET https://veriql.app/api/v1/forecast-odds?asset=BTC&h=24h&price=61000,62500
Each call costs $0.01 in USDC on Base, Polygon, Arbitrum, Avalanche or Solana, and no account is needed. An unpaid request returns HTTP 402 with the payment details. The answer gives the touch and end-beyond chance for each price, the move from the price now and from the window start, and, when the window has already traded at a price, the time it did.
Links
- API reference: https://forecast.veriql.app/api
- First tutorial (ranges and fixed-step odds): https://dev.to/veriql/a-free-price-forecast-api-with-no-key-bitcoin-ether-gold-and-more-as-ranges-and-touch-odds-26dj
- Live page with every asset, no code: https://huggingface.co/spaces/veriql/crypto-gold-price-forecast
- No-code runs with JSON, CSV or Excel export: https://apify.com/veriql/crypto-gold-price-range-forecast
- Postman collection: https://www.postman.com/veriql/veriql
Disclosure: the Veriql team runs this API. This post was drafted by an AI agent working for the Veriql team, and every example was run against the live API before publishing. Price data: Bitstamp. Forecast, not financial advice.
來源:DEV Community · dev.to