최적화

This commit is contained in:
2025-08-23 20:30:59 +09:00
parent 9be2b785f8
commit ba22081ce2
2 changed files with 96 additions and 42 deletions

1
.idea/misc.xml generated
View File

@@ -1,4 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="Black"> <component name="Black">
<option name="sdkName" value="Python 3.12 (trading)" /> <option name="sdkName" value="Python 3.12 (trading)" />

View File

@@ -1,11 +1,14 @@
import asyncio, json import asyncio, json
import time import time
from datetime import datetime, tzinfo from datetime import datetime, tzinfo
from zoneinfo import ZoneInfo
import gate_api import gate_api
import psycopg2, pandas as pd, pandas_ta as ta import psycopg2, pandas as pd, pandas_ta as ta
import requests
from gate_ws import Configuration, Connection, WebSocketResponse from gate_ws import Configuration, Connection, WebSocketResponse
from gate_ws.spot import SpotPublicTradeChannel from gate_ws.spot import SpotPublicTradeChannel
from gate_ws.futures import FuturesBalanceChannel, FuturesTickerChannel, FuturesPublicTradeChannel from gate_ws.futures import FuturesPublicTradeChannel, FuturesCandlesticksChannel
from psycopg2.extras import execute_values from psycopg2.extras import execute_values
from sqlalchemy import create_engine from sqlalchemy import create_engine
@@ -20,6 +23,7 @@ class gate :
options='-c synchronous_commit=off' options='-c synchronous_commit=off'
) )
self.cur = self.conn.cursor() self.cur = self.conn.cursor()
self.oldDt = 0
def getAccount(self): def getAccount(self):
api = gate_api.SpotApi(gate_api.ApiClient(self.config)) api = gate_api.SpotApi(gate_api.ApiClient(self.config))
@@ -35,60 +39,66 @@ class gate :
async def main(self): async def main(self):
# initialize default connection, which connects to spot WebSocket V4 # initialize default connection, which connects to spot WebSocket V4
# it is recommended to use one conn to initialize multiple channels # it is recommended to use one conn to initialize multiple channels
futures_conn = Connection(Configuration(app='futures', settle='usdt', test_net=False)) futures_conn = Connection(Configuration(app='futures', settle='usdt', test_net=False, api_key=self.config.key, api_secret=self.config.secret))
# subscribe to any channel you are interested into, with the callback function # subscribe to any channel you are interested into, with the callback function
channel = FuturesTickerChannel(futures_conn, self.on_ob_snapshot) channel = FuturesCandlesticksChannel(futures_conn, self.on_ob_snapshot)
channel.subscribe(["BTC_USDT"]) channel.subscribe(["5m","BTC_USDT"])
channel.subscribe(["ETH_USDT"]) channel.subscribe(["5m","ETH_USDT"])
channel.subscribe(["SOL_USDT"]) channel.subscribe(["5m","SOL_USDT"])
channel.subscribe(["XRP_USDT"]) channel.subscribe(["5m","XRP_USDT"])
channel.subscribe(["LINK_USDT"]) channel.subscribe(["5m","LINK_USDT"])
# start the client # start the client
await futures_conn.run() await futures_conn.run()
def on_ob_snapshot(self, conn: Connection, resp: WebSocketResponse): def on_ob_snapshot(self, conn: Connection, resp: WebSocketResponse):
try : if resp.event == 'update':
result = resp.result[0] result = resp.result[0]
except Exception as e:
print(f'start {e}')
global batch
batch.append((
result['contract'],
result['last'],
result['change_percentage'],
result['total_size'],
result['volume_24h'],
result['volume_24h_base'],
result['volume_24h_quote'],
result['volume_24h_settle'],
result['funding_rate'],
result['funding_rate_indicative'],
result['quanto_base_rate'],
result['low_24h'],
result['high_24h'],
result['price_type'],
result['change_from'],
result['change_price'],
datetime.now()
))
if len(batch) >= 4:
try : try :
execute_values(self.cur, insert_sql = '''
'''insert into ticker (contract, clast, change_percentage, total_size, volume_24h, volume_24h_base, volume_24h_quote, INSERT INTO candle (contract, open, close, high, low, volume, amount, time, ins_date)
volume_24h_settle, funding_rate, funding_rate_indicative, quanto_base_rate, low_24h, high_24h, SELECT %(contract)s,
price_type, change_from, change_price, ts) %(open)s,
VALUES %s''', %(close)s,
batch) %(high)s,
%(low)s,
%(volume)s,
%(amount)s,
%(time)s,
%(ins_date)s
ON CONFLICT (contract, time, ins_date)
DO UPDATE SET
open = EXCLUDED.open,
close = EXCLUDED.close,
high = EXCLUDED.high,
low = EXCLUDED.low,
volume = EXCLUDED.volume,
amount = EXCLUDED.amount,
ins_date = EXCLUDED.ins_date
'''
self.cur.execute(insert_sql, {
'contract': result['n'].replace('5m_', ''),
'open': result['o'],
'close': result['c'],
'high': result['h'],
'low': result['l'],
'volume': result['v'],
'amount': result['a'],
'time': result['t'],
'ins_date': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(result['t'])),
})
# execute_values(self.cur,
# '''insert into candle (contract, open, close, high, low, volume, amount, time, ins_date)
# VALUES (%s)''',
# batch)
self.conn.commit() self.conn.commit()
batch.clear()
except Exception as exc: except Exception as exc:
print(exc) print(exc)
self.conn.rollback() self.conn.rollback()
def getData(self, contract, time=None): def getData(self, contract, time=None):
limit = 50 limit = 50
if time is not None: if time is not None:
@@ -173,10 +183,55 @@ class gate :
return "SELL" return "SELL"
else: else:
return "HOLD" return "HOLD"
def init(self, contract, t):
res = requests.get(f'https://fx-api.gateio.ws/api/v4/futures/usdt/candlesticks?contract={contract}&interval=5m&from={t}&limit=2000')
lists = res.json()
if self.oldDt != lists[len(lists) -1]['t']:
self.save(contract, lists)
self.oldDt = lists[len(lists) -1]['t']
self.init(contract, lists[len(lists) -1]['t'])
def save(self, contract, lists):
for list in lists:
batch.append((
contract,
list['o'],
list['c'],
list['h'],
list['l'],
list['v'],
0,
list['t'],
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(list['t']))
))
try :
execute_values(self.cur,
'''insert into candle (contract, open, close, high, low, volume, amount, time, ins_date)
VALUES %s''',
batch)
self.conn.commit()
batch.clear()
except Exception as exc:
self.conn.rollback()
batch.clear()
# {'o': '7223.5', 'v': 0, 't': 1577860400, 'c': '7223.5', 'l': '7223.5', 'h': '7223.5', 'sum': '0'}
if __name__ == '__main__': if __name__ == '__main__':
gate = gate() gate = gate()
gate.getData("SOL_USDT", '5min') contracs = [
"BTC_USDT"
,"ETH_USDT"
,"SOL_USDT"
,"XRP_USDT"
,"LINK_USDT"
]
for co in contracs :
gate.init(co, 1755345900)
# loop = asyncio.get_event_loop() # loop = asyncio.get_event_loop()
# loop.run_until_complete(gate.main()) # loop.run_until_complete(gate.main())
# loop.close() # loop.close()
# gate.getData("SOL_USDT", '5min')
# print(datetime.now().timestamp()) # print(datetime.now().timestamp())