@lumencharts/trading-platform 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/LICENSE +55 -0
- package/README.md +53 -2
- package/dist/asset-entry.d.ts +3 -0
- package/dist/asset.d.ts +3 -0
- package/dist/asset.js +21689 -0
- package/dist/chart/bracket-links.d.ts +8 -0
- package/dist/chart/context-actions.d.ts +7 -0
- package/dist/chart/edit-presentation.d.ts +32 -0
- package/dist/chart/edit-preview.d.ts +26 -0
- package/dist/chart/exit-profit.d.ts +32 -0
- package/dist/chart/frame-batch.d.ts +15 -0
- package/dist/chart/overlay-coordinator.d.ts +18 -0
- package/dist/chart/overlay-events.d.ts +3 -0
- package/dist/chart/overlay-gesture.d.ts +40 -0
- package/dist/chart/overlay-index.d.ts +30 -0
- package/dist/chart/overlay-projection.d.ts +51 -0
- package/dist/chart/overlay-types.d.ts +42 -0
- package/dist/chart/parent-links.d.ts +33 -0
- package/dist/chart/position-profit.d.ts +15 -0
- package/dist/chart/review-lock.d.ts +14 -0
- package/dist/chart/ticket-projection.d.ts +36 -0
- package/dist/compat/default-formatters.d.ts +6 -0
- package/dist/compat/delegate.d.ts +11 -0
- package/dist/compat/factory.d.ts +5 -0
- package/dist/compat/formatters.d.ts +26 -0
- package/dist/compat/host-dialogs.d.ts +5 -0
- package/dist/compat/host-preferences.d.ts +8 -0
- package/dist/compat/host.d.ts +39 -0
- package/dist/compat/watched-value.d.ts +25 -0
- package/dist/conformance/index.d.ts +78 -0
- package/dist/conformance/index.js +6859 -0
- package/dist/conformance/replay.d.ts +35 -0
- package/dist/contracts/broker.d.ts +1122 -0
- package/dist/contracts/broker.js +168 -0
- package/dist/contracts/index.d.ts +3 -0
- package/dist/contracts/index.js +168 -0
- package/dist/contracts/market-data.d.ts +289 -0
- package/dist/contracts/market-data.js +11 -0
- package/dist/contracts/ports.d.ts +469 -0
- package/dist/contracts/ports.js +5 -0
- package/dist/core/account-datasets.d.ts +29 -0
- package/dist/core/account-lifecycle.d.ts +70 -0
- package/dist/core/account-types.d.ts +6 -0
- package/dist/core/bounded-map.d.ts +12 -0
- package/dist/core/bracket-input.d.ts +32 -0
- package/dist/core/bracket-modification.d.ts +6 -0
- package/dist/core/bracket-parent.d.ts +11 -0
- package/dist/core/broker-debug.d.ts +10 -0
- package/dist/core/capabilities.d.ts +34 -0
- package/dist/core/capability-metadata.d.ts +60 -0
- package/dist/core/capability-policy.d.ts +32 -0
- package/dist/core/chart-exit-level.d.ts +11 -0
- package/dist/core/chart-order-edit.d.ts +50 -0
- package/dist/core/clock.d.ts +2 -0
- package/dist/core/close-commands.d.ts +24 -0
- package/dist/core/close-flow.d.ts +14 -0
- package/dist/core/command-context.d.ts +16 -0
- package/dist/core/command-coordinator.d.ts +71 -0
- package/dist/core/command-follow.d.ts +32 -0
- package/dist/core/command-keys.d.ts +11 -0
- package/dist/core/context-orders.d.ts +19 -0
- package/dist/core/deferred.d.ts +5 -0
- package/dist/core/dialog-coordinator.d.ts +73 -0
- package/dist/core/display-preferences.d.ts +10 -0
- package/dist/core/disposal.d.ts +8 -0
- package/dist/core/entity-store.d.ts +56 -0
- package/dist/core/entity-validation.d.ts +9 -0
- package/dist/core/errors.d.ts +24 -0
- package/dist/core/execution-demand.d.ts +11 -0
- package/dist/core/execution-sound.d.ts +10 -0
- package/dist/core/exit-level-draft.d.ts +9 -0
- package/dist/core/exit-level-summary.d.ts +3 -0
- package/dist/core/exit-level-template.d.ts +16 -0
- package/dist/core/features.d.ts +39 -0
- package/dist/core/financial-rules.d.ts +70 -0
- package/dist/core/history-limit.d.ts +11 -0
- package/dist/core/identity.d.ts +14 -0
- package/dist/core/immutable.d.ts +8 -0
- package/dist/core/keyed-ref-count.d.ts +18 -0
- package/dist/core/leverage-commands.d.ts +42 -0
- package/dist/core/modification-context.d.ts +22 -0
- package/dist/core/modification-routing.d.ts +43 -0
- package/dist/core/notification-log.d.ts +33 -0
- package/dist/core/number-precision.d.ts +4 -0
- package/dist/core/order-commands.d.ts +50 -0
- package/dist/core/order-duration.d.ts +14 -0
- package/dist/core/order-labels.d.ts +7 -0
- package/dist/core/order-matching.d.ts +16 -0
- package/dist/core/order-modification.d.ts +20 -0
- package/dist/core/order-notifications.d.ts +30 -0
- package/dist/core/order-protection.d.ts +4 -0
- package/dist/core/parent-protection.d.ts +10 -0
- package/dist/core/position-commands.d.ts +45 -0
- package/dist/core/position-custom-fields.d.ts +5 -0
- package/dist/core/position-estimates.d.ts +22 -0
- package/dist/core/position-protection-permissions.d.ts +4 -0
- package/dist/core/preferences-key.d.ts +2 -0
- package/dist/core/preview-leases.d.ts +12 -0
- package/dist/core/protection-legs.d.ts +23 -0
- package/dist/core/protection-notifications.d.ts +9 -0
- package/dist/core/protection-rules.d.ts +21 -0
- package/dist/core/quantity-input.d.ts +53 -0
- package/dist/core/read-coordinator.d.ts +15 -0
- package/dist/core/readers.d.ts +6 -0
- package/dist/core/relative-price.d.ts +4 -0
- package/dist/core/review-policy.d.ts +17 -0
- package/dist/core/session-types.d.ts +1 -0
- package/dist/core/session.d.ts +114 -0
- package/dist/core/snapshot-dataset.d.ts +47 -0
- package/dist/core/symbol-catalog.d.ts +37 -0
- package/dist/core/tradability.d.ts +26 -0
- package/dist/core/trading-commands.d.ts +104 -0
- package/dist/core/trading-rules.d.ts +14 -0
- package/dist/core/trading-settings.d.ts +39 -0
- package/dist/core/trading-state.d.ts +52 -0
- package/dist/core/value-store.d.ts +11 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +6593 -0
- package/dist/market-data/depth-book.d.ts +18 -0
- package/dist/market-data/index.d.ts +3 -0
- package/dist/market-data/index.js +735 -0
- package/dist/market-data/session-demand.d.ts +15 -0
- package/dist/market-data/subscriptions.d.ts +13 -0
- package/dist/mock/broker.d.ts +75 -0
- package/dist/mock/clock.d.ts +12 -0
- package/dist/mock/feeds.d.ts +18 -0
- package/dist/mock/index.d.ts +5 -0
- package/dist/mock/index.js +1956 -0
- package/dist/mock/protection-cancellation.d.ts +7 -0
- package/dist/mock/scenarios.d.ts +5 -0
- package/dist/paper/broker.d.ts +41 -0
- package/dist/paper/index.d.ts +6 -0
- package/dist/paper/index.js +469 -0
- package/dist/paper/market.d.ts +57 -0
- package/dist/paper/rules.d.ts +40 -0
- package/dist/ui/account-manager/account-pages.d.ts +18 -0
- package/dist/ui/account-manager/column-presentation.d.ts +5 -0
- package/dist/ui/account-manager/context-menu.d.ts +13 -0
- package/dist/ui/account-manager/csv-downloads.d.ts +5 -0
- package/dist/ui/account-manager/custom-page.d.ts +16 -0
- package/dist/ui/account-manager/custom-table.d.ts +18 -0
- package/dist/ui/account-manager/format-account-value.d.ts +12 -0
- package/dist/ui/account-manager/position-reader.d.ts +19 -0
- package/dist/ui/account-manager/row-action-tracker.d.ts +12 -0
- package/dist/ui/account-manager/row-actions.d.ts +37 -0
- package/dist/ui/account-manager/status-counts.d.ts +6 -0
- package/dist/ui/account-manager/table-controls.d.ts +13 -0
- package/dist/ui/account-manager/table-export.d.ts +30 -0
- package/dist/ui/account-manager/table-model.d.ts +11 -0
- package/dist/ui/account-manager/table-toolbar.d.ts +25 -0
- package/dist/ui/account-manager/table.d.ts +24 -0
- package/dist/ui/account-manager/view.d.ts +19 -0
- package/dist/ui/account-manager/workspace.d.ts +15 -0
- package/dist/ui/chart-actions.d.ts +11 -0
- package/dist/ui/chart-controls/eligibility.d.ts +6 -0
- package/dist/ui/chart-controls/quote-buttons.d.ts +15 -0
- package/dist/ui/chart-controls/quote-controls.d.ts +12 -0
- package/dist/ui/chart-controls/quote-widths.d.ts +8 -0
- package/dist/ui/dialogs/close-amount-form.d.ts +8 -0
- package/dist/ui/dialogs/close-preview-dialog.d.ts +5 -0
- package/dist/ui/dialogs/confirm-dialog.d.ts +7 -0
- package/dist/ui/dialogs/dialog-body.d.ts +11 -0
- package/dist/ui/dialogs/leverage-form.d.ts +10 -0
- package/dist/ui/dialogs/message-dialog.d.ts +6 -0
- package/dist/ui/dialogs/position-protection.d.ts +14 -0
- package/dist/ui/dialogs/properties-dialog.d.ts +9 -0
- package/dist/ui/dialogs/sanitize-html.d.ts +2 -0
- package/dist/ui/dialogs/types.d.ts +5 -0
- package/dist/ui/dialogs/view.d.ts +5 -0
- package/dist/ui/dock-sizes.d.ts +20 -0
- package/dist/ui/dom/controller.d.ts +34 -0
- package/dist/ui/dom/ladder.d.ts +23 -0
- package/dist/ui/dom/view.d.ts +8 -0
- package/dist/ui/dom/workspace.d.ts +17 -0
- package/dist/ui/effective-mode.d.ts +11 -0
- package/dist/ui/financial-lease.d.ts +3 -0
- package/dist/ui/icons.d.ts +4 -0
- package/dist/ui/index.d.ts +9 -0
- package/dist/ui/index.js +15918 -0
- package/dist/ui/layout.d.ts +5 -0
- package/dist/ui/mount.d.ts +11 -0
- package/dist/ui/notifications/log.d.ts +6 -0
- package/dist/ui/notifications/toasts.d.ts +5 -0
- package/dist/ui/number-input.d.ts +2 -0
- package/dist/ui/order-ticket/chart-draft-controls.d.ts +8 -0
- package/dist/ui/order-ticket/chart-projection.d.ts +9 -0
- package/dist/ui/order-ticket/controller.d.ts +41 -0
- package/dist/ui/order-ticket/custom-field.d.ts +9 -0
- package/dist/ui/order-ticket/duration-input.d.ts +9 -0
- package/dist/ui/order-ticket/exit-input.d.ts +34 -0
- package/dist/ui/order-ticket/financial-controls.d.ts +10 -0
- package/dist/ui/order-ticket/layout-context.d.ts +7 -0
- package/dist/ui/order-ticket/market.d.ts +12 -0
- package/dist/ui/order-ticket/menu.d.ts +6 -0
- package/dist/ui/order-ticket/mode-rules.d.ts +4 -0
- package/dist/ui/order-ticket/modification-fields.d.ts +23 -0
- package/dist/ui/order-ticket/move-handle.d.ts +4 -0
- package/dist/ui/order-ticket/order-sent.d.ts +4 -0
- package/dist/ui/order-ticket/placement.d.ts +27 -0
- package/dist/ui/order-ticket/preview-message.d.ts +4 -0
- package/dist/ui/order-ticket/price-input.d.ts +14 -0
- package/dist/ui/order-ticket/quantity-input.d.ts +26 -0
- package/dist/ui/order-ticket/review-panel.d.ts +10 -0
- package/dist/ui/order-ticket/rules.d.ts +16 -0
- package/dist/ui/order-ticket/stop-input.d.ts +17 -0
- package/dist/ui/order-ticket/submit-bar.d.ts +13 -0
- package/dist/ui/order-ticket/symbol-search-controller.d.ts +50 -0
- package/dist/ui/order-ticket/symbol-search.d.ts +12 -0
- package/dist/ui/order-ticket/untradable-notice.d.ts +8 -0
- package/dist/ui/order-ticket/view.d.ts +16 -0
- package/dist/ui/panel-visibility.d.ts +6 -0
- package/dist/ui/pointer-drag.d.ts +20 -0
- package/dist/ui/popup-mount.d.ts +4 -0
- package/dist/ui/primitives.d.ts +29 -0
- package/dist/ui/protection/editor.d.ts +18 -0
- package/dist/ui/protection/fields.d.ts +30 -0
- package/dist/ui/protection/level.d.ts +14 -0
- package/dist/ui/protection/protected-size.d.ts +5 -0
- package/dist/ui/protection/ticket-workspace.d.ts +7 -0
- package/dist/ui/resize-handle.css +34 -0
- package/dist/ui/resize-handle.d.ts +20 -0
- package/dist/ui/resize-handle.js +185 -0
- package/dist/ui/select.d.ts +26 -0
- package/dist/ui/surface-theme.d.ts +3 -0
- package/dist/ui/switch.d.ts +7 -0
- package/dist/ui/symbol-logo.d.ts +7 -0
- package/dist/ui/tabs.d.ts +19 -0
- package/dist/ui/ticket-dock.d.ts +18 -0
- package/dist/ui/ticket-shell.d.ts +15 -0
- package/dist/ui/trading.css +1808 -0
- package/dist/ui/trap-tab.d.ts +11 -0
- package/dist/vendor/solid-ui/index.d.ts +3 -0
- package/dist/vendor/solid-ui/paged-list-window.d.ts +27 -0
- package/dist/vendor/solid-ui/virtual-list.d.ts +21 -0
- package/package.json +104 -3
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { StopType } from "../contracts/broker.js";
|
|
2
|
+
import type { BracketOrder, Brackets } from "../contracts/broker.js";
|
|
3
|
+
/** Broker-owned protection metadata follows canceled child orders without reallocating surviving levels. */
|
|
4
|
+
export declare function withoutCanceledProtection<T extends Brackets & {
|
|
5
|
+
stopType?: StopType;
|
|
6
|
+
trailingStopPrice?: number;
|
|
7
|
+
}>(parent: T, canceled: readonly BracketOrder[]): T;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { InstrumentInfo, SingleBrokerMetaInfo } from '../contracts/broker.js';
|
|
2
|
+
export declare const simulationProfiles: readonly ["equity-net", "equity-estimates", "fx-netting", "fx-multiposition", "crypto", "custom-ui", "failure-lab"];
|
|
3
|
+
export type SimulationProfile = typeof simulationProfiles[number];
|
|
4
|
+
export declare function simulationInstrument(profile: SimulationProfile): InstrumentInfo;
|
|
5
|
+
export declare function simulationConfig(profile: SimulationProfile): SingleBrokerMetaInfo;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { IBrokerConnectionAdapterHost, IBrokerTerminal, Order, Position, SingleBrokerMetaInfo } from '../contracts/broker.js';
|
|
2
|
+
import { type PaperFinanceSchedule, type PaperMarket } from './market.js';
|
|
3
|
+
/** What the paper broker supports: market, limit and stop orders with brackets, one net position per symbol. */
|
|
4
|
+
export declare const paperBrokerConfig: SingleBrokerMetaInfo;
|
|
5
|
+
/** What the next broker action does, for rehearsing failures: proceed, reject, or wait twelve seconds first. */
|
|
6
|
+
export type PaperFailureAction = 'normal' | 'reject' | 'delay';
|
|
7
|
+
export interface PaperBrokerOptions {
|
|
8
|
+
/** Fill orders as soon as the quote crosses their price. Off, orders wait for `fillNext`. Default true. */
|
|
9
|
+
readonly automaticFills?: boolean;
|
|
10
|
+
/** The account's starting balance. Default 100,000. */
|
|
11
|
+
readonly balance?: number;
|
|
12
|
+
/** The account currency, shown in the account manager. Default USD. */
|
|
13
|
+
readonly currency?: string;
|
|
14
|
+
/** How long a quote stays tradable. Default 15 seconds. */
|
|
15
|
+
readonly quoteMaxAgeMs?: number;
|
|
16
|
+
/** How P&L and equity updates are coalesced. Default: at most one every 250 ms. */
|
|
17
|
+
readonly financeSchedule?: (flush: () => void) => PaperFinanceSchedule;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A broker adapter that trades on paper in the browser: it fills market, limit
|
|
21
|
+
* and stop orders against the host's quotes, keeps one net position per symbol
|
|
22
|
+
* with take profit and stop loss, and reports through the chart's host updates.
|
|
23
|
+
* Nothing is persisted or sent anywhere. Use it for demos, tests, or as a
|
|
24
|
+
* starting point for a real adapter.
|
|
25
|
+
*/
|
|
26
|
+
export declare function createPaperBroker(market: PaperMarket, options?: PaperBrokerOptions): {
|
|
27
|
+
brokerFactory: (value: IBrokerConnectionAdapterHost) => IBrokerTerminal;
|
|
28
|
+
brokerConfig: SingleBrokerMetaInfo;
|
|
29
|
+
/** Fills the newest waiting order whose price has been reached, fully or by `amount`. */
|
|
30
|
+
fillNext(amount?: number): void;
|
|
31
|
+
/** Makes the next broker action proceed, reject, or wait twelve seconds first. */
|
|
32
|
+
setFailure(action: PaperFailureAction): void;
|
|
33
|
+
setConnected(value: boolean): void;
|
|
34
|
+
snapshot: () => {
|
|
35
|
+
orders: Order[];
|
|
36
|
+
positions: Position[];
|
|
37
|
+
balance: number;
|
|
38
|
+
};
|
|
39
|
+
dispose(): void;
|
|
40
|
+
};
|
|
41
|
+
export type PaperBroker = ReturnType<typeof createPaperBroker>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { createPaperBroker, paperBrokerConfig } from './broker.js';
|
|
2
|
+
export type { PaperBroker, PaperBrokerOptions, PaperFailureAction } from './broker.js';
|
|
3
|
+
export { intervalFinanceSchedule } from './market.js';
|
|
4
|
+
export type { PaperFinanceSchedule, PaperInstrument, PaperInstrumentLookup, PaperMarket, PaperQuote } from './market.js';
|
|
5
|
+
export { defaultQuoteMaxAgeMs, executableQuote, netFill, onTick, PaperRejection, shouldFill, validateProtection, validQuantity } from './rules.js';
|
|
6
|
+
export type { PaperRejectionCode } from './rules.js';
|
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
// src/paper/market.ts
|
|
2
|
+
function intervalFinanceSchedule(flush, intervalMs = 250) {
|
|
3
|
+
let timer;
|
|
4
|
+
return {
|
|
5
|
+
request() {
|
|
6
|
+
timer ??= setTimeout(() => {
|
|
7
|
+
timer = void 0;
|
|
8
|
+
flush();
|
|
9
|
+
}, intervalMs);
|
|
10
|
+
},
|
|
11
|
+
cancel() {
|
|
12
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
13
|
+
timer = void 0;
|
|
14
|
+
},
|
|
15
|
+
dispose() {
|
|
16
|
+
this.cancel();
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/paper/rules.ts
|
|
22
|
+
var PaperRejection = class extends Error {
|
|
23
|
+
code;
|
|
24
|
+
constructor(code, message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "PaperRejection";
|
|
27
|
+
this.code = code;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
var defaultQuoteMaxAgeMs = 15e3;
|
|
31
|
+
function executableQuote(quote, side, now = Date.now(), maxAgeMs = defaultQuoteMaxAgeMs) {
|
|
32
|
+
if (!quote || !quote.executableAt || now - quote.executableAt > maxAgeMs || now < quote.executableAt)
|
|
33
|
+
throw new PaperRejection("unavailable", "A fresh bid and ask are needed to trade.");
|
|
34
|
+
const price = side === 1 /* Buy */ ? quote.ask : quote.bid;
|
|
35
|
+
if (!price || !Number.isFinite(price)) throw new PaperRejection("unavailable", "An executable quote is unavailable.");
|
|
36
|
+
return price;
|
|
37
|
+
}
|
|
38
|
+
function shouldFill(type, side, price, limit, stop) {
|
|
39
|
+
if (type === 2 /* Market */) return true;
|
|
40
|
+
if (type === 1 /* Limit */) return limit !== void 0 && (side === 1 /* Buy */ ? price <= limit : price >= limit);
|
|
41
|
+
if (type === 3 /* Stop */) return stop !== void 0 && (side === 1 /* Buy */ ? price >= stop : price <= stop);
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
function validQuantity(item, quantity) {
|
|
45
|
+
return Number.isFinite(quantity) && quantity > 0 && quantity <= 1e6 && Math.abs(quantity / item.quantityStep - Math.round(quantity / item.quantityStep)) < 1e-6;
|
|
46
|
+
}
|
|
47
|
+
function netFill(previous, side, quantity, price) {
|
|
48
|
+
if (!previous) return { side, qty: quantity, avgPrice: price, realized: 0 };
|
|
49
|
+
if (previous.side === side)
|
|
50
|
+
return {
|
|
51
|
+
side,
|
|
52
|
+
qty: previous.qty + quantity,
|
|
53
|
+
avgPrice: (previous.qty * previous.avgPrice + quantity * price) / (previous.qty + quantity),
|
|
54
|
+
realized: 0
|
|
55
|
+
};
|
|
56
|
+
const closed = Math.min(previous.qty, quantity), remaining = previous.qty - quantity;
|
|
57
|
+
return {
|
|
58
|
+
side: remaining < 0 ? side : previous.side,
|
|
59
|
+
qty: Math.abs(remaining),
|
|
60
|
+
avgPrice: remaining < 0 ? price : previous.avgPrice,
|
|
61
|
+
realized: (price - previous.avgPrice) * closed * previous.side
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function validateProtection(side, reference, brackets) {
|
|
65
|
+
if (brackets.takeProfit !== void 0 && (brackets.takeProfit - reference) * side <= 0)
|
|
66
|
+
throw new PaperRejection("invalid", "Take profit must be beyond the reference price.");
|
|
67
|
+
if (brackets.stopLoss !== void 0 && (brackets.stopLoss - reference) * side >= 0)
|
|
68
|
+
throw new PaperRejection("invalid", "Stop loss must be behind the reference price.");
|
|
69
|
+
}
|
|
70
|
+
function onTick(price, tick) {
|
|
71
|
+
return Number.isFinite(price) && price > 0 && Math.abs(price / tick - Math.round(price / tick)) <= 1e-5;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/paper/broker.ts
|
|
75
|
+
var paperBrokerConfig = {
|
|
76
|
+
configFlags: {
|
|
77
|
+
supportOrdersHistory: true,
|
|
78
|
+
supportPositions: true,
|
|
79
|
+
supportExecutions: true,
|
|
80
|
+
// The chart and position table can mark paper positions directly from quotes.
|
|
81
|
+
supportPLUpdate: false,
|
|
82
|
+
supportClosePosition: true,
|
|
83
|
+
supportPartialClosePosition: true,
|
|
84
|
+
supportReversePosition: false,
|
|
85
|
+
supportOrderBrackets: true,
|
|
86
|
+
supportPositionBrackets: true,
|
|
87
|
+
supportStopLoss: true,
|
|
88
|
+
supportStopOrders: true,
|
|
89
|
+
supportStopLimitOrders: false,
|
|
90
|
+
supportLevel2Data: false,
|
|
91
|
+
supportMargin: false,
|
|
92
|
+
supportModifyDuration: false,
|
|
93
|
+
supportSymbolSearch: true
|
|
94
|
+
},
|
|
95
|
+
tradedGroupConfig: { supportAdaptiveLayout: true },
|
|
96
|
+
durations: [{ name: "Good until cancelled", value: "GTC", default: true }]
|
|
97
|
+
};
|
|
98
|
+
function createPaperBroker(market, options = {}) {
|
|
99
|
+
let host, sequence = 0, balance = options.balance ?? 1e5, disposed = false, connected = true, next = "normal";
|
|
100
|
+
const automaticFills = options.automaticFills ?? true;
|
|
101
|
+
const currency = options.currency ?? "USD";
|
|
102
|
+
const accountId = `paper-${currency.toLowerCase()}`;
|
|
103
|
+
const quoteMaxAgeMs = options.quoteMaxAgeMs ?? defaultQuoteMaxAgeMs;
|
|
104
|
+
const orders = /* @__PURE__ */ new Map(), positions = /* @__PURE__ */ new Map(), executions = [], releases = /* @__PURE__ */ new Map();
|
|
105
|
+
const pending = /* @__PURE__ */ new Map();
|
|
106
|
+
const finance = (options.financeSchedule ?? intervalFinanceSchedule)(() => notifyFinance());
|
|
107
|
+
const money = new Intl.NumberFormat("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
108
|
+
let summary;
|
|
109
|
+
let balanceValue, equityValue;
|
|
110
|
+
const parentId = (order) => "parentId" in order ? order.parentId : void 0;
|
|
111
|
+
const isOpenOrder = (order) => order.status === 6 /* Working */ || order.status === 3 /* Inactive */;
|
|
112
|
+
const id = (kind) => `paper-${kind}-${++sequence}`;
|
|
113
|
+
const priceFor = (symbol, side) => executableQuote(market.quote(symbol), side, Date.now(), quoteMaxAgeMs);
|
|
114
|
+
const publishOrder = (order) => {
|
|
115
|
+
orders.set(order.id, order);
|
|
116
|
+
host?.orderUpdate(structuredClone(order));
|
|
117
|
+
};
|
|
118
|
+
const refreshDemand = () => {
|
|
119
|
+
if (!market.demand) return;
|
|
120
|
+
const symbols = new Set([...orders.values()].filter((order) => order.status === 6 /* Working */).map((order) => order.symbol));
|
|
121
|
+
for (const position of positions.values()) symbols.add(position.symbol);
|
|
122
|
+
for (const [symbol, release] of releases)
|
|
123
|
+
if (!symbols.has(symbol)) {
|
|
124
|
+
release();
|
|
125
|
+
releases.delete(symbol);
|
|
126
|
+
}
|
|
127
|
+
for (const symbol of symbols) if (!releases.has(symbol)) releases.set(symbol, market.demand(symbol));
|
|
128
|
+
};
|
|
129
|
+
const instrument = (symbol) => {
|
|
130
|
+
const lookup = market.instrument(symbol);
|
|
131
|
+
if (!lookup.tradable) throw new PaperRejection("unsupported", lookup.reason);
|
|
132
|
+
return lookup.instrument;
|
|
133
|
+
};
|
|
134
|
+
const guard = () => {
|
|
135
|
+
if (disposed) throw new PaperRejection("unavailable", "Paper session ended.");
|
|
136
|
+
if (!connected) throw new PaperRejection("unavailable", "Paper account is disconnected.");
|
|
137
|
+
};
|
|
138
|
+
const mutate = async (action) => {
|
|
139
|
+
guard();
|
|
140
|
+
const failure = next;
|
|
141
|
+
next = "normal";
|
|
142
|
+
if (failure === "reject") throw new PaperRejection("rejected", "The QA broker rejected this action.");
|
|
143
|
+
if (failure === "delay")
|
|
144
|
+
await new Promise((resolve, reject) => {
|
|
145
|
+
const timer = setTimeout(() => {
|
|
146
|
+
pending.delete(timer);
|
|
147
|
+
resolve();
|
|
148
|
+
}, 12e3);
|
|
149
|
+
pending.set(timer, () => reject(new PaperRejection("unavailable", "Paper session ended.")));
|
|
150
|
+
});
|
|
151
|
+
guard();
|
|
152
|
+
action();
|
|
153
|
+
refreshDemand();
|
|
154
|
+
};
|
|
155
|
+
function notifyFinance() {
|
|
156
|
+
finance.cancel();
|
|
157
|
+
let unrealized = 0, complete = true;
|
|
158
|
+
for (const position of positions.values()) {
|
|
159
|
+
let pl;
|
|
160
|
+
try {
|
|
161
|
+
pl = (priceFor(position.symbol, position.side === 1 /* Buy */ ? -1 /* Sell */ : 1 /* Buy */) - position.avgPrice) * position.qty * position.side;
|
|
162
|
+
} catch {
|
|
163
|
+
complete = false;
|
|
164
|
+
}
|
|
165
|
+
if (pl !== void 0) {
|
|
166
|
+
unrealized += pl;
|
|
167
|
+
position.extra = { pl };
|
|
168
|
+
host?.plUpdate(position.id, pl);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (complete) host?.equityUpdate(balance + unrealized);
|
|
172
|
+
balanceValue?.setValue(money.format(balance));
|
|
173
|
+
if (complete) equityValue?.setValue(money.format(balance + unrealized));
|
|
174
|
+
}
|
|
175
|
+
function cancelProtection(parentKey) {
|
|
176
|
+
for (const order of orders.values())
|
|
177
|
+
if (parentId(order) === parentKey && isOpenOrder(order)) publishOrder({ ...order, status: 1 /* Canceled */ });
|
|
178
|
+
}
|
|
179
|
+
function cancelOrder(order) {
|
|
180
|
+
publishOrder({ ...order, status: 1 /* Canceled */ });
|
|
181
|
+
if (!("parentId" in order)) {
|
|
182
|
+
cancelProtection(order.id);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const field = order.type === 1 /* Limit */ ? "takeProfit" : "stopLoss";
|
|
186
|
+
if (order.parentType === 1 /* Order */) {
|
|
187
|
+
const parent = orders.get(order.parentId);
|
|
188
|
+
if (parent && isOpenOrder(parent)) publishOrder({ ...parent, [field]: void 0 });
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const position = positions.get(order.parentId);
|
|
192
|
+
if (!position) return;
|
|
193
|
+
position[field] = void 0;
|
|
194
|
+
host?.positionUpdate(structuredClone(position));
|
|
195
|
+
}
|
|
196
|
+
function syncProtectionOrders(parent, parentType, brackets, qty, previousParentId = parent.id) {
|
|
197
|
+
const children = [...orders.values()].filter((row) => parentId(row) === previousParentId && isOpenOrder(row));
|
|
198
|
+
const status = parentType === 1 /* Order */ ? 3 /* Inactive */ : 6 /* Working */;
|
|
199
|
+
for (const [kind, type, price] of [
|
|
200
|
+
["tp", 1 /* Limit */, brackets.takeProfit],
|
|
201
|
+
["sl", 3 /* Stop */, brackets.stopLoss]
|
|
202
|
+
]) {
|
|
203
|
+
const child = children.find((row) => row.type === type);
|
|
204
|
+
if (price === void 0 || qty <= 0) {
|
|
205
|
+
if (child) publishOrder({ ...child, status: 1 /* Canceled */ });
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const priceField = type === 1 /* Limit */ ? "limitPrice" : "stopPrice";
|
|
209
|
+
if (child && parentId(child) === parent.id && child.status === status && child.qty === qty && child[priceField] === price) continue;
|
|
210
|
+
publishOrder({
|
|
211
|
+
id: child?.id ?? id(kind),
|
|
212
|
+
symbol: parent.symbol,
|
|
213
|
+
side: parent.side === 1 /* Buy */ ? -1 /* Sell */ : 1 /* Buy */,
|
|
214
|
+
qty,
|
|
215
|
+
type,
|
|
216
|
+
status,
|
|
217
|
+
parentId: parent.id,
|
|
218
|
+
parentType,
|
|
219
|
+
[priceField]: price
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function protection(position, brackets, activatingOrderId) {
|
|
224
|
+
cancelProtection(position.id);
|
|
225
|
+
position.takeProfit = brackets.takeProfit;
|
|
226
|
+
position.stopLoss = brackets.stopLoss;
|
|
227
|
+
host?.positionUpdate(structuredClone(position));
|
|
228
|
+
syncProtectionOrders(position, 2 /* Position */, brackets, position.qty, activatingOrderId);
|
|
229
|
+
}
|
|
230
|
+
function fill(order, price, amount = order.qty - (order.filledQty ?? 0)) {
|
|
231
|
+
const filled = order.filledQty ?? 0;
|
|
232
|
+
if (amount <= 0 || amount > order.qty - filled || !validQuantity(instrument(order.symbol), amount))
|
|
233
|
+
throw new PaperRejection("invalid", "Invalid fill quantity.");
|
|
234
|
+
const positionId = `paper-position:${order.symbol}`, old = positions.get(positionId);
|
|
235
|
+
if (parentId(order) && (!old || parentId(order) !== old.id)) return;
|
|
236
|
+
const result = netFill(old, order.side, amount, price);
|
|
237
|
+
balance += result.realized;
|
|
238
|
+
const execution = { id: id("fill"), symbol: order.symbol, side: order.side, qty: amount, price, time: Date.now() / 1e3 };
|
|
239
|
+
executions.push(execution);
|
|
240
|
+
if (executions.length > 1e3) executions.shift();
|
|
241
|
+
const filledQty = filled + amount;
|
|
242
|
+
const remaining = order.qty - filledQty;
|
|
243
|
+
publishOrder({
|
|
244
|
+
...order,
|
|
245
|
+
status: remaining <= 0 ? 2 /* Filled */ : 6 /* Working */,
|
|
246
|
+
filledQty,
|
|
247
|
+
avgPrice: ((order.avgPrice ?? 0) * filled + price * amount) / filledQty
|
|
248
|
+
});
|
|
249
|
+
host?.executionUpdate(execution);
|
|
250
|
+
if (old) cancelProtection(old.id);
|
|
251
|
+
const position = { id: positionId, symbol: order.symbol, side: result.side, qty: result.qty, avgPrice: result.avgPrice };
|
|
252
|
+
if (result.qty > 0) {
|
|
253
|
+
positions.set(positionId, position);
|
|
254
|
+
host?.positionUpdate(position);
|
|
255
|
+
if (!parentId(order)) {
|
|
256
|
+
const opensOnOrderSide = position.side === order.side;
|
|
257
|
+
const existing = old?.side === position.side ? old : void 0;
|
|
258
|
+
const placed = opensOnOrderSide ? order : void 0;
|
|
259
|
+
protection(
|
|
260
|
+
position,
|
|
261
|
+
{ takeProfit: placed?.takeProfit ?? existing?.takeProfit, stopLoss: placed?.stopLoss ?? existing?.stopLoss },
|
|
262
|
+
opensOnOrderSide && remaining <= 0 ? order.id : void 0
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
} else {
|
|
266
|
+
positions.delete(positionId);
|
|
267
|
+
host?.positionUpdate(position);
|
|
268
|
+
}
|
|
269
|
+
if (!parentId(order)) syncProtectionOrders(order, 1 /* Order */, order, remaining);
|
|
270
|
+
const settled = [...orders.values()].filter((row) => !isOpenOrder(row));
|
|
271
|
+
for (const row of settled.slice(0, -500)) orders.delete(row.id);
|
|
272
|
+
notifyFinance();
|
|
273
|
+
refreshDemand();
|
|
274
|
+
}
|
|
275
|
+
function evaluate(symbol) {
|
|
276
|
+
if (disposed || !connected) return;
|
|
277
|
+
if (!automaticFills) {
|
|
278
|
+
if (positions.size) finance.request();
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
for (const order of [...orders.values()]) {
|
|
282
|
+
if (order.symbol !== symbol || order.status !== 6 /* Working */ || orders.get(order.id)?.status !== 6 /* Working */) continue;
|
|
283
|
+
try {
|
|
284
|
+
const price = priceFor(symbol, order.side);
|
|
285
|
+
if (shouldFill(order.type, order.side, price, order.limitPrice, order.stopPrice)) fill(order, price);
|
|
286
|
+
} catch {
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (positions.size) finance.request();
|
|
290
|
+
}
|
|
291
|
+
function validate(order) {
|
|
292
|
+
const item = instrument(order.symbol);
|
|
293
|
+
if (!validQuantity(item, order.qty)) throw new PaperRejection("invalid", "Enter a valid quantity.");
|
|
294
|
+
if (![2 /* Market */, 1 /* Limit */, 3 /* Stop */].includes(order.type)) throw new PaperRejection("unsupported", "This order type is unavailable.");
|
|
295
|
+
if (order.side !== 1 /* Buy */ && order.side !== -1 /* Sell */) throw new PaperRejection("invalid", "Invalid order side.");
|
|
296
|
+
for (const value of [order.limitPrice, order.stopPrice, order.takeProfit, order.stopLoss])
|
|
297
|
+
if (value !== void 0 && !onTick(value, item.tick)) throw new PaperRejection("invalid", "Enter a price on the instrument tick.");
|
|
298
|
+
if (order.type === 1 /* Limit */ && order.limitPrice === void 0 || order.type === 3 /* Stop */ && order.stopPrice === void 0)
|
|
299
|
+
throw new PaperRejection("invalid", "An order price is required.");
|
|
300
|
+
const price = priceFor(order.symbol, order.side);
|
|
301
|
+
validateProtection(order.side, order.limitPrice ?? order.stopPrice ?? price, order);
|
|
302
|
+
const activeSymbols = new Set([...positions.values()].map((position) => position.symbol));
|
|
303
|
+
for (const row of orders.values()) if (row.status === 6 /* Working */) activeSymbols.add(row.symbol);
|
|
304
|
+
if (!activeSymbols.has(order.symbol) && activeSymbols.size >= 10) throw new PaperRejection("rejected", "Paper trading supports up to ten active symbols.");
|
|
305
|
+
}
|
|
306
|
+
const off = market.onQuote((symbol) => evaluate(symbol));
|
|
307
|
+
const brokerFactory = (value) => {
|
|
308
|
+
host = value;
|
|
309
|
+
const broker = {
|
|
310
|
+
connectionStatus: () => connected ? 1 /* Connected */ : 3 /* Disconnected */,
|
|
311
|
+
accountsMetainfo: async () => [{ id: accountId, name: `Paper account \xB7 ${currency}`, type: "demo", currency }],
|
|
312
|
+
currentAccount: () => accountId,
|
|
313
|
+
chartContextMenuActions: (context, options2) => value.defaultContextMenuActions(context, options2),
|
|
314
|
+
isTradable: async (symbol) => market.instrument(symbol).tradable,
|
|
315
|
+
symbolInfo: async (symbol) => {
|
|
316
|
+
const item = instrument(symbol);
|
|
317
|
+
return {
|
|
318
|
+
description: item.description,
|
|
319
|
+
qty: { min: item.quantityStep, max: 1e6, step: item.quantityStep, default: item.defaultQuantity },
|
|
320
|
+
pipSize: item.tick,
|
|
321
|
+
pipValue: item.tick,
|
|
322
|
+
minTick: item.tick,
|
|
323
|
+
type: item.type,
|
|
324
|
+
currency: item.currency,
|
|
325
|
+
...item.baseCurrency === void 0 ? {} : { baseCurrency: item.baseCurrency },
|
|
326
|
+
quoteCurrency: item.currency,
|
|
327
|
+
brokerSymbol: item.symbol,
|
|
328
|
+
allowedOrderTypes: [2 /* Market */, 1 /* Limit */, 3 /* Stop */]
|
|
329
|
+
};
|
|
330
|
+
},
|
|
331
|
+
accountManagerInfo: () => summary ??= {
|
|
332
|
+
accountTitle: "Paper trading",
|
|
333
|
+
pages: [],
|
|
334
|
+
summary: [
|
|
335
|
+
{ text: `Balance \xB7 ${currency}`, wValue: balanceValue ??= value.factory.createWatchedValue(money.format(balance)) },
|
|
336
|
+
{ text: `Equity \xB7 ${currency}`, wValue: equityValue ??= value.factory.createWatchedValue(money.format(balance)) }
|
|
337
|
+
],
|
|
338
|
+
orderColumns: [
|
|
339
|
+
{ id: "symbol", label: "Symbol", dataFields: ["symbol"] },
|
|
340
|
+
{ id: "qty", label: "Quantity", dataFields: ["qty"], formatter: "formatQuantity" /* FormatQuantity */ },
|
|
341
|
+
{ id: "status", label: "Status", dataFields: ["status"], formatter: "status" /* Status */ }
|
|
342
|
+
],
|
|
343
|
+
positionColumns: [
|
|
344
|
+
{ id: "symbol", label: "Symbol", dataFields: ["symbol", "symbol"], formatter: "symbol" /* Symbol */ },
|
|
345
|
+
{ id: "side", label: "Side", dataFields: ["side"], formatter: "side" /* Side */ },
|
|
346
|
+
{ id: "qty", label: "Qty", dataFields: ["qty"], formatter: "formatQuantity" /* FormatQuantity */ },
|
|
347
|
+
{ id: "avgPrice", label: "Avg fill price", dataFields: ["avgPrice"], formatter: "formatPrice" /* FormatPrice */ },
|
|
348
|
+
{ id: "profitLoss", label: `P&L \xB7 ${currency}`, dataFields: [["extra", "pl"]], formatter: "profit" /* Profit */ },
|
|
349
|
+
{ id: "takeProfit", label: "Take profit", dataFields: ["takeProfit"], formatter: "formatPrice" /* FormatPrice */ },
|
|
350
|
+
{ id: "stopLoss", label: "Stop loss", dataFields: ["stopLoss"], formatter: "formatPrice" /* FormatPrice */ }
|
|
351
|
+
]
|
|
352
|
+
},
|
|
353
|
+
orders: async () => structuredClone([...orders.values()].filter(isOpenOrder)),
|
|
354
|
+
ordersHistory: async () => structuredClone([...orders.values()].filter((row) => !isOpenOrder(row))),
|
|
355
|
+
positions: async () => structuredClone([...positions.values()]),
|
|
356
|
+
executions: async (symbol) => structuredClone(executions.filter((row) => row.symbol === symbol)),
|
|
357
|
+
placeOrder: async (order) => {
|
|
358
|
+
let orderId = "";
|
|
359
|
+
await mutate(() => {
|
|
360
|
+
validate(order);
|
|
361
|
+
if ([...orders.values()].filter((row) => row.status === 6 /* Working */).length >= 100) throw new PaperRejection("rejected", "Paper order capacity reached.");
|
|
362
|
+
orderId = id("order");
|
|
363
|
+
const placed = { ...order, id: orderId, status: 6 /* Working */ };
|
|
364
|
+
publishOrder(placed);
|
|
365
|
+
if (placed.type !== 2 /* Market */ || !automaticFills) syncProtectionOrders(placed, 1 /* Order */, placed, placed.qty);
|
|
366
|
+
evaluate(order.symbol);
|
|
367
|
+
});
|
|
368
|
+
return { orderId };
|
|
369
|
+
},
|
|
370
|
+
modifyOrder: async (order) => mutate(() => {
|
|
371
|
+
const old = orders.get(order.id);
|
|
372
|
+
if (!old || old.status !== 6 /* Working */) throw new PaperRejection("rejected", "This order has changed.");
|
|
373
|
+
if (old.symbol !== order.symbol || old.side !== order.side || parentId(old)) throw new PaperRejection("rejected", "Edit protection from the position.");
|
|
374
|
+
validate(order);
|
|
375
|
+
if (order.qty <= (old.filledQty ?? 0)) throw new PaperRejection("invalid", "Quantity must exceed the filled quantity.");
|
|
376
|
+
const updated = { ...old, ...order, filledQty: old.filledQty, avgPrice: old.avgPrice };
|
|
377
|
+
publishOrder(updated);
|
|
378
|
+
if (updated.type !== 2 /* Market */ || !automaticFills)
|
|
379
|
+
syncProtectionOrders(updated, 1 /* Order */, updated, updated.qty - (updated.filledQty ?? 0));
|
|
380
|
+
evaluate(order.symbol);
|
|
381
|
+
}),
|
|
382
|
+
cancelOrder: async (orderId) => mutate(() => {
|
|
383
|
+
const order = orders.get(orderId);
|
|
384
|
+
if (!order || !isOpenOrder(order)) throw new PaperRejection("rejected", "This order has changed.");
|
|
385
|
+
cancelOrder(order);
|
|
386
|
+
}),
|
|
387
|
+
cancelOrders: async (symbol, side, ids) => mutate(() => {
|
|
388
|
+
for (const orderId of ids) {
|
|
389
|
+
const order = orders.get(orderId);
|
|
390
|
+
if (order?.symbol === symbol && (side === void 0 || order.side === side) && isOpenOrder(order)) cancelOrder(order);
|
|
391
|
+
}
|
|
392
|
+
}),
|
|
393
|
+
closePosition: async (positionId, amount) => mutate(() => {
|
|
394
|
+
const position = positions.get(positionId);
|
|
395
|
+
if (!position) throw new PaperRejection("rejected", "The position has closed.");
|
|
396
|
+
const side = position.side === 1 /* Buy */ ? -1 /* Sell */ : 1 /* Buy */, qty = amount ?? position.qty;
|
|
397
|
+
if (!validQuantity(instrument(position.symbol), qty) || qty > position.qty) throw new PaperRejection("invalid", "Enter a valid closing quantity.");
|
|
398
|
+
fill({ id: id("close"), symbol: position.symbol, side, qty, type: 2 /* Market */, status: 6 /* Working */ }, priceFor(position.symbol, side));
|
|
399
|
+
}),
|
|
400
|
+
editPositionBrackets: async (positionId, brackets) => mutate(() => {
|
|
401
|
+
const position = positions.get(positionId);
|
|
402
|
+
if (!position) throw new PaperRejection("rejected", "The position has closed.");
|
|
403
|
+
const item = instrument(position.symbol);
|
|
404
|
+
for (const price of [brackets.takeProfit, brackets.stopLoss])
|
|
405
|
+
if (price !== void 0 && !onTick(price, item.tick)) throw new PaperRejection("invalid", "Invalid protection price.");
|
|
406
|
+
const reference = priceFor(position.symbol, position.side === 1 /* Buy */ ? -1 /* Sell */ : 1 /* Buy */);
|
|
407
|
+
validateProtection(position.side, reference, brackets);
|
|
408
|
+
protection(position, brackets);
|
|
409
|
+
}),
|
|
410
|
+
subscribePipValue(symbol) {
|
|
411
|
+
const { tick } = instrument(symbol);
|
|
412
|
+
host?.pipValueUpdate(symbol, { buyPipValue: tick, sellPipValue: tick });
|
|
413
|
+
},
|
|
414
|
+
unsubscribePipValue() {
|
|
415
|
+
},
|
|
416
|
+
subscribeEquity: () => notifyFinance(),
|
|
417
|
+
unsubscribeEquity: () => {
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
return broker;
|
|
421
|
+
};
|
|
422
|
+
return {
|
|
423
|
+
brokerFactory,
|
|
424
|
+
brokerConfig: paperBrokerConfig,
|
|
425
|
+
/** Fills the newest waiting order whose price has been reached, fully or by `amount`. */
|
|
426
|
+
fillNext(amount) {
|
|
427
|
+
guard();
|
|
428
|
+
const order = [...orders.values()].reverse().find((row) => row.status === 6 /* Working */ && !parentId(row));
|
|
429
|
+
if (!order) throw new PaperRejection("rejected", "There are no waiting orders.");
|
|
430
|
+
const price = priceFor(order.symbol, order.side);
|
|
431
|
+
if (!shouldFill(order.type, order.side, price, order.limitPrice, order.stopPrice)) throw new PaperRejection("rejected", "The order price has not been reached.");
|
|
432
|
+
fill(order, price, amount);
|
|
433
|
+
},
|
|
434
|
+
/** Makes the next broker action proceed, reject, or wait twelve seconds first. */
|
|
435
|
+
setFailure(action) {
|
|
436
|
+
next = action;
|
|
437
|
+
},
|
|
438
|
+
setConnected(value) {
|
|
439
|
+
connected = value;
|
|
440
|
+
host?.connectionStatusUpdate(value ? 1 /* Connected */ : 3 /* Disconnected */);
|
|
441
|
+
},
|
|
442
|
+
snapshot: () => ({ orders: [...orders.values()], positions: [...positions.values()], balance }),
|
|
443
|
+
dispose() {
|
|
444
|
+
disposed = true;
|
|
445
|
+
finance.dispose();
|
|
446
|
+
off();
|
|
447
|
+
for (const [timer, reject] of pending) {
|
|
448
|
+
clearTimeout(timer);
|
|
449
|
+
reject();
|
|
450
|
+
}
|
|
451
|
+
pending.clear();
|
|
452
|
+
for (const release of releases.values()) release();
|
|
453
|
+
releases.clear();
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
export {
|
|
458
|
+
PaperRejection,
|
|
459
|
+
createPaperBroker,
|
|
460
|
+
defaultQuoteMaxAgeMs,
|
|
461
|
+
executableQuote,
|
|
462
|
+
intervalFinanceSchedule,
|
|
463
|
+
netFill,
|
|
464
|
+
onTick,
|
|
465
|
+
paperBrokerConfig,
|
|
466
|
+
shouldFill,
|
|
467
|
+
validQuantity,
|
|
468
|
+
validateProtection
|
|
469
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { SymbolType } from '../contracts/broker.js';
|
|
2
|
+
/** The prices the paper broker fills against. Any quote shape with these fields works. */
|
|
3
|
+
export interface PaperQuote {
|
|
4
|
+
readonly bid?: number;
|
|
5
|
+
readonly ask?: number;
|
|
6
|
+
/** When `bid` and `ask` became tradable, in milliseconds since the epoch. Missing means not tradable. */
|
|
7
|
+
readonly executableAt?: number;
|
|
8
|
+
}
|
|
9
|
+
/** What the paper broker needs to know about a symbol it trades. */
|
|
10
|
+
export interface PaperInstrument {
|
|
11
|
+
/** The symbol shown in the order ticket. */
|
|
12
|
+
readonly symbol: string;
|
|
13
|
+
readonly description: string;
|
|
14
|
+
readonly type: SymbolType;
|
|
15
|
+
/** The quote currency: profit, loss and the account are in this currency. */
|
|
16
|
+
readonly currency: string;
|
|
17
|
+
readonly baseCurrency?: string;
|
|
18
|
+
/** The price increment. Order and protection prices must be multiples of it. */
|
|
19
|
+
readonly tick: number;
|
|
20
|
+
/** The quantity increment, which is also the smallest quantity. */
|
|
21
|
+
readonly quantityStep: number;
|
|
22
|
+
readonly defaultQuantity: number;
|
|
23
|
+
}
|
|
24
|
+
/** Whether a symbol can be traded on paper, and why not when it cannot. */
|
|
25
|
+
export type PaperInstrumentLookup = {
|
|
26
|
+
readonly tradable: true;
|
|
27
|
+
readonly instrument: PaperInstrument;
|
|
28
|
+
} | {
|
|
29
|
+
readonly tradable: false;
|
|
30
|
+
readonly reason: string;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* The host's prices and symbols, as the paper broker reads them. It keeps no
|
|
34
|
+
* market state of its own: fills always use the host's latest quote.
|
|
35
|
+
*/
|
|
36
|
+
export interface PaperMarket {
|
|
37
|
+
instrument(symbol: string): PaperInstrumentLookup;
|
|
38
|
+
quote(symbol: string): PaperQuote | undefined;
|
|
39
|
+
/** Calls `listener` with a symbol whenever its quote changes. Returns the unsubscribe function. */
|
|
40
|
+
onQuote(listener: (symbol: string) => void): () => void;
|
|
41
|
+
/**
|
|
42
|
+
* Optional: keep quotes flowing for `symbol` while the broker has working
|
|
43
|
+
* orders or a position in it. Returns the release function.
|
|
44
|
+
*/
|
|
45
|
+
demand?(symbol: string): () => void;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Coalesces account updates (P&L and equity), which can be expensive to redraw
|
|
49
|
+
* on every quote. `request` asks for one update soon; `cancel` drops a pending one.
|
|
50
|
+
*/
|
|
51
|
+
export interface PaperFinanceSchedule {
|
|
52
|
+
request(): void;
|
|
53
|
+
cancel(): void;
|
|
54
|
+
dispose(): void;
|
|
55
|
+
}
|
|
56
|
+
/** One account update at most every `intervalMs`, using timers. */
|
|
57
|
+
export declare function intervalFinanceSchedule(flush: () => void, intervalMs?: number): PaperFinanceSchedule;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { OrderType, Side } from '../contracts/broker.js';
|
|
2
|
+
import type { PaperQuote } from './market.js';
|
|
3
|
+
/** The reason codes the chart understands; see `BrokerRejection`. */
|
|
4
|
+
export type PaperRejectionCode = 'rejected' | 'unavailable' | 'invalid' | 'unsupported';
|
|
5
|
+
/**
|
|
6
|
+
* An error the chart shows to the user: it carries the `BrokerRejection` shape
|
|
7
|
+
* (`code` and a user-safe `message`). A plain Error shows generic wording instead.
|
|
8
|
+
*/
|
|
9
|
+
export declare class PaperRejection extends Error {
|
|
10
|
+
readonly code: PaperRejectionCode;
|
|
11
|
+
constructor(code: PaperRejectionCode, message: string);
|
|
12
|
+
}
|
|
13
|
+
/** How long a quote stays tradable after `executableAt`. */
|
|
14
|
+
export declare const defaultQuoteMaxAgeMs = 15000;
|
|
15
|
+
/** The price a market order on `side` fills at: the ask to buy, the bid to sell. Throws without a fresh quote. */
|
|
16
|
+
export declare function executableQuote(quote: PaperQuote | undefined, side: Side, now?: number, maxAgeMs?: number): number;
|
|
17
|
+
/** Whether an order of `type` on `side` fills at `price`. */
|
|
18
|
+
export declare function shouldFill(type: OrderType, side: Side, price: number, limit?: number, stop?: number): boolean;
|
|
19
|
+
/** A positive quantity on the instrument's step, up to one million. */
|
|
20
|
+
export declare function validQuantity(item: {
|
|
21
|
+
readonly quantityStep: number;
|
|
22
|
+
}, quantity: number): boolean;
|
|
23
|
+
/** A net position after a fill: same side adds and averages, the other side reduces, closes or reverses. */
|
|
24
|
+
export declare function netFill(previous: {
|
|
25
|
+
side: Side;
|
|
26
|
+
qty: number;
|
|
27
|
+
avgPrice: number;
|
|
28
|
+
} | undefined, side: Side, quantity: number, price: number): {
|
|
29
|
+
side: Side;
|
|
30
|
+
qty: number;
|
|
31
|
+
avgPrice: number;
|
|
32
|
+
realized: number;
|
|
33
|
+
};
|
|
34
|
+
/** Take profit must be beyond `reference` in the position's favour, and stop loss behind it. */
|
|
35
|
+
export declare function validateProtection(side: Side, reference: number, brackets: {
|
|
36
|
+
takeProfit?: number;
|
|
37
|
+
stopLoss?: number;
|
|
38
|
+
}): void;
|
|
39
|
+
/** A positive price on the instrument's tick. */
|
|
40
|
+
export declare function onTick(price: number, tick: number): boolean;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { AccountManagerInfo, AccountManagerColumn } from "../../contracts/broker.js";
|
|
2
|
+
import type { CapabilityFlags } from "../../core/capabilities.js";
|
|
3
|
+
import type { TradingFeatures } from "../../core/features.js";
|
|
4
|
+
export interface AccountPage {
|
|
5
|
+
readonly id: "positions" | "individual" | "orders" | "history" | "notifications";
|
|
6
|
+
readonly reader: "positions" | "individualPositions" | "orders" | "history";
|
|
7
|
+
readonly actions?: "orders" | "positions" | "individual";
|
|
8
|
+
title(flags: CapabilityFlags): string;
|
|
9
|
+
enabled(flags: CapabilityFlags, features: TradingFeatures): boolean;
|
|
10
|
+
columns(metadata: AccountManagerInfo | undefined): readonly AccountManagerColumn[];
|
|
11
|
+
sorting?(metadata: AccountManagerInfo | undefined): AccountManagerInfo["orderColumnsSorting"];
|
|
12
|
+
statuses?(metadata: AccountManagerInfo | undefined): readonly number[];
|
|
13
|
+
/** What an empty table says; defaults to `DEFAULT_EMPTY_MESSAGE`. */
|
|
14
|
+
readonly emptyMessage?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare const DEFAULT_EMPTY_MESSAGE = "There is no trading data here yet";
|
|
17
|
+
export declare const accountPages: readonly AccountPage[];
|
|
18
|
+
export declare function accountPage(id: string): AccountPage;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AccountManagerColumn } from "../../contracts/broker.js";
|
|
2
|
+
/** Tooltip maps use the same owned field paths as formatter inputs; broker text stays plain text. */
|
|
3
|
+
export declare function columnTooltip(row: unknown, column: AccountManagerColumn): string | undefined;
|
|
4
|
+
/** Only the two pinned price formatters opt into standard directional highlighting. */
|
|
5
|
+
export declare function columnPriceTone(column: AccountManagerColumn, values: readonly unknown[], previous?: readonly unknown[]): "positive" | "negative" | undefined;
|