summaryrefslogtreecommitdiff
path: root/backend-go/internal/core/arbitrage.go
blob: 9cb26bbdfce8d8bdfeb4350cd9d212f37c897728 (plain)
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
package core

import (
	"fmt"
	"log"
)

const (
	ArbitrageCandidateLimit   = 30000
	ArbitrageTypeLimit        = 250
	ArbitrageStationPairLimit = 40
)

type ShortlistConfig struct {
	CandidateLimit   int
	TypeLimit        int
	StationPairLimit int
	RankMode         string
}

func DefaultShortlistConfig() *ShortlistConfig {
	return &ShortlistConfig{
		CandidateLimit:   ArbitrageCandidateLimit,
		TypeLimit:        ArbitrageTypeLimit,
		StationPairLimit: ArbitrageStationPairLimit,
		RankMode:         "and",
	}
}

// Arbitrage calculates profitable trade pairs between stations.
func Arbitrage(
	market *Market,
	cargoSpace int,
	taxRate float64,
	profitThreshold float64,
	maxCapital float64,
	shortlist *ShortlistConfig,
) ([]Trade, error) {
	taxRate = taxRate / 100.0
	if shortlist == nil {
		shortlist = DefaultShortlistConfig()
	}
	
	if shortlist.RankMode != "and" && shortlist.RankMode != "or" {
		return nil, fmt.Errorf("unsupported shortlist rank mode: %s", shortlist.RankMode)
	}
	
	rankOperator := "AND"
	if shortlist.RankMode == "or" {
		rankOperator = "OR"
	}

	query := fmt.Sprintf(`
	WITH buy_orders AS (
		SELECT * FROM orders WHERE is_buy_order = 1
	),
	sell_orders AS (
		SELECT * FROM orders WHERE is_buy_order = 0
	),
	raw_trades AS (
		SELECT 
			s.location_id as from_station,
			b.location_id as to_station,
			s.order_id as from_order_id,
			b.order_id as to_order_id,
			s.item_name,
			s.type_id,
			s.item_cargo_volume,
			s.price as from_price,
			b.price as to_price,
			MIN(
				s.volume_remain, 
				b.volume_remain,
				CAST(%d / NULLIF(s.item_cargo_volume, 0) AS INTEGER),
				CAST(%f / NULLIF(s.price, 0) AS INTEGER),
				CAST(%f / NULLIF(b.price, 0) AS INTEGER)
			) as quantity
		FROM sell_orders s
		JOIN buy_orders b ON s.type_id = b.type_id
		WHERE 
			b.price * (1 - %f) >= s.price
			AND s.item_cargo_volume > 0
			AND s.price > 0 AND b.price > 0
	),
	candidate_trades AS (
		SELECT
			*,
			quantity * (to_price * (1 - %f) - from_price) as gross_profit,
			quantity * item_cargo_volume as cargo,
			(quantity * (to_price * (1 - %f) - from_price)) / NULLIF(quantity * item_cargo_volume, 0) as profit_density,
			(quantity * (to_price * (1 - %f) - from_price)) / NULLIF(quantity * from_price, 0) as roi
		FROM raw_trades
		WHERE quantity > 0 AND quantity * (to_price * (1 - %f) - from_price) >= %f
	),
	ranked_trades AS (
		SELECT
			*,
			ROW_NUMBER() OVER (
				PARTITION BY type_id
				ORDER BY gross_profit DESC, roi DESC, profit_density DESC
			) as type_rank,
			ROW_NUMBER() OVER (
				PARTITION BY from_station, to_station
				ORDER BY gross_profit DESC, roi DESC, profit_density DESC
			) as station_pair_rank
		FROM candidate_trades
	)
	SELECT
		from_station,
		to_station,
		from_order_id,
		to_order_id,
		item_name,
		type_id,
		item_cargo_volume,
		from_price,
		to_price,
		quantity,
		cargo,
		gross_profit
	FROM ranked_trades
		WHERE (type_rank <= %d
			%s station_pair_rank <= %d)
	ORDER BY gross_profit DESC, roi DESC, profit_density DESC
		LIMIT %d
	`,
		cargoSpace, maxCapital, maxCapital, taxRate, 
		taxRate, taxRate, taxRate, taxRate, profitThreshold,
		shortlist.TypeLimit, rankOperator, shortlist.StationPairLimit, shortlist.CandidateLimit,
	)

	rows, err := market.DB.Query(query)
	if err != nil {
		return nil, fmt.Errorf("arbitrage query error: %v", err)
	}
	defer rows.Close()

	var trades []Trade
	for rows.Next() {
		var t Trade
		err := rows.Scan(
			&t.FromStation,
			&t.ToStation,
			&t.FromOrderID,
			&t.ToOrderID,
			&t.ItemName,
			&t.TypeID,
			&t.ItemCargoVolume,
			&t.FromPrice,
			&t.ToPrice,
			&t.Quantity,
			&t.Cargo,
			&t.GrossProfit,
		)
		if err != nil {
			return nil, fmt.Errorf("arbitrage scan error: %v", err)
		}
		
		if t.Quantity > 0 {
			trades = append(trades, t)
		}
	}

	log.Printf("Generated %d arbitrage candidates after shortlist (limit=%d, rank_mode=%s)", len(trades), shortlist.CandidateLimit, shortlist.RankMode)
	return trades, nil
}

// Snipe looks for immediate sell orders inside the current region that can be immediately flipped to buy orders.
func Snipe(
	market *Market,
	cargoSpace int,
	currentRegion int,
	taxRate float64,
	maxCapital float64,
	snipeProfitThreshold float64,
) (*Trade, error) {
	taxRate = taxRate / 100.0
	query := fmt.Sprintf(`
	WITH buy_orders AS (
		SELECT * FROM orders WHERE is_buy_order = 1
	),
	sell_orders AS (
		SELECT * FROM orders WHERE is_buy_order = 0 AND region_id = %d
	)
	SELECT 
		s.location_id as from_station,
		b.location_id as to_station,
		s.order_id as from_order_id,
		b.order_id as to_order_id,
		s.item_name,
		s.type_id,
		s.item_cargo_volume,
		s.price as from_price,
		b.price as to_price,
		MIN(
			s.volume_remain, 
			b.volume_remain,
			CAST(%d / NULLIF(s.item_cargo_volume, 0) AS INTEGER),
			CAST(%f / NULLIF(s.price, 0) AS INTEGER),
			CAST(%f / NULLIF(b.price, 0) AS INTEGER)
		) as quantity
	FROM sell_orders s
	JOIN buy_orders b ON s.type_id = b.type_id
	WHERE 
		b.price * (1 - %f) >= s.price
		AND s.item_cargo_volume > 0
		AND s.price > 0 AND b.price > 0
	`, currentRegion, cargoSpace, maxCapital, maxCapital, taxRate)

	rows, err := market.DB.Query(query)
	if err != nil {
		return nil, fmt.Errorf("snipe query error: %v", err)
	}
	defer rows.Close()

	var bestTrade *Trade
	maxProfit := 0.0

	for rows.Next() {
		var t Trade
		err := rows.Scan(
			&t.FromStation,
			&t.ToStation,
			&t.FromOrderID,
			&t.ToOrderID,
			&t.ItemName,
			&t.TypeID,
			&t.ItemCargoVolume,
			&t.FromPrice,
			&t.ToPrice,
			&t.Quantity,
		)
		if err != nil {
			return nil, fmt.Errorf("snipe scan error: %v", err)
		}

		if t.Quantity <= 0 {
			continue
		}

		effectiveBuyPrice := t.ToPrice * (1.0 - taxRate)
		grossProfit := float64(t.Quantity) * (effectiveBuyPrice - t.FromPrice)

		if grossProfit > maxProfit {
			t.Cargo = float64(t.Quantity) * t.ItemCargoVolume
			t.GrossProfit = grossProfit
			
			tradeCopy := t // copy
			bestTrade = &tradeCopy
			maxProfit = grossProfit
		}
	}

	if maxProfit > snipeProfitThreshold && bestTrade != nil {
		return bestTrade, nil
	}

	return nil, nil
}