-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinit.lua
More file actions
1723 lines (1466 loc) · 61.5 KB
/
init.lua
File metadata and controls
1723 lines (1466 loc) · 61.5 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local mq = require('mq')
local PackageMan = require('mq.PackageMan')
PackageMan.Require('lsqlite3')
local ICONS = require('mq.Icons')
local BazaarDB = require('bazaar_db')
local ImGui = require('ImGui')
local ImPlot = require('ImPlot')
require('baz_utils')
math.randomseed(os.time())
local animItems = mq.FindTextureAnimation("A_DragItem")
function GetTableEntry(t, v)
--printf("Serach %s for %s", t, v)
if not t then return false, 0 end
for idx, tv in pairs(t) do
--printf("%s == %s", v, tv.item)
if tv.item == v then return true, idx end
end
return false, 0
end
function Tooltip(desc)
ImGui.SameLine()
if ImGui.IsItemHovered() then
ImGui.BeginTooltip()
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 25.0)
ImGui.Text(desc)
ImGui.PopTextWrapPos()
ImGui.EndTooltip()
end
end
function Tokenize(inputStr, sep)
if sep == nil then
sep = "|"
end
local t = {}
if string.find(tostring(inputStr), "^#") == nil then
for str in string.gmatch(tostring(inputStr), "([^" .. sep .. "]+)") do
if string.find(str, "^#") == nil then
table.insert(t, str)
end
end
end
return t
end
-- Search for Items
local function searchFound(num, itemName)
printf("Found %d of %s!", num, itemName)
end
mq.event("searchFound", "There are #1# Buy Lines that match the search string '#2#'.", searchFound)
CharConfig = mq.TLO.Me.CleanName()
ServerName = mq.TLO.EverQuest.Server():gsub(" ", "")
local openGUI = true
local shouldDrawGUI = true
local openHistoryGUI = false
local shouldDrawHistoryGUI = false
local bgOpacity = 1.0
local doItemScan = false
local currentItemIdx = 0
local currentScanItem = nil
local scanItem = nil
local pauseScan = false
local itemDB
local itemList = {}
local allKnownItems = {}
local totalItems = 0
local settings = {}
local config_pickle_path = mq.configDir .. '/bazaar/' .. ServerName .. '_' .. CharConfig .. '.lua'
local newAuctionPopup = "new_auction_popup"
local lastAuction = 0
local AuctionText = {}
local pauseAuctioning = true
local popupAuctionCost = ""
local popupAuctionItem = ""
local cachedPriceHistory = {}
local openPopup = false
-- first scan should be about 2 seconds after startup.
local lastFullScan = 0
local BAZAAR_ACTION_PAUSE_MS = 1000
local BAZAAR_MIN_ITEM_PAUSE_MS = 1500
local BAZAAR_MAX_ITEM_PAUSE_MS = 6000
local BAZAAR_BREATHER_EVERY = 5
local BAZAAR_BREATHER_MS = 8000
local lastBazaarQueryDuration = 0
local function bazaarActionPause()
-- Keep Bazaar UI interactions from firing back-to-back too tightly.
mq.delay(BAZAAR_ACTION_PAUSE_MS)
end
local function bazaarItemPause(itemsScanned)
-- Pace the scan from Bazaar's actual response time instead of a rigid loop.
local responsePause = math.floor(lastBazaarQueryDuration * 500)
local pauseMs = BAZAAR_MIN_ITEM_PAUSE_MS + responsePause
pauseMs = math.min(BAZAAR_MAX_ITEM_PAUSE_MS, pauseMs)
if itemsScanned and itemsScanned > 0 and itemsScanned % BAZAAR_BREATHER_EVERY == 0 then
print("\ayTaking a short breather before the next batch...")
pauseMs = pauseMs + BAZAAR_BREATHER_MS
end
mq.delay(pauseMs)
end
local function clearCachedHistory()
cachedPriceHistory.max_x = 0
cachedPriceHistory.min_x = os.time()
cachedPriceHistory.max_y = 0
cachedPriceHistory.labels = {}
cachedPriceHistory.xs = {}
cachedPriceHistory.ys = {}
cachedPriceHistory.avg_xs = {}
cachedPriceHistory.avg_ys = {}
end
local function cacheItems()
local itemCount = 0
local line = ""
local lineCount = 1
if (settings and #AuctionText == 0) then
for _, v in pairs(settings.AuctionItems or {}) do
if line:len() > 0 then line = line .. " | " end
---@diagnostic disable-next-line: undefined-field
line = line .. mq.TLO.LinkDB("=" .. v.item)() .. " " .. v.cost
itemCount = itemCount + 1
if itemCount == 4 then
print(string.format("Cached[%d]: %s", lineCount, line))
AuctionText[lineCount] = line
lineCount = lineCount + 1
line = ""
itemCount = 0
end
end
end
if line:len() > 0 then
print(string.format("Cached[%d]: %s", lineCount, line))
AuctionText[lineCount] = line
end
end
local function SaveSettings(clearItems)
mq.pickle(config_pickle_path, settings)
if clearItems then
AuctionText = {}
cacheItems()
end
end
local DefaultConfig = {
['Timer'] = { Default = 5, Tooltip = "Time in minutes between manual auctions", },
['Channels'] = { Default = "auc", Tooltip = "| Separated list of channels to auction to. ex: auc|6|7", },
['UnderCutPercent'] = { Default = 1, Tooltip = "Minimum undercut percent", },
['UnderCutPercentMax'] = { Default = 1, Tooltip = "Maximum undercut percent", },
['UnderCutOOM'] = { Default = 0, Tooltip = "Round Undercut to Order of Magnitude X", },
['RaiseUnderpriced'] = { Default = false, Tooltip = "Raise prices that are far below the calculated target price.", },
['RaiseUnderpricedPercent'] = { Default = 10, Tooltip = "Only raise prices when current price is this percent or more below target.", },
['DefaultPrice'] = { Default = 2000000, Tooltip = "Default price", },
['DontUndercut'] = { Default = CharConfig .. "|", Tooltip = "| Separated list of traders not to undercut. ex: Bob|Derple", },
['AutoUpdatePrices'] = { Default = true, Tooltip = "Automatically update trader prices to the calculated target price after scanning.", },
['AuctionItems'] = { Default = {}, },
['scanTimer'] = { Default = 30, },
['DisabledAuctionItems'] = { Default = {}, },
}
local function LoadSettings()
CharConfig = mq.TLO.Me.CleanName()
local needSave = false
local config, err = loadfile(config_pickle_path)
if not config or err then
printf("Failed to Load Config: %s", config_pickle_path)
needSave = true
settings = {}
else
settings = config()
end
for k, v in pairs(DefaultConfig) do
if settings[k] == nil then settings[k] = v.Default end
end
lastFullScan = os.time() - ((60 * settings.scanTimer) - 2)
if needSave then SaveSettings(true) end
-- open the items db
local items_db_file = 'items.db'
itemDB = BazaarDB.new(mq.configDir .. '/bazaar/' .. items_db_file)
itemDB:setupDB()
allKnownItems = itemDB:getAllItems()
return true
end
----------------------------------------------------------------|
-- Manage /trader window
--------------------------------------------------------------**|
local function traderWindowControl(status)
if status == "Open" or status == "On" or status == "Off" then
if not mq.TLO.Window("BazaarWnd").Open() then
print("\ayOpening Trader window...")
mq.cmd("/trader")
end
if status == "On" then
if mq.TLO.Window("BazaarWnd").Child("BZW_Start_Button") then
mq.TLO.Window("BazaarWnd").Child("BZW_Start_Button").LeftMouseUp()
print("\aySetting Trader Window to Start Trading...")
end
end
if status == "Off" then
if mq.TLO.Window("BazaarWnd").Child("BZW_End_Button") then
mq.TLO.Window("BazaarWnd").Child("BZW_End_Button").LeftMouseUp()
print("\aySetting Trader Window to Stop Trading...")
end
end
end
if status == "Close" then
mq.cmd("/windowstate BazaarWnd Close")
print("\amClosed Trader Window...")
end
end
local function shouldUndercut(trader)
local tokens = Tokenize(settings.DontUndercut, "|")
for _, t in ipairs(tokens) do
if t == trader then return false end
end
return true
end
local setItem = nil
local setPrice = 2000000
local setAsyncItemFound = false
local function setTraderPrice(itemName, price)
print("Setting item \at" .. itemName .. "\ax to \ay" .. price)
setItem = itemName
setPrice = price
setAsyncItemFound = false
end
local asyncSetTraderPriceState = 0
local asyncSetTraderPriceTiming = 0
local function refreshItemInSlot(slot)
local currentItem = mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", slot)).Tooltip()
local currentPrice = mq.TLO.Window("BazaarWnd").Child("BZW_Money0").Text()
local itemRef = mq.TLO.FindItem(string.format("=%s", currentItem))
local currentItemIcon = itemRef.Icon()
if currentItem ~= nil and currentItem ~= "" then
local itemDBId = itemDB:getItemDBId(currentItem)
local listedDate = itemDB:getItemListedTime(itemDBId)
if not listedDate then
itemDB:cacheItemListedTime(itemDBId, currentPrice or 0, os.time())
listedDate = os.time()
end
itemList[currentItem] = itemList[currentItem] or {}
itemList[currentItem]["CurrentPrice"] = tonumber(currentPrice) or 0
itemList[currentItem]["slot"] = slot
itemList[currentItem]["IconID"] = currentItemIcon
itemList[currentItem]["ItemRef"] = itemRef
itemList[currentItem]["DBID"] = itemDBId
itemList[currentItem]["ListedDate"] = listedDate
print(string.format("Set price of \at%s\ax to \ay%d", currentItem, currentPrice))
end
end
local function refreshItemSlot(slot)
local currentItem = mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", slot)).Tooltip()
local currentPrice = mq.TLO.Window("BazaarWnd").Child("BZW_Money0").Text()
if currentItem ~= nil and currentItem ~= "" then
itemList[currentItem] = itemList[currentItem] or {}
if not itemList[currentItem]["CurrentPrice"] then
itemList[currentItem] = {}
itemList[currentItem]["CurrentPrice"] = tonumber(currentPrice) or 0
end
itemList[currentItem]["slot"] = slot
if currentItem == setItem then
setAsyncItemFound = true
end
end
end
local function refreshLocalSlots()
traderWindowControl("Open")
for slot = 0, 144 do
---@diagnostic disable-next-line: undefined-field
if (mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", slot)).Tooltip() or ""):len() == 0 then break end
mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", slot)).LeftMouseUp()
---@diagnostic disable-next-line: undefined-field
while not mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", slot)).InvSlot.Selected() do
mq.delay(1)
end
refreshItemSlot(slot)
end
end
local function refreshLocalItems()
traderWindowControl("Open")
for slot = 0, 144 do
---@diagnostic disable-next-line: undefined-field
if (mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", slot)).Tooltip() or ""):len() == 0 then break end
mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", slot)).LeftMouseUp()
---@diagnostic disable-next-line: undefined-field
while not mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", slot)).InvSlot.Selected() do
mq.delay(1)
end
refreshItemInSlot(slot)
end
totalItems = GetTableSize(itemList)
end
local function asyncSetTraderPrice()
if setItem == nil then return end
if asyncSetTraderPriceState == 0 then
refreshLocalSlots()
if not setAsyncItemFound then
print(string.format("Item \ar%s\ax no longer found -- Removing.", setItem))
if itemList[setItem] then
itemList[setItem] = nil
end
setItem = nil
asyncSetTraderPriceState = 0
totalItems = GetTableSize(itemList)
return
end
mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", itemList[setItem]["slot"])).LeftMouseUp()
asyncSetTraderPriceTiming = os.clock() + 1
asyncSetTraderPriceState = 1
return
end
if asyncSetTraderPriceState == 1 and os.clock() >= asyncSetTraderPriceTiming then
-- wait until we are acutally selected.
---@diagnostic disable-next-line: undefined-field
if not mq.TLO.Window("BazaarWnd").Child(string.format("BZR_BazaarSlot%d", itemList[setItem]["slot"])).InvSlot.Selected() then return end
mq.TLO.Window("BazaarWnd").Child("BZW_Money0").LeftMouseUp()
asyncSetTraderPriceTiming = os.clock() + 0.1
asyncSetTraderPriceState = 2
return
end
if asyncSetTraderPriceState == 2 and os.clock() >= asyncSetTraderPriceTiming then
mq.cmd(string.format("/notify QuantityWnd QTYW_Slider newvalue %d", setPrice))
mq.cmd("/notify QuantityWnd QTYW_Accept_Button leftmouseup")
mq.cmd("/notify BazaarWnd BZW_SetPrice_Button leftmouseup")
asyncSetTraderPriceTiming = os.clock() + 0.1
asyncSetTraderPriceState = 3
end
if asyncSetTraderPriceState == 3 and os.clock() >= asyncSetTraderPriceTiming then
mq.TLO.Window("BazaarWnd").Child("BZW_Add_Button").LeftMouseUp()
asyncSetTraderPriceState = 0
asyncSetTraderPriceTiming = 0
scanItem = setItem
itemList[scanItem]["LowestPrice"] = nil
setItem = nil
setPrice = 2000000
end
end
local function waitForTraderPriceUpdate(itemName)
local startTime = os.clock()
local timeoutSeconds = 20
while setItem ~= nil do
asyncSetTraderPrice()
mq.doevents()
mq.delay(50)
if os.clock() - startTime > timeoutSeconds then
print(string.format("\arTimed out while updating trader price for \am%s", itemName))
setItem = nil
setPrice = 2000000
asyncSetTraderPriceState = 0
asyncSetTraderPriceTiming = 0
return false
end
end
return true
end
-------------------------------------------------------------|
-- Checks your /trader prices and updates if needed.
-----------------------------------------------------------**|
local function bazaarSearchWindowControl(status)
if status == "Open" then
if not mq.TLO.Window("BazaarSearchWnd").Open() then
mq.cmd("/bazaar")
end
end
if status == "Close" then
if mq.TLO.Window("BazaarSearchWnd").Open() then
mq.cmd("/windowstate BazaarSearchWnd Close")
end
end
end
local function calcTargetPrice(best, curr, trader)
if curr == 0 and (best or 0) == 0 then
return settings.DefaultPrice
end
if not shouldUndercut(trader) then
return best
end
local ordMagDiff = 10 ^ settings.UnderCutOOM
-- math.floor(math.abs(math.log((best > 0 and best or 1) / (settings.UnderCutOOM > 0 and 10 ^ settings.UnderCutOOM or 10), 10)))
local minPercent = tonumber(settings.UnderCutPercent) or 0
local maxPercent = tonumber(settings.UnderCutPercentMax) or minPercent
if maxPercent < minPercent then
minPercent, maxPercent = maxPercent, minPercent
end
local undercutPercent = minPercent
if maxPercent > minPercent then
undercutPercent = math.random(minPercent, maxPercent)
end
local newPrice = math.ceil((best or 0) - (undercutPercent / 100 * (best or 0)))
if ordMagDiff <= best then
newPrice = math.floor(newPrice / ordMagDiff) * ordMagDiff
end
if curr == 0 or curr >= (best or 0) then
return newPrice
end
if settings.RaiseUnderpriced then
local raiseThresholdPercent = tonumber(settings.RaiseUnderpricedPercent) or 0
local raiseBelow = newPrice - ((raiseThresholdPercent / 100) * newPrice)
if curr <= raiseBelow then
return newPrice
end
end
return curr
end
local function recalcTargetPrices()
for _, itemData in pairs(itemList) do
itemData["TargetPrice"] = calcTargetPrice((tonumber(itemData["CompetitivePrice"]) or 0),
(tonumber(itemData["CurrentPrice"]) or -1), (itemData["CompetitiveTrader"] or "Unknown"))
end
end
local function bazaarQuery(itemName)
if not mq.TLO.Window("BazaarSearchWnd").Open() then
bazaarSearchWindowControl("Open")
mq.delay(1000, function() return mq.TLO.Window("BazaarSearchWnd").Open() end)
end
mq.TLO.Window("BazaarSearchWnd").Child("BZR_ItemNameInput").SetText(itemName)
mq.delay(500, function() return mq.TLO.Window("BazaarSearchWnd").Child("BZR_ItemNameInput").Text() == itemName end)
bazaarActionPause()
if not mq.TLO.Window("BazaarSearchWnd").Child("BZR_QueryButton").Enabled() then
print("\ayBazaar is still busy, skipping this search for now.")
return false
end
mq.TLO.Window("BazaarSearchWnd").Child("BZR_QueryButton").LeftMouseUp()
mq.delay(500, function() return not mq.TLO.Window("BazaarSearchWnd").Child("BZR_QueryButton").Enabled() end)
local waitStart = os.clock()
local lastStatus = waitStart
local timeoutSeconds = 45
repeat
mq.delay(250)
if os.clock() - waitStart > timeoutSeconds then
print(string.format("\arBazaar query timed out after %d seconds: \am%s", timeoutSeconds, itemName))
lastBazaarQueryDuration = timeoutSeconds
return false
end
if os.clock() - lastStatus > 15 then
print("\ayStill waiting on Bazaar results...")
lastStatus = os.clock()
end
---@diagnostic disable-next-line: undefined-field
until mq.TLO.Window("BazaarSearchWnd").Child("BZR_QueryButton").Enabled()
lastBazaarQueryDuration = os.clock() - waitStart
return true
end
local function autoUpdateTraderPrice(itemName)
if not settings.AutoUpdatePrices then return end
local itemData = itemList[itemName]
if not itemData then return end
local currentPrice = tonumber(itemData["CurrentPrice"]) or 0
local targetPrice = tonumber(itemData["TargetPrice"]) or 0
if targetPrice <= 0 then return end
if currentPrice == targetPrice then return end
print(string.format("\ayAuto-updating \am%s\ay from \aw%d\ay to \ag%d", itemName, currentPrice, targetPrice))
setTraderPrice(itemName, targetPrice)
if waitForTraderPriceUpdate(itemName) then
itemData["CurrentPrice"] = targetPrice
end
end
local function searchBazaar(itemName)
itemList[itemName] = itemList[itemName] or {}
itemList[itemName]["LowestPrice"] = nil
itemList[itemName]["Trader"] = nil
itemList[itemName]["NextLowestPrice"] = nil
itemList[itemName]["NextTrader"] = nil
itemList[itemName]["CompetitivePrice"] = nil
itemList[itemName]["CompetitiveTrader"] = nil
itemList[itemName]["TargetPrice"] = nil
bazaarSearchWindowControl("Open")
mq.TLO.Window("BazaarSearchWnd").Child("BZR_Default").LeftMouseUp()
mq.delay(500, function() return not mq.TLO.Window("BazaarSearchWnd").Child("BZR_Default").Checked() end)
bazaarActionPause()
if not bazaarQuery(itemName) then return end
if not mq.TLO.Window("BazaarSearchWnd").Child("BZR_ItemList").List(1, 3) then
print("\arSearch failed, trying 1 more time...")
bazaarActionPause()
if not bazaarQuery(itemName) then return end
end
local startSearchTime = os.clock()
local found = 0
while os.clock() - startSearchTime <= 30 and found == 0 do
mq.delay(5)
found = mq.TLO.Window("BazaarSearchWnd").Child("BZR_ItemList").List(1, 3)()
end
local allSellers = {}
local eligibleSellers = {}
for searchResult = 1, 255 do
local count = mq.TLO.Window("BazaarSearchWnd").Child("BZR_ItemList").List(searchResult, 3)()
if count and count ~= "NULL" then
local result = mq.TLO.Window("BazaarSearchWnd").Child("BZR_ItemList").List(searchResult, 2)()
if result == itemName then
local workingValue = NoComma(mq.TLO.Window("BazaarSearchWnd").Child("BZR_ItemList").List(searchResult, 4)())
local trader = mq.TLO.Window("BazaarSearchWnd").Child("BZR_ItemList").List(searchResult, 8)()
workingValue = tonumber(workingValue)
if workingValue and trader then
print(string.format("Found seller: \am%s \axwith price: \ag%d", trader, workingValue))
itemDB:cacheItemPrice(itemList[itemName]["DBID"], trader, workingValue)
table.insert(allSellers, { price = workingValue, trader = trader })
if shouldUndercut(trader) then
table.insert(eligibleSellers, { price = workingValue, trader = trader })
end
end
end
end
end
table.sort(allSellers, function(a, b)
if a.price == b.price then
return tostring(a.trader) < tostring(b.trader)
end
return a.price < b.price
end)
table.sort(eligibleSellers, function(a, b)
if a.price == b.price then
return tostring(a.trader) < tostring(b.trader)
end
return a.price < b.price
end)
local lowestSeller = allSellers[1]
local nextLowestSeller = nil
if lowestSeller then
for _, seller in ipairs(allSellers) do
if seller.trader ~= lowestSeller.trader then
nextLowestSeller = seller
break
end
end
end
if lowestSeller then
itemList[itemName]["LowestPrice"] = lowestSeller.price
itemList[itemName]["Trader"] = lowestSeller.trader
end
if nextLowestSeller then
itemList[itemName]["NextLowestPrice"] = nextLowestSeller.price
itemList[itemName]["NextTrader"] = nextLowestSeller.trader
end
local bestSeller = eligibleSellers[1]
if bestSeller then
itemList[itemName]["CompetitivePrice"] = bestSeller.price
itemList[itemName]["CompetitiveTrader"] = bestSeller.trader
itemList[itemName]["TargetPrice"] = calcTargetPrice((tonumber(bestSeller.price) or 0),
(tonumber(itemList[itemName]["CurrentPrice"]) or -1), bestSeller.trader)
end
--items_db:exec("PRAGMA schema.wal_checkpoint;")
end
local cancelCheckPrices = false
local traderCheckPrices = function()
print("\ayChecking current prices...")
for currentItem, _ in pairs(itemList) do
currentItemIdx = currentItemIdx + 1
currentScanItem = currentItem
print(string.format(" - \ag%d\ax/\ag%d\ax item = \am%s", currentItemIdx, totalItems, currentItem))
searchBazaar(currentItem)
autoUpdateTraderPrice(currentItem)
bazaarItemPause(currentItemIdx)
if cancelCheckPrices then
cancelCheckPrices = false
currentScanItem = nil
print("\arPrice Scan Canceled!")
return
end
end
currentScanItem = nil
print "\agPrice Scan Complete!"
end
local traderCheckItems = function()
if scanItem ~= nil then
searchBazaar(scanItem)
refreshItemSlot(itemList[scanItem]["slot"])
scanItem = nil
return
end
if doItemScan == false then return end
bazaarSearchWindowControl("Open")
print("\ayChecking for items...")
refreshLocalItems()
traderCheckPrices()
print "\agItem Scan Complete!"
doItemScan = false
currentScanItem = nil
end
local ColumnID_AuctionItemName = 0
local ColumnID_AuctionItemCost = 1
local ColumnID_AuctionItemActive = 2
local ColumnID_AuctionItemUnused = 3
local ColumnID_ItemIcon = 0
local ColumnID_Item = 1
local ColumnID_MyPrice = 2
local ColumnID_LowestPrice = 3
local ColumnID_BestTrader = 4
local ColumnID_NextLowestPrice = 5
local ColumnID_NextTrader = 6
local ColumnID_ListedDate = 7
local ColumnID_TargetPrice = 8
local ColumnID_LAST = ColumnID_TargetPrice + 1
local genericSort = function(k1, k2, dir)
if dir == 1 then
return k1 < k2
end
return k1 > k2
end
local auctionItemSorter = function(k1, k2, spec, tbl)
local i1 = tbl[k1]
local i2 = tbl[k2]
if spec then
---@type string, string
local a, b = i1.item or "", i2.item or ""
if spec.ColumnUserID == ColumnID_AuctionItemCost then
a = i1.cost or "0"
b = i2.cost or "0"
end
if a ~= b then return genericSort(a, b, spec.SortDirection) end
return genericSort(k1, k2, spec.SortDirection)
end
return genericSort(k1, k2, 1)
end
local itemSorter = function(k1, k2, spec)
local i1 = itemList[k1]
local i2 = itemList[k2]
if spec then
local a
local b
if spec.ColumnUserID == ColumnID_MyPrice then
a = tonumber(i1["CurrentPrice"] or 0)
b = tonumber(i2["CurrentPrice"] or 0)
end
if spec.ColumnUserID == ColumnID_LowestPrice then
a = tonumber(i1["LowestPrice"] or 2000000)
b = tonumber(i2["LowestPrice"] or 2000000)
end
if spec.ColumnUserID == ColumnID_NextLowestPrice then
a = tonumber(i1["NextLowestPrice"] or 2000000)
b = tonumber(i2["NextLowestPrice"] or 2000000)
end
if spec.ColumnUserID == ColumnID_TargetPrice then
a = tonumber(i1["TargetPrice"] or 0)
b = tonumber(i2["TargetPrice"] or 0)
end
if spec.ColumnUserID == ColumnID_ListedDate then
a = tonumber(i1["ListedDate"] or 0)
b = tonumber(i2["ListedDate"] or 0)
end
if spec.ColumnUserID == ColumnID_BestTrader then
a = (i1["Trader"] or "zUnknown")
b = (i2["Trader"] or "zUnknown")
end
if spec.ColumnUserID == ColumnID_NextTrader then
a = (i1["NextTrader"] or "zUnknown")
b = (i2["NextTrader"] or "zUnknown")
end
if a ~= b then return genericSort(a, b, spec.SortDirection) end
return genericSort(k1, k2, spec.SortDirection)
end
return genericSort(k1, k2, 1)
end
local ColumnID_HistoryPrice = 0
local ColumnID_HistoryTrader = 1
local ColumnID_HistoryDate = 2
local ColumnID_HistoryLAST = ColumnID_HistoryDate + 1
---@param k1 table<any>: object 1 to sort
---@param k2 table<any>: object 2 to sort
---@param spec table<any>: sorting spec
---@return boolean
local historySorter = function(k1, k2, spec)
if spec then
local a
local b
if spec.ColumnUserID == ColumnID_HistoryPrice then
a = tonumber(k1["Price"] or 0)
b = tonumber(k2["Price"] or 0)
elseif spec.ColumnUserID == ColumnID_HistoryTrader then
a = (k1["Trader"])
b = (k2["Trader"])
else
a = tonumber(k1["Date"])
b = tonumber(k2["Date"])
end
if a ~= b then return genericSort(a, b, spec.SortDirection) end
if spec.ColumnUserID == ColumnID_HistoryPrice then
a = (k1["Trader"])
b = (k2["Trader"])
elseif spec.ColumnUserID == ColumnID_HistoryTrader then
a = tonumber(k1["Date"])
b = tonumber(k2["Date"])
else
a = tonumber(k1["Price"] or 0)
b = tonumber(k2["Price"] or 0)
end
if a ~= b then return genericSort(a, b, spec.SortDirection) end
if spec.ColumnUserID == ColumnID_HistoryPrice then
a = tonumber(k1["Date"])
b = tonumber(k2["Date"])
elseif spec.ColumnUserID == ColumnID_HistoryTrader then
a = tonumber(k1["Price"] or 0)
b = tonumber(k2["Price"] or 0)
else
a = (k1["Trader"])
b = (k2["Trader"])
end
return genericSort(a, b, spec.SortDirection)
end
return genericSort(k1["Date"], k2["Date"], 1)
end
local function DisabledButton(text)
ImGui.PushStyleColor(ImGuiCol.Button, 0.2, 0.2, 0.2, 0.5)
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, 0.2, 0.2, 0.2, 0.5)
ImGui.PushStyleColor(ImGuiCol.ButtonActive, 0.2, 0.2, 0.2, 0.5)
ImGui.SmallButton(text) -- noop
ImGui.PopStyleColor(3)
end
local ICON_SIZE = 20
local function drawInspectableIcon(iconID, item)
if not item then return end
if not iconID then iconID = 0 end
local cursor_x, cursor_y = ImGui.GetCursorPos()
animItems:SetTextureCell(iconID or 0)
ImGui.DrawTextureAnimation(animItems, ICON_SIZE, ICON_SIZE)
ImGui.SetCursorPos(cursor_x, cursor_y)
ImGui.PushID((tostring(iconID or 0) or "0") .. (item.Name() or "") .. "_invis_btn")
ImGui.InvisibleButton(item.Name() or "NotFound", ImVec2(ICON_SIZE, ICON_SIZE),
bit32.bor(ImGuiButtonFlags.MouseButtonLeft))
if ImGui.IsItemHovered() and ImGui.IsMouseReleased(ImGuiMouseButton.Left) then
item.Inspect()
end
ImGui.PopID()
end
local sortedItemKeys = {}
local sortedAuctionItemKeys = {}
local sortedDisabledAuctionItemKeys = {}
local editingTargetItem = nil
local showAdvancedPricing = false
local function renderTraderUI()
local pressed
ImGui.PushStyleColor(ImGuiCol.Text, 0.0, 1.0, 0.0, 1)
ImGui.Text("Bazaar running for %s", CharConfig)
ImGui.PopStyleColor(1)
local used
ImGui.Text("Trader Controls")
if ImGui.Button("Open Trader", 150, 25) then
traderWindowControl("Open")
end
ImGui.SameLine()
if mq.TLO.Me.Trader() then
ImGui.PushStyleColor(ImGuiCol.Button, 0.6, 0.3, 0.3, 1.0)
if ImGui.Button("Turn Off Trader", 150, 25) then
traderWindowControl("Off")
end
else
ImGui.PushStyleColor(ImGuiCol.Button, 0.3, 0.6, 0.3, 1.0)
if ImGui.Button("Turn On Trader", 150, 25) then
traderWindowControl("On")
end
end
ImGui.PopStyleColor(1)
ImGui.Separator()
ImGui.Text("Scan Controls")
ImGui.Text("Scan every")
ImGui.SameLine()
ImGui.PushItemWidth(80)
settings.scanTimer, pressed = ImGui.InputInt("##scan_minutes", settings.scanTimer)
if pressed then
if settings.scanTimer < 30 then settings.scanTimer = 30 end
SaveSettings(false)
end
ImGui.PopItemWidth()
ImGui.SameLine()
ImGui.Text("minutes")
if ImGui.Button("Check Bazaar Prices", 170, 25) then
doItemScan = true
currentItemIdx = 0
currentScanItem = nil
lastFullScan = os.time()
end
ImGui.SameLine()
ImGui.PushStyleColor(ImGuiCol.Text, 0.3, 0.6, 0.6, 1.0)
ImGui.Text(string.format("Next scan: %s", FormatTime((60 * settings.scanTimer) - (os.time() - lastFullScan))))
ImGui.PopStyleColor(1)
ImGui.SameLine()
pauseScan, _ = ImGui.Checkbox("Pause timer", pauseScan)
ImGui.SameLine()
settings.AutoUpdatePrices, pressed = ImGui.Checkbox("Update prices after scan", settings.AutoUpdatePrices)
if pressed then
SaveSettings()
end
Tooltip("When enabled, Scan Items will update your trader prices to the calculated Target Price.")
ImGui.Text("")
ImGui.Text("Pricing Rules")
ImGui.Text("Undercut range")
ImGui.SameLine()
ImGui.PushItemWidth(70)
settings.UnderCutPercent, used = ImGui.InputInt("##min_undercut_percent", settings.UnderCutPercent)
if used then
if settings.UnderCutPercent < 0 then settings.UnderCutPercent = 0 end
if settings.UnderCutPercent > 90 then settings.UnderCutPercent = 90 end
if settings.UnderCutPercentMax < settings.UnderCutPercent then
settings.UnderCutPercentMax = settings.UnderCutPercent
end
recalcTargetPrices()
SaveSettings()
end
ImGui.SameLine()
ImGui.Text("% to")
ImGui.SameLine()
settings.UnderCutPercentMax, used = ImGui.InputInt("##max_undercut_percent", settings.UnderCutPercentMax)
if used then
if settings.UnderCutPercentMax < 0 then settings.UnderCutPercentMax = 0 end
if settings.UnderCutPercentMax > 90 then settings.UnderCutPercentMax = 90 end
if settings.UnderCutPercent > settings.UnderCutPercentMax then
settings.UnderCutPercent = settings.UnderCutPercentMax
end
recalcTargetPrices()
SaveSettings()
end
ImGui.PopItemWidth()
ImGui.SameLine()
ImGui.Text("% below lowest eligible seller")
ImGui.PushStyleColor(ImGuiCol.Text, 0.9, 0.85, 0.45, 1.0)
if settings.AutoUpdatePrices then
ImGui.Text("Auto-update is ON: prices may change during scans.")
else
ImGui.Text("Auto-update is OFF: scans only calculate target prices.")
end
ImGui.PopStyleColor(1)
settings.RaiseUnderpriced, used = ImGui.Checkbox("Raise prices that are way under target", settings.RaiseUnderpriced)
if used then
SaveSettings()
end
if settings.RaiseUnderpriced then
ImGui.SameLine()
ImGui.Text("if under by")
ImGui.SameLine()
ImGui.PushItemWidth(95)
settings.RaiseUnderpricedPercent, used = ImGui.InputInt("##raise_underpriced_percent", settings.RaiseUnderpricedPercent)
if used then
if settings.RaiseUnderpricedPercent < 0 then settings.RaiseUnderpricedPercent = 0 end
if settings.RaiseUnderpricedPercent > 90 then settings.RaiseUnderpricedPercent = 90 end
recalcTargetPrices()
SaveSettings()