File size: 8,755 Bytes
5024af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff9cc9
5024af9
 
 
 
 
 
 
 
 
 
 
0ff9cc9
5024af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff9cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5024af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff9cc9
5024af9
 
0ff9cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5024af9
0ff9cc9
 
5024af9
 
 
0ff9cc9
5024af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff9cc9
5024af9
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff9cc9
5024af9
 
 
 
 
0ff9cc9
 
 
5024af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff9cc9
 
5024af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ff9cc9
5024af9
 
 
 
 
 
 
 
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import gradio as gr
import pandas as pd
import requests
from prophet import Prophet
import logging

logging.basicConfig(level=logging.INFO)

########################################
# OKX endpoints & utility
########################################

OKX_TICKERS_ENDPOINT = "https://www.okx.com/api/v5/market/tickers?instType=SPOT"
OKX_CANDLE_ENDPOINT = "https://www.okx.com/api/v5/market/candles"

# For demonstration, only these mappings
TIMEFRAME_MAPPING = {
    "1m": "1m",
    "5m": "5m",
    "15m": "15m",
    "30m": "30m",
    "1h": "1H",
    "2h": "2H",
    "4h": "4H",
    "6h": "6H",
    "12h": "12H",
    "1d": "1D",
    "1w": "1W",
}

def fetch_okx_symbols():
    """
    Fetch the list of symbols (instId) from OKX Spot tickers.
    """
    logging.info("Fetching symbols from OKX Spot tickers...")
    try:
        resp = requests.get(OKX_TICKERS_ENDPOINT, timeout=30)
        resp.raise_for_status()
        json_data = resp.json()

        if json_data.get("code") != "0":
            logging.error(f"Non-zero code returned: {json_data}")
            return ["Error: Could not fetch OKX symbols"]

        data = json_data.get("data", [])
        # Example item in data: { "instId": "ETH-USDT", "instType": "SPOT", ... }
        symbols = [item["instId"] for item in data if item.get("instType") == "SPOT"]
        if not symbols:
            logging.warning("No spot symbols found.")
            return ["Error: No spot symbols found."]
        
        logging.info(f"Fetched {len(symbols)} OKX spot symbols.")
        return sorted(symbols)

    except Exception as e:
        logging.error(f"Error fetching OKX symbols: {e}")
        return [f"Error: {str(e)}"]

def fetch_okx_candles(symbol, timeframe="1H", limit=100):
    """
    Fetch historical candle data for a symbol from OKX.

    OKX data columns:
    [ts, o, h, l, c, vol, volCcy, volCcyQuote, confirm]

    Example:
    [
      "1597026383085",  # ts
      "3.721",          # o
      "3.743",          # h
      "3.677",          # l
      "3.708",          # c
      "8422410",        # vol
      "22698348.04828491",  # volCcy
      "12698348.04828491",  # volCcyQuote
      "0"               # confirm
    ]
    """
    logging.info(f"Fetching {limit} candles for {symbol} @ {timeframe} from OKX...")
    params = {
        "instId": symbol,
        "bar": timeframe,
        "limit": limit
    }

    try:
        resp = requests.get(OKX_CANDLE_ENDPOINT, params=params, timeout=30)
        resp.raise_for_status()
        json_data = resp.json()

        if json_data.get("code") != "0":
            msg = f"OKX returned code={json_data.get('code')}, msg={json_data.get('msg')}"
            logging.error(msg)
            return pd.DataFrame(), msg

        items = json_data.get("data", [])
        if not items:
            warning_msg = f"No candle data returned for {symbol}."
            logging.warning(warning_msg)
            return pd.DataFrame(), warning_msg
        
        # OKX returns newest data first, so reverse to chronological
        items.reverse()

        # Expecting 9 columns per the docs
        columns = [
            "ts",       # timestamp
            "o",        # open
            "h",        # high
            "l",        # low
            "c",        # close
            "vol",      # volume (base currency)
            "volCcy",   # volume in quote currency (for SPOT)
            "volCcyQuote", 
            "confirm"
        ]
        df = pd.DataFrame(items, columns=columns)

        # Rename columns to be more descriptive or consistent
        df.rename(columns={
            "ts": "timestamp",
            "o": "open",
            "h": "high",
            "l": "low",
            "c": "close"
        }, inplace=True)

        # Convert numeric columns
        # 'confirm' often is "0" or "1" string, which you can parse as float or int if you want
        df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
        numeric_cols = ["open", "high", "low", "close", "vol", "volCcy", "volCcyQuote", "confirm"]
        df[numeric_cols] = df[numeric_cols].astype(float)

        logging.info(f"Fetched {len(df)} rows for {symbol}.")
        return df, ""

    except Exception as e:
        err_msg = f"Error fetching candles for {symbol}: {e}"
        logging.error(err_msg)
        return pd.DataFrame(), err_msg

########################################
# Prophet pipeline
########################################

def prepare_data_for_prophet(df):
    """
    Convert the DataFrame to a Prophet-compatible format.
    """
    if df.empty:
        logging.warning("Empty DataFrame, cannot prepare data for Prophet.")
        return pd.DataFrame(columns=["ds", "y"])

    df_prophet = df.rename(columns={"timestamp": "ds", "close": "y"})
    return df_prophet[["ds", "y"]]

def prophet_forecast(df_prophet, periods=10, freq="H"):
    """
    Train a Prophet model and forecast.
    """
    if df_prophet.empty:
        logging.warning("Prophet input is empty, no forecast can be generated.")
        return pd.DataFrame(), "No data to forecast."

    try:
        model = Prophet()
        model.fit(df_prophet)
        future = model.make_future_dataframe(periods=periods, freq=freq)
        forecast = model.predict(future)
        return forecast, ""
    except Exception as e:
        logging.error(f"Forecast error: {e}")
        return pd.DataFrame(), f"Forecast error: {e}"

def prophet_wrapper(df_prophet, forecast_steps, freq):
    """
    Do the forecast, then slice out the new/future rows.
    """
    if len(df_prophet) < 10:
        return pd.DataFrame(), "Not enough data for forecasting (need >=10 rows)."

    full_forecast, err = prophet_forecast(df_prophet, forecast_steps, freq)
    if err:
        return pd.DataFrame(), err

    # Only keep newly generated portion
    future_only = full_forecast.iloc[len(df_prophet):, ["ds", "yhat", "yhat_lower", "yhat_upper"]]
    return future_only, ""

########################################
# Main Gradio logic
########################################

def predict(symbol, timeframe, forecast_steps):
    """
    Orchestrate candle fetch + prophet forecast.
    """
    # Convert user timeframe to OKX bar param
    okx_bar = TIMEFRAME_MAPPING.get(timeframe, "1H")

    # Let's fetch 500 candles
    df_raw, err = fetch_okx_candles(symbol, timeframe=okx_bar, limit=500)
    if err:
        return pd.DataFrame(), err

    df_prophet = prepare_data_for_prophet(df_raw)

    # We'll guess the freq for Prophet: if timeframe has 'h', let's use 'H', else 'D'
    freq = "H" if "h" in timeframe.lower() else "D"

    future_df, err2 = prophet_wrapper(df_prophet, forecast_steps, freq)
    if err2:
        return pd.DataFrame(), err2

    return future_df, ""

def display_forecast(symbol, timeframe, forecast_steps):
    """
    For the Gradio UI, returns forecast or error message.
    """
    logging.info(f"User requested: symbol={symbol}, timeframe={timeframe}, steps={forecast_steps}")
    forecast_df, error = predict(symbol, timeframe, forecast_steps)
    if error:
        return f"Error: {error}"
    return forecast_df

def main():
    # Fetch OKX symbols
    symbols = fetch_okx_symbols()
    if not symbols or "Error" in symbols[0]:
        symbols = ["No symbols available"]

    with gr.Blocks() as demo:
        gr.Markdown("# OKX Price Forecasting with Prophet")
        gr.Markdown(
            "This app uses OKX's spot market candles to predict future price movements. "
            "It requests up to 500 candles (1,440 max on OKX side). If you get errors, "
            "please try a different symbol or timeframe."
        )

        symbol_dd = gr.Dropdown(
            label="Symbol",
            choices=symbols,
            value=symbols[0] if symbols else None
        )
        timeframe_dd = gr.Dropdown(
            label="Timeframe",
            choices=["1m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "12h", "1d", "1w"],
            value="1h"
        )
        steps_slider = gr.Slider(
            label="Forecast Steps (hours/days depending on timeframe)",
            minimum=1,
            maximum=100,
            value=10
        )
        forecast_btn = gr.Button("Generate Forecast")

        output_df = gr.Dataframe(
            label="Future Forecast Only",
            headers=["ds", "yhat", "yhat_lower", "yhat_upper"]
        )

        forecast_btn.click(
            fn=display_forecast,
            inputs=[symbol_dd, timeframe_dd, steps_slider],
            outputs=output_df
        )

        gr.Markdown(
            "Need more tools? Check out this "
            "[crypto trading bot](https://www.gunbot.com)."
        )

    return demo

if __name__ == "__main__":
    app = main()
    app.launch()