@forgecharts/sdk 1.1.23 → 1.1.27

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.
@@ -0,0 +1,156 @@
1
+ /**
2
+ * TradingBridge — host-side trading callback contract for Unmanaged mode.
3
+ *
4
+ * When a chart user performs a trading action (drag-to-place, cancel, bracket
5
+ * adjust, etc.) the chart emits a typed Intent and defers all confirmation to
6
+ * the host. The chart NEVER self-confirms order state. The host must push
7
+ * the resulting confirmed ChartOrder back via TradingOverlayStore.
8
+ *
9
+ * Usage (consumer / host app):
10
+ *
11
+ * ```tsx
12
+ * import type { TradingBridgeCallbacks } from '@forgecharts/sdk/react';
13
+ *
14
+ * const bridge: TradingBridgeCallbacks = {
15
+ * onPlaceOrderIntent: (intent) => myBroker.placeOrder(intent),
16
+ * onModifyOrderIntent: (intent) => myBroker.modifyOrder(intent),
17
+ * onCancelOrderIntent: (intent) => myBroker.cancelOrder(intent),
18
+ * onBracketAdjustIntent: (intent) => myBroker.adjustBracket(intent),
19
+ * };
20
+ *
21
+ * <ChartCanvas
22
+ * symbol="BTCUSDT"
23
+ * timeframe="1h"
24
+ * tradingBridge={bridge}
25
+ * />
26
+ * ```
27
+ *
28
+ * Debug logging:
29
+ * Wrap your callbacks with `createTradingBridgeLogger` to get structured
30
+ * console output in development:
31
+ *
32
+ * ```ts
33
+ * tradingBridge={createTradingBridgeLogger(bridge, 'MyChart')}
34
+ * ```
35
+ */
36
+
37
+ import type {
38
+ PlaceOrderIntent,
39
+ ModifyOrderIntent,
40
+ CancelOrderIntent,
41
+ BracketAdjustIntent,
42
+ } from '@forgecharts/types';
43
+
44
+ // ─── Public callback contract ─────────────────────────────────────────────────
45
+
46
+ /**
47
+ * Injectable callback bag for the chart-to-host trading bridge.
48
+ *
49
+ * All callbacks are optional — omit any you do not handle. The chart will
50
+ * still emit the intent but silently discard it if the corresponding callback
51
+ * is not provided.
52
+ *
53
+ * The return types are `void | Promise<void>` so hosts can fire-and-forget or
54
+ * await before side-effects. The chart does not await the returned promise —
55
+ * confirmation always flows back through `TradingOverlayStore`.
56
+ */
57
+ export interface TradingBridgeCallbacks {
58
+ /**
59
+ * Called when the user triggers a new order placement.
60
+ * The host should validate, forward to the broker, and then call
61
+ * `overlayStore.upsertOrder(confirmedOrder)` once acknowledged.
62
+ */
63
+ onPlaceOrderIntent?: (intent: PlaceOrderIntent) => void | Promise<void>;
64
+
65
+ /**
66
+ * Called when the user drags an order line to a new price or edits it via UI.
67
+ * The host should send the modification to the broker and update the overlay
68
+ * store with the modified order.
69
+ */
70
+ onModifyOrderIntent?: (intent: ModifyOrderIntent) => void | Promise<void>;
71
+
72
+ /**
73
+ * Called when the user clicks the cancel control on an order line.
74
+ * The host should cancel at the venue and call `overlayStore.removeOrder(id)`.
75
+ */
76
+ onCancelOrderIntent?: (intent: CancelOrderIntent) => void | Promise<void>;
77
+
78
+ /**
79
+ * Called when the user drags a bracket leg (stop-loss or take-profit).
80
+ * The host adjusts both legs atomically and updates the overlay store.
81
+ */
82
+ onBracketAdjustIntent?: (intent: BracketAdjustIntent) => void | Promise<void>;
83
+ }
84
+
85
+ // ─── Debug logger ─────────────────────────────────────────────────────────────
86
+
87
+ /**
88
+ * Wraps a `TradingBridgeCallbacks` object and logs all emitted intents to the
89
+ * console. Only active when `process.env.NODE_ENV !== 'production'`.
90
+ *
91
+ * @param callbacks The real callbacks to delegate to after logging.
92
+ * @param label Optional label prepended to log messages (e.g. chart id or symbol).
93
+ * @returns A new `TradingBridgeCallbacks` that logs then delegates.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * tradingBridge={createTradingBridgeLogger(bridge, 'BTCUSDT')}
98
+ * ```
99
+ */
100
+ export function createTradingBridgeLogger(
101
+ callbacks: TradingBridgeCallbacks,
102
+ label?: string,
103
+ ): TradingBridgeCallbacks {
104
+ if (process.env.NODE_ENV === 'production') return callbacks;
105
+
106
+ const tag = label ? `[TradingBridge:${label}]` : '[TradingBridge]';
107
+
108
+ return {
109
+ onPlaceOrderIntent: (intent) => {
110
+ console.debug(
111
+ `${tag} PLACE side=%s type=%s qty=%s price=%s stopPrice=%s correlationId=%s`,
112
+ intent.side,
113
+ intent.orderType,
114
+ intent.qty,
115
+ intent.limitPrice ?? '—',
116
+ intent.stopPrice ?? '—',
117
+ intent.correlationId,
118
+ intent,
119
+ );
120
+ return callbacks.onPlaceOrderIntent?.(intent);
121
+ },
122
+
123
+ onModifyOrderIntent: (intent) => {
124
+ console.debug(
125
+ `${tag} MODIFY orderId=%s limitPrice=%s stopPrice=%s qty=%s`,
126
+ intent.orderId,
127
+ intent.limitPrice ?? '—',
128
+ intent.stopPrice ?? '—',
129
+ intent.qty ?? '—',
130
+ intent,
131
+ );
132
+ return callbacks.onModifyOrderIntent?.(intent);
133
+ },
134
+
135
+ onCancelOrderIntent: (intent) => {
136
+ console.debug(
137
+ `${tag} CANCEL orderId=%s symbol=%s`,
138
+ intent.orderId,
139
+ intent.symbol,
140
+ intent,
141
+ );
142
+ return callbacks.onCancelOrderIntent?.(intent);
143
+ },
144
+
145
+ onBracketAdjustIntent: (intent) => {
146
+ console.debug(
147
+ `${tag} BRACKET_ADJUST entry=%s sl=%s tp=%s`,
148
+ intent.entryOrderId,
149
+ intent.stopLossPrice ?? '—',
150
+ intent.takeProfitPrice ?? '—',
151
+ intent,
152
+ );
153
+ return callbacks.onBracketAdjustIntent?.(intent);
154
+ },
155
+ };
156
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * ChartWorkspace — structural layout assembly.
3
+ *
4
+ * Renders: TabBar + TopToolbar + (ChartCanvas slots + RightToolbar) + BottomToolbar.
5
+ *
6
+ * This component is intentionally stateless — all state lives in the parent
7
+ * (ManagedAppShell). It provides the visual skeleton and prop routing only.
8
+ */
9
+
10
+ import React from 'react';
11
+ import { TabBar } from './TabBar';
12
+ import type { TabItem } from './TabBar';
13
+ import { TopToolbar } from './toolbars/TopToolbar';
14
+ import { RightToolbar } from './toolbars/RightToolbar';
15
+ import { BottomToolbar } from './toolbars/BottomToolbar';
16
+ import type { TradingSession } from './toolbars/BottomToolbar';
17
+ import type { LayoutRecord } from './LayoutMenu';
18
+ import type { ChartTheme, IndicatorConfig, ISymbolResolver } from '@forgecharts/types';
19
+
20
+ export type { TradingSession };
21
+
22
+ export type ChartWorkspaceProps = {
23
+ // ── TabBar ─────────────────────────────────────────────────────────────────
24
+ tabs: Array<{ id: string; label: string; isSaved?: boolean }>;
25
+ activeTabId: string;
26
+ onSelectTab: (id: string) => void;
27
+ onAddTab: () => void;
28
+ onCloseTab: (id: string) => void;
29
+ onRenameTab: (id: string, label: string) => void;
30
+ // ── TopToolbar ─────────────────────────────────────────────────────────────
31
+ symbol: string;
32
+ timeframe: string;
33
+ theme: ChartTheme;
34
+ customTimeframes: string[];
35
+ favoriteTfs: string[];
36
+ onSymbolChange: (s: string) => void;
37
+ onTimeframeChange: (tf: string) => void;
38
+ onAddCustomTimeframe: (tf: string) => void;
39
+ onFavoriteTfsChange: (favs: string[]) => void;
40
+ onAddIndicator: (config: IndicatorConfig) => void;
41
+ onToggleTheme: () => void;
42
+ onCopyScreenshot: () => void;
43
+ onDownloadScreenshot: () => void;
44
+ onFullscreen: () => void;
45
+ isFullscreen: boolean;
46
+ currentLayoutName?: string;
47
+ currentLayoutId?: string;
48
+ autoSave: boolean;
49
+ onFetchLayouts: () => Promise<LayoutRecord[]>;
50
+ onSaveLayout: (name: string) => Promise<void>;
51
+ onLoadLayout: (id: string) => Promise<void>;
52
+ onRenameLayout: (name: string) => Promise<void>;
53
+ onCopyLayout: (name: string) => Promise<void>;
54
+ onToggleAutoSave: (enabled: boolean) => void;
55
+ /** Resolver used by the symbol search dialog. */
56
+ symbolResolver: ISymbolResolver;
57
+ onDeleteLayout: (id: string) => Promise<void>;
58
+ onOpenLayoutInNewTab: (id: string) => Promise<void>;
59
+ // ── RightToolbar ────────────────────────────────────────────────────────────
60
+
61
+ watchlistOpen: boolean;
62
+ onToggleWatchlist: () => void;
63
+ // ── BottomToolbar ───────────────────────────────────────────────────────────
64
+ activeSymbol: string;
65
+ timezone: string;
66
+ onTimezoneChange: (tz: string) => void;
67
+ session: TradingSession;
68
+ onSessionChange: (s: TradingSession) => void;
69
+ scriptDrawerOpen: boolean;
70
+ onToggleScriptDrawer: () => void;
71
+ // ── Trade button (TopToolbar) ────────────────────────────────────────────────
72
+ showTradeButton?: boolean;
73
+ tradeDrawerOpen?: boolean;
74
+ onToggleTradeDrawer?: () => void;
75
+ // ── Chart slot (parent renders all tab charts) ───────────────────────────────
76
+ chartSlots: React.ReactNode;
77
+ // ── Unlicensed overlay ───────────────────────────────────────────────────────
78
+ isLicensed: boolean;
79
+ // ── Loading overlay ──────────────────────────────────────────────────────────
80
+ wsLoaded: boolean;
81
+ // ── Drawers (passed through as assembled React nodes) ────────────────────────
82
+ drawers?: React.ReactNode;
83
+ };
84
+
85
+ // ─── Re-export TabItem for consumers ─────────────────────────────────────────
86
+ export type { TabItem };
87
+
88
+ export function ChartWorkspace({
89
+ // TabBar
90
+ tabs, activeTabId, onSelectTab, onAddTab, onCloseTab, onRenameTab,
91
+ // TopToolbar
92
+ symbol, timeframe, theme, customTimeframes, favoriteTfs,
93
+ onSymbolChange, onTimeframeChange, onAddCustomTimeframe, onFavoriteTfsChange,
94
+ onAddIndicator, onToggleTheme, onCopyScreenshot, onDownloadScreenshot,
95
+ onFullscreen, isFullscreen, currentLayoutName, currentLayoutId, autoSave,
96
+ onFetchLayouts, onSaveLayout, onLoadLayout, onRenameLayout, onCopyLayout,
97
+ onToggleAutoSave, onDeleteLayout, onOpenLayoutInNewTab,
98
+ showTradeButton, tradeDrawerOpen, onToggleTradeDrawer, symbolResolver,
99
+ // RightToolbar
100
+ watchlistOpen, onToggleWatchlist,
101
+ // BottomToolbar
102
+ activeSymbol, timezone, onTimezoneChange, session, onSessionChange,
103
+ scriptDrawerOpen, onToggleScriptDrawer,
104
+ // Chart + state
105
+ chartSlots, isLicensed, wsLoaded, drawers,
106
+ }: ChartWorkspaceProps) {
107
+ const tabItems: TabItem[] = tabs.map((t) => ({
108
+ id: t.id,
109
+ label: t.label,
110
+ ...(t.isSaved !== undefined ? { isSaved: t.isSaved } : {}),
111
+ }));
112
+
113
+ return (
114
+ <div
115
+ style={{
116
+ display: 'flex',
117
+ flexDirection: 'column',
118
+ height: '100%',
119
+ background: 'var(--shelf-bg)',
120
+ padding: 6,
121
+ gap: 4,
122
+ }}
123
+ >
124
+ {/* ── Loading overlay ──────────────────────────────────────────────── */}
125
+ {!wsLoaded && (
126
+ <div style={{
127
+ position: 'absolute', inset: 0, display: 'flex',
128
+ alignItems: 'center', justifyContent: 'center',
129
+ background: 'var(--bg)', zIndex: 1000,
130
+ }}>
131
+ <svg width="32" height="32" viewBox="0 0 32 32" style={{ animation: 'spin 0.9s linear infinite' }}>
132
+ <circle cx="16" cy="16" r="12" fill="none" stroke="var(--border)" strokeWidth="3" />
133
+ <path d="M16 4 A12 12 0 0 1 28 16" fill="none" stroke="var(--primary)" strokeWidth="3" strokeLinecap="round" />
134
+ </svg>
135
+ <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
136
+ </div>
137
+ )}
138
+
139
+ <TabBar
140
+ tabs={tabItems}
141
+ activeId={activeTabId}
142
+ onSelect={onSelectTab}
143
+ onAdd={onAddTab}
144
+ onClose={onCloseTab}
145
+ onRename={onRenameTab}
146
+ />
147
+
148
+ {/* ── Top toolbar ──────────────────────────────────────────────────── */}
149
+ <TopToolbar
150
+ symbol={symbol}
151
+ timeframe={timeframe}
152
+ theme={theme}
153
+ customTimeframes={customTimeframes}
154
+ favorites={favoriteTfs}
155
+ onSymbolChange={onSymbolChange}
156
+ onTimeframeChange={onTimeframeChange}
157
+ onAddCustomTimeframe={onAddCustomTimeframe}
158
+ onFavoritesChange={onFavoriteTfsChange}
159
+ onAddIndicator={onAddIndicator}
160
+ onToggleTheme={onToggleTheme}
161
+ onCopyScreenshot={onCopyScreenshot}
162
+ onDownloadScreenshot={onDownloadScreenshot}
163
+ onFullscreen={onFullscreen}
164
+ isFullscreen={isFullscreen}
165
+ currentLayoutName={currentLayoutName}
166
+ currentLayoutId={currentLayoutId}
167
+ autoSave={autoSave}
168
+ onFetchLayouts={onFetchLayouts}
169
+ onSaveLayout={onSaveLayout}
170
+ onLoadLayout={onLoadLayout}
171
+ onRenameLayout={onRenameLayout}
172
+ onCopyLayout={onCopyLayout}
173
+ onToggleAutoSave={onToggleAutoSave}
174
+ onDeleteLayout={onDeleteLayout}
175
+ onOpenLayoutInNewTab={onOpenLayoutInNewTab}
176
+ symbolResolver={symbolResolver}
177
+ {...(showTradeButton !== undefined ? { showTradeButton } : {})}
178
+ {...(tradeDrawerOpen !== undefined ? { tradeDrawerOpen } : {})}
179
+ {...(onToggleTradeDrawer !== undefined ? { onToggleTradeDrawer } : {})}
180
+ />
181
+
182
+ {/* ── Chart area ───────────────────────────────────────────────────── */}
183
+ <div style={{ flex: 1, display: 'flex', gap: 8, minHeight: 0, overflow: 'hidden' }}>
184
+ <div style={{ position: 'relative', flex: 1, display: 'flex', gap: 8, minWidth: 0, minHeight: 0 }}>
185
+ {/* Unlicensed overlay */}
186
+ {!isLicensed && (
187
+ <div style={{
188
+ position: 'absolute', inset: 0, zIndex: 100,
189
+ background: 'rgba(0,0,0,0.6)',
190
+ backdropFilter: 'blur(4px)',
191
+ display: 'flex', flexDirection: 'column',
192
+ alignItems: 'center', justifyContent: 'center',
193
+ gap: 12,
194
+ }}>
195
+ <svg viewBox="0 0 24 24" width="40" height="40" fill="none" stroke="rgba(255,255,255,0.7)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
196
+ <rect x="3" y="11" width="18" height="11" rx="2" />
197
+ <path d="M7 11V7a5 5 0 0110 0v4" />
198
+ </svg>
199
+ <div style={{ color: '#fff', fontWeight: 700, fontSize: 18, letterSpacing: '0.01em' }}>Unlicensed</div>
200
+ <div style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>Please activate your license in the admin studio</div>
201
+ </div>
202
+ )}
203
+ {/* Chart instance slots */}
204
+ <div style={{ position: 'relative', flex: 1, minWidth: 0, minHeight: 0 }}>
205
+ {chartSlots}
206
+ </div>
207
+ <RightToolbar
208
+ watchlistOpen={watchlistOpen}
209
+ onToggleWatchlist={onToggleWatchlist}
210
+ />
211
+ </div>
212
+ {/* Drawer panels passed from parent (ScriptDrawer, WatchlistDrawer) */}
213
+ {drawers}
214
+ </div>
215
+
216
+ {/* ── Bottom bar ───────────────────────────────────────────────────── */}
217
+ <BottomToolbar
218
+ symbol={activeSymbol}
219
+ timezone={timezone}
220
+ onTimezoneChange={onTimezoneChange}
221
+ session={session}
222
+ onSessionChange={onSessionChange}
223
+ onToggleScriptDrawer={onToggleScriptDrawer}
224
+ scriptDrawerOpen={scriptDrawerOpen}
225
+ />
226
+ </div>
227
+ );
228
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * FloatingPanel — a draggable, resizable floating panel shell.
3
+ *
4
+ * Renders `position: fixed` with a title bar (drag to move) and 8 resize
5
+ * handles (edges + corners). Pass panel content as `children`.
6
+ */
7
+
8
+ import { useRef, useState } from 'react';
9
+
10
+ type Pos = { x: number; y: number };
11
+ type Size = { w: number; h: number };
12
+
13
+ type Props = {
14
+ title: React.ReactNode;
15
+ onClose: () => void;
16
+ defaultWidth?: number;
17
+ defaultHeight?: number;
18
+ minWidth?: number;
19
+ minHeight?: number;
20
+ children: React.ReactNode;
21
+ };
22
+
23
+ export function FloatingPanel({
24
+ title,
25
+ onClose,
26
+ defaultWidth = 380,
27
+ defaultHeight = 520,
28
+ minWidth = 200,
29
+ minHeight = 120,
30
+ children,
31
+ }: Props) {
32
+ const [pos, setPos] = useState<Pos>(() => ({
33
+ x: Math.max(0, window.innerWidth - defaultWidth - 24),
34
+ y: 72,
35
+ }));
36
+ const [size, setSize] = useState<Size>({ w: defaultWidth, h: defaultHeight });
37
+
38
+ // Refs capture drag-start values to avoid stale-closure accumulation
39
+ const moveRef = useRef<{ ox: number; oy: number; px: number; py: number } | null>(null);
40
+ const resizeRef = useRef<{
41
+ edges: string;
42
+ ox: number; oy: number;
43
+ pw: number; ph: number;
44
+ px: number; py: number;
45
+ } | null>(null);
46
+
47
+ // ── Drag to move ──────────────────────────────────────────────────────────
48
+ const startMove = (e: React.MouseEvent) => {
49
+ if ((e.target as HTMLElement).closest('.fp-close')) return;
50
+ e.preventDefault();
51
+ moveRef.current = { ox: e.clientX, oy: e.clientY, px: pos.x, py: pos.y };
52
+ const onMove = (ev: MouseEvent) => {
53
+ if (!moveRef.current) return;
54
+ setPos({
55
+ x: moveRef.current.px + ev.clientX - moveRef.current.ox,
56
+ y: moveRef.current.py + ev.clientY - moveRef.current.oy,
57
+ });
58
+ };
59
+ const onUp = () => {
60
+ moveRef.current = null;
61
+ window.removeEventListener('mousemove', onMove);
62
+ window.removeEventListener('mouseup', onUp);
63
+ };
64
+ window.addEventListener('mousemove', onMove);
65
+ window.addEventListener('mouseup', onUp);
66
+ };
67
+
68
+ // ── Resize from any edge/corner ───────────────────────────────────────────
69
+ const startResize = (e: React.MouseEvent, edges: string) => {
70
+ e.preventDefault();
71
+ e.stopPropagation();
72
+ resizeRef.current = {
73
+ edges,
74
+ ox: e.clientX, oy: e.clientY,
75
+ pw: size.w, ph: size.h,
76
+ px: pos.x, py: pos.y,
77
+ };
78
+ const onMove = (ev: MouseEvent) => {
79
+ if (!resizeRef.current) return;
80
+ const { edges: ed, ox, oy, pw, ph, px, py } = resizeRef.current;
81
+ const dx = ev.clientX - ox;
82
+ const dy = ev.clientY - oy;
83
+ let nx = px, ny = py, nw = pw, nh = ph;
84
+ if (ed.includes('e')) nw = Math.max(minWidth, pw + dx);
85
+ if (ed.includes('s')) nh = Math.max(minHeight, ph + dy);
86
+ if (ed.includes('w')) { nw = Math.max(minWidth, pw - dx); nx = px + pw - nw; }
87
+ if (ed.includes('n')) { nh = Math.max(minHeight, ph - dy); ny = py + ph - nh; }
88
+ setSize({ w: nw, h: nh });
89
+ setPos({ x: nx, y: ny });
90
+ };
91
+ const onUp = () => {
92
+ resizeRef.current = null;
93
+ window.removeEventListener('mousemove', onMove);
94
+ window.removeEventListener('mouseup', onUp);
95
+ };
96
+ window.addEventListener('mousemove', onMove);
97
+ window.addEventListener('mouseup', onUp);
98
+ };
99
+
100
+ return (
101
+ <div
102
+ className="fp-shell"
103
+ style={{ left: pos.x, top: pos.y, width: size.w, height: size.h }}
104
+ >
105
+ {/* Title bar — drag handle */}
106
+ <div className="fp-titlebar" onMouseDown={startMove}>
107
+ <span className="fp-title">{title}</span>
108
+ <button className="fp-close" onClick={onClose} title="Close">
109
+ <svg viewBox="0 0 14 14" width="12" height="12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
110
+ <line x1="2" y1="2" x2="12" y2="12" />
111
+ <line x1="12" y1="2" x2="2" y2="12" />
112
+ </svg>
113
+ </button>
114
+ </div>
115
+
116
+ {/* Content */}
117
+ <div className="fp-content">{children}</div>
118
+
119
+ {/* Edge resize handles */}
120
+ <div className="fp-resize fp-resize-n" onMouseDown={(e) => startResize(e, 'n')} />
121
+ <div className="fp-resize fp-resize-s" onMouseDown={(e) => startResize(e, 's')} />
122
+ <div className="fp-resize fp-resize-e" onMouseDown={(e) => startResize(e, 'e')} />
123
+ <div className="fp-resize fp-resize-w" onMouseDown={(e) => startResize(e, 'w')} />
124
+ {/* Corner resize handles */}
125
+ <div className="fp-resize fp-resize-nw" onMouseDown={(e) => startResize(e, 'nw')} />
126
+ <div className="fp-resize fp-resize-ne" onMouseDown={(e) => startResize(e, 'ne')} />
127
+ <div className="fp-resize fp-resize-sw" onMouseDown={(e) => startResize(e, 'sw')} />
128
+ <div className="fp-resize fp-resize-se" onMouseDown={(e) => startResize(e, 'se')} />
129
+ </div>
130
+ );
131
+ }