Example bots
Two complete, small moving-average crossover bots, one in Python and one in TypeScript. They show the patterns every trading program needs. They are examples to learn from, not trading advice.
Downloads
requirements.txt below.
TypeScriptma-cross-bot.tsNode.js 20+, fetch and ws. With package.json below.
Also: requirements.txt · package.json · openapi.yaml (to generate a client in your own language)
What they do
- Read
/meand refuse to run unless the key is for a demo account, then read the instrument (GET /symbols/{symbol}). - Every 15 seconds, read five-minute candles and compare a fast and a slow moving average of the closed bars.
- When the signal flips, read the instrument again: while its market is closed (
trading_hours), wait until it opens. - Close the bot's opposite positions and open one in the new direction, tagged with the bot's
client_tag, with a stop loss and a take profit (20 and 40 pips from the entry unless you choose others), never nearer the closing price than twice the spread or the instrument'sstops_leveland 10 points. - Print order events from the stream as they happen.
Run them
pip install -r requirements.txt
export JAFX_API_KEY='jafx_demo_…'
python ma_cross_bot.py --symbol EURUSD --timeframe M5 --volume 0.01 --sl-pips 20 --tp-pips 40npm install
export JAFX_API_KEY='jafx_demo_…'
npx tsx ma-cross-bot.ts EURUSD M5 0.01 --sl-pips 20 --tp-pips 40A pip is 10 points on 5- and 3-digit prices (EURUSD 0.0001, USDJPY 0.01) and 1 point elsewhere, so give an instrument such as gold or bitcoin a distance in its own terms (bitcoin's 2 digits make 30000 pips $300). Where a distance would fall inside a wide spread, as on crypto, the bots widen it to twice the spread. Mind the size too: a lot is contract_size units, so 0.01 lot of BTCUSD is 0.1 bitcoin (Numbers).
Patterns worth copying
- Every order carries its stop loss and take profit. They are set from the price the bot just read, beyond
stops_leveland the spread with a margin, so a position is never left unprotected. - One idempotency key per intended action. The key is generated when the bot decides to trade, and every retry of that call reuses it. A dropped connection can never open a second position.
- Retry only what is safe to retry, as the error table says. A network error,
429,503and409 request_in_progresswait for theRetry-Afterheader and try again with the same key.409 order_busywaits too, then tries with a new key: the broker refused that request, and its key keeps the refusal. Other errors are reported, not retried. - Wait out a closed market.
422 market_closedwaits untildetails.opens_at; the order then goes with a new key. - Follow, never resend. A
202answer (pendingoroutcome_unknown) is followed by polling the request until it is decided. - Respect the platform's brakes.
trading_haltedpauses the bot;daily_loss_limit_reachedstops it for the day. - Streams reconnect with backoff and stop on
4401(bad key) and4409(another copy running). - Tags keep strategies apart. The bot only ever touches positions carrying its own
client_tag, so you can run it next to manual trading.
Python
"""
Moving-average crossover bot for the JAFX Trading API (demo accounts).
pip install -r requirements.txt
export JAFX_API_KEY=jafx_demo_... # from the web terminal: Developers -> Create API key
python ma_cross_bot.py --symbol EURUSD --timeframe M5 --volume 0.01 --sl-pips 20 --tp-pips 40
What it shows: authentication, reading /me limits, the instrument's trading hours and
minimum stop distance, M5 candles, orders that always carry a stop loss and a take
profit, retries by the API's error rules (the same Idempotency-Key, except after
order_busy), handling 202 pending / outcome_unknown, waiting out a closed market,
stopping on trading_halted, and the orders stream. It is an example, not trading advice.
"""
import argparse
import asyncio
import json
import os
import sys
import uuid
from datetime import datetime, timezone
import httpx
import websockets
BASE = os.environ.get("JAFX_API_BASE", "https://terminal.jafx.com/trading-api/v1")
KEY = os.environ.get("JAFX_API_KEY", "")
TAG = "ma-cross"
class ApiError(Exception):
def __init__(self, status, problem):
super().__init__(f"{status} {problem.get('code')}: {problem.get('detail') or problem.get('title')}")
self.status = status
self.code = problem.get("code")
self.details = problem.get("details") or {}
def retry_after(response, default=1.0):
"""Seconds to wait: the Retry-After header, the only place the API says it."""
try:
return max(float(response.headers.get("Retry-After", default)), 0.0)
except ValueError:
return default
async def call(client, method, path, body=None, idempotency_key=None):
"""One API call, retried only where the API's error rules say a retry is safe.
A network error, 429, 503 and 409 request_in_progress are retried with the SAME
Idempotency-Key, so a write that got through is answered again, never placed twice.
409 order_busy is retried with a NEW key: the broker refused the request while the
position or order was being processed, and the old key keeps that refusal.
"""
for attempt in range(5):
headers = {"Authorization": f"Bearer {KEY}"}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
try:
r = await client.request(method, f"{BASE}{path}", json=body, headers=headers, timeout=20)
except httpx.TransportError:
await asyncio.sleep(1 + attempt)
continue
try:
data = r.json() if r.content else None
except ValueError:
data = None
code = (data or {}).get("code") if r.status_code >= 400 else None
if r.status_code in (429, 503) or code == "request_in_progress":
await asyncio.sleep(retry_after(r))
continue
if code == "order_busy" and idempotency_key:
await asyncio.sleep(retry_after(r))
idempotency_key = str(uuid.uuid4())
continue
if r.status_code >= 400:
raise ApiError(r.status_code, data or {})
return r.status_code, data
raise RuntimeError(f"{method} {path} kept failing")
def sma(values, n):
return sum(values[-n:]) / n if len(values) >= n else None
def seconds_until(iso):
"""Seconds from now until an ISO-8601 time; 0 if it has passed."""
when = datetime.fromisoformat(iso.replace("Z", "+00:00"))
return max((when - datetime.now(timezone.utc)).total_seconds(), 0.0)
def pip_size(symbol):
"""A pip: 10 points on 5- and 3-digit prices (EURUSD 0.0001, USDJPY 0.01), else 1 point."""
point = 10 ** -symbol["digits"]
return point * 10 if symbol["digits"] in (3, 5) else point
def protective_levels(side, quote, symbol, sl_pips, tp_pips):
"""Stop loss and take profit for a market order, sl_pips and tp_pips from the entry.
The broker measures stops from the price the position would close at (the bid for a
buy, the ask for a sell) and refuses one nearer than stops_level points (0: no
minimum). Each level stays beyond that price by at least stops_level + 10 points and
twice the spread, so a pip distance that would fall inside a wide spread (crypto,
indices) is widened, and the price can move a little before the order arrives.
"""
point = 10 ** -symbol["digits"]
floor = max((symbol.get("stops_level", 0) + 10) * point, 2 * (quote["ask"] - quote["bid"]))
if side == "buy":
entry, close_at = quote["ask"], quote["bid"]
sl = min(entry - sl_pips * pip_size(symbol), close_at - floor)
tp = max(entry + tp_pips * pip_size(symbol), close_at + floor)
else:
entry, close_at = quote["bid"], quote["ask"]
sl = max(entry + sl_pips * pip_size(symbol), close_at + floor)
tp = min(entry - tp_pips * pip_size(symbol), close_at - floor)
return round(sl, symbol["digits"]), round(tp, symbol["digits"])
async def wait_while_closed(symbol, hours):
"""True after waiting out a closed market (trading_hours from /symbols); False if it is open."""
if not hours or hours["open_now"]:
return False
opens = hours["next_open"]
print(f"{symbol} is closed; it opens at {opens or 'an unknown time'}. Waiting.")
# Look again at least hourly: a schedule can change.
await asyncio.sleep(min(seconds_until(opens) + 1, 3600) if opens else 3600)
return True
async def follow_request(client, account, result):
"""A 202 means the broker is still deciding (or the answer was lost): poll, never resend."""
while result.get("status") in ("pending", "outcome_unknown"):
await asyncio.sleep(1)
_, result = await call(client, "GET", f"/accounts/{account}/requests/{result['request_id']}")
return result
async def stream_orders(key):
url = BASE.replace("https://", "wss://").replace("http://", "ws://") + "/stream"
delay = 1
while True:
try:
async with websockets.connect(url, additional_headers={"Authorization": f"Bearer {key}"}) as ws:
delay = 1
await ws.send(json.dumps({"op": "subscribe", "channels": ["orders"]}))
async for raw in ws:
frame = json.loads(raw)
if frame.get("ch") == "orders":
print(f"[stream] {frame['event']}: {frame['data']}")
except websockets.ConnectionClosed as e:
code = e.rcvd.code if e.rcvd else None
if code in (4401, 4409):
print(f"[stream] closed with {code}; not reconnecting")
return
except OSError as e:
print(f"[stream] {e}")
await asyncio.sleep(delay)
delay = min(delay * 2, 30)
async def main():
p = argparse.ArgumentParser(description="Moving-average crossover bot for JAFX demo accounts. An example, not trading advice.")
p.add_argument("--symbol", default="EURUSD")
p.add_argument("--timeframe", default="M5")
p.add_argument("--volume", default="0.01")
p.add_argument("--fast", type=int, default=10)
p.add_argument("--slow", type=int, default=30)
p.add_argument("--sl-pips", type=float, default=20, help="stop loss, in pips from the entry (default 20)")
p.add_argument("--tp-pips", type=float, default=40, help="take profit, in pips from the entry (default 40)")
args = p.parse_args()
if not KEY:
sys.exit("Set JAFX_API_KEY")
async with httpx.AsyncClient() as client:
_, me = await call(client, "GET", "/me")
account = me["account"]
print(f"key {me['name']} on account {account} ({me['mode']}); limits: {me['constraints']}")
if me["mode"] != "demo":
sys.exit("This example only runs on demo accounts")
# The instrument as JAFX spells it (USOil, not USOIL), with its digits and stops_level.
_, instrument = await call(client, "GET", f"/symbols/{args.symbol}")
symbol = instrument["symbol"]
asyncio.create_task(stream_orders(KEY))
last_signal = None
while True:
try:
_, candles = await call(client, "GET", f"/candles/{symbol}?timeframe={args.timeframe}&limit={args.slow + 5}")
closes = [c["close"] for c in candles["data"] if c["complete"]]
fast, slow = sma(closes, args.fast), sma(closes, args.slow)
if fast is None or slow is None:
await asyncio.sleep(10)
continue
signal = "buy" if fast > slow else "sell"
if signal != last_signal:
# Its trading hours and minimum stop distance now, on this account's server.
_, instrument = await call(client, "GET", f"/symbols/{symbol}")
if await wait_while_closed(symbol, instrument.get("trading_hours")):
continue
_, positions = await call(client, "GET", f"/accounts/{account}/positions?client_tag={TAG}")
for pos in positions["data"]:
if pos["side"] != signal:
# One idempotency key per intended action.
_, r = await call(client, "POST", f"/accounts/{account}/positions/{pos['ticket']}/close", {}, str(uuid.uuid4()))
print("closed", pos["ticket"], (await follow_request(client, account, r))["status"])
if not any(pos["side"] == signal for pos in positions["data"]):
_, quotes = await call(client, "GET", f"/quotes?symbols={symbol}")
if not quotes["data"]:
print(f"No price for {symbol} yet")
await asyncio.sleep(15)
continue
sl, tp = protective_levels(signal, quotes["data"][0], instrument, args.sl_pips, args.tp_pips)
order = {"symbol": symbol, "side": signal, "type": "market", "volume": args.volume,
"stop_loss": sl, "take_profit": tp, "client_tag": TAG}
_, r = await call(client, "POST", f"/accounts/{account}/orders", order, str(uuid.uuid4()))
r = await follow_request(client, account, r)
print(f"{signal} {args.volume} {symbol} SL {sl} TP {tp}: {r['status']} ticket={r.get('ticket')}")
last_signal = signal
except ApiError as e:
if e.code == "market_closed":
# Outside its trading hours: nothing was traded. The next order goes with a new key.
opens = e.details.get("opens_at")
print(f"{e}; waiting until {opens or 'it opens'}")
await asyncio.sleep(min(seconds_until(opens) + 1, 3600) if opens else 600)
continue
if e.code == "trading_halted":
print("Trading halted by JAFX; waiting a minute")
await asyncio.sleep(60)
elif e.code == "daily_loss_limit_reached":
print("Daily loss limit reached; stopping for today")
return
else:
print("API error:", e)
await asyncio.sleep(15)
if __name__ == "__main__":
asyncio.run(main())TypeScript
/**
* Moving-average crossover bot for the JAFX Trading API (demo accounts).
*
* npm install
* JAFX_API_KEY=jafx_demo_… npx tsx ma-cross-bot.ts EURUSD M5 0.01 --sl-pips 20 --tp-pips 40
*
* Shows: authentication, /me limits, the instrument's trading hours and minimum stop
* distance, M5 candles, orders that always carry a stop loss and a take profit, retries
* by the API's error rules (the same Idempotency-Key, except after order_busy), 202
* handling, waiting out a closed market, trading_halted, and the orders stream.
* An example, not trading advice.
*/
import { randomUUID } from 'node:crypto'
import { parseArgs } from 'node:util'
import WebSocket from 'ws'
const BASE = process.env.JAFX_API_BASE ?? 'https://terminal.jafx.com/trading-api/v1'
const KEY = process.env.JAFX_API_KEY ?? ''
const TAG = 'ma-cross-ts'
const { values: opts, positionals } = parseArgs({
allowPositionals: true,
options: { 'sl-pips': { type: 'string', default: '20' }, 'tp-pips': { type: 'string', default: '40' } },
})
const [asked = 'EURUSD', timeframe = 'M5', volume = '0.01'] = positionals
const slPips = Number(opts['sl-pips'])
const tpPips = Number(opts['tp-pips'])
class ApiError extends Error {
constructor(readonly status: number, readonly code: string, detail: string, readonly details: any = {}) {
super(`${status} ${code}: ${detail}`)
}
}
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms))
/** Seconds to wait: the Retry-After header, the only place the API says it. */
const retryAfter = (res: Response) => Math.max(Number(res.headers.get('retry-after') ?? '1') || 1, 0)
/**
* One API call, retried only where the API's error rules say a retry is safe. A network
* error, 429, 503 and 409 request_in_progress are retried with the SAME Idempotency-Key,
* so a write that got through is answered again, never placed twice. 409 order_busy is
* retried with a NEW key: the broker refused the request while the position or order was
* being processed, and the old key keeps that refusal.
*/
async function call<T = any>(method: string, path: string, body?: unknown, idempotencyKey?: string): Promise<{ status: number; data: T }> {
for (let attempt = 0; attempt < 5; attempt++) {
const headers: Record<string, string> = { Authorization: `Bearer ${KEY}` }
if (body !== undefined) headers['Content-Type'] = 'application/json'
if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey
let res: Response
try {
res = await fetch(`${BASE}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) })
} catch {
await sleep(1000 * (attempt + 1))
continue
}
const data = res.status === 204 ? null : await res.json().catch(() => null)
const code: string | undefined = res.ok ? undefined : data?.code
if (res.status === 429 || res.status === 503 || code === 'request_in_progress') {
await sleep(retryAfter(res) * 1000)
continue
}
if (code === 'order_busy' && idempotencyKey) {
await sleep(retryAfter(res) * 1000)
idempotencyKey = randomUUID()
continue
}
if (!res.ok) throw new ApiError(res.status, code ?? 'unknown', data?.detail ?? data?.title ?? '', data?.details ?? {})
return { status: res.status, data }
}
throw new Error(`${method} ${path} kept failing`)
}
/** 202 = still deciding (or answer lost): poll the request, never resend under a new key. */
async function follow(account: number, result: any): Promise<any> {
while (result.status === 'pending' || result.status === 'outcome_unknown') {
await sleep(1000)
result = (await call(`GET`, `/accounts/${account}/requests/${result.request_id}`)).data
}
return result
}
function sma(values: number[], n: number): number | null {
return values.length >= n ? values.slice(-n).reduce((a, b) => a + b, 0) / n : null
}
const msUntil = (iso: string) => Math.max(Date.parse(iso) - Date.now(), 0)
/** A pip: 10 points on 5- and 3-digit prices (EURUSD 0.0001, USDJPY 0.01), else 1 point. */
const pipSize = (s: { digits: number }) => (s.digits === 3 || s.digits === 5 ? 10 : 1) * 10 ** -s.digits
/**
* Stop loss and take profit for a market order, slPips and tpPips from the entry. The
* broker measures stops from the price the position would close at (the bid for a buy,
* the ask for a sell) and refuses one nearer than stops_level points (0: no minimum).
* Each level stays beyond that price by at least stops_level + 10 points and twice the
* spread, so a pip distance that would fall inside a wide spread (crypto, indices) is
* widened, and the price can move a little before the order arrives.
*/
function protectiveLevels(side: 'buy' | 'sell', q: { bid: number; ask: number }, s: { digits: number; stops_level?: number }) {
const floor = Math.max(((s.stops_level ?? 0) + 10) * 10 ** -s.digits, 2 * (q.ask - q.bid))
const round = (x: number) => Number(x.toFixed(s.digits))
if (side === 'buy') {
return { stop_loss: round(Math.min(q.ask - slPips * pipSize(s), q.bid - floor)), take_profit: round(Math.max(q.ask + tpPips * pipSize(s), q.bid + floor)) }
}
return { stop_loss: round(Math.max(q.bid + slPips * pipSize(s), q.ask + floor)), take_profit: round(Math.min(q.bid - tpPips * pipSize(s), q.ask - floor)) }
}
/** True after waiting out a closed market (trading_hours from /symbols); false if it is open. */
async function waitWhileClosed(symbol: string, hours: any): Promise<boolean> {
if (!hours || hours.open_now) return false
console.log(`${symbol} is closed; it opens at ${hours.next_open ?? 'an unknown time'}. Waiting.`)
// Look again at least hourly: a schedule can change.
await sleep(hours.next_open ? Math.min(msUntil(hours.next_open) + 1000, 3_600_000) : 3_600_000)
return true
}
function streamOrders(delayMs = 1000): void {
const ws = new WebSocket(`${BASE.replace(/^http/, 'ws')}/stream`, { headers: { Authorization: `Bearer ${KEY}` } })
ws.on('open', () => {
delayMs = 1000
ws.send(JSON.stringify({ op: 'subscribe', channels: ['orders'] }))
})
ws.on('message', raw => {
const f = JSON.parse(raw.toString())
if (f.ch === 'orders') console.log(`[stream] ${f.event}`, f.data)
})
ws.on('error', e => console.error('[stream] error:', e.message))
ws.on('close', code => {
if (code === 4401 || code === 4409) return console.error(`[stream] closed with ${code}; not reconnecting`)
setTimeout(() => streamOrders(Math.min(delayMs * 2, 30_000)), delayMs)
})
}
async function main(): Promise<void> {
if (!KEY) throw new Error('Set JAFX_API_KEY')
const me = (await call('GET', '/me')).data
if (me.mode !== 'demo') throw new Error('This example only runs on demo accounts')
const account: number = me.account
console.log(`key ${me.name} on account ${account}; limits`, me.constraints)
// The instrument as JAFX spells it (USOil, not USOIL), with its digits and stops_level.
const symbol: string = (await call('GET', `/symbols/${asked}`)).data.symbol
streamOrders()
let last: 'buy' | 'sell' | null = null
for (;;) {
try {
const candles = (await call('GET', `/candles/${symbol}?timeframe=${timeframe}&limit=40`)).data
const closes: number[] = candles.data.filter((c: any) => c.complete).map((c: any) => c.close)
const fast = sma(closes, 10)
const slow = sma(closes, 30)
if (fast !== null && slow !== null) {
const signal = fast > slow ? 'buy' : 'sell'
if (signal !== last) {
// Its trading hours and minimum stop distance now, on this account's server.
const instrument = (await call('GET', `/symbols/${symbol}`)).data
if (await waitWhileClosed(symbol, instrument.trading_hours)) continue
const positions = (await call('GET', `/accounts/${account}/positions?client_tag=${TAG}`)).data.data
for (const p of positions.filter((p: any) => p.side !== signal)) {
const r = await follow(account, (await call('POST', `/accounts/${account}/positions/${p.ticket}/close`, {}, randomUUID())).data)
console.log('closed', p.ticket, r.status)
}
if (!positions.some((p: any) => p.side === signal)) {
const quote = (await call('GET', `/quotes?symbols=${symbol}`)).data.data[0]
if (!quote) {
console.log(`No price for ${symbol} yet`)
await sleep(15_000)
continue
}
const stops = protectiveLevels(signal, quote, instrument)
const order = { symbol, side: signal, type: 'market', volume, ...stops, client_tag: TAG }
const r = await follow(account, (await call('POST', `/accounts/${account}/orders`, order, randomUUID())).data)
console.log(`${signal} ${volume} ${symbol} SL ${stops.stop_loss} TP ${stops.take_profit}: ${r.status} ticket=${r.ticket}`)
}
last = signal
}
}
} catch (e) {
if (e instanceof ApiError && e.code === 'market_closed') {
// Outside its trading hours: nothing was traded. The next order goes with a new key.
const opens: string | undefined = e.details?.opens_at
console.log(`${e.message}; waiting until ${opens ?? 'it opens'}`)
await sleep(opens ? Math.min(msUntil(opens) + 1000, 3_600_000) : 600_000)
continue
}
if (e instanceof ApiError && e.code === 'trading_halted') { console.log('Trading halted by JAFX; waiting'); await sleep(60_000) }
else if (e instanceof ApiError && e.code === 'daily_loss_limit_reached') { console.log('Daily loss limit reached; stopping'); return }
else console.error(e)
}
await sleep(15_000)
}
}
main().catch(e => { console.error(e); process.exit(1) })