forked from piraterobot0/Tracking-Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatcher.exs
More file actions
452 lines (385 loc) · 13.4 KB
/
watcher.exs
File metadata and controls
452 lines (385 loc) · 13.4 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#!/usr/bin/env elixir
# Derive Options Market Watcher - Standalone Version
#
# This script monitors Derive protocol ETH options markets and identifies trading opportunities.
# It scans all available ETH options, calculates spreads, volumes, and opportunity scores.
#
# Usage:
# elixir watcher.exs [output_dir]
#
# Output:
# - JSON files with market data snapshots
# - Opportunity scores for each instrument
# - Spread and volume analytics
Mix.install([
{:httpoison, "~> 2.0"},
{:jason, "~> 1.4"},
{:decimal, "~> 2.0"}
])
defmodule MarketConfig do
@moduledoc """
Configuration for market scanning.
Replace with your own configuration values.
"""
def get_config do
%{
# API Configuration - REPLACE WITH YOUR VALUES
api_key: System.get_env("DERIVE_API_KEY") || "YOUR_API_KEY_HERE",
api_secret: System.get_env("DERIVE_API_SECRET") || "YOUR_API_SECRET_HERE",
subaccount_id: System.get_env("DERIVE_SUBACCOUNT_ID") || "YOUR_SUBACCOUNT_ID",
# API Endpoints
rpc_url: System.get_env("DERIVE_RPC_URL") || "https://api.derive.xyz",
# Scanning Parameters
days_ahead: 90, # How many days ahead to scan
strike_range_percent: 50, # +/- 50% from current ETH price
min_volume_threshold: 0.1, # Minimum 24h volume to consider
# Output Configuration
output_dir: System.get_env("MARKET_DATA_DIR") || "market_data",
save_to_file: true,
verbose: true
}
end
end
defmodule DeriveAPI do
@moduledoc """
Simplified Derive API client for market data.
"""
def get_instruments(config) do
case make_request(config, "public/get_instruments", %{currency: "ETH", kind: "option"}) do
{:ok, %{"result" => instruments}} -> {:ok, instruments}
error -> error
end
end
def get_orderbook(config, instrument_name) do
params = %{instrument_name: instrument_name, depth: 10}
case make_request(config, "public/get_order_book", params) do
{:ok, %{"result" => orderbook}} -> {:ok, orderbook}
error -> error
end
end
def get_ticker(config, instrument_name) do
params = %{instrument_name: instrument_name}
case make_request(config, "public/ticker", params) do
{:ok, %{"result" => ticker}} -> {:ok, ticker}
error -> error
end
end
def get_index_price(config, index_name \\ "eth_usd") do
case make_request(config, "public/get_index_price", %{index_name: index_name}) do
{:ok, %{"result" => %{"index_price" => price}}} -> {:ok, price}
error -> error
end
end
defp make_request(config, method, params) do
url = "#{config.rpc_url}/api/v2/#{method}"
headers = [
{"Content-Type", "application/json"},
{"Accept", "application/json"}
]
body = Jason.encode!(%{
jsonrpc: "2.0",
method: method,
params: params,
id: :os.system_time(:millisecond)
})
case HTTPoison.post(url, body, headers, timeout: 10_000, recv_timeout: 10_000) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
Jason.decode(body)
{:ok, %HTTPoison.Response{status_code: code}} ->
{:error, "HTTP #{code}"}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, reason}
end
end
end
defmodule MarketAnalyzer do
@moduledoc """
Analyzes market data and calculates opportunity scores.
"""
def calculate_opportunity_score(market_data) do
spread_score = calculate_spread_score(market_data.spread_dollars)
volume_score = calculate_volume_score(market_data.volume_24h)
oi_score = calculate_oi_score(market_data.open_interest)
competition_score = calculate_competition_score(market_data.spread_dollars)
# Weighted average
score = (spread_score * 0.4 +
volume_score * 0.3 +
oi_score * 0.2 +
competition_score * 0.1)
%{
total_score: round(score),
spread_score: spread_score,
volume_score: volume_score,
oi_score: oi_score,
competition_score: competition_score
}
end
defp calculate_spread_score(spread) do
cond do
spread < 1 -> 20 # Too tight, heavy competition
spread >= 1 and spread <= 3 -> 60
spread > 3 and spread <= 10 -> 100 # Sweet spot
spread > 10 and spread <= 20 -> 80
spread > 20 -> 40 # Too wide, likely illiquid
end
end
defp calculate_volume_score(volume) do
cond do
volume < 10 -> 10
volume >= 10 and volume < 50 -> 40
volume >= 50 and volume < 100 -> 70
volume >= 100 -> 100
end
end
defp calculate_oi_score(oi) do
cond do
oi < 10 -> 20
oi >= 10 and oi < 50 -> 50
oi >= 50 and oi < 100 -> 80
oi >= 100 -> 100
end
end
defp calculate_competition_score(spread) do
cond do
spread < 0.5 -> 10 # Extreme competition
spread >= 0.5 and spread < 1 -> 30
spread >= 1 and spread < 5 -> 70
spread >= 5 -> 100 # Low competition
end
end
def analyze_instruments(instruments) do
instruments
|> Enum.map(fn inst ->
scores = calculate_opportunity_score(inst)
Map.put(inst, :opportunity_scores, scores)
end)
|> Enum.sort_by(fn inst -> -inst.opportunity_scores.total_score end)
end
end
defmodule MarketWatcher do
@moduledoc """
Main market watching logic.
"""
def run(config \\ MarketConfig.get_config()) do
IO.puts("\n=== Derive Options Market Watcher ===")
IO.puts("Starting market scan at #{DateTime.utc_now()}")
# Get current ETH price
eth_price = case DeriveAPI.get_index_price(config) do
{:ok, price} ->
IO.puts("Current ETH Price: $#{Float.round(price, 2)}")
price
{:error, _} ->
IO.puts("Warning: Could not fetch ETH price, using default 3800")
3800.0
end
# Get all instruments
IO.puts("\nFetching available instruments...")
instruments = case DeriveAPI.get_instruments(config) do
{:ok, instruments} ->
filtered = filter_instruments(instruments, eth_price, config)
IO.puts("Found #{length(filtered)} relevant instruments")
filtered
{:error, reason} ->
IO.puts("Error fetching instruments: #{inspect(reason)}")
[]
end
# Scan each instrument
IO.puts("\nScanning orderbooks and tickers...")
market_data = scan_instruments(instruments, config)
# Analyze opportunities
IO.puts("\nAnalyzing opportunities...")
analyzed_data = MarketAnalyzer.analyze_instruments(market_data)
# Save results
if config.save_to_file do
save_results(analyzed_data, config)
end
# Display top opportunities
display_top_opportunities(analyzed_data)
analyzed_data
end
defp filter_instruments(instruments, eth_price, config) do
min_strike = eth_price * (1 - config.strike_range_percent / 100)
max_strike = eth_price * (1 + config.strike_range_percent / 100)
max_expiry = DateTime.utc_now()
|> DateTime.add(config.days_ahead * 24 * 3600, :second)
instruments
|> Enum.filter(fn inst ->
inst["is_active"] and
inst["kind"] == "option" and
parse_strike(inst["instrument_name"]) >= min_strike and
parse_strike(inst["instrument_name"]) <= max_strike and
parse_expiry(inst["instrument_name"]) <= max_expiry
end)
end
defp scan_instruments(instruments, config) do
total = length(instruments)
instruments
|> Enum.with_index(1)
|> Enum.map(fn {inst, idx} ->
if config.verbose and rem(idx, 10) == 0 do
IO.write("\rProgress: #{idx}/#{total}")
end
instrument_name = inst["instrument_name"]
# Get orderbook
orderbook_data = case DeriveAPI.get_orderbook(config, instrument_name) do
{:ok, data} -> data
{:error, _} -> %{"bids" => [], "asks" => []}
end
# Get ticker
ticker_data = case DeriveAPI.get_ticker(config, instrument_name) do
{:ok, data} -> data
{:error, _} -> %{}
end
# Process data
process_instrument_data(inst, orderbook_data, ticker_data)
end)
|> Enum.filter(fn data -> data != nil end)
end
defp process_instrument_data(instrument, orderbook, ticker) do
best_bid = get_best_price(orderbook["bids"], :bid)
best_ask = get_best_price(orderbook["asks"], :ask)
if best_bid && best_ask do
%{
instrument_name: instrument["instrument_name"],
strike: parse_strike(instrument["instrument_name"]),
type: parse_type(instrument["instrument_name"]),
expiry: parse_expiry_string(instrument["instrument_name"]),
days_to_expiry: calculate_days_to_expiry(instrument["instrument_name"]),
best_bid: best_bid,
best_ask: best_ask,
spread_dollars: Float.round(best_ask - best_bid, 2),
spread_percent: Float.round((best_ask - best_bid) / best_ask * 100, 2),
volume_24h: ticker["stats"]["volume"] || 0,
open_interest: ticker["open_interest"] || 0,
greeks: %{
delta: ticker["greeks"]["delta"] || 0,
gamma: ticker["greeks"]["gamma"] || 0,
theta: ticker["greeks"]["theta"] || 0,
vega: ticker["greeks"]["vega"] || 0,
iv: ticker["mark_iv"] || 0
},
timestamp: DateTime.utc_now() |> DateTime.to_iso8601()
}
else
nil
end
end
defp get_best_price([], _), do: nil
defp get_best_price(orders, _) when is_list(orders) do
case List.first(orders) do
[price, _] when is_number(price) -> price * 3800 # Convert to USD
_ -> nil
end
end
defp parse_strike(instrument_name) do
case Regex.run(~r/-(\d+)-/, instrument_name) do
[_, strike] -> String.to_integer(strike)
_ -> 0
end
end
defp parse_type(instrument_name) do
cond do
String.ends_with?(instrument_name, "-C") -> "CALL"
String.ends_with?(instrument_name, "-P") -> "PUT"
true -> "UNKNOWN"
end
end
defp parse_expiry(instrument_name) do
case Regex.run(~r/-(\d+[A-Z]+\d+)-/, instrument_name) do
[_, date_str] ->
parse_date_string(date_str)
_ ->
DateTime.utc_now() |> DateTime.add(30 * 24 * 3600, :second)
end
end
defp parse_expiry_string(instrument_name) do
case Regex.run(~r/-(\d+[A-Z]+\d+)-/, instrument_name) do
[_, date_str] -> date_str
_ -> "UNKNOWN"
end
end
defp parse_date_string(date_str) do
# Parse format like "31JAN25"
try do
{day, rest} = Integer.parse(date_str)
month_str = String.slice(rest, 0, 3)
year_str = String.slice(rest, 3, 2)
year = 2000 + String.to_integer(year_str)
month = case month_str do
"JAN" -> 1
"FEB" -> 2
"MAR" -> 3
"APR" -> 4
"MAY" -> 5
"JUN" -> 6
"JUL" -> 7
"AUG" -> 8
"SEP" -> 9
"OCT" -> 10
"NOV" -> 11
"DEC" -> 12
_ -> 1
end
{:ok, date} = Date.new(year, month, day)
DateTime.new!(date, ~T[08:00:00], "Etc/UTC")
rescue
_ -> DateTime.utc_now() |> DateTime.add(30 * 24 * 3600, :second)
end
end
defp calculate_days_to_expiry(instrument_name) do
expiry = parse_expiry(instrument_name)
diff = DateTime.diff(expiry, DateTime.utc_now(), :second)
Float.round(diff / 86400, 1)
end
defp save_results(data, config) do
timestamp = DateTime.utc_now() |> DateTime.to_unix(:millisecond)
filename = Path.join(config.output_dir, "market_#{timestamp}.json")
File.mkdir_p!(config.output_dir)
output = %{
timestamp: DateTime.utc_now() |> DateTime.to_iso8601(),
markets_scanned: length(data),
data: data
}
File.write!(filename, Jason.encode!(output, pretty: true))
IO.puts("\n\nResults saved to: #{filename}")
end
defp display_top_opportunities(data) do
IO.puts("\n\n=== Top 10 Trading Opportunities ===")
IO.puts("Score | Instrument | Strike | Type | Days | Spread$ | Volume | OI")
IO.puts("------|---------------------|--------|------|------|---------|--------|-----")
data
|> Enum.take(10)
|> Enum.each(fn market ->
score = market.opportunity_scores.total_score
name = String.pad_trailing(market.instrument_name, 20)
strike = String.pad_leading("#{market.strike}", 6)
type = String.pad_trailing(market.type, 4)
days = String.pad_leading("#{Float.round(market.days_to_expiry, 0)}", 4)
spread = String.pad_leading("$#{market.spread_dollars}", 7)
volume = String.pad_leading("#{Float.round(market.volume_24h, 0)}", 6)
oi = String.pad_leading("#{Float.round(market.open_interest, 0)}", 5)
IO.puts("#{String.pad_leading("#{score}", 5)} | #{name} | #{strike} | #{type} | #{days} | #{spread} | #{volume} | #{oi}")
end)
# Group by expiry
IO.puts("\n=== Opportunities by Expiration ===")
data
|> Enum.group_by(fn m -> m.expiry end)
|> Enum.sort_by(fn {exp, _} -> exp end)
|> Enum.take(5)
|> Enum.each(fn {expiry, markets} ->
top = markets |> Enum.take(3)
IO.puts("\n#{expiry}: #{length(markets)} opportunities")
Enum.each(top, fn m ->
IO.puts(" Score #{m.opportunity_scores.total_score}: #{m.instrument_name} - Spread: $#{m.spread_dollars}")
end)
end)
end
end
# Main execution
case System.argv() do
[output_dir] ->
config = MarketConfig.get_config() |> Map.put(:output_dir, output_dir)
MarketWatcher.run(config)
_ ->
MarketWatcher.run()
end