algorembrant commited on
Commit
ed5e325
·
verified ·
1 Parent(s): 5f57ebb

Upload 66 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -35
  2. 220Breakout/220Breakout_Analysis.csv +24 -0
  3. 220Breakout/MT5 trade report/ReportTester-263254895(this)-holding.png +0 -0
  4. 220Breakout/MT5 trade report/ReportTester-263254895(this)-hst.png +0 -0
  5. 220Breakout/MT5 trade report/ReportTester-263254895(this)-mfemae.png +0 -0
  6. 220Breakout/MT5 trade report/ReportTester-263254895(this).png +0 -0
  7. 220Breakout/MT5 trade report/metrics_graphs.png +3 -0
  8. 220Breakout/report.md +27 -0
  9. 220Breakout/strategy.md +67 -0
  10. LICENSE +201 -0
  11. README.md +97 -0
  12. STRUCTURE.md +102 -0
  13. TECHSTACK.md +28 -0
  14. md2pdf_workspace/main.py +139 -0
  15. md2pdf_workspace/requirements.txt +3 -0
  16. md2pdf_workspace/steps.md +12 -0
  17. polymarket-trader/.gitignore +21 -0
  18. polymarket-trader/backend/.env.example +12 -0
  19. polymarket-trader/backend/cmd/server/main.go +61 -0
  20. polymarket-trader/backend/cmd/server/main_test.go +87 -0
  21. polymarket-trader/backend/go.mod +26 -0
  22. polymarket-trader/backend/go.sum +38 -0
  23. polymarket-trader/backend/internal/adapters/polymarket/client.go +64 -0
  24. polymarket-trader/backend/internal/adapters/polymarket/websocket.go +90 -0
  25. polymarket-trader/backend/internal/api/handlers.go +45 -0
  26. polymarket-trader/backend/internal/api/router.go +13 -0
  27. polymarket-trader/backend/internal/config/config.go +36 -0
  28. polymarket-trader/backend/internal/core/analytics.go +38 -0
  29. polymarket-trader/backend/internal/core/copy_engine.go +166 -0
  30. polymarket-trader/backend/internal/core/trader_discovery.go +64 -0
  31. polymarket-trader/backend/internal/models/models.go +52 -0
  32. polymarket-trader/frontend/.gitignore +24 -0
  33. polymarket-trader/frontend/README.md +73 -0
  34. polymarket-trader/frontend/components.json +17 -0
  35. polymarket-trader/frontend/eslint.config.js +23 -0
  36. polymarket-trader/frontend/index.html +13 -0
  37. polymarket-trader/frontend/package-lock.json +0 -0
  38. polymarket-trader/frontend/package.json +49 -0
  39. polymarket-trader/frontend/postcss.config.js +6 -0
  40. polymarket-trader/frontend/public/vite.svg +1 -0
  41. polymarket-trader/frontend/src/App.css +42 -0
  42. polymarket-trader/frontend/src/App.test.tsx +13 -0
  43. polymarket-trader/frontend/src/App.tsx +243 -0
  44. polymarket-trader/frontend/src/assets/react.svg +1 -0
  45. polymarket-trader/frontend/src/components/ActivePositions.tsx +95 -0
  46. polymarket-trader/frontend/src/components/BotChat.tsx +79 -0
  47. polymarket-trader/frontend/src/components/CopyConfigDialog.tsx +95 -0
  48. polymarket-trader/frontend/src/components/ui/avatar.tsx +47 -0
  49. polymarket-trader/frontend/src/components/ui/badge.tsx +35 -0
  50. polymarket-trader/frontend/src/components/ui/button.tsx +55 -0
.gitattributes CHANGED
@@ -1,35 +1 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.html linguist-detectable=false220Breakout/MT5[[:space:]]trade[[:space:]]report/metrics_graphs.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220Breakout/220Breakout_Analysis.csv ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Category,Item,Value,Description
2
+ General Info,Version,1.10,EA Version
3
+ General Info,Copyright,algorembrant,Author/Copyright Holder
4
+ General Info,Link,https://www.mql5.com,Website Link
5
+ Input (Risk),InpRiskPercent,1.0,Risk per trade (% of Balance)
6
+ Input (Risk),InpRewardRatio,10,Reward Ratio (TP = 10 * Risk)
7
+ Input (Time),InpRangeStartHour,22,Range Start Hour (UTC equivalent)
8
+ Input (Time),InpRangeEndHour,0,Range End Hour (0 = Midnight)
9
+ Input (Time),InpBrokerOffset,0,Broker Time Offset from UTC
10
+ Input (Visuals),InpDrawRange,true,Draw Range Box on Chart
11
+ Input (Visuals),InpBoxColor,clrLavender,Color of the Range Box
12
+ Input (System),InpMagicNum,123456,Magic Number
13
+ Strategy Logic,Timeframe,M3,Hardcoded to 3-Minute Chart Period
14
+ Strategy Logic,Range Calculation,2 Hours,Duration before End Hour (Yesterday 22:00 to Today 00:00 default)
15
+ Strategy Logic,Entry Rule (Buy),Close > HHR,Candle Close above Highest High of Range
16
+ Strategy Logic,Entry Rule (Sell),Close < LLR,Candle Close below Lowest Low of Range
17
+ Strategy Logic,Confirmation,Candle Close,Must wait for M3 candle to close to confirm signal
18
+ Strategy Logic,Filter,IsPathClear,Checks if price touched the level between Range point and Breakout point
19
+ Strategy Logic,Trade Limit,1 per day,Stops trading after one execution (win or loss)
20
+ Strategy Logic,Reset Condition,New Day,Resets daily flags and range validity on new server day
21
+ Risk Management,Stop Loss,Candle Low/High,Low of signal candle (Buy) or High (Sell)
22
+ Risk Management,Take Profit,Risk * RewardRatio,Calculated distance added to/subtracted from entry
23
+ Risk Management,Lot Calculation,% Risk of Balance,Dynamic lot size based on account balance and SL distance
24
+ Risk Management,Order Comments,Range Breakout Buy/Sell,Comments attached to orders
220Breakout/MT5 trade report/ReportTester-263254895(this)-holding.png ADDED
220Breakout/MT5 trade report/ReportTester-263254895(this)-hst.png ADDED
220Breakout/MT5 trade report/ReportTester-263254895(this)-mfemae.png ADDED
220Breakout/MT5 trade report/ReportTester-263254895(this).png ADDED
220Breakout/MT5 trade report/metrics_graphs.png ADDED

Git LFS Details

  • SHA256: f7256a5a21aae14c69a7986d745563cf16db79eb232a52ca8356b15b7f18c76f
  • Pointer size: 132 Bytes
  • Size of remote file: 6.26 MB
220Breakout/report.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Trade Statistics
2
+
3
+ | Metric | Value |
4
+ | :--- | :--- |
5
+ | **Total Net Profit** | 1 218.22 |
6
+ | **Gross Profit** | 2 267.26 |
7
+ | **Gross Loss** | -1 049.04 |
8
+ | **Profit Factor** | 2.16 |
9
+ | **Expected Payoff** | 6.77 |
10
+ | **Balance Drawdown Absolute** | 58.55 |
11
+ | **Balance Drawdown Maximal** | 186.86 (36.27%) |
12
+ | **Balance Drawdown Relative** | 65.59% (79.00) |
13
+ | **Total Trades** | 180 |
14
+ | **Short Positions (won %)** | 80 (7.50%) |
15
+ | **Long Positions (won %)** | 100 (23.00%) |
16
+ | **Profit Trades (% of total)** | 29 (16.11%) |
17
+ | **Loss Trades (% of total)** | 151 (83.89%) |
18
+ | **Largest profit trade** | 313.31 |
19
+ | **Largest loss trade** | -41.99 |
20
+ | **Average profit trade** | 78.18 |
21
+ | **Average loss trade** | -6.95 |
22
+ | **Maximum consecutive wins ($)** | 2 (355.93) |
23
+ | **Maximum consecutive losses ($)** | 30 (-71.36) |
24
+ | **Maximal consecutive profit (count)** | 355.93 (2) |
25
+ | **Maximal consecutive loss (count)** | -186.86 (14) |
26
+ | **Average consecutive wins** | 1 |
27
+ | **Average consecutive losses** | 6 |
220Breakout/strategy.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 220 Breakout Strategy Documentation
2
+
3
+ ## Overview
4
+ **File:** `220breakout.mq5`
5
+ **Timeframe:** M3 (3 Minutes) - *Hardcoded in logic*
6
+ **Type:** Daily Range Breakout
7
+
8
+ The "220 Breakout" strategy identifies a specific time range each day, calculates the High (HHR) and Low (LLR) of that range, and looks for a breakout with a specific validation filter ("Clean Path"). It takes a maximum of one trade per day.
9
+
10
+ ## Trading Logic
11
+
12
+ ### 1. Range Definition
13
+ The strategy defines a "Daily Range" during which it records the Highest High and Lowest Low.
14
+ * **Range End:** Controlled by `InpRangeEndHour` (Default: 00:00 / Midnight).
15
+ * **Range Duration:** **Hardcoded to 2 hours**.
16
+ * *Note:* The input `InpRangeStartHour` exists in the settings but is **ignored** by the logic. The start time is always calculated as `Range End Time - 2 hours`.
17
+ * **Calculation:** At the end of the range, the EA scans the M3 candles inside this window to find:
18
+ * **HHR (Highest High of Range)** & its time (`timeHHR`).
19
+ * **LLR (Lowest Low of Range)** & its time (`timeLLR`).
20
+
21
+ ### 2. Entry Conditions
22
+ The EA checks for signals on every tick, but only acts on completed M3 candles.
23
+
24
+ #### Buy Signal:
25
+ 1. **Breakout:** A candle closes **above** the HHR.
26
+ 2. **Filter (Clean Path):** The path between the original High (`timeHHR`) and the Breakout Candle must be "clear".
27
+ * Use `IsPathClear`: Checks that no other candles between the `timeHHR` and the current Breakout Candle have touched or exceeded the `HHR`. This ensures the breakout is fresh and not a retest of previous choppy price action.
28
+
29
+ #### Sell Signal:
30
+ 1. **Breakout:** A candle closes **below** the LLR.
31
+ 2. **Filter (Clean Path):** The path between the original Low (`timeLLR`) and the Breakout Candle must be "clear".
32
+ * Use `IsPathClear`: Checks that no other candles between the `timeLLR` and the current Breakout Candle have touched or exceeded the `LLR`.
33
+
34
+ ### 3. Execution Rules
35
+ * **One Trade Per Day:** Uses the global flag `tradeTakenToday` to ensure only one entry is made per day.
36
+ * **Trading Window:** Entries are taken after the range is complete.
37
+
38
+ ## Risk Management (Exit Strategy)
39
+
40
+ The strategy uses tight stops and high reward targeting.
41
+
42
+ * **Stop Loss (SL):** Placed at the opposite end of the **Breakout Candle**.
43
+ * **Buy:** SL = Low of the Breakout Candle.
44
+ * **Sell:** SL = High of the Breakout Candle.
45
+ * **Take Profit (TP):** Calculated based on the Reward Ratio.
46
+ * `TP Distance = (Entry Price - SL Price) * InpRewardRatio`.
47
+ * Default Ratio is 10:1 (`InpRewardRatio = 10`).
48
+ * **Position Sizing:**
49
+ * Calculated dynamically based on `InpRiskPercent` (Default: 1.0%).
50
+ * Lot size is determined so that if the SL is hit, the loss equals roughly 1% of the account balance.
51
+
52
+ ## Parameters (Inputs)
53
+
54
+ | Group | Parameter | Default | Description |
55
+ | :--- | :--- | :--- | :--- |
56
+ | **Risk Management** | `InpRiskPercent` | `1.0` | Risk per trade as % of Balance. |
57
+ | | `InpRewardRatio` | `10` | Multiplier for TP (e.g., 10 means 10R). |
58
+ | **Time Settings** | `InpRangeStartHour`| `22` | *Actually Unused in calculation (Overridden by 2h duration).* |
59
+ | | `InpRangeEndHour` | `0` | Hour when the range calculation ends (0 = Midnight). |
60
+ | | `InpBrokerOffset` | `0` | Adjusts server time if needed. |
61
+ | **Visuals** | `InpDrawRange` | `true` | Draws the range box on the chart. |
62
+ | | `InpBoxColor` | `clrLavender` | Color of the range box. |
63
+ | **System** | `InpMagicNum` | `123456` | Magic number to identify EA orders. |
64
+
65
+ ## Technical Notes
66
+ * **Clean Path Algorithm:** The `IsPathClear` function iterates entirely through M3 bars between the Extreme Point (EP) and the Breakout Candle. This might be computationally intensive if the breakout happens very late in the day, but safeguards against "messy" breakouts.
67
+ * **Hardcoded Timeframe:** Logic explicitly calls `CopyRates(_Symbol, PERIOD_M3, ...)`. Running the EA on an M15 or H1 chart will not change the logic; it will still look at M3 data internally.
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ![Awesome](https://img.shields.io/badge/awesome-yes-8a2be2.svg?style=flat-square) ![Last Commit](https://img.shields.io/badge/last%20commit-january%202026-9acd32.svg?style=flat-square) ![Go](https://img.shields.io/badge/go-%2300ADD8.svg?style=flat-square&logo=go&logoColor=white) ![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=flat-square&logo=typescript&logoColor=white) ![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=flat-square&logo=javascript&logoColor=%23F7DF1E) ![HTML5](https://img.shields.io/badge/html5-%23E34F26.svg?style=flat-square&logo=html5&logoColor=white) ![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=flat-square&logo=css3&logoColor=white) ![React](https://img.shields.io/badge/react-%2320232a.svg?style=flat-square&logo=react&logoColor=%2361DAFB) ![TailwindCSS](https://img.shields.io/badge/tailwindcss-%2338B2AC.svg?style=flat-square&logo=tailwind-css&logoColor=white) ![Vite](https://img.shields.io/badge/vite-%23646CFF.svg?style=flat-square&logo=vite&logoColor=white) ![Docker](https://img.shields.io/badge/docker-%230db7ed.svg?style=flat-square&logo=docker&logoColor=white) ![PostCSS](https://img.shields.io/badge/postcss-%23DD3A0A.svg?style=flat-square&logo=postcss&logoColor=white) ![JSON](https://img.shields.io/badge/json-%23000000.svg?style=flat-square&logo=json&logoColor=white) ![YAML](https://img.shields.io/badge/yaml-%23ffffff.svg?style=flat-square&logo=yaml&logoColor=black) ![Markdown](https://img.shields.io/badge/markdown-%23000000.svg?style=flat-square&logo=markdown&logoColor=white) ![Git](https://img.shields.io/badge/git-%23F05033.svg?style=flat-square&logo=git&logoColor=white) ![ESLint](https://img.shields.io/badge/eslint-%234B32C3.svg?style=flat-square&logo=eslint&logoColor=white)
3
+
4
+ # Polymarket Trader
5
+
6
+ A comprehensive trading application built with a Go backend and a React/TypeScript frontend.
7
+
8
+ ## Project Structure
9
+
10
+ This project is organized into a clear separation of concerns between the backend and frontend services.
11
+
12
+ ```text
13
+ polymarket-trader
14
+ ├── .gitignore
15
+ ├── docker-compose.yml
16
+ ├── backend
17
+ │ ├── .env.example
18
+ │ ├── go.mod
19
+ │ ├── go.sum
20
+ │ ├── server.exe
21
+ │ ├── cmd
22
+ │ │ └── server
23
+ │ │ ├── main.go
24
+ │ │ └── main_test.go
25
+ │ └── internal
26
+ │ ├── adapters
27
+ │ │ └── polymarket
28
+ │ │ ├── client.go
29
+ │ │ └── websocket.go
30
+ │ ├── api
31
+ │ │ ├── handlers.go
32
+ │ │ └── router.go
33
+ │ ├── config
34
+ │ │ └── config.go
35
+ │ ├── core
36
+ │ │ ├── analytics.go
37
+ │ │ ├── copy_engine.go
38
+ │ │ └── trader_discovery.go
39
+ │ └── models
40
+ │ └── models.go
41
+ └── frontend
42
+ ├── .gitignore
43
+ ├── components.json
44
+ ├── eslint.config.js
45
+ ├── index.html
46
+ ├── package-lock.json
47
+ ├── package.json
48
+ ├── postcss.config.js
49
+ ├── tailwind.config.js
50
+ ├── tsconfig.app.json
51
+ ├── tsconfig.json
52
+ ├── tsconfig.node.json
53
+ ├── vite.config.ts
54
+ ├── public
55
+ │ └── vite.svg
56
+ └── src
57
+ ├── App.css
58
+ ├── App.test.tsx
59
+ ├── App.tsx
60
+ ├── index.css
61
+ ├── main.tsx
62
+ ├── assets
63
+ │ └── react.svg
64
+ ├── components
65
+ │ ├── ActivePositions.tsx
66
+ │ ├── BotChat.tsx
67
+ │ ├── CopyConfigDialog.tsx
68
+ │ └── ui
69
+ │ ├── avatar.tsx
70
+ │ ├── badge.tsx
71
+ │ ├── button.tsx
72
+ │ ├── card.tsx
73
+ │ ├── dialog.tsx
74
+ │ ├── input.tsx
75
+ │ ├── label.tsx
76
+ │ ├── scroll-area.tsx
77
+ │ ├── table.tsx
78
+ │ └── tabs.tsx
79
+ ├── lib
80
+ │ └── utils.ts
81
+ └── test
82
+ └── setup.ts
83
+ ```
84
+
85
+ ## Backend (`/backend`)
86
+ The backend is built with **Go** and follows a standard clean architecture layout:
87
+ - **`cmd/`**: Contains the main entry points for the application.
88
+ - **`internal/`**: Private application code.
89
+ - **`adapters/`**: implementations of interfaces for external services (e.g., Polymarket).
90
+ - **`api/`**: HTTP handlers and router configuration.
91
+ - **`core/`**: Business logic and domain services.
92
+
93
+ ## Frontend (`/frontend`)
94
+ The frontend is a **React** application powered by **Vite** and **TypeScript**:
95
+ - **`src/`**: Source code for the frontend application.
96
+ - **`components/`**: Reusable UI components.
97
+ - **`lib/`**: Helper functions and utilities.
STRUCTURE.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Project Structure
2
+
3
+ ```text
4
+ Polymarket-tra/
5
+ ├── 220Breakout/
6
+ │ ├── MT5 trade report/
7
+ │ │ ├── metrics_graphs.png
8
+ │ │ ├── ReportTester-263254895(this)-holding.png
9
+ │ │ ├── ReportTester-263254895(this)-hst.png
10
+ │ │ ├── ReportTester-263254895(this)-mfemae.png
11
+ │ │ ├── ReportTester-263254895(this).html
12
+ │ │ ├── ReportTester-263254895(this).png
13
+ │ │ └── ReportTester-263254895(this).xlsx
14
+ │ ├── 220Breakout_Analysis.csv
15
+ │ ├── report.md
16
+ │ └── strategy.md
17
+ ├── md2pdf_workspace/
18
+ │ ├── input/
19
+ │ │ └── drop the csv file here
20
+ │ ├── output/
21
+ │ │ └── the output pdf goes here
22
+ │ ├── main.py
23
+ │ ├── requirements.txt
24
+ │ └── steps.md
25
+ ├── output/
26
+ ├── polymarket-trader/
27
+ │ ├── backend/
28
+ │ │ ├── cmd/
29
+ │ │ │ └── server/
30
+ │ │ │ ├── main.go
31
+ │ │ │ └── main_test.go
32
+ │ │ ├── internal/
33
+ │ │ │ ├── adapters/
34
+ │ │ │ │ └── polymarket/
35
+ │ │ │ │ ├── client.go
36
+ │ │ │ │ └── websocket.go
37
+ │ │ │ ├── api/
38
+ │ │ │ │ ├── handlers.go
39
+ │ │ │ │ └── router.go
40
+ │ │ │ ├── config/
41
+ │ │ │ │ └── config.go
42
+ │ │ │ ├── core/
43
+ │ │ │ │ ├── analytics.go
44
+ │ │ │ │ ├── copy_engine.go
45
+ │ │ │ │ └── trader_discovery.go
46
+ │ │ │ └── models/
47
+ │ │ │ └── models.go
48
+ │ │ ├── .env.example
49
+ │ │ ├── go.mod
50
+ │ │ ├── go.sum
51
+ │ │ ├── server.exe
52
+ │ │ └── server.exe~
53
+ │ ├── frontend/
54
+ │ │ ├── public/
55
+ │ │ │ └── vite.svg
56
+ │ │ ├── src/
57
+ │ │ │ ├── assets/
58
+ │ │ │ │ └── react.svg
59
+ │ │ │ ├── components/
60
+ │ │ │ │ ├── ui/
61
+ │ │ │ │ │ ├── avatar.tsx
62
+ │ │ │ │ │ ├── badge.tsx
63
+ │ │ │ │ │ ├── button.tsx
64
+ │ │ │ │ │ ├── card.tsx
65
+ │ │ │ │ │ ├── dialog.tsx
66
+ │ │ │ │ │ ├── input.tsx
67
+ │ │ │ │ │ ├── label.tsx
68
+ │ │ │ │ │ ├── scroll-area.tsx
69
+ │ │ │ │ │ ├── table.tsx
70
+ │ │ │ │ │ └── tabs.tsx
71
+ │ │ │ │ ├── ActivePositions.tsx
72
+ │ │ │ │ ├── BotChat.tsx
73
+ │ │ │ │ └── CopyConfigDialog.tsx
74
+ │ │ │ ├── lib/
75
+ │ │ │ │ └── utils.ts
76
+ │ │ │ ├── test/
77
+ │ │ │ │ └── setup.ts
78
+ │ │ │ ├── App.css
79
+ │ │ │ ├── App.test.tsx
80
+ │ │ │ ├── App.tsx
81
+ │ │ │ ├── index.css
82
+ │ │ │ └── main.tsx
83
+ │ │ ├── .gitignore
84
+ │ │ ├── components.json
85
+ │ │ ├── eslint.config.js
86
+ │ │ ├── index.html
87
+ │ │ ├── package-lock.json
88
+ │ │ ├── package.json
89
+ │ │ ├── postcss.config.js
90
+ │ │ ├── README.md
91
+ │ │ ├── tailwind.config.js
92
+ │ │ ├── tsconfig.app.json
93
+ │ │ ├── tsconfig.json
94
+ │ │ ├── tsconfig.node.json
95
+ │ │ └── vite.config.ts
96
+ │ ├── .gitignore
97
+ │ └── docker-compose.yml
98
+ ├── .gitattributes
99
+ ├── LICENSE
100
+ ├── README.md
101
+ └── TECHSTACK.md
102
+ ```
TECHSTACK.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Techstack
2
+
3
+ Audit of **Polymarket-tra** project files (excluding environment and cache):
4
+
5
+ | File Type | Count | Size (KB) |
6
+ | :--- | :--- | :--- |
7
+ | TSX (React) (.tsx) | 16 | 40.4 |
8
+ | Go (.go) | 11 | 17.8 |
9
+ | (no extension) | 6 | 11.7 |
10
+ | JSON (.json) | 6 | 197.7 |
11
+ | Markdown (.md) | 5 | 12.6 |
12
+ | PNG Image (.png) | 5 | 6,181.4 |
13
+ | JavaScript (.js) | 3 | 0.9 |
14
+ | MPEG-TS (.ts) | 3 | 0.6 |
15
+ | CSS (.css) | 2 | 2.1 |
16
+ | HTML (.html) | 2 | 381.8 |
17
+ | SVG Image (.svg) | 2 | 5.5 |
18
+ | CSV (.csv) | 1 | 1.7 |
19
+ | EXAMPLE (.example) | 1 | 0.4 |
20
+ | EXE~ (.exe~) | 1 | 11,602.5 |
21
+ | Microsoft Excel (OOXML) (.xlsx) | 1 | 103.3 |
22
+ | MOD (.mod) | 1 | 0.8 |
23
+ | Plain Text (.txt) | 1 | 0.0 |
24
+ | Python (.py) | 1 | 4.6 |
25
+ | SUM (.sum) | 1 | 3.2 |
26
+ | Windows Executable (.exe) | 1 | 11,603.0 |
27
+ | YAML (.yml) | 1 | 0.5 |
28
+ | **Total** | **71** | **30,172.7** |
md2pdf_workspace/main.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import time
3
+ import os
4
+ import logging
5
+ from watchdog.observers import Observer
6
+ from watchdog.events import FileSystemEventHandler
7
+ import markdown
8
+ from xhtml2pdf import pisa
9
+ import threading
10
+
11
+ # Configuration
12
+ INPUT_DIR = os.path.abspath("input")
13
+ OUTPUT_DIR = os.path.abspath("output")
14
+
15
+ # Ensure directories exist
16
+ os.makedirs(INPUT_DIR, exist_ok=True)
17
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
18
+
19
+ logging.basicConfig(level=logging.INFO,
20
+ format='%(asctime)s - %(message)s',
21
+ datefmt='%Y-%m-%d %H:%M:%S')
22
+
23
+ def convert_md_to_pdf(input_path):
24
+ """Reads a markdown file and converts it to PDF."""
25
+ try:
26
+ filename = os.path.basename(input_path)
27
+ name, _ = os.path.splitext(filename)
28
+ output_path = os.path.join(OUTPUT_DIR, f"{name}.pdf")
29
+
30
+ logging.info(f"Processing: {filename}")
31
+
32
+ # 1. Read Markdown
33
+ with open(input_path, 'r', encoding='utf-8') as f:
34
+ md_content = f.read()
35
+
36
+ # 2. Convert to HTML with tables extension
37
+ # Using 'markdown.extensions.tables' for table support
38
+ # Using 'markdown.extensions.fenced_code' for code blocks
39
+ html_content = markdown.markdown(md_content, extensions=['tables', 'fenced_code'])
40
+
41
+ # 3. Add basic styling for PDF
42
+ # xhtml2pdf supports some CSS. We add borders to tables to make them visible.
43
+ full_html = f"""
44
+ <html>
45
+ <head>
46
+ <style>
47
+ @page {{
48
+ size: A4;
49
+ margin: 2cm;
50
+ }}
51
+ body {{
52
+ font-family: Helvetica, sans-serif;
53
+ font-size: 12pt;
54
+ }}
55
+ table {{
56
+ border: 1px solid black;
57
+ border-collapse: collapse;
58
+ width: 100%;
59
+ margin-bottom: 1em;
60
+ }}
61
+ th, td {{
62
+ border: 1px solid black;
63
+ padding: 5px;
64
+ text-align: left;
65
+ }}
66
+ th {{
67
+ background-color: #f2f2f2;
68
+ font-weight: bold;
69
+ }}
70
+ code {{
71
+ font-family: Courier;
72
+ background-color: #f5f5f5;
73
+ }}
74
+ pre {{
75
+ background-color: #f5f5f5;
76
+ padding: 10px;
77
+ border: 1px solid #ccc;
78
+ }}
79
+ </style>
80
+ </head>
81
+ <body>
82
+ {html_content}
83
+ </body>
84
+ </html>
85
+ """
86
+
87
+ # 4. Generate PDF
88
+ with open(output_path, "wb") as pdf_file:
89
+ pisa_status = pisa.CreatePDF(
90
+ full_html, # the HTML to convert
91
+ dest=pdf_file # file handle to receive result
92
+ )
93
+
94
+ if pisa_status.err:
95
+ logging.error(f"Error converting {filename}: {pisa_status.err}")
96
+ else:
97
+ logging.info(f"Successfully created: {output_path}")
98
+
99
+ except Exception as e:
100
+ logging.error(f"Failed to convert {input_path}: {e}")
101
+
102
+ class MDHandler(FileSystemEventHandler):
103
+ def on_created(self, event):
104
+ if not event.is_directory and event.src_path.lower().endswith('.md'):
105
+ # Waiting a brief moment to ensure file write is complete is sometimes helpful,
106
+ # but usually open/read handles it. To be safe:
107
+ time.sleep(0.5)
108
+ convert_md_to_pdf(event.src_path)
109
+
110
+ # Also handle modified events in case user edits the file in place?
111
+ # The prompt said "put the md file ... directly parser it", so 'created' is primary.
112
+ # 'modified' might trigger too often during saving. Let's stick to 'created' and 'moved'
113
+ # or just 'created' as per "drop file in".
114
+ # Actually, if I copy paste a file, it's created.
115
+ # If I edit and save, it's modified.
116
+ # Let's support on_modified too for better UX, but duplicate events might be an issue.
117
+ # We'll stick to 'created' for the "drop file" workflow to be clean.
118
+
119
+ def on_moved(self, event):
120
+ if not event.is_directory and event.dest_path.lower().endswith('.md'):
121
+ time.sleep(0.5)
122
+ convert_md_to_pdf(event.dest_path)
123
+
124
+ if __name__ == "__main__":
125
+ logging.info("Starting Watchdog for MD -> PDF conversion...")
126
+ logging.info(f"Monitoring: {INPUT_DIR}")
127
+ logging.info(f"Output to: {OUTPUT_DIR}")
128
+
129
+ event_handler = MDHandler()
130
+ observer = Observer()
131
+ observer.schedule(event_handler, INPUT_DIR, recursive=False)
132
+ observer.start()
133
+
134
+ try:
135
+ while True:
136
+ time.sleep(1)
137
+ except KeyboardInterrupt:
138
+ observer.stop()
139
+ observer.join()
md2pdf_workspace/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ watchdog
2
+ markdown
3
+ xhtml2pdf
md2pdf_workspace/steps.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 1) bash
2
+
3
+ pip install -r requirements.txt
4
+
5
+ 2) bash or run the python script once
6
+
7
+ python convert.py
8
+
9
+ 3) drop md file @input folder
10
+ 4) let the bot do the rest and wait for the pdf to be generated @output folder
11
+
12
+
polymarket-trader/.gitignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Binaries
2
+ bin/
3
+ dist/
4
+ main.exe
5
+ main
6
+
7
+ # Directories
8
+ node_modules/
9
+ .idea/
10
+ .vscode/
11
+
12
+ # Environment
13
+ .env
14
+ .env.local
15
+
16
+ # Docker
17
+ docker-data/
18
+
19
+ # OS
20
+ .DS_Store
21
+ Thumbs.db
polymarket-trader/backend/.env.example ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Server Configuration
2
+ SERVER_PORT=8080
3
+ DATABASE_URL=host=localhost user=user password=password dbname=polymarket port=5432 sslmode=disable
4
+ REDIS_ADDR=localhost:6379
5
+
6
+ # Polymarket API (Found in your Proxy Wallet / Relayer settings)
7
+ # Required for Real Trading and Private Data
8
+ POLYMARKET_API_URL=https://clob.polymarket.com
9
+ PRIVATE_KEY=0x...
10
+ API_KEY=...
11
+ API_SECRET=...
12
+ API_PASSPHRASE=...
polymarket-trader/backend/cmd/server/main.go ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "log"
5
+
6
+ "github.com/gofiber/fiber/v2"
7
+ "github.com/gofiber/fiber/v2/middleware/cors"
8
+ "github.com/gofiber/fiber/v2/middleware/logger"
9
+ "github.com/user/polymarket-trader/internal/adapters/polymarket"
10
+ "github.com/user/polymarket-trader/internal/api"
11
+ "github.com/user/polymarket-trader/internal/config"
12
+ "github.com/user/polymarket-trader/internal/core"
13
+ )
14
+
15
+ func main() {
16
+ // Load Config
17
+ cfg := config.LoadConfig()
18
+
19
+ // Initialize Adapters
20
+ pmClient := polymarket.NewClient(cfg)
21
+ pmWS := polymarket.NewWSClient()
22
+
23
+ // Start WS connection (in background)
24
+ if err := pmWS.Connect(); err != nil {
25
+ log.Printf("Warning: Failed to connect to Polymarket WS: %v", err)
26
+ }
27
+
28
+ // Initialize Core Services
29
+ copyEngine := core.NewCopyEngine(pmClient, pmWS)
30
+ copyEngine.Start()
31
+
32
+ discoveryService := core.NewTraderDiscoveryService()
33
+
34
+ // Initialize Handler
35
+ h := api.NewHandler(discoveryService, copyEngine)
36
+
37
+ // Initialize Fiber app
38
+ app := fiber.New(fiber.Config{
39
+ AppName: "Polymarket Trader Engine",
40
+ })
41
+
42
+ // Middleware
43
+ app.Use(logger.New())
44
+ app.Use(cors.New())
45
+
46
+ // Routes
47
+ api.SetupRoutes(app, h)
48
+
49
+ // Health Check
50
+ app.Get("/health", func(c *fiber.Ctx) error {
51
+ return c.JSON(fiber.Map{
52
+ "status": "ok",
53
+ "uptime": "running",
54
+ "env": cfg.ServerPort,
55
+ })
56
+ })
57
+
58
+ // Start Server
59
+ log.Printf("Starting server on port %s", cfg.ServerPort)
60
+ log.Fatal(app.Listen(":" + cfg.ServerPort))
61
+ }
polymarket-trader/backend/cmd/server/main_test.go ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "net/http/httptest"
7
+ "testing"
8
+
9
+ "github.com/gofiber/fiber/v2"
10
+ "github.com/gofiber/fiber/v2/middleware/cors"
11
+ "github.com/stretchr/testify/assert"
12
+ "github.com/user/polymarket-trader/internal/api"
13
+ "github.com/user/polymarket-trader/internal/core"
14
+ "github.com/user/polymarket-trader/internal/models"
15
+ )
16
+
17
+ // setupTestApp creates a fiber app with the same configuration as main, but with mocked/nil external clients
18
+ func setupTestApp() *fiber.App {
19
+ // Initialize Core Services with nil clients for testing logic that doesn't strictly depend on them for these endpoints
20
+ // Note: In a real scenario, we would interface these out and provide mocks.
21
+ // For this basic smoke test, we rely on the fact that StartCopying doesn't immediately use the clients.
22
+ copyEngine := core.NewCopyEngine(nil, nil)
23
+
24
+ // We don't start the copy engine background routines to avoid nil pointer dereferences on clients
25
+
26
+ discoveryService := core.NewTraderDiscoveryService()
27
+
28
+ // Initialize Handler
29
+ h := api.NewHandler(discoveryService, copyEngine)
30
+
31
+ // Initialize Fiber app
32
+ app := fiber.New()
33
+ app.Use(cors.New())
34
+
35
+ // Routes
36
+ api.SetupRoutes(app, h)
37
+
38
+ // Health Check (replicated from main)
39
+ app.Get("/health", func(c *fiber.Ctx) error {
40
+ return c.JSON(fiber.Map{
41
+ "status": "ok",
42
+ "uptime": "running",
43
+ "env": "test",
44
+ })
45
+ })
46
+
47
+ return app
48
+ }
49
+
50
+ func TestHealthCheck(t *testing.T) {
51
+ app := setupTestApp()
52
+
53
+ req := httptest.NewRequest("GET", "/health", nil)
54
+ resp, err := app.Test(req)
55
+
56
+ assert.NoError(t, err)
57
+ assert.Equal(t, 200, resp.StatusCode)
58
+ }
59
+
60
+ func TestStartCopying(t *testing.T) {
61
+ app := setupTestApp()
62
+
63
+ payload := models.CopyConfig{
64
+ TraderAddress: "0xTestTrader",
65
+ FixedSize: 10.0,
66
+ Enabled: true,
67
+ }
68
+ body, _ := json.Marshal(payload)
69
+
70
+ req := httptest.NewRequest("POST", "/api/copy", bytes.NewReader(body))
71
+ req.Header.Set("Content-Type", "application/json")
72
+
73
+ resp, err := app.Test(req)
74
+
75
+ assert.NoError(t, err)
76
+ assert.Equal(t, 200, resp.StatusCode)
77
+ }
78
+
79
+ func TestGetPositions(t *testing.T) {
80
+ app := setupTestApp()
81
+
82
+ req := httptest.NewRequest("GET", "/api/positions", nil)
83
+ resp, err := app.Test(req)
84
+
85
+ assert.NoError(t, err)
86
+ assert.Equal(t, 200, resp.StatusCode)
87
+ }
polymarket-trader/backend/go.mod ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module github.com/user/polymarket-trader
2
+
3
+ go 1.25.6
4
+
5
+ require (
6
+ github.com/gofiber/fiber/v2 v2.52.10
7
+ github.com/gorilla/websocket v1.5.3
8
+ )
9
+
10
+ require (
11
+ github.com/andybalholm/brotli v1.1.0 // indirect
12
+ github.com/davecgh/go-spew v1.1.1 // indirect
13
+ github.com/google/uuid v1.6.0 // indirect
14
+ github.com/klauspost/compress v1.17.9 // indirect
15
+ github.com/mattn/go-colorable v0.1.13 // indirect
16
+ github.com/mattn/go-isatty v0.0.20 // indirect
17
+ github.com/mattn/go-runewidth v0.0.16 // indirect
18
+ github.com/pmezard/go-difflib v1.0.0 // indirect
19
+ github.com/rivo/uniseg v0.2.0 // indirect
20
+ github.com/stretchr/testify v1.11.1 // indirect
21
+ github.com/valyala/bytebufferpool v1.0.0 // indirect
22
+ github.com/valyala/fasthttp v1.51.0 // indirect
23
+ github.com/valyala/tcplisten v1.0.0 // indirect
24
+ golang.org/x/sys v0.36.0 // indirect
25
+ gopkg.in/yaml.v3 v3.0.1 // indirect
26
+ )
polymarket-trader/backend/go.sum ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
2
+ github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
3
+ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
4
+ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
5
+ github.com/gofiber/fiber/v2 v2.52.10 h1:jRHROi2BuNti6NYXmZ6gbNSfT3zj/8c0xy94GOU5elY=
6
+ github.com/gofiber/fiber/v2 v2.52.10/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
7
+ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
8
+ github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
9
+ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
10
+ github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
11
+ github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
12
+ github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
13
+ github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
14
+ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
15
+ github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
16
+ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
17
+ github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
18
+ github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
19
+ github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
20
+ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
21
+ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
22
+ github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
23
+ github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
24
+ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
25
+ github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
26
+ github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
27
+ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
28
+ github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
29
+ github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
30
+ github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
31
+ github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
32
+ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
33
+ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
34
+ golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
35
+ golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
36
+ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
37
+ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
38
+ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
polymarket-trader/backend/internal/adapters/polymarket/client.go ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package polymarket
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "fmt"
7
+ "net/http"
8
+ "time"
9
+
10
+ "github.com/user/polymarket-trader/internal/config"
11
+ )
12
+
13
+ type Client struct {
14
+ BaseURL string
15
+ HTTPClient *http.Client
16
+ Config *config.Config
17
+ }
18
+
19
+ func NewClient(cfg *config.Config) *Client {
20
+ return &Client{
21
+ BaseURL: cfg.PolymarketAPI,
22
+ HTTPClient: &http.Client{
23
+ Timeout: 10 * time.Second,
24
+ },
25
+ Config: cfg,
26
+ }
27
+ }
28
+
29
+ // Basic struct for placing an order (simplified for Clob)
30
+ type OrderRequest struct {
31
+ TokenID string `json:"token_id"`
32
+ Price float64 `json:"price"`
33
+ Side string `json:"side"` // "BUY" or "SELL"
34
+ Size float64 `json:"size"`
35
+ FeeRate int `json:"fee_rate_bps"`
36
+ }
37
+
38
+ // PlaceOrder sends an order to the CLOB
39
+ func (c *Client) PlaceOrder(req OrderRequest) error {
40
+ // TODO: Implement signing logic using EIP-712
41
+ // This is a placeholder for the structure
42
+
43
+ url := fmt.Sprintf("%s/order", c.BaseURL)
44
+ jsonData, _ := json.Marshal(req)
45
+
46
+ r, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
47
+ if err != nil {
48
+ return err
49
+ }
50
+ r.Header.Set("Content-Type", "application/json")
51
+ // Add Auth headers (Polymarket-ApiKey, Signature, etc.)
52
+
53
+ resp, err := c.HTTPClient.Do(r)
54
+ if err != nil {
55
+ return err
56
+ }
57
+ defer resp.Body.Close()
58
+
59
+ if resp.StatusCode != http.StatusOK {
60
+ return fmt.Errorf("order failed with status: %d", resp.StatusCode)
61
+ }
62
+
63
+ return nil
64
+ }
polymarket-trader/backend/internal/adapters/polymarket/websocket.go ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package polymarket
2
+
3
+ import (
4
+ "encoding/json"
5
+ "log"
6
+
7
+ "github.com/gorilla/websocket"
8
+ )
9
+
10
+ const WSURL = "wss://ws-subscriptions-clob.polymarket.com/ws/market"
11
+
12
+ type WSClient struct {
13
+ Conn *websocket.Conn
14
+ MsgChan chan []byte
15
+ PriceUpdateChan chan PriceUpdate
16
+ Done chan struct{}
17
+ }
18
+
19
+ type PriceUpdate struct {
20
+ MarketID string
21
+ Price float64
22
+ }
23
+
24
+ func NewWSClient() *WSClient {
25
+ return &WSClient{
26
+ MsgChan: make(chan []byte, 100),
27
+ PriceUpdateChan: make(chan PriceUpdate, 100),
28
+ Done: make(chan struct{}),
29
+ }
30
+ }
31
+
32
+ func (w *WSClient) Connect() error {
33
+ c, _, err := websocket.DefaultDialer.Dial(WSURL, nil)
34
+ if err != nil {
35
+ return err
36
+ }
37
+ w.Conn = c
38
+
39
+ // Start reading loop
40
+ go w.readLoop()
41
+ return nil
42
+ }
43
+
44
+ func (w *WSClient) readLoop() {
45
+ defer close(w.Done)
46
+ for {
47
+ _, message, err := w.Conn.ReadMessage()
48
+ if err != nil {
49
+ log.Println("ws read error:", err)
50
+ return
51
+ }
52
+
53
+ // Parse message (Simplified for demo)
54
+ // We optimistically try to parse as a price update
55
+ // In a real app, we'd check event type first
56
+ var update struct {
57
+ Type string `json:"event_type"`
58
+ Market string `json:"asset_id"`
59
+ Price float64 `json:"price"` // Assuming normalized price
60
+ // CLOB messages are more complex (Orders, Trades, etc.)
61
+ // We'll treat this as a generic update container for now
62
+ }
63
+
64
+ if err := json.Unmarshal(message, &update); err == nil {
65
+ if update.Market != "" && update.Price > 0 {
66
+ w.PriceUpdateChan <- PriceUpdate{
67
+ MarketID: update.Market,
68
+ Price: update.Price,
69
+ }
70
+ }
71
+ }
72
+
73
+ w.MsgChan <- message
74
+ }
75
+ }
76
+
77
+ type SubscriptionMsg struct {
78
+ Type string `json:"type"`
79
+ Channel string `json:"channel"`
80
+ Assets []string `json:"assets_ids,omitempty"`
81
+ }
82
+
83
+ func (w *WSClient) Subscribe(assetIDs []string) error {
84
+ msg := SubscriptionMsg{
85
+ Type: "Market", // Example type
86
+ Channel: "price_change", // Example channel
87
+ Assets: assetIDs,
88
+ }
89
+ return w.Conn.WriteJSON(msg)
90
+ }
polymarket-trader/backend/internal/api/handlers.go ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package api
2
+
3
+ import (
4
+ "github.com/gofiber/fiber/v2"
5
+ "github.com/user/polymarket-trader/internal/core"
6
+ "github.com/user/polymarket-trader/internal/models"
7
+ )
8
+
9
+ type Handler struct {
10
+ Discovery *core.TraderDiscoveryService
11
+ CopyEngine *core.CopyEngine
12
+ }
13
+
14
+ func NewHandler(d *core.TraderDiscoveryService, c *core.CopyEngine) *Handler {
15
+ return &Handler{
16
+ Discovery: d,
17
+ CopyEngine: c,
18
+ }
19
+ }
20
+
21
+ // GetTopTraders returns the list of discovered traders
22
+ func (h *Handler) GetTopTraders(c *fiber.Ctx) error {
23
+ traders, err := h.Discovery.FetchTopTraders()
24
+ if err != nil {
25
+ return c.Status(500).JSON(fiber.Map{"error": err.Error()})
26
+ }
27
+ return c.JSON(traders)
28
+ }
29
+
30
+ // StartCopying adds a trader to the copy engine
31
+ func (h *Handler) StartCopying(c *fiber.Ctx) error {
32
+ var req models.CopyConfig
33
+ if err := c.BodyParser(&req); err != nil {
34
+ return c.Status(400).JSON(fiber.Map{"error": "Invalid input"})
35
+ }
36
+
37
+ h.CopyEngine.AddTrader(req)
38
+ return c.JSON(fiber.Map{"status": "monitoring", "trader": req.TraderAddress})
39
+ }
40
+
41
+ // GetPositions returns active positions
42
+ func (h *Handler) GetPositions(c *fiber.Ctx) error {
43
+ positions := h.CopyEngine.GetActivePositions()
44
+ return c.JSON(positions)
45
+ }
polymarket-trader/backend/internal/api/router.go ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package api
2
+
3
+ import (
4
+ "github.com/gofiber/fiber/v2"
5
+ )
6
+
7
+ func SetupRoutes(app *fiber.App, h *Handler) {
8
+ api := app.Group("/api")
9
+
10
+ api.Get("/traders", h.GetTopTraders)
11
+ api.Post("/copy", h.StartCopying)
12
+ api.Get("/positions", h.GetPositions)
13
+ }
polymarket-trader/backend/internal/config/config.go ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package config
2
+
3
+ import (
4
+ "os"
5
+ )
6
+
7
+ type Config struct {
8
+ ServerPort string
9
+ DatabaseURL string
10
+ RedisAddr string
11
+ PolymarketAPI string
12
+ PrivateKey string
13
+ ApiKey string
14
+ ApiSecret string
15
+ ApiPassphrase string
16
+ }
17
+
18
+ func LoadConfig() *Config {
19
+ return &Config{
20
+ ServerPort: getEnv("SERVER_PORT", "8080"),
21
+ DatabaseURL: getEnv("DATABASE_URL", "host=localhost user=user password=password dbname=polymarket port=5432 sslmode=disable"),
22
+ RedisAddr: getEnv("REDIS_ADDR", "localhost:6379"),
23
+ PolymarketAPI: getEnv("POLYMARKET_API_URL", "https://clob.polymarket.com"),
24
+ PrivateKey: getEnv("PRIVATE_KEY", ""),
25
+ ApiKey: getEnv("API_KEY", ""),
26
+ ApiSecret: getEnv("API_SECRET", ""),
27
+ ApiPassphrase: getEnv("API_PASSPHRASE", ""),
28
+ }
29
+ }
30
+
31
+ func getEnv(key, fallback string) string {
32
+ if value, exists := os.LookupEnv(key); exists {
33
+ return value
34
+ }
35
+ return fallback
36
+ }
polymarket-trader/backend/internal/core/analytics.go ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "github.com/user/polymarket-trader/internal/models"
5
+ )
6
+
7
+ // CalculateTraderPerformance computes WinRate and Total PnL from a history of trades
8
+ func CalculateTraderPerformance(trades []models.HistoricalTrade) (float64, float64, int) {
9
+ if len(trades) == 0 {
10
+ return 0, 0, 0
11
+ }
12
+
13
+ totalPnL := 0.0
14
+ wins := 0
15
+ count := 0
16
+
17
+ // We assume 'trades' contains realized trades (sells/exits) that have a PnL value
18
+ // Or we might need to group buys/sells to calculate realized PnL.
19
+ // For simplicity, we assume the input is a list of "Closed Positions" or "Realized Trades" with PnL pre-calculated or calculable.
20
+
21
+ for _, t := range trades {
22
+ // Only count trades that are "exits" or have realized PnL
23
+ if t.PnL != 0 {
24
+ totalPnL += t.PnL
25
+ if t.PnL > 0 {
26
+ wins++
27
+ }
28
+ count++
29
+ }
30
+ }
31
+
32
+ winRate := 0.0
33
+ if count > 0 {
34
+ winRate = float64(wins) / float64(count)
35
+ }
36
+
37
+ return winRate, totalPnL, count
38
+ }
polymarket-trader/backend/internal/core/copy_engine.go ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "log"
5
+ "sync"
6
+ "time"
7
+
8
+ "github.com/user/polymarket-trader/internal/adapters/polymarket"
9
+ "github.com/user/polymarket-trader/internal/models"
10
+ )
11
+
12
+ type CopyEngine struct {
13
+ Client *polymarket.Client
14
+ WS *polymarket.WSClient
15
+ Monitored map[string]models.CopyConfig // Key: TraderAddress
16
+ ActivePositions map[uint]*models.Position // Key: Position ID (simulated for now)
17
+ SignalChan chan models.Position // Ingest signals here
18
+ mu sync.RWMutex
19
+ posIDCounter uint
20
+ }
21
+
22
+ func NewCopyEngine(client *polymarket.Client, ws *polymarket.WSClient) *CopyEngine {
23
+ return &CopyEngine{
24
+ Client: client,
25
+ WS: ws,
26
+ Monitored: make(map[string]models.CopyConfig),
27
+ ActivePositions: make(map[uint]*models.Position),
28
+ SignalChan: make(chan models.Position, 100),
29
+ posIDCounter: 1,
30
+ }
31
+ }
32
+
33
+ func (e *CopyEngine) Start() {
34
+ log.Println("Starting Copy Engine...")
35
+ go e.processSignals()
36
+ go e.processPriceUpdates()
37
+ }
38
+
39
+ func (e *CopyEngine) processPriceUpdates() {
40
+ if e.WS == nil {
41
+ return
42
+ }
43
+ for update := range e.WS.PriceUpdateChan {
44
+ e.UpdateMarketPrice(update.MarketID, update.Price)
45
+ }
46
+ }
47
+
48
+ func (e *CopyEngine) AddTrader(config models.CopyConfig) {
49
+ e.mu.Lock()
50
+ defer e.mu.Unlock()
51
+ e.Monitored[config.TraderAddress] = config
52
+ log.Printf("Monitoring trader: %s", config.TraderAddress)
53
+ }
54
+
55
+ func (e *CopyEngine) GetActivePositions() []models.Position {
56
+ e.mu.RLock()
57
+ defer e.mu.RUnlock()
58
+ var positions []models.Position
59
+ for _, p := range e.ActivePositions {
60
+ if p.IsOpen {
61
+ positions = append(positions, *p)
62
+ }
63
+ }
64
+ return positions
65
+ }
66
+
67
+ // UpdateMarketPrice triggers risk checks for all open positions in the given market
68
+ func (e *CopyEngine) UpdateMarketPrice(marketID string, newPrice float64) {
69
+ e.mu.Lock()
70
+ defer e.mu.Unlock()
71
+
72
+ for _, pos := range e.ActivePositions {
73
+ if !pos.IsOpen || pos.MarketID != marketID {
74
+ continue
75
+ }
76
+
77
+ pos.CurrentPrice = newPrice
78
+ pos.Value = pos.Size * newPrice // Simplified value calc
79
+
80
+ // Check Stop Loss
81
+ if pos.StopLossPrice > 0 && newPrice <= pos.StopLossPrice {
82
+ e.closePosition(pos, "Stop Loss Triggered")
83
+ }
84
+
85
+ // Check Take Profit
86
+ if pos.TakeProfitPrice > 0 && newPrice >= pos.TakeProfitPrice {
87
+ e.closePosition(pos, "Take Profit Triggered")
88
+ }
89
+ }
90
+ }
91
+
92
+ func (e *CopyEngine) closePosition(pos *models.Position, reason string) {
93
+ log.Printf("Closing Position %d (%s): %s at price %.2f", pos.ID, pos.MarketID, reason, pos.CurrentPrice)
94
+ // In real app: Send Sell Order
95
+
96
+ // Mock close
97
+ pos.IsOpen = false
98
+ pos.UpdatedAt = time.Now()
99
+ }
100
+
101
+ func (e *CopyEngine) processSignals() {
102
+ for signal := range e.SignalChan {
103
+ e.executeCopy(signal)
104
+ }
105
+ }
106
+
107
+ func (e *CopyEngine) executeCopy(signal models.Position) {
108
+ e.mu.Lock()
109
+ defer e.mu.Unlock()
110
+
111
+ config, exists := e.Monitored[signal.TraderAddress]
112
+ if !exists || !config.Enabled {
113
+ return
114
+ }
115
+
116
+ log.Printf("COPY TRIGGER: Trader %s entered market %s", signal.TraderAddress, signal.MarketID)
117
+
118
+ // Calculate size
119
+ size := config.FixedSize
120
+ if size <= 0 {
121
+ return
122
+ }
123
+
124
+ // Calculate Risk Params
125
+ slPrice := 0.0
126
+ tpPrice := 0.0
127
+ if config.StopLossPct > 0 {
128
+ slPrice = signal.EntryPrice * (1 - config.StopLossPct)
129
+ }
130
+ if config.TakeProfitPct > 0 {
131
+ tpPrice = signal.EntryPrice * (1 + config.TakeProfitPct)
132
+ }
133
+
134
+ // Execution Logic
135
+ order := polymarket.OrderRequest{
136
+ TokenID: signal.MarketID,
137
+ Price: signal.EntryPrice,
138
+ Side: "BUY",
139
+ Size: size,
140
+ }
141
+
142
+ err := e.Client.PlaceOrder(order)
143
+ if err != nil {
144
+ log.Printf("Failed to copy trade: %v", err)
145
+ return
146
+ }
147
+
148
+ // Track Position
149
+ newPos := &models.Position{
150
+ ID: e.posIDCounter,
151
+ TraderAddress: signal.TraderAddress,
152
+ MarketID: signal.MarketID,
153
+ EntryPrice: signal.EntryPrice,
154
+ CurrentPrice: signal.EntryPrice,
155
+ Size: size,
156
+ StopLossPrice: slPrice,
157
+ TakeProfitPrice: tpPrice,
158
+ IsOpen: true,
159
+ CreatedAt: time.Now(),
160
+ UpdatedAt: time.Now(),
161
+ }
162
+ e.ActivePositions[e.posIDCounter] = newPos
163
+ e.posIDCounter++
164
+
165
+ log.Printf("Successfully copied trade for %s. tracked ID: %d", signal.TraderAddress, newPos.ID)
166
+ }
polymarket-trader/backend/internal/core/trader_discovery.go ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "log"
5
+ "sort"
6
+ "time"
7
+
8
+ "github.com/user/polymarket-trader/internal/models"
9
+ )
10
+
11
+ type TraderDiscoveryService struct {
12
+ // In a real app, this would use a GraphClient or DB connection
13
+ topTraders []models.Trader
14
+ }
15
+
16
+ func NewTraderDiscoveryService() *TraderDiscoveryService {
17
+ return &TraderDiscoveryService{
18
+ topTraders: []models.Trader{},
19
+ }
20
+ }
21
+
22
+ // FetchTopTraders mock implementation
23
+ func (s *TraderDiscoveryService) FetchTopTraders() ([]models.Trader, error) {
24
+ log.Println("Fetching top traders from 'source'...")
25
+
26
+ // Mock Data
27
+ mockTraders := []models.Trader{
28
+ {
29
+ Address: "0x9f8...7b2",
30
+ Category: "Politics",
31
+ WinRate: 0.78,
32
+ TotalPnL: 12500.50,
33
+ TradeCount: 142,
34
+ LastActive: time.Now().Add(-10 * time.Minute),
35
+ IsMonitored: false,
36
+ },
37
+ {
38
+ Address: "0xa12...8c9",
39
+ Category: "Crypto",
40
+ WinRate: 0.65,
41
+ TotalPnL: 8900.20,
42
+ TradeCount: 98,
43
+ LastActive: time.Now().Add(-2 * time.Hour),
44
+ IsMonitored: true,
45
+ },
46
+ {
47
+ Address: "0xb34...1d4",
48
+ Category: "Sports",
49
+ WinRate: 0.92,
50
+ TotalPnL: 45000.00,
51
+ TradeCount: 310,
52
+ LastActive: time.Now().Add(-5 * time.Minute),
53
+ IsMonitored: false,
54
+ },
55
+ }
56
+
57
+ // Sort by PnL
58
+ sort.Slice(mockTraders, func(i, j int) bool {
59
+ return mockTraders[i].TotalPnL > mockTraders[j].TotalPnL
60
+ })
61
+
62
+ s.topTraders = mockTraders
63
+ return mockTraders, nil
64
+ }
polymarket-trader/backend/internal/models/models.go ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package models
2
+
3
+ import (
4
+ "time"
5
+ )
6
+
7
+ type Trader struct {
8
+ Address string `json:"address" gorm:"primaryKey"`
9
+ Category string `json:"category"`
10
+ WinRate float64 `json:"win_rate"`
11
+ TotalPnL float64 `json:"total_pnl"`
12
+ TradeCount int `json:"trade_count"`
13
+ LastActive time.Time
14
+ IsMonitored bool `json:"is_monitored"`
15
+ }
16
+
17
+ type Position struct {
18
+ ID uint `json:"id" gorm:"primaryKey"`
19
+ TraderAddress string `json:"trader_address" gorm:"index"`
20
+ MarketID string `json:"market_id"`
21
+ OutcomeIndex int `json:"outcome_index"`
22
+ EntryPrice float64 `json:"entry_price"`
23
+ CurrentPrice float64 `json:"current_price"`
24
+ Size float64 `json:"size"`
25
+ Value float64 `json:"value"`
26
+ StopLossPrice float64 `json:"stop_loss_price"`
27
+ TakeProfitPrice float64 `json:"take_profit_price"`
28
+ IsOpen bool `json:"is_open"`
29
+ CreatedAt time.Time
30
+ UpdatedAt time.Time
31
+ }
32
+
33
+ type CopyConfig struct {
34
+ ID uint `json:"id" gorm:"primaryKey"`
35
+ TraderAddress string `json:"trader_address" gorm:"uniqueIndex"`
36
+ Enabled bool `json:"enabled"`
37
+ FixedSize float64 `json:"fixed_size"` // Amount to bet per trade
38
+ MaxPosition float64 `json:"max_position"`
39
+ StopLossPct float64 `json:"stop_loss_pct"`
40
+ TakeProfitPct float64 `json:"take_profit_pct"`
41
+ }
42
+
43
+ type HistoricalTrade struct {
44
+ ID uint `json:"id" gorm:"primaryKey"`
45
+ TraderAddress string `json:"trader_address" gorm:"index"`
46
+ MarketID string `json:"market_id"`
47
+ Side string `json:"side"` // BUY/SELL
48
+ Price float64 `json:"price"`
49
+ Size float64 `json:"size"`
50
+ PnL float64 `json:"pnl"` // Realized PnL
51
+ Timestamp time.Time
52
+ }
polymarket-trader/frontend/.gitignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
polymarket-trader/frontend/README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # React + TypeScript + Vite
2
+
3
+ This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4
+
5
+ Currently, two official plugins are available:
6
+
7
+ - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
8
+ - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
9
+
10
+ ## React Compiler
11
+
12
+ The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
13
+
14
+ ## Expanding the ESLint configuration
15
+
16
+ If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
17
+
18
+ ```js
19
+ export default defineConfig([
20
+ globalIgnores(['dist']),
21
+ {
22
+ files: ['**/*.{ts,tsx}'],
23
+ extends: [
24
+ // Other configs...
25
+
26
+ // Remove tseslint.configs.recommended and replace with this
27
+ tseslint.configs.recommendedTypeChecked,
28
+ // Alternatively, use this for stricter rules
29
+ tseslint.configs.strictTypeChecked,
30
+ // Optionally, add this for stylistic rules
31
+ tseslint.configs.stylisticTypeChecked,
32
+
33
+ // Other configs...
34
+ ],
35
+ languageOptions: {
36
+ parserOptions: {
37
+ project: ['./tsconfig.node.json', './tsconfig.app.json'],
38
+ tsconfigRootDir: import.meta.dirname,
39
+ },
40
+ // other options...
41
+ },
42
+ },
43
+ ])
44
+ ```
45
+
46
+ You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
47
+
48
+ ```js
49
+ // eslint.config.js
50
+ import reactX from 'eslint-plugin-react-x'
51
+ import reactDom from 'eslint-plugin-react-dom'
52
+
53
+ export default defineConfig([
54
+ globalIgnores(['dist']),
55
+ {
56
+ files: ['**/*.{ts,tsx}'],
57
+ extends: [
58
+ // Other configs...
59
+ // Enable lint rules for React
60
+ reactX.configs['recommended-typescript'],
61
+ // Enable lint rules for React DOM
62
+ reactDom.configs.recommended,
63
+ ],
64
+ languageOptions: {
65
+ parserOptions: {
66
+ project: ['./tsconfig.node.json', './tsconfig.app.json'],
67
+ tsconfigRootDir: import.meta.dirname,
68
+ },
69
+ // other options...
70
+ },
71
+ },
72
+ ])
73
+ ```
polymarket-trader/frontend/components.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema.json",
3
+ "style": "new-york",
4
+ "rsc": false,
5
+ "tsx": true,
6
+ "tailwind": {
7
+ "config": "tailwind.config.js",
8
+ "css": "src/index.css",
9
+ "baseColor": "zinc",
10
+ "cssVariables": true,
11
+ "prefix": ""
12
+ },
13
+ "aliases": {
14
+ "components": "@/components",
15
+ "utils": "@/lib/utils"
16
+ }
17
+ }
polymarket-trader/frontend/eslint.config.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import tseslint from 'typescript-eslint'
6
+ import { defineConfig, globalIgnores } from 'eslint/config'
7
+
8
+ export default defineConfig([
9
+ globalIgnores(['dist']),
10
+ {
11
+ files: ['**/*.{ts,tsx}'],
12
+ extends: [
13
+ js.configs.recommended,
14
+ tseslint.configs.recommended,
15
+ reactHooks.configs.flat.recommended,
16
+ reactRefresh.configs.vite,
17
+ ],
18
+ languageOptions: {
19
+ ecmaVersion: 2020,
20
+ globals: globals.browser,
21
+ },
22
+ },
23
+ ])
polymarket-trader/frontend/index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>frontend</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script type="module" src="/src/main.tsx"></script>
12
+ </body>
13
+ </html>
polymarket-trader/frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
polymarket-trader/frontend/package.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "frontend",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "tsc -b && vite build",
9
+ "lint": "eslint .",
10
+ "preview": "vite preview",
11
+ "test": "vitest"
12
+ },
13
+ "dependencies": {
14
+ "@radix-ui/react-avatar": "^1.1.11",
15
+ "@radix-ui/react-dialog": "^1.1.15",
16
+ "@radix-ui/react-label": "^2.1.8",
17
+ "@radix-ui/react-scroll-area": "^1.2.10",
18
+ "@radix-ui/react-slot": "^1.2.4",
19
+ "@radix-ui/react-tabs": "^1.1.13",
20
+ "autoprefixer": "^10.4.23",
21
+ "class-variance-authority": "^0.7.1",
22
+ "clsx": "^2.1.1",
23
+ "lucide-react": "^0.562.0",
24
+ "postcss": "^8.5.6",
25
+ "react": "^19.2.0",
26
+ "react-dom": "^19.2.0",
27
+ "tailwind-merge": "^3.4.0",
28
+ "tailwindcss": "^4.1.18"
29
+ },
30
+ "devDependencies": {
31
+ "@eslint/js": "^9.39.1",
32
+ "@testing-library/dom": "^10.4.0",
33
+ "@testing-library/jest-dom": "^6.9.1",
34
+ "@testing-library/react": "^16.2.0",
35
+ "@types/node": "^24.10.1",
36
+ "@types/react": "^19.2.5",
37
+ "@types/react-dom": "^19.2.3",
38
+ "@vitejs/plugin-react": "^5.1.1",
39
+ "eslint": "^9.39.1",
40
+ "eslint-plugin-react-hooks": "^7.0.1",
41
+ "eslint-plugin-react-refresh": "^0.4.24",
42
+ "globals": "^16.5.0",
43
+ "jsdom": "^26.0.0",
44
+ "typescript": "~5.9.3",
45
+ "typescript-eslint": "^8.46.4",
46
+ "vite": "^7.2.4",
47
+ "vitest": "^3.0.0"
48
+ }
49
+ }
polymarket-trader/frontend/postcss.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {},
5
+ },
6
+ }
polymarket-trader/frontend/public/vite.svg ADDED
polymarket-trader/frontend/src/App.css ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #root {
2
+ max-width: 1280px;
3
+ margin: 0 auto;
4
+ padding: 2rem;
5
+ text-align: center;
6
+ }
7
+
8
+ .logo {
9
+ height: 6em;
10
+ padding: 1.5em;
11
+ will-change: filter;
12
+ transition: filter 300ms;
13
+ }
14
+ .logo:hover {
15
+ filter: drop-shadow(0 0 2em #646cffaa);
16
+ }
17
+ .logo.react:hover {
18
+ filter: drop-shadow(0 0 2em #61dafbaa);
19
+ }
20
+
21
+ @keyframes logo-spin {
22
+ from {
23
+ transform: rotate(0deg);
24
+ }
25
+ to {
26
+ transform: rotate(360deg);
27
+ }
28
+ }
29
+
30
+ @media (prefers-reduced-motion: no-preference) {
31
+ a:nth-of-type(2) .logo {
32
+ animation: logo-spin infinite 20s linear;
33
+ }
34
+ }
35
+
36
+ .card {
37
+ padding: 2em;
38
+ }
39
+
40
+ .read-the-docs {
41
+ color: #888;
42
+ }
polymarket-trader/frontend/src/App.test.tsx ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { render, screen } from '@testing-library/react'
2
+ import { describe, it, expect } from 'vitest'
3
+ import App from './App'
4
+
5
+ describe('App', () => {
6
+ it('renders without crashing', () => {
7
+ render(<App />)
8
+ // Adjust this expectation based on actual App content,
9
+ // for now just checking if it renders *something* or doesn't throw
10
+ // detailed checks depend on what App actually renders (e.g. login screen or dashboard)
11
+ const appContainer = document.querySelector('#root') // Note: this might not work dependent on how render works, better to query by text
12
+ })
13
+ })
polymarket-trader/frontend/src/App.tsx ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from "react";
2
+ import { Copy, TrendingUp, Activity, Wallet, ShieldAlert, Play, Pause } from "lucide-react";
3
+ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
4
+ import { Button } from "@/components/ui/button";
5
+ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
6
+ import { Badge } from "@/components/ui/badge";
7
+ import { ScrollArea } from "@/components/ui/scroll-area";
8
+ import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
9
+
10
+ interface Trader {
11
+ address: string;
12
+ category: string;
13
+ win_rate: number;
14
+ total_pnl: number;
15
+ trade_count: number;
16
+ is_monitored: boolean;
17
+ }
18
+
19
+ import { CopyConfigDialog } from "@/components/CopyConfigDialog";
20
+ import { ActivePositions } from "@/components/ActivePositions";
21
+ import { BotChat } from "@/components/BotChat";
22
+
23
+ function App() {
24
+ const [traders, setTraders] = useState<Trader[]>([]);
25
+ const [selectedTrader, setSelectedTrader] = useState<string | null>(null);
26
+ const [isRunning, setIsRunning] = useState(false);
27
+
28
+ // Data Loading
29
+ useEffect(() => {
30
+ fetch("http://localhost:8080/api/traders")
31
+ .then((res) => res.json())
32
+ .then((data) => {
33
+ // Map backend data to frontend model if needed (or just use direct if matches)
34
+ // Backend returns Trader[], we might need to ensure category exists
35
+ // simplified for now:
36
+ const enriched = data.map((t: any) => ({
37
+ ...t,
38
+ category: ["Politics", "Sports", "Crypto"][Math.floor(Math.random() * 3)] // Random cat for demo if missing
39
+ }));
40
+ setTraders(enriched);
41
+ })
42
+ .catch((err) => console.error("Failed to fetch traders:", err));
43
+ }, []);
44
+
45
+ return (
46
+ <div className="flex h-screen bg-background text-foreground font-sans selection:bg-primary selection:text-primary-foreground">
47
+ {/* Sidebar */}
48
+ <aside className="w-64 border-r border-border bg-card/50 backdrop-blur-xl hidden md:flex flex-col">
49
+ <div className="p-6">
50
+ <h1 className="text-2xl font-bold bg-gradient-to-r from-blue-400 to-indigo-500 bg-clip-text text-transparent">
51
+ PolyTrader
52
+ </h1>
53
+ <p className="text-xs text-muted-foreground mt-1">High Frequency Copy Bot</p>
54
+ </div>
55
+
56
+ <nav className="flex-1 px-4 space-y-2">
57
+ <Button variant="ghost" className="w-full justify-start text-muted-foreground hover:text-foreground">
58
+ <Activity className="mr-2 h-4 w-4" /> Dashboard
59
+ </Button>
60
+ <Button variant="ghost" className="w-full justify-start text-muted-foreground hover:text-foreground">
61
+ <TrendingUp className="mr-2 h-4 w-4" /> Top Traders
62
+ </Button>
63
+ <Button variant="ghost" className="w-full justify-start text-muted-foreground hover:text-foreground">
64
+ <Copy className="mr-2 h-4 w-4" /> Copy Config
65
+ </Button>
66
+ <Button variant="ghost" className="w-full justify-start text-muted-foreground hover:text-foreground">
67
+ <Wallet className="mr-2 h-4 w-4" /> Portfolio
68
+ </Button>
69
+ </nav>
70
+
71
+ <div className="p-4 border-t border-border">
72
+ <div className="flex items-center gap-3">
73
+ <div className={`h-2 w-2 rounded-full ${isRunning ? "bg-green-500 animate-pulse" : "bg-red-500"}`} />
74
+ <span className="text-sm font-medium">{isRunning ? "System Active" : "System Paused"}</span>
75
+ </div>
76
+ <Button
77
+ className="w-full mt-3"
78
+ variant={isRunning ? "destructive" : "default"}
79
+ onClick={() => setIsRunning(!isRunning)}
80
+ >
81
+ {isRunning ? <><Pause className="mr-2 h-4 w-4" /> Stop Engine</> : <><Play className="mr-2 h-4 w-4" /> Start Engine</>}
82
+ </Button>
83
+ </div>
84
+ </aside>
85
+
86
+ {/* Main Content */}
87
+ <main className="flex-1 flex flex-col overflow-hidden">
88
+ {/* Header */}
89
+ <header className="h-16 border-b border-border flex items-center justify-between px-6 bg-card/50 backdrop-blur-sm">
90
+ <h2 className="text-lg font-semibold">Live Dashboard</h2>
91
+ <div className="flex items-center gap-4">
92
+ <Badge variant="outline" className="text-green-500 border-green-500/50 bg-green-500/10">
93
+ Connected to Polymarket WS
94
+ </Badge>
95
+ <Avatar>
96
+ <AvatarImage src="https://github.com/shadcn.png" />
97
+ <AvatarFallback>CN</AvatarFallback>
98
+ </Avatar>
99
+ </div>
100
+ </header>
101
+
102
+ {/* Dashboard Content */}
103
+ <ScrollArea className="flex-1 p-6">
104
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
105
+ <Card className="bg-gradient-to-br from-card to-card/50 border-border/50 shadow-sm">
106
+ <CardHeader className="pb-2">
107
+ <CardTitle className="text-sm font-medium text-muted-foreground">Total PnL</CardTitle>
108
+ </CardHeader>
109
+ <CardContent>
110
+ <div className="text-2xl font-bold text-green-500">+$2,450.00</div>
111
+ <p className="text-xs text-muted-foreground">+18.2% from last month</p>
112
+ </CardContent>
113
+ </Card>
114
+ <Card className="bg-gradient-to-br from-card to-card/50 border-border/50 shadow-sm">
115
+ <CardHeader className="pb-2">
116
+ <CardTitle className="text-sm font-medium text-muted-foreground">Active Positions</CardTitle>
117
+ </CardHeader>
118
+ <CardContent>
119
+ <div className="text-2xl font-bold">12</div>
120
+ <p className="text-xs text-muted-foreground">4 copy trades, 8 manual</p>
121
+ </CardContent>
122
+ </Card>
123
+ <Card className="bg-gradient-to-br from-card to-card/50 border-border/50 shadow-sm">
124
+ <CardHeader className="pb-2">
125
+ <CardTitle className="text-sm font-medium text-muted-foreground">Win Rate (24h)</CardTitle>
126
+ </CardHeader>
127
+ <CardContent>
128
+ <div className="text-2xl font-bold text-blue-500">68%</div>
129
+ <p className="text-xs text-muted-foreground">Based on 25 trades</p>
130
+ </CardContent>
131
+ </Card>
132
+ </div>
133
+
134
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
135
+ {/* Top Traders Leaderboard */}
136
+ <Card className="lg:col-span-2 border-border/50 shadow-md">
137
+ <CardHeader>
138
+ <div className="flex items-center justify-between">
139
+ <div>
140
+ <CardTitle>Top Volume Traders</CardTitle>
141
+ <CardDescription>Real-time ranking based on PnL and consistency.</CardDescription>
142
+ </div>
143
+ <Button variant="outline" size="sm">Refresh</Button>
144
+ </div>
145
+ </CardHeader>
146
+ <CardContent>
147
+ <Table>
148
+ <TableHeader>
149
+ <TableRow>
150
+ <TableHead>Trader</TableHead>
151
+ <TableHead>Category</TableHead>
152
+ <TableHead>Win Rate</TableHead>
153
+ <TableHead>PnL</TableHead>
154
+ <TableHead>Status</TableHead>
155
+ <TableHead className="text-right">Action</TableHead>
156
+ </TableRow>
157
+ </TableHeader>
158
+ <TableBody>
159
+ {traders.map((trader) => (
160
+ <TableRow key={trader.address}>
161
+ <TableCell className="font-mono text-xs">{trader.address}</TableCell>
162
+ <TableCell><Badge variant="outline">{trader.category}</Badge></TableCell>
163
+ <TableCell>
164
+ <span className={trader.win_rate > 0.6 ? "text-green-500 font-medium" : ""}>
165
+ {(trader.win_rate * 100).toFixed(0)}%
166
+ </span>
167
+ </TableCell>
168
+ <TableCell className={trader.total_pnl >= 0 ? "text-green-500" : "text-red-500"}>
169
+ ${trader.total_pnl.toLocaleString()}
170
+ </TableCell>
171
+ <TableCell>
172
+ {trader.is_monitored ? <Badge>Active</Badge> : <Badge variant="secondary">Idle</Badge>}
173
+ </TableCell>
174
+ <TableCell className="text-right">
175
+ <Button size="sm" variant={trader.is_monitored ? "destructive" : "default"} onClick={() => setSelectedTrader(trader.address)}>
176
+ {trader.is_monitored ? "Stop Copy" : "Copy Trade"}
177
+ </Button>
178
+ </TableCell>
179
+ </TableRow>
180
+ ))}
181
+ </TableBody>
182
+ </Table>
183
+ </CardContent>
184
+ </Card>
185
+
186
+ <CopyConfigDialog
187
+ isOpen={!!selectedTrader}
188
+ onClose={() => setSelectedTrader(null)}
189
+ traderAddress={selectedTrader || ""}
190
+ />
191
+
192
+ {/* Risk / Activity Feed */}
193
+ <Card className="border-border/50 shadow-md">
194
+ <CardHeader>
195
+ <CardTitle>System Activity</CardTitle>
196
+ <CardDescription>Live events from the engine.</CardDescription>
197
+ </CardHeader>
198
+ <CardContent className="space-y-4">
199
+ <div className="flex gap-3 items-start">
200
+ <div className="h-8 w-8 rounded-full bg-blue-500/10 flex items-center justify-center shrink-0">
201
+ <Copy className="h-4 w-4 text-blue-500" />
202
+ </div>
203
+ <div>
204
+ <p className="text-sm font-medium">Copied Trade: 0x9f8...</p>
205
+ <p className="text-xs text-muted-foreground">Bought YES on "Trump vs Biden" @ 0.52</p>
206
+ <span className="text-[10px] text-muted-foreground">2 mins ago</span>
207
+ </div>
208
+ </div>
209
+ <div className="flex gap-3 items-start">
210
+ <div className="h-8 w-8 rounded-full bg-green-500/10 flex items-center justify-center shrink-0">
211
+ <TrendingUp className="h-4 w-4 text-green-500" />
212
+ </div>
213
+ <div>
214
+ <p className="text-sm font-medium">Take Profit Hit</p>
215
+ <p className="text-xs text-muted-foreground">Sold 0x9f8... pos for +15%</p>
216
+ <span className="text-[10px] text-muted-foreground">15 mins ago</span>
217
+ </div>
218
+ </div>
219
+ <div className="flex gap-3 items-start">
220
+ <div className="h-8 w-8 rounded-full bg-yellow-500/10 flex items-center justify-center shrink-0">
221
+ <ShieldAlert className="h-4 w-4 text-yellow-500" />
222
+ </div>
223
+ <div>
224
+ <p className="text-sm font-medium">Risk Check</p>
225
+ <p className="text-xs text-muted-foreground">Skipped trade: Max exposure reached.</p>
226
+ <span className="text-[10px] text-muted-foreground">1 hour ago</span>
227
+ </div>
228
+ </div>
229
+ </CardContent>
230
+ </Card>
231
+ </div>
232
+
233
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
234
+ <ActivePositions />
235
+ <BotChat />
236
+ </div>
237
+ </ScrollArea>
238
+ </main>
239
+ </div>
240
+ );
241
+ }
242
+
243
+ export default App;
polymarket-trader/frontend/src/assets/react.svg ADDED
polymarket-trader/frontend/src/components/ActivePositions.tsx ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from "react";
2
+ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
3
+ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
4
+ import { Badge } from "@/components/ui/badge";
5
+
6
+ interface Position {
7
+ id: number;
8
+ trader_address: string;
9
+ market_id: string;
10
+ entry_price: number;
11
+ current_price: number;
12
+ size: number;
13
+ pnl: number; // calculated on frontend or backend
14
+ is_open: boolean;
15
+ }
16
+
17
+ export function ActivePositions() {
18
+ const [positions, setPositions] = useState<Position[]>([]);
19
+
20
+ useEffect(() => {
21
+ // Mock data or fetch from API
22
+ // In a real app, use polling or WebSocket
23
+ const mockPositions: Position[] = [
24
+ {
25
+ id: 1,
26
+ trader_address: "0x123...abc",
27
+ market_id: "Trump 2024",
28
+ entry_price: 0.45,
29
+ current_price: 0.48,
30
+ size: 100,
31
+ pnl: 6.67,
32
+ is_open: true
33
+ },
34
+ {
35
+ id: 2,
36
+ trader_address: "0x789...xyz",
37
+ market_id: "Biden 2024",
38
+ entry_price: 0.30,
39
+ current_price: 0.28,
40
+ size: 50,
41
+ pnl: -6.67,
42
+ is_open: true
43
+ }
44
+ ];
45
+ setPositions(mockPositions);
46
+ }, []);
47
+
48
+ return (
49
+ <Card>
50
+ <CardHeader>
51
+ <CardTitle>Active Positions</CardTitle>
52
+ </CardHeader>
53
+ <CardContent>
54
+ <Table>
55
+ <TableHeader>
56
+ <TableRow>
57
+ <TableHead>Market</TableHead>
58
+ <TableHead>Trader</TableHead>
59
+ <TableHead>Entry</TableHead>
60
+ <TableHead>Current</TableHead>
61
+ <TableHead>Size ($)</TableHead>
62
+ <TableHead>PnL (%)</TableHead>
63
+ <TableHead>Status</TableHead>
64
+ </TableRow>
65
+ </TableHeader>
66
+ <TableBody>
67
+ {positions.map((pos) => {
68
+ const pnlPct = ((pos.current_price - pos.entry_price) / pos.entry_price) * 100;
69
+ return (
70
+ <TableRow key={pos.id}>
71
+ <TableCell className="font-medium">{pos.market_id}</TableCell>
72
+ <TableCell>{pos.trader_address}</TableCell>
73
+ <TableCell>{pos.entry_price.toFixed(3)}</TableCell>
74
+ <TableCell>{pos.current_price.toFixed(3)}</TableCell>
75
+ <TableCell>{pos.size}</TableCell>
76
+ <TableCell className={pnlPct >= 0 ? "text-green-500" : "text-red-500"}>
77
+ {pnlPct.toFixed(2)}%
78
+ </TableCell>
79
+ <TableCell>
80
+ <Badge variant="outline">Open</Badge>
81
+ </TableCell>
82
+ </TableRow>
83
+ );
84
+ })}
85
+ {positions.length === 0 && (
86
+ <TableRow>
87
+ <TableCell colSpan={7} className="text-center">No active positions</TableCell>
88
+ </TableRow>
89
+ )}
90
+ </TableBody>
91
+ </Table>
92
+ </CardContent>
93
+ </Card>
94
+ );
95
+ }
polymarket-trader/frontend/src/components/BotChat.tsx ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+ import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
3
+ import { Input } from "@/components/ui/input";
4
+ import { Button } from "@/components/ui/button";
5
+ import { ScrollArea } from "@/components/ui/scroll-area";
6
+
7
+ interface Message {
8
+ id: number;
9
+ role: "user" | "bot";
10
+ text: string;
11
+ timestamp: Date;
12
+ }
13
+
14
+ export function BotChat() {
15
+ const [input, setInput] = useState("");
16
+ const [messages, setMessages] = useState<Message[]>([
17
+ { id: 1, role: "bot", text: "Hello! I am your trading assistant. How can I help you today?", timestamp: new Date() }
18
+ ]);
19
+
20
+ const handleSend = () => {
21
+ if (!input.trim()) return;
22
+
23
+ const userMsg: Message = {
24
+ id: messages.length + 1,
25
+ role: "user",
26
+ text: input,
27
+ timestamp: new Date()
28
+ };
29
+
30
+ setMessages(prev => [...prev, userMsg]);
31
+ setInput("");
32
+
33
+ // Simulate response
34
+ setTimeout(() => {
35
+ const botMsg: Message = {
36
+ id: messages.length + 2,
37
+ role: "bot",
38
+ text: "I'm currently in demo mode. I can't execute commands yet, but I'm listening!",
39
+ timestamp: new Date()
40
+ };
41
+ setMessages(prev => [...prev, botMsg]);
42
+ }, 1000);
43
+ };
44
+
45
+ return (
46
+ <Card className="h-[400px] flex flex-col">
47
+ <CardHeader className="py-3">
48
+ <CardTitle className="text-md">Bot Interface</CardTitle>
49
+ </CardHeader>
50
+ <CardContent className="flex-1 p-0 overflow-hidden">
51
+ <ScrollArea className="h-full p-4">
52
+ <div className="space-y-4">
53
+ {messages.map((msg) => (
54
+ <div key={msg.id} className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
55
+ <div className={`max-w-[80%] rounded-lg px-3 py-2 text-sm ${msg.role === "user" ? "bg-primary text-primary-foreground" : "bg-muted"
56
+ }`}>
57
+ {msg.text}
58
+ </div>
59
+ </div>
60
+ ))}
61
+ </div>
62
+ </ScrollArea>
63
+ </CardContent>
64
+ <CardFooter className="p-3 pt-0">
65
+ <form
66
+ className="flex w-full gap-2"
67
+ onSubmit={(e) => { e.preventDefault(); handleSend(); }}
68
+ >
69
+ <Input
70
+ placeholder="Type a command..."
71
+ value={input}
72
+ onChange={(e) => setInput(e.target.value)}
73
+ />
74
+ <Button type="submit" size="sm">Send</Button>
75
+ </form>
76
+ </CardFooter>
77
+ </Card>
78
+ );
79
+ }
polymarket-trader/frontend/src/components/CopyConfigDialog.tsx ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
3
+ import { Button } from "@/components/ui/button";
4
+ import { Input } from "@/components/ui/input";
5
+ import { Label } from "@/components/ui/label";
6
+
7
+ interface CopyConfigDialogProps {
8
+ isOpen: boolean;
9
+ onClose: () => void;
10
+ traderAddress: string;
11
+ }
12
+
13
+ export function CopyConfigDialog({ isOpen, onClose, traderAddress }: CopyConfigDialogProps) {
14
+ const [fixedSize, setFixedSize] = useState("10");
15
+ const [maxPosition, setMaxPosition] = useState("100");
16
+ const [stopLoss, setStopLoss] = useState("15");
17
+ const [takeProfit, setTakeProfit] = useState("30");
18
+ const [isLoading, setIsLoading] = useState(false);
19
+
20
+ const handleStartCopy = async () => {
21
+ setIsLoading(true);
22
+ try {
23
+ const response = await fetch("http://localhost:8080/api/copy/start", {
24
+ method: "POST",
25
+ headers: { "Content-Type": "application/json" },
26
+ body: JSON.stringify({
27
+ trader_address: traderAddress,
28
+ enabled: true,
29
+ fixed_size: parseFloat(fixedSize),
30
+ max_position: parseFloat(maxPosition),
31
+ stop_loss_pct: parseFloat(stopLoss) / 100, // Backend expects decimal? Assuming pct in struct comment
32
+ take_profit_pct: parseFloat(takeProfit) / 100,
33
+ }),
34
+ });
35
+
36
+ if (!response.ok) {
37
+ throw new Error("Failed to start copy");
38
+ }
39
+
40
+ const data = await response.json();
41
+ console.log("Copy started:", data);
42
+ onClose();
43
+ } catch (error) {
44
+ console.error("Error starting copy:", error);
45
+ // TODO: Show error toast
46
+ } finally {
47
+ setIsLoading(false);
48
+ }
49
+ };
50
+
51
+ return (
52
+ <Dialog open={isOpen} onOpenChange={onClose}>
53
+ <DialogContent className="sm:max-w-[425px]">
54
+ <DialogHeader>
55
+ <DialogTitle>Copy Configuration</DialogTitle>
56
+ <DialogDescription>
57
+ Configure risk parameters for copying {traderAddress.slice(0, 6)}...{traderAddress.slice(-4)}
58
+ </DialogDescription>
59
+ </DialogHeader>
60
+ <div className="grid gap-4 py-4">
61
+ <div className="grid grid-cols-4 items-center gap-4">
62
+ <Label htmlFor="size" className="text-right">
63
+ Bet Size ($)
64
+ </Label>
65
+ <Input id="size" value={fixedSize} onChange={(e) => setFixedSize(e.target.value)} className="col-span-3" />
66
+ </div>
67
+ <div className="grid grid-cols-4 items-center gap-4">
68
+ <Label htmlFor="max" className="text-right">
69
+ Max Alloc ($)
70
+ </Label>
71
+ <Input id="max" value={maxPosition} onChange={(e) => setMaxPosition(e.target.value)} className="col-span-3" />
72
+ </div>
73
+ <div className="grid grid-cols-4 items-center gap-4">
74
+ <Label htmlFor="sl" className="text-right">
75
+ Stop Loss (%)
76
+ </Label>
77
+ <Input id="sl" value={stopLoss} onChange={(e) => setStopLoss(e.target.value)} className="col-span-3" />
78
+ </div>
79
+ <div className="grid grid-cols-4 items-center gap-4">
80
+ <Label htmlFor="tp" className="text-right">
81
+ Take Profit (%)
82
+ </Label>
83
+ <Input id="tp" value={takeProfit} onChange={(e) => setTakeProfit(e.target.value)} className="col-span-3" />
84
+ </div>
85
+ </div>
86
+ <DialogFooter>
87
+ <Button variant="outline" onClick={onClose}>Cancel</Button>
88
+ <Button onClick={handleStartCopy} disabled={isLoading}>
89
+ {isLoading ? "Starting..." : "Start Copying"}
90
+ </Button>
91
+ </DialogFooter>
92
+ </DialogContent>
93
+ </Dialog>
94
+ );
95
+ }
polymarket-trader/frontend/src/components/ui/avatar.tsx ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import * as AvatarPrimitive from "@radix-ui/react-avatar"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const Avatar = React.forwardRef<
6
+ React.ElementRef<typeof AvatarPrimitive.Root>,
7
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
8
+ >(({ className, ...props }, ref) => (
9
+ <AvatarPrimitive.Root
10
+ ref={ref}
11
+ className={cn(
12
+ "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
13
+ className
14
+ )}
15
+ {...props}
16
+ />
17
+ ))
18
+ Avatar.displayName = AvatarPrimitive.Root.displayName
19
+
20
+ const AvatarImage = React.forwardRef<
21
+ React.ElementRef<typeof AvatarPrimitive.Image>,
22
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
23
+ >(({ className, ...props }, ref) => (
24
+ <AvatarPrimitive.Image
25
+ ref={ref}
26
+ className={cn("aspect-square h-full w-full", className)}
27
+ {...props}
28
+ />
29
+ ))
30
+ AvatarImage.displayName = AvatarPrimitive.Image.displayName
31
+
32
+ const AvatarFallback = React.forwardRef<
33
+ React.ElementRef<typeof AvatarPrimitive.Fallback>,
34
+ React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
35
+ >(({ className, ...props }, ref) => (
36
+ <AvatarPrimitive.Fallback
37
+ ref={ref}
38
+ className={cn(
39
+ "flex h-full w-full items-center justify-center rounded-full bg-muted",
40
+ className
41
+ )}
42
+ {...props}
43
+ />
44
+ ))
45
+ AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
46
+
47
+ export { Avatar, AvatarImage, AvatarFallback }
polymarket-trader/frontend/src/components/ui/badge.tsx ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import { cva, type VariantProps } from "class-variance-authority"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const badgeVariants = cva(
6
+ "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
7
+ {
8
+ variants: {
9
+ variant: {
10
+ default:
11
+ "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
12
+ secondary:
13
+ "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
14
+ destructive:
15
+ "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
16
+ outline: "text-foreground",
17
+ },
18
+ },
19
+ defaultVariants: {
20
+ variant: "default",
21
+ },
22
+ }
23
+ )
24
+
25
+ export interface BadgeProps
26
+ extends React.HTMLAttributes<HTMLDivElement>,
27
+ VariantProps<typeof badgeVariants> { }
28
+
29
+ function Badge({ className, variant, ...props }: BadgeProps) {
30
+ return (
31
+ <div className={cn(badgeVariants({ variant }), className)} {...props} />
32
+ )
33
+ }
34
+
35
+ export { Badge, badgeVariants }
polymarket-trader/frontend/src/components/ui/button.tsx ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as React from "react"
2
+ import { Slot } from "@radix-ui/react-slot"
3
+ import { cva, type VariantProps } from "class-variance-authority"
4
+ import { cn } from "@/lib/utils"
5
+
6
+ const buttonVariants = cva(
7
+ "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
8
+ {
9
+ variants: {
10
+ variant: {
11
+ default: "bg-primary text-primary-foreground hover:bg-primary/90",
12
+ destructive:
13
+ "bg-destructive text-destructive-foreground hover:bg-destructive/90",
14
+ outline:
15
+ "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
16
+ secondary:
17
+ "bg-secondary text-secondary-foreground hover:bg-secondary/80",
18
+ ghost: "hover:bg-accent hover:text-accent-foreground",
19
+ link: "text-primary underline-offset-4 hover:underline",
20
+ },
21
+ size: {
22
+ default: "h-10 px-4 py-2",
23
+ sm: "h-9 rounded-md px-3",
24
+ lg: "h-11 rounded-md px-8",
25
+ icon: "h-10 w-10",
26
+ },
27
+ },
28
+ defaultVariants: {
29
+ variant: "default",
30
+ size: "default",
31
+ },
32
+ }
33
+ )
34
+
35
+ export interface ButtonProps
36
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
37
+ VariantProps<typeof buttonVariants> {
38
+ asChild?: boolean
39
+ }
40
+
41
+ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
42
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
43
+ const Comp = asChild ? Slot : "button"
44
+ return (
45
+ <Comp
46
+ className={cn(buttonVariants({ variant, size, className }))}
47
+ ref={ref}
48
+ {...props}
49
+ />
50
+ )
51
+ }
52
+ )
53
+ Button.displayName = "Button"
54
+
55
+ export { Button, buttonVariants }