我如何打造 Algocdk:供 Deriv 交易者使用的算法交易平台
How I Built Algocdk: An Algorithmic Trading Platform for Deriv Traders
作者打造 Algocdk,為 Deriv 交易者整合即時市場數據、分析、交易及 24/7 自動交易機械人。平台支援以 JavaScript 或 Python 編寫機械人、自訂 JavaScript 指標,並提供隔離容器和以真實數據進行的 walk-forward 回測。平台可透過瀏覽器使用,亦可安裝為流動網頁應用程式。
Most retail traders I know do the same thing every day: stare at a chart, wait for a setup, click buy, click sell, repeat. It works until you are tired, distracted, or asleep, and the markets never are.
So I built Algocdk, an algorithmic trading platform for Deriv traders. It lets you analyze markets, build indicators, run bots 24/7 and trade, all from one place, with no installs.
You can try it here: algocdk.site
In this post I'll walk through why I built it, what it does, and how you can build your own custom indicator with it.
Why I built it
Deriv offers a great API and a huge range of markets: Forex, crypto, commodities, indices and its own synthetic indices that run around the clock. But the tooling around it was split across many places. Charts lived in one tab, analysis in a spreadsheet, bots in another tool, and nothing talked to anything else.
I wanted a single developer-friendly terminal where I could:
- see live Deriv market data
- analyze it with real tools
- write my own indicators in JavaScript
- turn an idea into a running bot without babysitting it
That became Algocdk.
The architecture in a nutshell
At a high level, the platform has three layers:
- Market data layer. A live connection to Deriv APIs streams ticks and candles into the app in real time.
- Analysis and charting layer. Interactive charts, indicators and analysis tools sit on top of that stream.
- Automation layer. Bots run inside isolated containers so each strategy executes on its own, continuously watching the market.
The isolation part was a deliberate decision. Every bot runs in its own container, so a bug or a bad strategy in one bot can't take down the others or the rest of your account setup.
Features
Here is everything Algocdk does today.
1. Live markets and charting
- Real-time quotes across Forex, Crypto, Synthetic Indices, Commodities and Global Indices
- A full candlestick chart with candle, line and area views
- Timeframe switching and an indicators menu, plus a compare mode
- A market overview with crypto, forex, indices and commodities (Bitcoin, Ethereum, EUR/USD, S&P 500, Gold, Crude Oil and more)
- Synthetic Indices such as Volatility 10, 25, 50, 75 and 100, and Boom/Crash, streaming a tick every second, 24/7
2. A trading platform for Deriv contract types
You can trade directly from the platform across the main Deriv contract types:
- Rise / Fall
- Higher / Lower (barriers)
- Multipliers
- Accumulators
- Digital Options
- Digits trading
3. Market analysis tools
This is the part I'm most excited about, because it turns gut feeling into data:
- Rise/Fall market analysis
- Higher/Lower market analysis
- Digit Analysis for studying last-digit distributions
- Digit Lab for experimenting with digit strategies
- Digit Hit Map for visualizing which digits are hitting
- Market News and an Economic Calendar so you know when volatility is coming
4. Automated trading bots
Algocdk ships with strategy types that cover the common approaches:
| Strategy | What it does |
|---|---|
| Momentum | Trend-following with real-time signal validation |
| Breakout | Catches volatility expansions with adaptive risk management |
| Mean Reversion | Exploits deviations from historical averages |
| Grid | Places buy and sell orders at set intervals in range-bound markets |
| Scalping | Targets quick, small moves |
| Build Your Own | Visual bot builder, or code your own in JavaScript or Python |
On the bot side you also get:
- A Bot Marketplace (Bot Store) to browse and deploy ready-made bots
- DBot support
- An AI Over/Under Bot
- Copy Trading
- Isolated bot containers, one per bot, running continuously
- Walk-forward backtesting, so you can validate a strategy on real data before risking real money
5. Built for developers
I built this as a developer first, so there is a lot of room to extend it:
- Custom JavaScript indicators, with an Indicator Template to start from
- A Developer Guide documenting how to build on the platform
- A Terminal CLI for people who live in the command line
- A Trading Tools section
- Programmable access built on Deriv APIs
6. AI assistance
- An AI Assistant to help you reason about markets and strategies
- A Kiro Bot Assistant to help you build bots
7. Community
- A community hub for sharing trade ideas and technical analysis on forex, crypto, futures and more
- Explore Sites, where users can browse public sites
- A support center and a feedback page, because I read all of it
8. Getting started takes about three steps
- Create an account. Start on a zero-risk demo account and explore everything.
- Connect your Deriv API token. Set your own risk limits.
- Deploy a bot. Pick a strategy or build your own, and let it run.
It works in the browser and is set up as an installable mobile web app, so it feels at home on a phone too.
Build your own indicator (using NEXUS AI as the example)
An Algocdk indicator is one JavaScript object that computes values from candles and then draws them on the chart. To show how it works, I'll use NEXUS AI, an indicator I wrote that detects chart patterns, candlestick patterns, support and resistance zones, smart money concepts and overall market behavior. It's about 1,000 lines, but the structure is small enough to learn in a few minutes.
The example follows the
calculate → drawindicator API. Check the Developer Guide and the Indicator Template for the exact loader details.
The shape of an indicator
The whole file is a single object literal wrapped in parentheses, so it evaluates to an object you can paste into the indicator loader:
({
name: "NEXUS AI — Pattern & Behavior Engine",
window: 1, // 1 = draw on top of the main chart
color: "#00f5d4",
defaultParams: { sensitivity: 2, rsiPeriod: 14, lookback: 60 /* ... */ },
calculate: function (data, params) { /* runs on ALL candles */ },
draw: function (ctx, values, pad, spacing, yFunc, params, visibleStartIdx) { /* paints */ },
})
| Field | What it does | In NEXUS AI |
|---|---|---|
name |
Label shown in the indicator list | "NEXUS AI — Pattern & Behavior Engine" |
window |
Where it renders; 1 overlays the main chart |
1 |
color |
Default accent color | #00f5d4 |
defaultParams |
User-editable settings and their defaults | sensitivity, RSI/ATR periods, show/hide toggles for each layer |
calculate(data, params) |
Receives every candle and does the math; returns one value per candle | Runs all detectors, caches results, returns EMA 20 |
draw(ctx, values, pad, spacing, yFunc, params, visibleStartIdx) |
Paints onto a canvas for the visible candles | Draws EMAs, zones, patterns, labels and the info panel |
How the two functions work together
-
calculatereceivesdata, an array of candles, each withopen,high,lowandclose. - It computes everything once and returns an array the same length as
data, usingnullwhere a value doesn't exist yet (for example, during an EMA's warm-up). NEXUS returnsdata.map(() => null)if there are fewer than 30 candles. - It stores richer results on the object itself (
this._computed) sodrawcan read them. -
drawreceives a canvas 2Dctxand a few helpers:pad(left padding in pixels),spacing(pixels per candle),yFunc(converts a price to a y coordinate) andvisibleStartIdx(which candle the screen starts at). - It converts candle indexes to x positions, then draws with normal canvas calls like
moveTo,lineTo,fillRectandfillText.
Your first indicator: an EMA cross
Here is a small indicator that uses the same structure as NEXUS AI. It draws a fast and a slow EMA and marks the candles where they cross. Paste it into the indicator loader to try it.
({
name: "EMA Cross",
window: 1,
color: "#00f5d4",
defaultParams: { fast: 9, slow: 21 },
calculate: function (data, params) {
if (!data || data.length < params.slow) return data.map(() => null);
// Same EMA idea NEXUS uses in _indicators.ema
const ema = (period) => {
const k = 2 / (period + 1);
let prev = data[0].close;
return data.map((c, i) => {
prev = i === 0 ? c.close : c.close * k + prev * (1 - k);
return prev;
});
};
const fast = ema(params.fast);
const slow = ema(params.slow);
// Find crossovers once, here, not on every redraw
const crosses = [];
for (let i = 1; i < data.length; i++) {
if (fast[i - 1] <= slow[i - 1] && fast[i] > slow[i]) crosses.push({ idx: i, bias: "bullish" });
if (fast[i - 1] >= slow[i - 1] && fast[i] < slow[i]) crosses.push({ idx: i, bias: "bearish" });
}
this._computed = { fast, slow, crosses, data }; // cache for draw()
return fast; // one value per candle
},
draw: function (ctx, values, pad, spacing, yFunc, params, visibleStartIdx) {
if (!this._computed) return;
const { fast, slow, crosses, data } = this._computed;
const start = visibleStartIdx || 0;
const end = start + values.length;
const x = (i) => pad + (i - start) * spacing + spacing / 2; // candle index -> pixels
const line = (arr, color) => {
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.beginPath();
let started = false;
for (let i = start; i < end; i++) {
if (arr[i] == null) continue;
if (!started) { ctx.moveTo(x(i), yFunc(arr[i])); started = true; }
else ctx.lineTo(x(i), yFunc(arr[i]));
}
ctx.stroke();
};
ctx.save();
line(fast, "#00f5d4");
line(slow, "#ffa500");
crosses.forEach((c) => {
if (c.idx < start || c.idx >= end) return; // skip off-screen signals
const bull = c.bias === "bullish";
ctx.fillStyle = bull ? "#00e676" : "#ff5252";
ctx.font = "12px sans-serif";
const y = bull ? yFunc(data[c.idx].low) + 14 : yFunc(data[c.idx].high) - 6;
ctx.fillText(bull ? "▲" : "▼", x(c.idx) - 5, y);
});
ctx.restore();
},
})
The parts map straight onto NEXUS AI:
-
defaultParamsholds the fast and slow periods, likersiPeriodandatrPeriodin NEXUS. -
calculatedoes all the math and stores it inthis._computed. -
drawonly paints, using astartoffset so signals line up with the visible candles. - Crossovers are plain objects (
idx,bias), the same way NEXUS stores{ idx, type, bias, strength }for each candlestick pattern.
Change the periods, swap EMA for another average, or add a volume filter, and you already have your own indicator.
What NEXUS AI teaches: patterns worth copying
Once the basics click, NEXUS AI shows how to scale an indicator without turning it into a mess.
-
Split the work into small detectors. Each concern lives in its own sub-object (
_candlePatterns,_chartPatterns,_srZones,_smc,_behavior) with adetect()oranalyze()method.calculatejust calls them in turn. -
Keep helpers on the object.
_utils(averages, pivots, slope, similarity checks) and_indicators(RSI, EMA, ATR, MACD, ADX) are reused by every detector. The underscore marks them as internal. -
Detectors return plain data, not drawings. A detector produces objects like
{ idx, type: "Bullish Engulfing", bias: "bullish", strength: 3 }. Onlydrawdecides how they look. -
Compute in
calculate, render indraw.drawcan run every time the user pans or zooms, so the heavy work happens once and is cached inthis._computed. -
Convert global indexes to screen positions. NEXUS uses
ix(globalIdx) = pad + (globalIdx - startIdx) * spacing + spacing / 2and anisVisible()check, so it only draws what's on screen. -
Give every layer a toggle. Params like
showSRZones,showSMCandshowCandlePatternsare tested withparams.x !== false, so each layer can be switched off without breaking the rest. -
Draw in layers and wrap it in
ctx.save()/ctx.restore(). NEXUS paints EMAs first, then zones, smart money concepts, chart patterns, candle patterns and finally the info panel, so important labels end up on top.
Here is a trimmed detector from the file to show the style. It flags a bullish engulfing candle:
if (
u.isBearish(p) && u.isBullish(c) &&
c.open < p.close && c.close > p.open &&
u.bodySize(c) > u.bodySize(p)
) {
patterns.push({ idx: i, type: "Bullish Engulfing", bias: "bullish", strength: 3 });
}
Every pattern in NEXUS follows that same recipe: a condition on the last few candles, then a record with an index, a name, a bias and a strength.
What NEXUS AI detects, and where to extend it
- Candlestick patterns: Doji, Hammer, Shooting Star, Pin Bars, Engulfing, Morning/Evening Star, Harami, Three White Soldiers and Three Black Crows
- Chart patterns: Head & Shoulders (and inverse), Double Top/Bottom, triangles, Cup & Handle, rising and falling wedges
- Structure: Support and resistance zones ranked by how often price touched them, plus order blocks and fair value gaps
- Market behavior panel: trend (slope + ADX), momentum (RSI + MACD), volatility (ATR), a Wyckoff-style market phase and an overall bias score
Good first extensions: add a new candlestick pattern to _candlePatterns.detect, add a Bollinger Band layer to _indicators, or add a new show... toggle in defaultParams.
Tips before you publish
-
Return an array as long as
data. Usenullfor candles that don't have a value yet. - Guard against short history. Return early if there are too few candles for your longest period.
-
Treat patterns as signals, not guarantees. The rules in NEXUS are simple heuristics, so tune
sensitivityand validate any idea with backtesting before trading it live. - Start on a demo account and watch how your indicator behaves on live ticks before you rely on it.
Challenges along the way
A few themes any platform like this has to deal with:
- Real-time data is unforgiving. Dropped connections, duplicate ticks and out-of-order messages all need handling.
- Backtests can lie. That's why I added walk-forward testing instead of trusting a single in-sample result.
- Risk controls can't be an afterthought. Limits and isolation belong in the core design, not bolted on.
What's next
- More strategies in the bot store
- Deeper backtesting tools
- A richer community and indicator-sharing layer
- Better docs and examples in the developer guide
If you have ideas, tell me in the comments.
Try it
- Platform: algocdk.site
- Developer Guide: algocdk.site/dev-guide
- Indicator Template: algocdk.site/indicator-template
- Bot Store: algocdk.site/botstore
- Live charts: algocdk.site/marketchart
I'd love feedback from fellow developers and traders. What would you want an algo trading platform to do that none of them do today?
Disclaimer: Trading derivatives and synthetic indices carries a high level of risk and you can lose your capital. Past performance does not guarantee future results. Nothing in this post is financial advice. Start on a demo account and only trade what you can afford to lose.
來源:DEV Community · dev.to