Introduction
insider trading orderbook data analysis Python API is a practical way to analyze market activity from two different perspectives: orderbook data and insider trading data. Orderbook data helps us understand buy and sell activity in the market, while insider trading data helps us monitor transaction activity related to company insiders.
In this tutorial, we will use Python in Google Colab to fetch BBCA orderbook data and insider trading data from an API. Then, we will inspect the API structure, convert the data into DataFrames, and create simple visualizations so the data becomes easier to understand.
Cell 1 — Import Library
import requests
import pandas as pd
import matplotlib.pyplot as plt
import timeThis cell imports the libraries needed for the notebook. requests is used to fetch data from the API, pandas is used to process data into table format, matplotlib.pyplot is used to create visualizations, and time is used to add a delay before sending API requests.
Cell 2 — API Key Configuration
RAPIDAPI_KEY = "YOUR_RAPIDAPI_KEY_HERE"
headers = {
"Content-Type": "application/json",
"x-rapidapi-host": "indonesia-stock-exchange-idx.p.rapidapi.com",
"x-rapidapi-key": RAPIDAPI_KEY
}This cell prepares the API authentication. The RAPIDAPI_KEY is your private access key, while headers contains the required information for connecting to RapidAPI. Never publish your real API key publicly.
Cell 3 — API URL
orderbook_url = "https://indonesia-stock-exchange-idx.p.rapidapi.com/api/emiten/BBCA/orderbook"
insider_url = "https://indonesia-stock-exchange-idx.p.rapidapi.com/api/emiten/BBCA/insider?page=1&source_type=SOURCE_TYPE_UNSPECIFIED&date_end=2025-12-31&date_start=2025-11-01&limit=20&action_type=ACTION_TYPE_UNSPECIFIED"This cell defines two API endpoints. orderbook_url is used to fetch BBCA orderbook data, while insider_url is used to fetch BBCA insider trading data with filters such as page, date range, limit, source type, and action type.
Cell 4 — Function to Fetch API Data
def get_api_data(url):
time.sleep(2)
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print("Gagal mengambil data:", response.status_code)
print(response.text)
return NoneThis cell creates a reusable function called get_api_data(). The function waits for 2 seconds, sends a request to the API, checks whether the response status is successful, and returns JSON data if the request works. If the request fails, it prints the error status and response text.
Cell 5 — Fetch Orderbook and Insider Trading Data
orderbook_data = get_api_data(orderbook_url)
insider_data = get_api_data(insider_url)This cell fetches data from both endpoints. orderbook_data stores the API response from the orderbook endpoint, while insider_data stores the API response from the insider trading endpoint.
Cell 6 — Check Data Structure
print("Orderbook Data:")
print(type(orderbook_data))
print(orderbook_data.keys())
print("\nInsider Trading Data:")
print(type(insider_data))
print(insider_data.keys())This cell checks the structure of both API responses. It prints the data type and the available keys. This is important because API responses are usually nested, so we need to understand their structure before processing the data.
Cell 7 — Function to Find List Data
def cari_list_data(data, path="root"):
if isinstance(data, list):
print("List ditemukan di:", path)
return data
if isinstance(data, dict):
for key, value in data.items():
hasil = cari_list_data(value, path + " -> " + str(key))
if len(hasil) > 0:
return hasil
return []This cell creates a helper function to automatically find list data inside a nested API response. For beginners, this is useful because the main data is often hidden inside several layers of JSON.
Cell 8 — Process Orderbook Data
orderbook_list = cari_list_data(orderbook_data)
df_orderbook = pd.DataFrame(orderbook_list)
df_orderbook["sumber_api"] = "Orderbook"
df_orderbook.head()This cell extracts orderbook data using cari_list_data(), converts it into a pandas DataFrame, and adds a new column called sumber_api with the value "Orderbook". The head() function displays the first few rows.
Cell 9 — Process Insider Trading Data
insider_movement = insider_data["data"]["movement"]
if len(insider_movement) == 0:
print("Tidak ada data insider trading untuk periode dan saham yang dipilih.")
df_insider = pd.DataFrame(columns=["sumber_api"])
else:
df_insider = pd.DataFrame(insider_movement)
df_insider["sumber_api"] = "Insider Trading"
df_insider.head()This cell extracts insider trading movement data from insider_data["data"]["movement"]. If the movement data is empty, the notebook prints a message and creates an empty DataFrame. If data exists, it converts the movement data into a DataFrame and labels it as "Insider Trading".
Cell 10 — Check Insider Trading JSON Detail
import json
print(json.dumps(insider_data["data"], indent=2)[:3000])This cell prints part of the insider trading data structure in a readable JSON format. The [:3000] limit prevents the output from becoming too long.
Cell 11 — Visualize Data Count
jumlah_data = {
"Orderbook": len(df_orderbook),
"Insider Trading": len(df_insider)
}
plt.figure(figsize=(8, 5))
plt.bar(jumlah_data.keys(), jumlah_data.values())
plt.title("Jumlah Data Orderbook dan Insider Trading")
plt.xlabel("Jenis Data")
plt.ylabel("Jumlah Data")
plt.show()This cell creates a bar chart comparing the number of orderbook records and insider trading records. It helps show whether both data sources contain enough information for analysis.
Cell 12 — Visualize Orderbook Buy and Sell
print(df_orderbook.columns.tolist())
calon_bid = ["bid", "buy", "bid_price", "bidPrice", "price"]
calon_offer = ["offer", "ask", "sell", "offer_price", "offerPrice"]
calon_volume = ["volume", "lot", "qty", "quantity"]
kolom_harga = None
kolom_volume = None
for kolom in df_orderbook.columns:
if any(kata in kolom.lower() for kata in ["price", "bid", "offer", "ask"]):
kolom_harga = kolom
break
for kolom in df_orderbook.columns:
if any(kata in kolom.lower() for kata in ["volume", "lot", "qty", "quantity"]):
kolom_volume = kolom
break
if kolom_harga and kolom_volume:
df_orderbook["harga"] = pd.to_numeric(df_orderbook[kolom_harga], errors="coerce")
df_orderbook["volume"] = pd.to_numeric(df_orderbook[kolom_volume], errors="coerce")
df_plot = df_orderbook.dropna(subset=["harga", "volume"]).head(20)
plt.figure(figsize=(12, 6))
plt.bar(df_plot["harga"].astype(str), df_plot["volume"])
plt.title("Visualisasi Orderbook BBCA")
plt.xlabel("Harga")
plt.ylabel("Volume")
plt.xticks(rotation=45)
plt.show()
else:
print("Kolom harga atau volume orderbook tidak ditemukan.")
print(df_orderbook.columns.tolist())This cell visualizes orderbook data. First, it prints all available columns, then searches for possible price and volume columns automatically. If both columns are found, the data is converted into numeric values and displayed as a bar chart. If not, the notebook prints a warning and shows the available columns.
Cell 13 — Visualize Insider Trading by Action Type
if len(df_insider) == 0 or df_insider.shape[1] <= 1:
print("Visualisasi action type tidak dapat dibuat karena data insider trading kosong.")
else:
kolom_action = None
for kolom in df_insider.columns:
if "action" in kolom.lower() or "type" in kolom.lower():
kolom_action = kolom
break
if kolom_action:
jumlah_action = df_insider[kolom_action].value_counts()
plt.figure(figsize=(8, 5))
jumlah_action.plot(kind="bar")
plt.title("Jumlah Insider Trading Berdasarkan Action Type")
plt.xlabel("Action Type")
plt.ylabel("Jumlah Data")
plt.xticks(rotation=45)
plt.show()
else:
print("Kolom action type tidak ditemukan.")
print(df_insider.columns.tolist())This cell visualizes insider trading based on action type. If the insider trading data is empty, the visualization is skipped. If data exists, the code searches for an action-related column, counts each action type, and displays the result as a bar chart.
Cell 14 — Visualize Insider Trading by Date
kolom_tanggal = None
for kolom in df_insider.columns:
if "date" in kolom.lower() or "tanggal" in kolom.lower():
kolom_tanggal = kolom
break
if kolom_tanggal:
df_insider["tanggal"] = pd.to_datetime(df_insider[kolom_tanggal], errors="coerce")
df_clean = df_insider.dropna(subset=["tanggal"]).copy()
insider_harian = df_clean.groupby(df_clean["tanggal"].dt.date).size()
plt.figure(figsize=(12, 6))
insider_harian.plot(kind="line", marker="o")
plt.title("Tren Insider Trading BBCA")
plt.xlabel("Tanggal")
plt.ylabel("Jumlah Transaksi")
plt.xticks(rotation=45)
plt.show()
else:
print("Kolom tanggal insider trading tidak ditemukan.")
print(df_insider.columns.tolist())This cell analyzes insider trading trends by date. It automatically searches for a date column, converts it into datetime format, groups the data by day, and visualizes the number of insider trading transactions over time using a line chart.
Cell 15 — Analysis Conclusion
print("KESIMPULAN ANALISIS")
print("- Jumlah data Orderbook:", len(df_orderbook))
print("- Jumlah data Insider Trading:", len(df_insider))
if len(df_orderbook) > 0:
print("- Data orderbook berhasil diolah.")
if len(df_insider) > 0:
print("- Data insider trading berhasil diolah.")
print("\nAnalisis selesai. Data Orderbook dan Insider Trading berhasil divisualisasikan.")This final cell prints the analysis summary. It shows the number of orderbook records, the number of insider trading records, and whether each dataset was successfully processed.
Result:
Conclusion
insider trading orderbook data analysis Python API helps beginners understand market data by combining orderbook analysis and insider trading activity. This notebook shows a full workflow, starting from API requests, checking JSON structures, processing data into DataFrames, and creating visualizations for data count, orderbook volume, insider action types, and insider trading trends.
The key takeaway is simple: raw API data becomes more useful when it is cleaned, structured, and visualized clearly.
