-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstlit.py
1631 lines (1409 loc) · 68.9 KB
/
stlit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from datetime import datetime
import concurrent.futures
import asyncio
import psycopg2
import streamlit as st
import pandas as pd
from st_aggrid import AgGrid, GridOptionsBuilder
import subprocess
# from multi_short import get_open_orders , get_wallet_balance , get_market_ticker , get_latest_buy_order
import time
import psutil
import plotly.express as px
from psycopg2 import sql
from sqlalchemy import create_engine
import pytz
import sys
import numpy as np
import threading
from concurrent.futures import ThreadPoolExecutor
import hmac
import hashlib
import time
import requests
from dotenv import load_dotenv
import os
from decimal import Decimal
import psycopg2
from datetime import datetime
import asyncio
# โหลดไฟล์ .env
load_dotenv()
API_KEY = os.getenv("BITKUB_API_KEY")
API_SECRET = os.getenv("BITKUB_API_SECRET")
API_URL = "https://api.bitkub.com"
DATABASE_URL = os.getenv("DB_CONNECTION")
engine = create_engine(DATABASE_URL)
# Retrieve database credentials from environment variables
DB_HOST = os.getenv("DB_HOST")
DB_PORT = os.getenv("DB_PORT")
DB_NAME = os.getenv("DB_NAME")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_SSLMODE = os.getenv("DB_SSLMODE")
# ดึงรายการ Asset จาก Bitkub API
def fetch_assets_from_bitkub():
API_URL = "https://api.bitkub.com/api/market/symbols"
try:
response = requests.get(API_URL)
if response.status_code == 200:
data = response.json()
symbols = [
f"{symbol['symbol'].split('_')[1]}_{symbol['symbol'].split('_')[0]}"
for symbol in data['result']
]
return symbols
else:
st.error(f"Failed to fetch assets: {response.status_code}")
return []
except Exception as e:
st.error(f"Error fetching assets: {str(e)}")
return []
def create_signature(api_secret, method, path, query, payload = None):
"""สร้าง Signature สำหรับ Bitkub API V3"""
# รวมข้อมูลที่ใช้ในการสร้าง Signature
data = f"{payload['ts']}{method}{path}"
if query:
data += f"?{query}"
if payload:
data += str(payload).replace("'", '"') # JSON payload ต้องเป็นแบบ double quotes
# เข้ารหัส HMAC SHA-256
signature = hmac.new(api_secret.encode(), msg=data.encode(), digestmod=hashlib.sha256).hexdigest()
return signature
def create_signature_params(api_secret, method, path, query, payload):
"""สร้าง Signature สำหรับ Bitkub API V3"""
# Query string (แปลง Query Parameters ให้เป็น string)
query_string = "&".join([f"{key}={value}" for key, value in query.items()]) if query else ""
# สร้างข้อมูลที่ใช้ใน Signature
data = f"{payload['ts']}{method}{path}"
if query_string:
data += f"?{query_string}"
# เข้ารหัส HMAC SHA-256
signature = hmac.new(api_secret.encode(), msg=data.encode(), digestmod=hashlib.sha256).hexdigest()
return signature
def get_server_time():
"""ดึงเวลาจากเซิร์ฟเวอร์ของ Bitkub"""
response = requests.get(f"{API_URL}/api/v3/servertime")
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}, {response.text}")
return None
def get_market_ticker(symbol="BTC_THB"):
"""ดึงราคาล่าสุดของตลาด"""
endpoint = f"{API_URL}/api/v3/market/ticker"
params = {"sym": symbol}
response = requests.get(endpoint, params=params)
if response.status_code == 200:
data = response.json() # ข้อมูลที่ส่งกลับมา
if isinstance(data, list): # ตรวจสอบว่าข้อมูลเป็น list
for item in data:
if item.get("symbol") == symbol: # ตรวจสอบว่าตรงกับ symbol ที่ต้องการ
return item
print(f"Symbol {symbol} ไม่พบในผลลัพธ์")
return None
else:
print("รูปแบบข้อมูลไม่รองรับ:", type(data))
return None
else:
print(f"HTTP Error: {response.status_code}, {response.text}")
return None
def place_order(symbol, side, amount, rate):
"""ส่งคำสั่งซื้อหรือขาย"""
# ดึงเวลาจากเซิร์ฟเวอร์ (มิลลิวินาที)
ts = get_server_time()
if not ts:
print("ไม่สามารถดึงเวลาจากเซิร์ฟเวอร์ได้")
return None
amount = float(Decimal(amount).normalize())
# JSON Payload
payload = {
"sym": symbol,
"amt": amount,
"rat": rate,
"typ": "limit",
"ts": ts
}
# กำหนด Endpoint และ Path
path = "/api/v3/market/place-bid" if side == "buy" else "/api/v3/market/place-ask"
endpoint = f"{API_URL}{path}"
# สร้าง Signature
method = "POST"
query = "" # ไม่มี Query Parameters
signature = create_signature(API_SECRET, method, path, query, payload)
# ใส่ Header
headers = {
"X-BTK-APIKEY": API_KEY,
"X-BTK-TIMESTAMP": str(ts),
"X-BTK-SIGN": signature,
"Content-Type": "application/json"
}
# ส่งคำสั่งซื้อหรือขาย
response = requests.post(endpoint, json=payload, headers=headers)
if response.status_code == 200:
save_order_log(symbol,side, amount, rate, "success")
return response.json()
else:
print(f"HTTP Error: {response.status_code}, {response.text}")
save_order_log(symbol,side, amount, rate, f"failed : HTTP Error: {response.status_code}, {response.text}")
return None
def get_trade_limits():
"""ดึงข้อมูลค่าขั้นต่ำในการซื้อ/ขาย"""
endpoint = f"{API_URL}/api/v3/user/limits"
ts = get_server_time()
if not ts:
print("ไม่สามารถดึงเวลาจากเซิร์ฟเวอร์ได้")
return None
payload = {"ts": ts}
payload_string = str(payload).replace("'", '"') # JSON payload ใช้ double quotes
signature = create_signature(API_SECRET, "POST", "/api/v3/user/limits", "", payload)
headers = {
"X-BTK-APIKEY": API_KEY,
"X-BTK-TIMESTAMP": str(ts),
"X-BTK-SIGN": signature,
"Content-Type": "application/json"
}
response = requests.post(endpoint, json=payload, headers=headers)
if response.status_code == 200:
return response.json()
else:
print(f"HTTP Error: {response.status_code}, {response.text}")
return None
def get_wallet_balance():
"""ดึงยอดคงเหลือในกระเป๋า"""
ts = get_server_time()
if not ts:
print("ไม่สามารถดึงเวลาจากเซิร์ฟเวอร์ได้")
return None
payload = {"ts": ts}
signature = create_signature(API_SECRET, "POST", "/api/v3/market/wallet", "", payload)
headers = {
"X-BTK-APIKEY": API_KEY,
"X-BTK-TIMESTAMP": str(ts),
"X-BTK-SIGN": signature,
"Content-Type": "application/json"
}
response = requests.post(f"{API_URL}/api/v3/market/wallet", json=payload, headers=headers)
if response.status_code == 200:
return response.json().get("result", {})
else:
print(f"HTTP Error: {response.status_code}, {response.text}")
return None
def get_open_orders(symbol):
"""ดึงรายการคำสั่งค้าง"""
ts = get_server_time()
if not ts:
print("ไม่สามารถดึงเวลาจากเซิร์ฟเวอร์ได้")
return None
if symbol is None:
params = {"ts":ts}
else:
params = {"sym": symbol, "ts": ts}
signature = create_signature_params(API_SECRET, "GET", "/api/v3/market/my-open-orders", params, params)
headers = {
"X-BTK-APIKEY": API_KEY,
"X-BTK-TIMESTAMP": str(ts),
"X-BTK-SIGN": signature
}
response = requests.get(f"{API_URL}/api/v3/market/my-open-orders", params=params, headers=headers)
if response.status_code == 200:
return response.json().get("result", [])
else:
print(f"HTTP Error: {response.status_code}, {response.text}")
return None
def cancel_all_orders(symbol):
"""ยกเลิกคำสั่งซื้อ/ขายที่ยังค้าง"""
open_orders = get_open_orders(symbol)
if not open_orders:
print("ไม่มีคำสั่งค้าง")
return
for order in open_orders:
if order is None:
continue
order_id = order.get("id")
order_side = order.get("side") # เปลี่ยนจาก "sd" เป็น "side"
ts = get_server_time()
if not ts:
print("ไม่สามารถดึงเวลาจากเซิร์ฟเวอร์ได้")
return
# สร้าง payload
payload = {"sym": symbol, "id": order_id, "sd": order_side, "ts": ts}
# สร้าง Signature
signature = create_signature(API_SECRET, "POST", "/api/v3/market/cancel-order", {}, payload)
# Headers
headers = {
"X-BTK-APIKEY": API_KEY,
"X-BTK-TIMESTAMP": str(ts),
"X-BTK-SIGN": signature,
"Content-Type": "application/json"
}
# ส่งคำขอยกเลิกคำสั่ง
response = requests.post(f"{API_URL}/api/v3/market/cancel-order", json=payload, headers=headers)
if response.status_code == 200:
print(f"คำสั่ง {order_id} ถูกยกเลิกสำเร็จ")
save_cancel_order_log(symbol, order_id , order_side, "success")
else:
print(f"HTTP Error: {response.status_code}, {response.text}")
save_cancel_order_log(symbol, order_id , order_side, "failed")
def get_latest_buy_order(symbol):
"""ดึงคำสั่งซื้อ (buy) ล่าสุดที่ดำเนินการ"""
ts = get_server_time()
if not ts:
print(f"{symbol}: ไม่สามารถดึงเวลาจากเซิร์ฟเวอร์ได้")
return None
# Query Parameters
params = {"sym": symbol, "lmt": 10, "ts": ts}
# สร้าง Signature
signature = create_signature_params(API_SECRET, "GET", "/api/v3/market/my-order-history", params , {"ts": ts})
# Headers
headers = {
"X-BTK-APIKEY": API_KEY,
"X-BTK-TIMESTAMP": str(ts),
"X-BTK-SIGN": signature
}
# ส่งคำขอ GET
response = requests.get(f"{API_URL}/api/v3/market/my-order-history", params=params, headers=headers)
if response.status_code == 200:
orders = response.json().get("result", [])
if orders:
# กรองคำสั่งซื้อที่มี side == "buy" และจัดเรียงตาม ts (timestamp) มากที่สุด
buy_orders = sorted(
[order for order in orders if order.get("side") == "buy"],
key=lambda x: x.get("ts", 0),
reverse=True
)
if buy_orders:
latest_buy_order = buy_orders[0]
return {
"buy_price": float(latest_buy_order["rate"]),
"amount": float(latest_buy_order["amount"]),
"fee": float(latest_buy_order["fee"]),
"timestamp": latest_buy_order["ts"]
}
else:
# print(f"{symbol}: ไม่มีคำสั่งซื้อในประวัติ")
return {
"buy_price": 0, # กำหนดค่าเริ่มต้นหากไม่พบข้อมูล
"amount": 0,
"fee": 0,
"timestamp": 0
}
else:
# print(f"{symbol}: ไม่พบข้อมูลคำสั่งซื้อ")
return {
"buy_price": 0, # กำหนดค่าเริ่มต้นหากไม่พบข้อมูล
"amount": 0,
"fee": 0,
"timestamp": 0
}
else:
print(f"{symbol}: HTTP Error: {response.status_code}, {response.text}")
return {
"buy_price": 0,
"amount": 0,
"fee": 0,
"timestamp": 0
}
# ฟังก์ชันสำหรับสร้างฐานข้อมูลและตาราง Log
def initialize_database():
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
sslmode=DB_SSLMODE
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS logs (
id SERIAL PRIMARY KEY,
symbol TEXT,
message TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Create the `trade_records` table
cursor.execute("""
CREATE TABLE IF NOT EXISTS trade_records (
id SERIAL PRIMARY KEY,
symbol TEXT,
order_type TEXT,
profit_loss REAL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Create the `rebalance_logs` table
cursor.execute("""
CREATE TABLE IF NOT EXISTS rebalance_logs (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP,
asset TEXT,
type TEXT,
amount REAL,
price REAL,
potential_profit REAL
)
""")
# Commit changes and close the connection
conn.commit()
cursor.close()
conn.close()
def save_log(symbol, message):
try:
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
sslmode=DB_SSLMODE
)
cursor = conn.cursor()
cursor.execute("INSERT INTO logs (symbol, message) VALUES (%s, %s)", (symbol, message))
conn.commit()
cursor.close()
conn.close()
except psycopg2.Error as e:
print(f"Error saving log: {e}")
if conn:
conn.rollback() # Rollback the transaction to clear the error state
if cursor:
cursor.close()
if conn:
conn.close()
def save_order_log(symbol, order_type, amount, rate, status):
try:
"""บันทึก log การวางคำสั่ง Order ลง SQLite"""
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
sslmode=DB_SSLMODE
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS order_logs (
id SERIAL PRIMARY KEY,
symbol TEXT,
order_type TEXT,
amount REAL,
rate REAL,
status TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
cursor.execute(
"INSERT INTO order_logs (symbol, order_type, amount, rate, status) VALUES (%s, %s, %s, %s, %s)",
(symbol, order_type, amount, rate, status)
)
conn.commit()
conn.close()
except Exception as e:
print(f"Error : {e}")
def save_cancel_order_log(symbol, order_id, side, status):
"""บันทึก log การยกเลิกคำสั่งลง SQLite"""
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
sslmode=DB_SSLMODE
)
cursor = conn.cursor()
# Create the table if it does not exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS cancel_order_logs (
id SERIAL PRIMARY KEY,
symbol TEXT,
order_id TEXT,
side TEXT,
status TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Insert the log record
cursor.execute(
"INSERT INTO cancel_order_logs (symbol, order_id, side, status) VALUES (%s, %s, %s, %s)",
(symbol, order_id, side, status)
)
# Commit the transaction and close the connection
conn.commit()
cursor.close()
conn.close()
def save_trade_record(symbol, order_type, profit_loss):
"""
บันทึกข้อมูลกำไร/ขาดทุนลงในตาราง trade_records
"""
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
sslmode=DB_SSLMODE
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS trade_records (
id SERIAL PRIMARY KEY,
symbol TEXT,
order_type TEXT,
profit_loss REAL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
cursor.execute(
"""
INSERT INTO trade_records (symbol, order_type, profit_loss)
VALUES (%s, %s, %s)
""",
(symbol, order_type, profit_loss)
)
conn.commit()
conn.close()
def save_rebalance_log_to_db(timestamp, asset, transaction_type, amount, price, potential_profit):
"""
บันทึก Log ของ Rebalance ลง SQLite
"""
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
sslmode=DB_SSLMODE
)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO rebalance_logs (timestamp, asset, type, amount, price, potential_profit)
VALUES (%s, %s, %s, %s, %s, %s)
""", (timestamp, asset, transaction_type, amount, price, potential_profit))
conn.commit()
conn.close()
def calculate_overall_profit_loss():
"""
คำนวณกำไร/ขาดทุนรวมจากตาราง trade_records
"""
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
sslmode=DB_SSLMODE
)
cursor = conn.cursor()
cursor.execute("""
SELECT SUM(profit_loss) FROM trade_records
""")
result = cursor.fetchone()
conn.close()
return result[0] if result and result[0] is not None else 0.0
def scalping_bot(symbol, budget=100, profit_percent=2, cut_loss_percent=3, trading_fee_percent=0.25 , timetosleep=10 , reloadtime=120, max_iterations=12):
"""บอท Scalping พร้อม Take Profit และ Cut Loss"""
trading_fee_rate = trading_fee_percent / 100 # แปลงค่าธรรมเนียมเป็นอัตราส่วน
# ตรวจสอบยอดคงเหลือ
wallet = get_wallet_balance()
balance = float(wallet.get(symbol.split("_")[0], 0)) # ดึงยอดคงเหลือของเหรียญที่สนใจ
# save_log(symbol,f"{symbol}: คงเหลือ {balance}")
buy_price = None
buy_fee = 0
if balance > 0:
save_log(symbol,f"{symbol}: มีอยู่แล้ว รอขาย...")
# ดึงข้อมูลราคาซื้อจากคำสั่งซื้อที่ดำเนินการล่าสุด
latest_buy = get_latest_buy_order(symbol)
if latest_buy:
buy_price = latest_buy["buy_price"]
buy_fee = latest_buy["fee"] # คำนวณค่าธรรมเนียมการซื้อ
# save_log(symbol,f"{symbol}: ราคาซื้อจากคำสั่งล่าสุด: {buy_price:.2f} THB (ค่าธรรมเนียม: {buy_fee:.2f} THB)")
else:
# save_log(symbol,f"{symbol}: ไม่พบข้อมูลราคาซื้อจากคำสั่งล่าสุด")
return
# ตรวจสอบว่า buy_price มีค่า
if buy_price is None:
# save_log(symbol,f"{symbol}: ไม่สามารถกำหนดราคาซื้อได้")
return
# คำนวณเป้าหมาย Take Profit และ Cut Loss
target_sell_price = buy_price * (1 + profit_percent / 100) / (1 - trading_fee_rate)
cut_loss_price = buy_price * (1 - cut_loss_percent / 100) / (1 - trading_fee_rate)
# save_log(symbol,f"{symbol}: เป้าหมายขายกำไร {target_sell_price:.2f} THB (รวมค่าธรรมเนียม)")
# save_log(symbol,f"{symbol}: เป้าหมาย Cut Loss {cut_loss_price:.2f} THB (รวมค่าธรรมเนียม)")
else:
# ยกเลิกคำสั่งค้าง (ถ้ามี)
cancel_all_orders(symbol)
# ดึงราคาล่าสุด
ticker = get_market_ticker(symbol)
if not ticker or "last" not in ticker:
save_log(symbol,f"{symbol}: (New) ไม่สามารถดึงราคาล่าสุดได้")
return
current_price = float(ticker.get("last"))
save_log(symbol,f"{symbol}: (New) ราคาปัจจุบัน {current_price:.2f} THB")
# คำนวณจำนวนที่ต้องการซื้อ
amount_to_buy = budget / current_price
buy_fee = amount_to_buy * current_price * trading_fee_rate
save_log(symbol,f"{symbol}: (New) กำลังซื้อ {amount_to_buy:.6f} ที่ราคา {current_price:.2f} THB ({budget} + ค่าธรรมเนียม {buy_fee:.2f} THB)")
buy_response = place_order(symbol, "buy", budget, current_price)
if buy_response and buy_response.get("error") == 0:
buy_price = current_price
save_log(symbol,f"{symbol}: (New) ซื้อสำเร็จที่ราคา {buy_price:.2f} THB")
else:
save_log(symbol,f"{symbol}: (New) ไม่สามารถซื้อได้")
return
# คำนวณเป้าหมาย Take Profit และ Cut Loss
target_sell_price = buy_price * (1 + profit_percent / 100) / (1 - trading_fee_rate)
cut_loss_price = buy_price * (1 - cut_loss_percent / 100) / (1 - trading_fee_rate)
save_log(symbol,f"{symbol}: (New) เป้าหมายขายกำไร {target_sell_price:.2f} THB (รวมค่าธรรมเนียม)")
save_log(symbol,f"{symbol}: (New) เป้าหมาย Cut Loss {cut_loss_price:.2f} THB (รวมค่าธรรมเนียม)")
# รอขาย
for _ in range(max_iterations):
# save_log(symbol,f"Check Price ({symbol})")
ticker = get_market_ticker(symbol)
if ticker and "last" in ticker:
current_price = float(ticker.get("last"))
# save_log(symbol,f"{symbol}: ราคาปัจจุบัน {current_price:.2f} THB")
# ตรวจสอบยอดคงเหลือ
wallet = get_wallet_balance()
balance = float(wallet.get(symbol.split("_")[0], 0)) # ดึงยอดคงเหลือของเหรียญที่สนใจ
balancestr = format(balance, '.10f')
# save_log(symbol,f"{symbol}: คงเหลือ {balancestr}")
if(balance > 0):
# sell_fee = balance * target_sell_price * trading_fee_rate
# net_profit = (balance * target_sell_price) - (balance * buy_price) - buy_fee - sell_fee
# save_log(symbol,f"{symbol}: กำไรสุทธิ หาก ขายตรงเป้า({target_sell_price:.2f}): {net_profit:.2f} THB ค่า fee ไปกลับ ")
# net_loss = (balance * cut_loss_price) - (balance * buy_price) - buy_fee - sell_fee
# save_log(symbol,f"{symbol}: ขาดทุนสุทธิหาก ขายตรงเป้า({cut_loss_price:.2f}): {net_loss:.2f} THB ค่า fee ไปกลับ ")
# ขายเมื่อถึงเป้าหมาย Take Profit
if current_price >= target_sell_price:
save_log(symbol,f"{symbol}: ถึงเป้าหมายกำไร! กำลังขาย...")
sell_response = place_order(symbol, "sell", balance, current_price)
save_log(symbol,f"{symbol}: ผลลัพธ์การขาย: {sell_response}")
# คำนวณ Net Profit
sell_fee = balance * current_price * trading_fee_rate
net_profit = (balance * current_price) - (balance * buy_price) - buy_fee - sell_fee
save_log(symbol,f"{symbol}: กำไรสุทธิหลังขาย: {net_profit:.2f} THB")
save_trade_record(symbol, "sell", net_profit)
break
# ขายเมื่อถึงเป้าหมาย Cut Loss
elif current_price <= cut_loss_price:
save_log(symbol,f"{symbol}: ถึงเป้าหมาย Cut Loss! กำลังขาย...")
sell_response = place_order(symbol, "sell", balance, current_price)
save_log(symbol,f"{symbol}: ผลลัพธ์การขาย: {sell_response}")
# คำนวณ Net Loss
sell_fee = balance * current_price * trading_fee_rate
net_loss = (balance * current_price) - (balance * buy_price) - buy_fee - sell_fee
save_log(symbol,f"{symbol}: ขาดทุนสุทธิหลังขาย: {net_loss:.2f} THB")
save_trade_record(symbol, "sell", net_loss)
break
# save_log(symbol,f"ไม่ซื้อไม่ขาย รอ {timetosleep} วิ โหลดใหม่")
else:
save_log(symbol,f"{symbol}: สงสัยยังซื้อไม่สำเร็จ")
time.sleep(timetosleep) # ตรวจสอบราคาใหม่ทุก 10 วินาที
stop_flag = threading.Event()
def run_parallel(symbols, budget=50, profit_percent=1.5, cut_loss_percent=3, trading_fee_percent=0.25):
"""รัน Scalping Bot แบบ Parallel"""
timetosleep = 5
reloadtime = 30
while not stop_flag.is_set():
with ThreadPoolExecutor(max_workers=len(symbols)) as executor:
futures = [
executor.submit(scalping_bot, symbol, budget, profit_percent, cut_loss_percent, trading_fee_percent , timetosleep , reloadtime)
for symbol in symbols
]
for future in futures:
future.result() # รอให้แต่ละ Task เสร็จสิ้น
if stop_flag.is_set():
break
save_log("",f"รอบเสร็จสิ้น รอ {reloadtime} นาทีเพื่อเริ่มรอบใหม่...")
time.sleep(reloadtime) # รอ 1 นาทีเพื่อเริ่มรอบใหม่
save_log("", "Bot stopped.")
async def run_parallel_async(symbols, budget=50, profit_percent=1.5, cut_loss_percent=3, trading_fee_percent=0.25):
timetosleep = 5
reloadtime = 60 # In seconds for testing; adjust as needed
while not stop_flag.is_set():
if stop_flag.is_set():
save_log("", "Bot stopped.")
break
tasks = [
asyncio.to_thread(scalping_bot, symbol, budget, profit_percent, cut_loss_percent, trading_fee_percent, timetosleep, reloadtime , max_iterations=5)
for symbol in symbols
]
# Run all tasks concurrently
await asyncio.gather(*tasks)
# Log after the completion of one round of tasks
save_log("", f"รอบเสร็จสิ้น รอ {reloadtime} วินาทีเพื่อเริ่มรอบใหม่...")
# Wait for the reload time before starting the next round
await asyncio.sleep(reloadtime)
save_log("", "Bot stopped.")
def run(symbols, budget=50, profit_percent=1.5, cut_loss_percent=3, trading_fee_percent=0.25):
"""รัน Scalping Bot แบบ Parallel"""
timetosleep = 5
reloadtime = 30
while True:
save_log("","เริ่มรอบใหม่...")
for symbol in symbols:
scalping_bot(symbol, budget, profit_percent, cut_loss_percent, trading_fee_percent , timetosleep)
save_log("",f"รอบเสร็จสิ้น รอ {reloadtime} นาทีเพื่อเริ่มรอบใหม่...")
time.sleep(reloadtime) # รอ 1 นาทีเพื่อเริ่มรอบใหม่
def cancel_all_orders_my():
"""ยกเลิกคำสั่งซื้อขายทั้งหมดที่ยังค้าง"""
open_orders = get_open_orders()
if not open_orders:
print("No open orders to cancel.")
return
for order in open_orders:
order_id = order.get("id")
symbol = order.get("sym")
if not order_id or not symbol:
print("Invalid order data:", order)
continue
cancel_all_orders(symbol)
print("All orders processed.")
####################################################################################################################################################################################
# ตรวจสอบว่ามี session_state สำหรับบอทหรือไม่
if "bot_process" not in st.session_state:
st.session_state.bot_process = None
st.session_state.bot_status = "Stopped"
def start_bot():
if st.session_state.bot_process is None or st.session_state.bot_status == "Stopped":
# symbols_to_trade = ["BTC_THB", "ETH_THB", "XRP_THB", "ADA_THB"]
# budget = 55
# profit_percent = 2.0
# cut_loss_percent = 4.0
# trading_fee_percent = 0.25
def bot_runner():
run_parallel(symbols_to_trade, budget, profit_percent, cut_loss_percent, trading_fee_percent)
st.session_state.bot_process = threading.Thread(target=bot_runner, daemon=True)
st.session_state.bot_process.start()
st.session_state.bot_status = "Running"
st.success("Bot started successfully!")
else:
st.warning("Bot is already running!")
def start_bot_async():
if st.session_state.bot_process is None or st.session_state.bot_status == "Stopped":
symbols_to_trade = ["BTC_THB", "ETH_THB", "XRP_THB", "ADA_THB"]
budget = 55
profit_percent = 2.0
cut_loss_percent = 4.0
trading_fee_percent = 0.25
asyncio.run(run_parallel_async(symbols_to_trade, budget, profit_percent, cut_loss_percent, trading_fee_percent))
st.session_state.bot_status = "Running"
st.success("Bot started successfully!")
else:
st.warning("Bot is already running!")
# def start_bot():
# if st.session_state.bot_process is None or st.session_state.bot_status == "Stopped":
# symbols_to_trade = ["BTC_THB", "ETH_THB", "XRP_THB", "ADA_THB"] # สกุลเงินที่ต้องการเทรด
# initialize_database()
# budget = 55 # ตั้งงบประมาณที่เหมาะสมต่อเหรียญ
# profit_percent = 2.0 # ตั้งเป้าหมายกำไรที่สมดุล
# cut_loss_percent = 4.0 # ตั้งค่าการหยุดขาดทุนเพื่อลดความเสี่ยง
# trading_fee_percent = 0.25 # ค่าธรรมเนียมการเทรดของตลาด
# timetosleep = 6 # เวลารอระหว่างการตรวจสอบ
# reloadtime = 10*60 # เวลารีโหลดบอทรอบใหม่
# # run_parallel(symbols_to_trade)
# run_parallel(symbols_to_trade, budget, profit_percent, cut_loss_percent, trading_fee_percent)
# # st.session_state.bot_process = subprocess.Popen(["python", "multi_short.py"])
# # st.session_state.bot_process = run_parallel(symbols, budget, profit_percent, cut_loss_percent, trading_fee_percent)
# st.session_state.bot_status = "Running"
# st.success("Bot started successfully!")
# else:
# st.warning("Bot is already running!")
# ฟังก์ชันหยุดบอท
def stop_bot():
if st.session_state.bot_process and st.session_state.bot_status == "Running":
# Signal the thread to stop
stop_flag.set() # This is the flag used to control the thread loop
st.session_state.bot_status = "Stopped"
st.session_state.bot_process = None # Clear the thread reference
st.success("Bot stopped successfully!")
else:
st.warning("Bot is not running!")
# ฟังก์ชันรีสตาร์ทบอท
def restart_bot():
stop_bot()
start_bot()
####################################################################################################################################################################################
####################################################################################################################################################################################
####################################################################################################################################################################################
####################################################################################################################################################################################
####################################################################################################################################################################################
####################################################################################################################################################################################
####################################################################################################################################################################################
st.set_page_config(page_title="Bot", page_icon="🦈", layout="wide", initial_sidebar_state="expanded", menu_items=None)
# เพิ่มส่วนของ Bot Configuration
st.subheader("Bot Configuration")
# กำหนดรหัสผ่านที่ถูกต้อง
CORRECT_PASSWORD = "@As23522521"
# ตรวจสอบว่ามีการสร้าง session state หรือไม่
if "password_correct" not in st.session_state:
st.session_state.password_correct = False
# ส่วนของการกรอกรหัสผ่าน
password = st.text_input("กรอกรหัสผ่านเพื่อเปิดใช้งานปุ่ม:", type="password")
if st.button("ยืนยันรหัสผ่าน"):
if password == CORRECT_PASSWORD:
st.session_state.password_correct = True
st.success("รหัสผ่านถูกต้อง! ปุ่มทั้งหมดเปิดใช้งานแล้ว")
else:
st.session_state.password_correct = False
st.error("รหัสผ่านไม่ถูกต้อง! กรุณาลองอีกครั้ง")
# สร้าง 2 คอลัมน์
col_left, col_right = st.columns(2)
# คอลัมน์ซ้าย: การตั้งค่า
with col_left:
st.write("### Set Configuration")
assets_to_trade = fetch_assets_from_bitkub()
default_assets_to_trade = ["BTC_THB", "ETH_THB", "XRP_THB", "ADA_THB"]
valid_defaults = [asset for asset in default_assets_to_trade if asset in assets_to_trade]
if not assets_to_trade:
st.error("Unable to fetch assets from Bitkub API.")
else:
symbols_to_trade = st.multiselect(
"Select Symbols to Trade",
options=assets_to_trade,
default=valid_defaults
)
budget = st.number_input("Budget per Symbol (THB)", min_value=10, value=375)
profit_percent = st.number_input("Profit Target (%)", min_value=0.1, value=2.0)
cut_loss_percent = st.number_input("Cut Loss Threshold (%)", min_value=0.1, value=4.0)
trading_fee_percent = st.number_input("Trading Fee (%)", min_value=0.0, value=0.25)
# คอลัมน์ขวา: การแสดงค่าปัจจุบัน
with col_right:
st.write("### Current Configuration")
st.write(f"**Symbols to Trade:** {symbols_to_trade}")
st.write(f"**Budget per Symbol:** {budget} THB")
st.write(f"**Profit Target:** {profit_percent}%")
st.write(f"**Cut Loss Threshold:** {cut_loss_percent}%")
st.write(f"**Trading Fee:** {trading_fee_percent}%")
refresh_auto = st.checkbox("Show Details")
# Streamlit App
# st.title("Trading, Order, and Cancel Order Logs with Drag-and-Drop")
# แสดง UI สำหรับควบคุมบอท
st.title("Bot Control Panel")
# ฟังก์ชันตรวจสอบสถานะบอท
def check_bot_status():
if st.session_state.bot_process:
return "Running"
return "Stopped"
# แสดงสถานะปัจจุบันของบอท
st.session_state.bot_status = check_bot_status()
st.write(f"**Bot Status:** {st.session_state.bot_status}")
col1, col2, col3 , col4 = st.columns(4)
with col1:
if st.button("Start Bot",disabled=not st.session_state.password_correct):
start_bot()
with col2:
if st.button("Stop Bot",disabled=not st.session_state.password_correct):
stop_bot()
with col3:
if st.button("Restart Bot",disabled=not st.session_state.password_correct):
restart_bot()
with col4:
if st.button("Cancel All Orders",disabled=not st.session_state.password_correct):
stop_bot()
cancel_all_orders_my()
# subprocess.Popen(["python", "multi_short.py", "--cancel-all"])
st.success("Command to cancel all orders sent!")
start_bot()
# ฟังก์ชันเริ่มบอท
# st.subheader("Trading Bot Configuration")
# # รับค่าพารามิเตอร์จากผู้ใช้
# symbols = st.multiselect("Select Symbols", ["BTC_THB", "ETH_THB", "ADA_THB"])
# budget = st.number_input("Budget (THB)", min_value=10, value=50)
# profit_percent = st.number_input("Profit Percent (%)", min_value=0.1, value=2.0)
# cut_loss_percent = st.number_input("Cut Loss Percent (%)", min_value=0.1, value=3.0)
# trading_fee_percent = st.number_input("Trading Fee Percent (%)", min_value=0.0, value=0.25)
def calculate_overall_profit_loss():
"""
คำนวณกำไร/ขาดทุนรวมจากตาราง trade_records
"""
try:
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
sslmode=DB_SSLMODE
)
cursor = conn.cursor()
cursor.execute("""
SELECT SUM(profit_loss) FROM trade_records
""")
result = cursor.fetchone()
conn.close()
return result[0] if result and result[0] is not None else 0.0
except Exception as e:
# จัดการข้อผิดพลาดอื่น ๆ
print(f"An error occurred: {e}")
return 0.0
def get_trade_records():
"""
Fetch trade records from the `trade_records` table using SQLAlchemy.
"""
query = "SELECT * FROM trade_records ORDER BY timestamp DESC"
try:
# Use SQLAlchemy engine with pandas
df_records = pd.read_sql(query, engine)
return df_records
except Exception as e:
print(f"Error fetching trade records: {e}")
return pd.DataFrame() # Return an empty DataFrame on error
def calculate_profit(asset, balance, current_price, buy_price):
"""คำนวณกำไรที่เป็นไปได้"""
profit = (current_price - buy_price) * balance
return profit
def fetch_assets_with_profit():
"""ดึงข้อมูลทรัพย์สินพร้อมกำไรที่คาดการณ์ (แบบขนาน)"""
wallet = get_wallet_balance()
data = []
def process_asset(asset, balance):
"""ประมวลผลสินทรัพย์แต่ละรายการ"""
ass = f"{asset}_THB"
if balance > 0 and asset.upper() != "THB":
buy_order = get_latest_buy_order(ass) # ฟังก์ชันที่คุณใช้ดึงราคาซื้อ
if buy_order:
buy_price = buy_order.get("buy_price", 0)
market_data = get_market_ticker(ass) # ใช้ API ดึงข้อมูลราคาล่าสุด
current_price = float(market_data.get("last", 0))
profit = (current_price - buy_price) * balance
if buy_price > 0:
percent_profit = ((current_price - buy_price) / buy_price) * 100
else:
percent_profit = 0