File size: 4,890 Bytes
86abcb2
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86abcb2
 
 
 
740fcec
 
86abcb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc3aa02
86abcb2
 
 
 
 
740fcec
86abcb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
 
86abcb2
 
 
 
 
 
 
 
740fcec
 
 
86abcb2
 
 
 
 
 
 
 
740fcec
86abcb2
 
740fcec
 
86abcb2
740fcec
 
 
 
 
 
 
86abcb2
 
 
 
 
 
740fcec
86abcb2
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
86abcb2
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { apiClient } from './client';

export const BYBIT_SESSION_CREDS_KEY = 'perps_bybit_session_creds';

export interface BybitSessionCredentials {
  api_key: string;
  api_secret: string;
  mode: 'demo' | 'testnet' | 'real';
}

export function getStoredBybitCredentials(): BybitSessionCredentials | null {
  if (typeof window === 'undefined') return null;
  try {
    const raw = window.sessionStorage.getItem(BYBIT_SESSION_CREDS_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (parsed?.api_key && parsed?.api_secret) {
      return {
        api_key: String(parsed.api_key).trim(),
        api_secret: String(parsed.api_secret).trim(),
        mode: (parsed.mode || 'demo') as 'demo' | 'testnet' | 'real',
      };
    }
  } catch {
    // ignore malformed session storage
  }
  return null;
}

export function saveStoredBybitCredentials(creds: BybitSessionCredentials): void {
  if (typeof window === 'undefined') return;
  window.sessionStorage.setItem(BYBIT_SESSION_CREDS_KEY, JSON.stringify({
    api_key: creds.api_key.trim(),
    api_secret: creds.api_secret.trim(),
    mode: creds.mode,
  }));
}

export function clearStoredBybitCredentials(): void {
  if (typeof window === 'undefined') return;
  window.sessionStorage.removeItem(BYBIT_SESSION_CREDS_KEY);
}

function buildBybitHeaders(overrideMode?: string): Record<string, string> {
  const creds = getStoredBybitCredentials();
  if (!creds) {
    return overrideMode ? { 'X-Bybit-Mode': overrideMode } : {};
  }
  return {
    'X-Bybit-Api-Key': creds.api_key,
    'X-Bybit-Api-Secret': creds.api_secret,
    'X-Bybit-Mode': overrideMode || creds.mode,
  };
}

export interface BybitSettings {
  configured: boolean;
  masked_key: string;
  mode: 'demo' | 'testnet' | 'real';
  source?: string;
  stateless?: boolean;
}

export interface BybitWalletBalance {
  coin: string;
  available_balance: number;
  total_equity: number;
  mode: string;
  raw?: any;
}

export interface ExecuteOrderPayload {
  symbol: string;
  side: 'Buy' | 'Sell' | 'Long' | 'Short';
  order_type: 'Market' | 'Limit';
  margin_usd: number;
  margin_percent?: number | null;
  leverage: number;
  stop_loss: number;
  take_profit_1: number;
  take_profit_2?: number | null;
  tp1_percent: number;
  auto_breakeven?: boolean;
  entry_price?: number | null;
  mark_price?: number | null;
  api_key?: string;
  api_secret?: string;
  mode?: string;
  log_to_journal?: boolean;
  summary_tldr?: string;
  model_used?: string;
}

export interface ExecutionResult {
  success: boolean;
  message: string;
  execution: {
    symbol: string;
    side: string;
    order_type: string;
    margin_usd: number;
    leverage: number;
    notional_usd: number;
    total_qty: number;
    entry_order_id: string;
    stop_loss: number;
    tp_orders: Array<{
      tp_level: string;
      percent: number;
      order_id?: string;
      price: number;
      qty: number;
    }>;
    tp2_watcher_scheduled?: boolean;
    breakeven_watcher_scheduled?: boolean;
    breakeven_status?: string;
    mode: string;
    timestamp: number;
  };
  journal_entry?: any;
}

export const executionApi = {
  getSettings: async (): Promise<BybitSettings> => {
    const { data } = await apiClient.get<BybitSettings>('/api/execution/bybit/settings', {
      headers: buildBybitHeaders(),
    });
    return data;
  },

  saveSettings: async (payload: {
    api_key?: string;
    api_secret?: string;
    mode?: string;
  }): Promise<{ success: boolean; message: string; balance?: BybitWalletBalance }> => {
    const mode = (payload.mode || 'demo') as 'demo' | 'testnet' | 'real';
    const { data } = await apiClient.post<{ success: boolean; message: string; balance?: BybitWalletBalance }>(
      '/api/execution/bybit/settings',
      payload,
      { headers: buildBybitHeaders(mode) }
    );
    if (data.success && payload.api_key && payload.api_secret) {
      saveStoredBybitCredentials({
        api_key: payload.api_key,
        api_secret: payload.api_secret,
        mode,
      });
    }
    return data;
  },

  getBalance: async (mode?: string): Promise<BybitWalletBalance> => {
    const { data } = await apiClient.get<BybitWalletBalance>('/api/execution/bybit/balance', {
      params: mode ? { mode } : {},
      headers: buildBybitHeaders(mode),
    });
    return data;
  },

  executeOrder: async (payload: ExecuteOrderPayload): Promise<ExecutionResult> => {
    const creds = getStoredBybitCredentials();
    const enrichedPayload: ExecuteOrderPayload = {
      ...payload,
      api_key: payload.api_key || creds?.api_key,
      api_secret: payload.api_secret || creds?.api_secret,
      mode: payload.mode || creds?.mode,
    };
    const { data } = await apiClient.post<ExecutionResult>('/api/execution/bybit/order', enrichedPayload, {
      headers: buildBybitHeaders(enrichedPayload.mode),
    });
    return data;
  },
};