Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions apps/daemon/src/sources/crypto-dca.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import type { SourceWorker, UserContext } from '../types.js';
import {
KrakenFeed, CoinbaseFeed, BinanceUsFeed, GeminiFeed,
placeOrder as placeKrakenOrder,
getKrakenPairDecimals,
formatKrakenPrice,
placeBinanceOrder,
placeCoinbaseOrder,
placeGeminiOrder,
Expand Down Expand Up @@ -111,12 +113,13 @@ async function executeDcaBuy(buy: DcaBuy): Promise<{ ok: true; orderId: string;
try {
if (buy.exchange === 'kraken') {
const krakenPair = pair.replace('-', '').replace('BTC', 'XBT');
const decimals = await getKrakenPairDecimals(krakenPair).catch(() => null);
const result = await placeKrakenOrder({
pair: krakenPair,
type: 'buy',
ordertype: 'limit',
volume: quantity.toFixed(8),
price: limitPrice.toFixed(2),
volume: quantity.toFixed(decimals?.volume ?? 8),
price: formatKrakenPrice(limitPrice, decimals?.price),
timeinforce: 'IOC',
});
return { ok: true, orderId: result.txid?.[0] ?? result.descr?.order ?? 'unknown', filled: quantity };
Expand Down
14 changes: 14 additions & 0 deletions packages/source-crypto-arb/src/feeds/kraken-price.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest';
import { formatKrakenPrice } from './kraken-private.js';

describe('formatKrakenPrice', () => {
it('rounds to the pair price precision (BTC/USD takes 1 decimal)', () => {
expect(formatKrakenPrice(77289.4567, 1)).toBe('77289.5');
expect(formatKrakenPrice(2236.887, 2)).toBe('2236.89');
expect(formatKrakenPrice(0.123456, 5)).toBe('0.12346');
});
it('falls back to 2 decimals when precision is unknown', () => {
expect(formatKrakenPrice(91.237, null)).toBe('91.24');
expect(formatKrakenPrice(91.237, undefined)).toBe('91.24');
});
});
30 changes: 28 additions & 2 deletions packages/source-crypto-arb/src/feeds/kraken-private.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const MAX_POSITION_USD = 100;
export const KRAKEN_TAKER_FEE = 0.0026;
let assetPairsFetchedAt = 0;
let tradablePairs = new Set<string>();
let assetPairMeta = new Map<string, { altname?: string; status?: string; ordermin?: string }>();
let assetPairMeta = new Map<string, { altname?: string; status?: string; ordermin?: string; pair_decimals?: number; lot_decimals?: number }>();
let privateBlockedUntil = 0;
let privateLockoutBackoffMs = KRAKEN_LOCKOUT_BASE_MS;

Expand Down Expand Up @@ -106,7 +106,7 @@ async function syncAssetPairs(force = false): Promise<void> {
if (!force && Date.now() - assetPairsFetchedAt < ASSET_PAIR_CACHE_TTL_MS && tradablePairs.size > 0) return;
const res = await fetch(`${BASE}/0/public/AssetPairs`, { signal: AbortSignal.timeout(15_000) });
if (!res.ok) throw new Error(`Kraken /0/public/AssetPairs: ${res.status} ${res.statusText}`);
const data = (await res.json()) as { error: string[]; result: Record<string, { altname?: string; status?: string; ordermin?: string }> };
const data = (await res.json()) as { error: string[]; result: Record<string, { altname?: string; status?: string; ordermin?: string; pair_decimals?: number; lot_decimals?: number }> };
if (data.error?.length) throw new Error(`Kraken /0/public/AssetPairs: ${data.error.join(', ')}`);
assetPairMeta = new Map(Object.entries(data.result ?? {}));
tradablePairs = new Set(
Expand All @@ -133,6 +133,32 @@ export async function getPairMinVolume(pair: string): Promise<number | null> {
return null;
}

/**
* Decimal places Kraken accepts for a pair's price (pair_decimals) and volume
* (lot_decimals). BTC/USD takes 1 price decimal, so a blanket toFixed(2) is
* refused with "EOrder:Invalid price ... can only be specified up to 1 decimals".
*/
export async function getPairDecimals(pair: string): Promise<{ price: number; volume: number } | null> {
await syncAssetPairs();
for (const [id, meta] of assetPairMeta.entries()) {
if (id === pair || meta.altname === pair) {
const price = Number(meta.pair_decimals);
const volume = Number(meta.lot_decimals);
return {
price: Number.isInteger(price) && price >= 0 ? price : 2,
volume: Number.isInteger(volume) && volume >= 0 ? volume : 8,
};
}
}
return null;
}

/** Round a limit price to the pair's allowed decimals (default 2 if unknown). */
export function formatKrakenPrice(price: number, decimals: number | null | undefined): string {
const d = Number.isInteger(decimals) && (decimals as number) >= 0 ? (decimals as number) : 2;
return price.toFixed(d);
}

export async function getBalance(): Promise<Record<string, string>> {
return krakenPrivate<Record<string, string>>('/0/private/Balance');
}
Expand Down
2 changes: 1 addition & 1 deletion packages/source-crypto-arb/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export {
__getWsCacheStateForTests,
__injectGeminiBookTickerForTests,
} from './feeds/index.js';
export { getBalance, placeOrder, getOpenOrders, cancelOrder as cancelKrakenOrder, getTradeHistory, getPairMinVolume as getKrakenPairMinVolume, MAX_POSITION_USD, KRAKEN_TAKER_FEE, type TradeEntry, type OpenOrder } from './feeds/kraken-private.js';
export { getBalance, placeOrder, getOpenOrders, cancelOrder as cancelKrakenOrder, getTradeHistory, getPairMinVolume as getKrakenPairMinVolume, getPairDecimals as getKrakenPairDecimals, formatKrakenPrice, MAX_POSITION_USD, KRAKEN_TAKER_FEE, type TradeEntry, type OpenOrder } from './feeds/kraken-private.js';
export { hasTradingPair as hasKrakenTradingPair } from './feeds/kraken-private.js';
export {
getBalance as getBinanceBalance,
Expand Down
Loading