├── windows
├── caddyrun.bat
├── activate.bat
├── start.bat
├── pip_install.txt
├── install.bat
└── Caddyfile
├── exchange
├── model
│ ├── __init__.py
│ └── schemas.py
├── stock
│ ├── __init__.py
│ ├── error.py
│ ├── schemas.py
│ └── kis.py
├── utility
│ ├── setting.py
│ ├── __init__.py
│ ├── ws.py
│ └── LogMaker.py
├── __init__.py
├── pocket.py
├── error.py
├── database.py
├── upbit.py
├── bitget.py
├── bybit.py
├── okx.py
├── binance.py
└── pexchange.py
├── .vscode
└── settings.json
├── pb_data
└── data.db
├── requirements.txt
├── run.py
├── README.md
├── .gitignore
├── main.py
└── LICENSE
/windows/caddyrun.bat:
--------------------------------------------------------------------------------
1 | call caddy run
2 | pause
--------------------------------------------------------------------------------
/exchange/model/__init__.py:
--------------------------------------------------------------------------------
1 | from exchange.model.schemas import *
2 |
--------------------------------------------------------------------------------
/exchange/stock/__init__.py:
--------------------------------------------------------------------------------
1 | from exchange.stock.kis import KoreaInvestment
2 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.analysis.typeCheckingMode": "off"
3 | }
4 |
--------------------------------------------------------------------------------
/pb_data/data.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jangdokang/POA/HEAD/pb_data/data.db
--------------------------------------------------------------------------------
/windows/activate.bat:
--------------------------------------------------------------------------------
1 | FOR %%A IN (%~dp0\.) DO SET folder=%%~dpA
2 | call %folder%\.venv\Scripts\activate.bat
--------------------------------------------------------------------------------
/windows/start.bat:
--------------------------------------------------------------------------------
1 | FOR %%A IN (%~dp0\.) DO SET folder=%%~dpA
2 | call %folder%\.venv\Scripts\activate.bat
3 | call python %folder%\run.py
4 | pause
--------------------------------------------------------------------------------
/exchange/utility/setting.py:
--------------------------------------------------------------------------------
1 | from exchange.model import Settings
2 | from functools import lru_cache
3 |
4 |
5 | @lru_cache()
6 | def get_settings():
7 | return Settings()
8 |
9 |
10 | settings = get_settings()
11 |
--------------------------------------------------------------------------------
/windows/pip_install.txt:
--------------------------------------------------------------------------------
1 | pip install fastapi
2 | pip install "uvicorn[standard]"
3 | pip install fire
4 | pip install dhooks
5 | pip install loguru
6 | pip install httpx
7 | pip install ccxt
8 | pip install orjson
9 | pip install pocketbase
10 | pip install pyjwt
--------------------------------------------------------------------------------
/windows/install.bat:
--------------------------------------------------------------------------------
1 | FOR %%A IN (%~dp0\.) DO SET folder=%%~dpA
2 | call python -m venv %folder%\.venv
3 | call %folder%\.venv\Scripts\activate.bat
4 | call %folder%\.venv\Scripts\python.exe -m pip install --upgrade pip
5 | call pip install -r %folder%\requirements.txt
6 | pause
--------------------------------------------------------------------------------
/exchange/utility/__init__.py:
--------------------------------------------------------------------------------
1 | from exchange.utility.setting import settings
2 | from exchange.utility.LogMaker import log_message, log_error_message, log_order_message, log_alert_message, print_alert_message, log_order_error_message, logger_test, log_validation_error_message, log_hedge_message
--------------------------------------------------------------------------------
/windows/Caddyfile:
--------------------------------------------------------------------------------
1 | YourDomain.com {
2 | @whitelist {
3 | remote_ip 52.89.214.238 34.212.75.30 54.218.53.128 52.32.178.7
4 | }
5 | handle @whitelist {
6 | reverse_proxy 127.0.0.1:8000
7 | }
8 | respond 403
9 | }
10 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | PyJWT==2.7.0
2 | ccxt==4.4.20
3 | dhooks==1.1.4
4 | fastapi==0.99.0
5 | uvicorn[standard]==0.22.0
6 | fire==0.5.0
7 | httpx==0.23.3
8 | loguru==0.7.0
9 | pocketbase==0.8.2
10 | pydantic[dotenv]==1.10.10
11 | devtools[pygments]==0.11.0
12 | orjson==3.9.1
13 | pendulum==2.1.2
--------------------------------------------------------------------------------
/run.py:
--------------------------------------------------------------------------------
1 | import uvicorn
2 | import fire
3 | from exchange.utility import settings
4 | from main import app
5 |
6 |
7 | def start_server(host="0.0.0.0", port=8000 if settings.PORT is None else settings.PORT):
8 | app.state.port = port
9 | uvicorn.run("main:app", host=host, port=port, reload=False)
10 |
11 |
12 | if __name__ == "__main__":
13 | fire.Fire(start_server)
14 |
--------------------------------------------------------------------------------
/exchange/stock/error.py:
--------------------------------------------------------------------------------
1 | class TokenExpired(Exception):
2 | def __init__(self, msg="Token Expired!", *args, **kwargs):
3 | super().__init__(msg, *args, **kwargs)
4 |
5 |
6 | # {'rt_cd': '1', 'msg_cd': 'EGW00205', 'msg1': 'credentials_type이 유효하지 않습니다.(Bearer)'}
7 | # {'rt_cd': '7', 'msg_cd': 'APAC0081', 'msg1': '계좌번호 입력 오류입니다'}
8 | # {'rt_cd': '7', 'msg_cd': 'APBK0919', 'msg1': '장운영일자가 주문일과 상이합니다'}
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PoABOT - Power of Algorithm
2 |
3 | ## 트레이딩뷰에서 전달되는 웹훅을 처리하는 봇입니다.
4 |
5 |
6 |
7 | - 지원 거래소
8 | - 업비트 KRW(원화) 마켓
9 | - 바이낸스 현물/선물 USDT,BUSD 마켓
10 | - 바이비트 현물/선물 USDT 마켓
11 | - 비트겟 현물/선물 USDT 마켓
12 | - 한국투자증권 한국/미국 주식 마켓
13 |
14 |
15 |
16 | # <주의>
17 |
18 | _본 프로젝트는 개인적으로 개발한 프로젝트를 오픈소스로 공유한 것으로_
19 |
20 | _발생하는 문제에 대한 모든 책임은 본인에게 있습니다._
21 |
22 | # Dependency
23 |
24 | > [fastapi](https://github.com/tiangolo/fastapi) , [ccxt](https://github.com/ccxt/ccxt) , [uvicorn](https://github.com/encode/uvicorn)
25 |
--------------------------------------------------------------------------------
/exchange/__init__.py:
--------------------------------------------------------------------------------
1 | # from exchange.binance import Binance
2 | # from exchange.upbit import Upbit
3 | # from exchange.bybit import Bybit
4 | # from exchange.bitget import Bitget
5 | # from exchange.kis import KoreaInvestment
6 | from exchange.pexchange import get_bot, get_exchange
7 | from exchange.database import db
8 | from exchange.model import (
9 | PriceRequest,
10 | MarketOrder,
11 | OrderRequest,
12 | EXCHANGE_LITERAL,
13 | QUOTE_LITERAL,
14 | )
15 | from exchange.utility import (
16 | log_order_message,
17 | print_alert_message,
18 | log_order_error_message,
19 | log_alert_message,
20 | log_message,
21 | settings,
22 | )
23 |
--------------------------------------------------------------------------------
/exchange/pocket.py:
--------------------------------------------------------------------------------
1 | from pocketbase import PocketBase
2 | import jwt
3 | from exchange.utility import log_message, log_error_message, settings
4 | import time
5 | import traceback
6 |
7 | pb = PocketBase("http://127.0.0.1:8090")
8 |
9 |
10 | def auth():
11 | try:
12 | DB_ID = settings.DB_ID
13 | DB_PASSWORD = settings.DB_PASSWORD
14 | pb.admins.auth_with_password(DB_ID, DB_PASSWORD)
15 | except Exception as e:
16 | raise Exception("DB auth error")
17 |
18 |
19 | def reauth():
20 | try:
21 | token = pb.auth_store.base_token
22 | decoded_token = jwt.decode(token, options={"verify_signature": False})
23 | expire_time = decoded_token["exp"]
24 | current_time = int(time.time())
25 | if current_time > expire_time:
26 | auth()
27 | except:
28 | raise Exception("DB reauth error")
29 |
30 |
31 | def create(collection, data):
32 | try:
33 | reauth()
34 | pb.collection(collection).create(data)
35 | except:
36 | raise Exception("DB create error")
37 |
38 |
39 | def delete(collection, id):
40 | try:
41 | reauth()
42 | pb.collection(collection).delete(id)
43 | except:
44 | raise Exception("DB delete error")
45 |
46 |
47 | def get_full_list(collection, batch_size=200, query_params=None):
48 | try:
49 | reauth()
50 | return pb.collection(collection).get_full_list(
51 | batch=batch_size, query_params=query_params
52 | )
53 | except:
54 | raise Exception("DB get_full_list error")
55 |
56 |
57 | try:
58 | auth()
59 | except:
60 | log_error_message(traceback.format_exc(), "DB auth error")
61 |
--------------------------------------------------------------------------------
/exchange/error.py:
--------------------------------------------------------------------------------
1 | from exchange.model import MarketOrder
2 | from devtools import debug
3 |
4 |
5 | class AmountError(Exception):
6 | def __init__(self, msg="", *args, **kwargs):
7 | super().__init__(f"[수량 오류]\n{msg}", *args, **kwargs)
8 |
9 |
10 | class AmountPercentNoneError(AmountError):
11 | def __init__(self, *args, **kwargs):
12 | msg = "amount와 percent 중 적어도 하나는 입력해야 합니다!"
13 | super().__init__(msg, *args, **kwargs)
14 |
15 |
16 | class AmountPercentBothError(AmountError):
17 | def __init__(self, *args, **kwargs):
18 | msg = "amount와 percent는 동시에 입력할 수 없습니다!"
19 | super().__init__(msg, *args, **kwargs)
20 |
21 |
22 | class FreeAmountNoneError(AmountError):
23 | def __init__(self, *args, **kwargs):
24 | msg = "거래할 수량이 없습니다"
25 | super().__init__(msg, *args, **kwargs)
26 |
27 |
28 | class MinAmountError(AmountError):
29 | def __init__(self, *args, **kwargs):
30 | msg = "최소 거래 수량을 만족하지 못했습니다!"
31 | super().__init__(msg, *args, **kwargs)
32 |
33 |
34 | class PositionError(Exception):
35 | def __init__(self, msg="", *args, **kwargs):
36 | super().__init__(f"[포지션 오류]\n{msg}", *args, **kwargs)
37 |
38 |
39 | class PositionNoneError(PositionError):
40 | def __init__(self, msg="", *args, **kwargs):
41 | super().__init__(f"{msg} 포지션이 없습니다", *args, **kwargs)
42 |
43 |
44 | class LongPositionNoneError(PositionNoneError):
45 | def __init__(self, *args, **kwargs):
46 | msg = "롱"
47 | super().__init__(msg, *args, **kwargs)
48 |
49 |
50 | class ShortPositionNoneError(PositionNoneError):
51 | def __init__(self, *args, **kwargs):
52 | msg = "숏"
53 | super().__init__(msg, *args, **kwargs)
54 |
55 |
56 | class OrderError(Exception):
57 | def __init__(self, msg="", order_info: MarketOrder = None, *args, **kwargs):
58 | side = ""
59 | if order_info is not None:
60 | if order_info.is_futures:
61 | if order_info.is_entry:
62 | if order_info.is_buy:
63 | side = "롱 진입"
64 | elif order_info.is_sell:
65 | side = "숏 진입"
66 | elif order_info.is_close:
67 | if order_info.is_buy:
68 | side = "숏 종료"
69 | elif order_info.is_sell:
70 | side = "롱 종료"
71 |
72 | elif order_info.is_buy:
73 | side = "매수"
74 | elif order_info.is_sell:
75 | side = "매도"
76 |
77 | super().__init__(f"[{side} 주문 오류]\n{msg}", *args, **kwargs)
78 |
--------------------------------------------------------------------------------
/exchange/utility/ws.py:
--------------------------------------------------------------------------------
1 | # from toolbox import Client
2 |
3 | from client import Client
4 | import websocket
5 | import _thread
6 | import time
7 | import rel
8 | import json
9 | from pprint import pprint
10 |
11 |
12 | class Websocket:
13 |
14 | def __init__(self):
15 | self.client = Client()
16 | self.binance = self.client.get_binance()
17 | self.listen_key = self.binance.get_listen_key()
18 | self.ws_url = f"wss://fstream.binance.com/ws/{self.listen_key}"
19 |
20 | def on_message(self, ws, message):
21 |
22 | datas: dict = json.loads(message)
23 | event = datas.get("e")
24 | event_time = datas.get("E")
25 | transaction_time = datas.get("T")
26 | cross_wallt_balance = datas.get("cw")
27 | order = datas.get("o")
28 |
29 | if event == "listenKeyExpired":
30 | print("Listen key expired")
31 | self.listen_key = self.binance.get_listen_key()
32 | elif event == "ORDER_TRADE_UPDATE":
33 | order_type = order.get("ot") # TAKE_PROFIT_MARKET, STOP_MARKET
34 | order_status = order.get("X") # 새로운 주문은 NEW
35 | if order_type in ("TAKE_PROFIT_MARKET", "STOP_MARKET"):
36 | order_id = order.get("i") # 주문 ID
37 | client_order_id = order.get("c") # 주문 고유 ID
38 | order_symbol = order.get("s") # 주문 심볼
39 | order_price = order.get("sp") # 스탑 가격
40 | order_side = order.get("S") # 주문 종류
41 | order_qty = order.get("q") # 주문 수량
42 |
43 | print(f"{order_symbol=}, {order_price=}, {order_type=}, {order_status=}, {order_id=}, {client_order_id=}")
44 |
45 | print("=====끝=====")
46 |
47 | def on_error(self, ws, error):
48 | print(error)
49 |
50 | def on_close(self, ws, close_status_code, close_msg):
51 | print("### closed ###")
52 |
53 | def on_open(self, ws):
54 | print("Opened connection")
55 |
56 | def start(self):
57 | ws = websocket.WebSocketApp(self.ws_url,
58 | on_open=self.on_open,
59 | on_message=self.on_message,
60 | on_error=self.on_error,
61 | on_close=self.on_close)
62 |
63 | ws.run_forever(dispatcher=rel, reconnect=5) # Set dispatcher to automatic reconnection, 5 second reconnect delay if connection closed unexpectedly
64 | rel.signal(2, rel.abort) # Keyboard Interrupt
65 | rel.dispatch()
66 |
67 |
68 | if __name__ == "__main__":
69 | ws = Websocket()
70 | ws.start()
71 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | log/
41 | logs/
42 |
43 | # Unit test / coverage reports
44 | htmlcov/
45 | .tox/
46 | .nox/
47 | .coverage
48 | .coverage.*
49 | .cache
50 | nosetests.xml
51 | coverage.xml
52 | *.cover
53 | *.py,cover
54 | .hypothesis/
55 | .pytest_cache/
56 |
57 | # Translations
58 | *.mo
59 | *.pot
60 |
61 | # Django stuff:
62 | *.log
63 | local_settings.py
64 | db.sqlite3
65 | db.sqlite3-journal
66 |
67 | # Flask stuff:
68 | instance/
69 | .webassets-cache
70 |
71 | # Scrapy stuff:
72 | .scrapy
73 |
74 | # Sphinx documentation
75 | docs/_build/
76 |
77 | # PyBuilder
78 | target/
79 |
80 | # Jupyter Notebook
81 | .ipynb_checkpoints
82 |
83 | # IPython
84 | profile_default/
85 | ipython_config.py
86 |
87 | # pyenv
88 | .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
98 | __pypackages__/
99 |
100 | # Celery stuff
101 | celerybeat-schedule
102 | celerybeat.pid
103 |
104 | # SageMath parsed files
105 | *.sage.py
106 |
107 | # Environments
108 | .venv
109 | .env
110 | env/
111 | venv/
112 | ENV/
113 | env.bak/
114 | venv.bak/
115 |
116 | # Spyder project settings
117 | .spyderproject
118 | .spyproject
119 |
120 | # Rope project settings
121 | .ropeproject
122 |
123 | # mkdocs documentation
124 | /site
125 |
126 | # mypy
127 | .mypy_cache/
128 | .dmypy.json
129 | dmypy.json
130 |
131 | # Pyre type checker
132 | .pyre/
133 |
134 | # test
135 | start_dev.bat
136 | dev.env
137 | caddy.exe
138 | Caddyfile_test
139 | caddyrun_test.bat
140 | test.http
141 | test.py
142 | my_*
143 | my-*
144 | ecosystem.config.js
145 |
146 | # db
147 | pocketbase.exe
148 | store.db
149 | pb_data/logs.db*
150 | pb_data/data.db-*
151 | pb_migrations/
152 |
--------------------------------------------------------------------------------
/exchange/database.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | import traceback
3 | import os
4 | from pathlib import Path
5 |
6 | current_file_direcotry = os.path.dirname(os.path.realpath(__file__))
7 | parent_directory = Path(current_file_direcotry).parent
8 |
9 | class Database:
10 | def __new__(cls, *args, **kwargs):
11 | if not hasattr(cls, "_instance"):
12 | cls._instance = super().__new__(cls)
13 | return cls._instance
14 |
15 | def __init__(self, database_url: str = f"{parent_directory}/store.db"):
16 | cls = type(self)
17 | if not hasattr(cls, "_init"):
18 | self.database_url = database_url
19 | self.con = sqlite3.connect(self.database_url)
20 | self.cursor = self.con.cursor()
21 | cls._init = True
22 |
23 | def close(self):
24 | self.con.close()
25 |
26 | def excute(self, query: str, value: dict | tuple):
27 | self.cursor.execute(query, value)
28 | self.con.commit()
29 |
30 | def excute_many(self, query: str, values: list[dict | tuple]):
31 | self.cursor.executemany(query, values)
32 | self.con.commit()
33 |
34 | def fetch_one(self, query: str, value: dict | tuple):
35 | self.cursor.execute(query, value)
36 | return self.cursor.fetchone()
37 |
38 | def fetch_all(self, query: str, value: dict | tuple):
39 | self.cursor.execute(query, value)
40 | return self.cursor.fetchall()
41 |
42 | def set_auth(self, exchange, access_token, access_token_token_expired):
43 | query = """
44 | INSERT INTO auth (exchange, access_token, access_token_token_expired)
45 | VALUES (:exchange, :access_token, :access_token_token_expired)
46 | ON CONFLICT(exchange) DO UPDATE SET
47 | access_token=excluded.access_token,
48 | access_token_token_expired=excluded.access_token_token_expired;
49 | """
50 | return self.excute(query, {"exchange": exchange, "access_token": access_token, "access_token_token_expired": access_token_token_expired})
51 |
52 | def get_auth(self, exchange):
53 | query = """
54 | SELECT access_token, access_token_token_expired FROM auth WHERE exchange = :exchange;
55 | """
56 | return self.fetch_one(query, {"exchange": exchange})
57 |
58 | def clear_auth(self):
59 | self.set_auth("KIS1", "nothing", "nothing")
60 | self.set_auth("KIS2", "nothing", "nothing")
61 | self.set_auth("KIS3", "nothing", "nothing")
62 | self.set_auth("KIS4", "nothing", "nothing")
63 |
64 | def init_db(self):
65 | query = """
66 | CREATE TABLE IF NOT EXISTS auth (
67 | exchange TEXT PRIMARY KEY,
68 | access_token TEXT,
69 | access_token_token_expired TEXT
70 | );
71 | """
72 | self.excute(query, {})
73 | # self.clear_auth()
74 |
75 |
76 | db = Database()
77 | # print(os.path.realpath(__file__))
78 | # print(os.getcwd())
79 | # print(os.path.dirname(os.path.realpath(__file__)))
80 | try:
81 | db.init_db()
82 | except Exception as e:
83 | print(traceback.format_exc())
84 |
--------------------------------------------------------------------------------
/exchange/upbit.py:
--------------------------------------------------------------------------------
1 | from exchange.pexchange import ccxt, ccxt_async
2 | from exchange.database import db
3 | from exchange.model import MarketOrder
4 | import exchange.error as error
5 |
6 |
7 | class Upbit:
8 | def __init__(self, key, secret):
9 | self.client = ccxt.upbit(
10 | {
11 | "apiKey": key,
12 | "secret": secret,
13 | }
14 | )
15 | self.client.load_markets()
16 | self.order_info: MarketOrder = None
17 |
18 | def init_info(self, order_info: MarketOrder):
19 | self.order_info = order_info
20 | unified_symbol = order_info.unified_symbol
21 | market = self.client.market(unified_symbol)
22 |
23 | if order_info.amount is not None:
24 | order_info.amount = float(self.client.amount_to_precision(order_info.unified_symbol, order_info.amount))
25 |
26 | self.client.options["defaultType"] = "spot"
27 |
28 | # async def aclose(self):
29 | # await self.spot_async.close()
30 | def get_ticker(self, symbol: str):
31 | return self.client.fetch_ticker(symbol)
32 |
33 | def get_price(self, symbol: str):
34 | return self.get_ticker(symbol)["last"]
35 |
36 | def get_balance(self, base: str) -> float:
37 | free_balance_by_base = (self.client.fetch_free_balance()).get(base)
38 | if free_balance_by_base is None or free_balance_by_base == 0:
39 | raise error.FreeAmountNoneError()
40 | else:
41 | return free_balance_by_base
42 |
43 | def get_amount(self, order_info: MarketOrder) -> float:
44 | if order_info.amount is not None and order_info.percent is not None:
45 | raise error.AmountPercentBothError()
46 | elif order_info.amount is not None:
47 | result = order_info.amount
48 | elif order_info.percent is not None:
49 | if self.order_info.side in ("buy"):
50 | free_quote = self.get_balance(order_info.quote)
51 | cash = free_quote * order_info.percent / 100
52 | current_price = self.get_price(order_info.unified_symbol)
53 | result = cash / current_price
54 | elif self.order_info.side in ("sell"):
55 | free_amount = self.get_balance(order_info.base)
56 | if free_amount is None:
57 | raise error.FreeAmountNoneError()
58 | result = free_amount * order_info.percent / 100
59 | else:
60 | raise error.AmountPercentNoneError()
61 | return result
62 |
63 | def market_order(self, order_info: MarketOrder):
64 | from exchange.pexchange import retry
65 |
66 | params = {}
67 | try:
68 | return retry(
69 | self.client.create_order,
70 | order_info.unified_symbol,
71 | order_info.type.lower(),
72 | order_info.side,
73 | order_info.amount,
74 | order_info.price,
75 | params,
76 | order_info=order_info,
77 | max_attempts=5,
78 | instance=self,
79 | )
80 | except Exception as e:
81 | raise error.OrderError(e, order_info)
82 |
83 | def market_buy(self, order_info: MarketOrder):
84 | from exchange.pexchange import retry
85 |
86 | # 비용주문
87 | buy_amount = self.get_amount(order_info)
88 | order_info.amount = buy_amount
89 | order_info.price = self.get_price(order_info.unified_symbol)
90 | return self.market_order(order_info)
91 |
92 | def market_sell(self, order_info: MarketOrder):
93 | sell_amount = self.get_amount(order_info)
94 | order_info.amount = sell_amount
95 | return self.market_order(order_info)
96 |
97 | def get_order(self, order_id: str):
98 | return self.client.fetch_order(order_id)
99 |
100 | def get_order_amount(self, order_id: str):
101 | return self.get_order(order_id)["filled"]
102 |
--------------------------------------------------------------------------------
/exchange/stock/schemas.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 | from typing import Literal
3 | from pydantic import BaseModel
4 |
5 | korea_stocks = ("KRX")
6 | us_stocks = ("NASDAQ", "NYSE", "AMEX")
7 |
8 |
9 | class BaseUrls(str, Enum):
10 | base_url = "https://openapi.koreainvestment.com:9443"
11 | paper_base_url = "https://openapivts.koreainvestment.com:29443"
12 |
13 |
14 | class BaseHeaders(BaseModel):
15 | authorization: str
16 | appkey: str
17 | appsecret: str
18 | custtype: str = "P"
19 | # tr_id: str = Literal[TransactionId.korea_buy, TransactionId.korea_sell, TransactionId.korea_paper_buy, TransactionId.korea_paper_sell,
20 | # TransactionId.korea_paper_cancel, TransactionId.usa_buy, TransactionId.usa_sell, TransactionId.usa_paper_buy, TransactionId.usa_paper_sell]
21 |
22 |
23 | class Endpoints(str, Enum):
24 | korea_order_base = "/uapi/domestic-stock/v1"
25 | korea_order = f"{korea_order_base}/trading/order-cash"
26 | korea_order_buyable = f"{korea_order_base}/trading/inquire-psbl-order"
27 |
28 | usa_order_base = "/uapi/overseas-stock/v1"
29 | usa_order = f"{usa_order_base}/trading/order"
30 | usa_order_buyable = f"{usa_order_base}/trading/inquire-psamount"
31 | usa_current_price = f"/uapi/overseas-price/v1/quotations/price"
32 |
33 | korea_ticker = "/uapi/domestic-stock/v1/quotations/inquire-price"
34 | usa_ticker = "/uapi/overseas-price/v1/quotations/price"
35 |
36 |
37 | class TransactionId(str, Enum):
38 |
39 | korea_buy = "TTTC0802U"
40 | korea_sell = "TTTC0801U"
41 |
42 | korea_paper_buy = "VTTC0802U"
43 | korea_paper_sell = "VTTC0801U"
44 | korea_paper_cancel = "VTTC0803U"
45 |
46 | usa_buy = "JTTT1002U"
47 | usa_sell = "JTTT1006U"
48 |
49 | usa_paper_buy = "VTTT1002U"
50 | usa_paper_sell = "VTTT1001U"
51 |
52 | korea_ticker = "FHKST01010100"
53 | usa_ticker = "HHDFS00000300"
54 |
55 |
56 | class KoreaTickerQuery(BaseModel):
57 | FID_COND_MRKT_DIV_CODE: str = "J"
58 | FID_INPUT_ISCD: str
59 |
60 |
61 | class UsaTickerQuery(BaseModel):
62 | AUTH: str = ""
63 | EXCD: Literal["NYS", "NAS", "AMS"]
64 | SYMB: str # 종목코드
65 |
66 |
67 | class ExchangeCode(str, Enum):
68 | NYSE = "NYSE"
69 | NASDAQ = "NASD"
70 | AMEX = "AMEX"
71 |
72 |
73 | class QueryExchangeCode(str, Enum):
74 | NYSE = "NYS"
75 | NASDAQ = "NAS"
76 | AMEX = "AMS"
77 |
78 |
79 | class KoreaOrderType(str, Enum):
80 | market = "01" # 시장가
81 | limit = "00" # 지정가
82 |
83 |
84 | class UsaOrderType(str, Enum):
85 | limit = "00" # 지정가
86 |
87 |
88 | class OrderSide(str, Enum):
89 | buy = "buy"
90 | sell = "sell"
91 |
92 |
93 | class TokenInfo(BaseModel):
94 | access_token: str
95 | access_token_token_expired: str
96 |
97 |
98 | class KoreaTickerHeaders(BaseHeaders):
99 | tr_id: str = TransactionId.korea_ticker.value
100 |
101 |
102 | class UsaTickerHeaders(BaseHeaders):
103 | tr_id: str = TransactionId.usa_ticker.value
104 |
105 |
106 | class KoreaBuyOrderHeaders(BaseHeaders):
107 | tr_id: str = TransactionId.korea_buy.value
108 |
109 |
110 | class KoreaSellOrderHeaders(BaseHeaders):
111 | tr_id: str = TransactionId.korea_sell.value
112 |
113 |
114 | class KoreaPaperBuyOrderHeaders(BaseHeaders):
115 | tr_id: str = TransactionId.korea_paper_buy.value
116 |
117 |
118 | class KoreaPaperSellOrderHeaders(BaseHeaders):
119 | tr_id: str = TransactionId.korea_paper_sell.value
120 |
121 |
122 | class UsaBuyOrderHeaders(BaseHeaders):
123 | tr_id: str = TransactionId.usa_buy.value
124 |
125 |
126 | class UsaSellOrderHeaders(BaseHeaders):
127 | tr_id: str = TransactionId.usa_sell.value
128 |
129 |
130 | class UsaPaperBuyOrderHeaders(BaseHeaders):
131 | tr_id: str = TransactionId.usa_paper_buy.value
132 |
133 |
134 | class UsaPaperSellOrderHeaders(BaseHeaders):
135 | tr_id: str = TransactionId.usa_paper_sell.value
136 |
137 |
138 | class AccountInfo(BaseModel):
139 | CANO: str # 계좌번호 앞 8자리
140 | ACNT_PRDT_CD: str # 계좌번호 뒤 2자리
141 |
142 |
143 | # class BaseBody(BaseModel):
144 |
145 |
146 | class OrderBody(AccountInfo):
147 | PDNO: str # 종목코드 6자리
148 | ORD_QTY: str # 주문수량
149 |
150 |
151 | class KoreaOrderBody(OrderBody):
152 | ORD_DVSN: Literal[f"{KoreaOrderType.market}", f"{KoreaOrderType.limit}"]
153 | ORD_UNPR: str # 주문가격
154 |
155 |
156 | class KoreaMarketOrderBody(KoreaOrderBody):
157 | ORD_DVSN: str = KoreaOrderType.market.value
158 | ORD_UNPR: str = "0"
159 |
160 |
161 | class UsaOrderBody(OrderBody):
162 | ORD_DVSN: str = UsaOrderType.limit.value # 주문구분
163 | OVRS_ORD_UNPR: str # 주문가격
164 | OVRS_EXCG_CD: Literal[ExchangeCode.NYSE, ExchangeCode.NASDAQ, ExchangeCode.AMEX] # 거래소코드 NASD : 나스닥, NYSE: 뉴욕, AMEX: 아멕스
165 | ORD_SVR_DVSN_CD: str = "0"
166 |
167 |
168 | # class OrderType(str, Enum):
169 | # limit = "limit"
170 | # market = "market"
171 |
172 |
173 | # class OrderBase(BaseModel):
174 | # ticker: str
175 | # type: Literal[OrderType.limit, OrderType.market]
176 | # side: Literal[OrderSide.buy, OrderSide.sell]
177 | # amount: int
178 | # price: float
179 | # exchange_code: Literal[ExchangeCode.NYSE, ExchangeCode.NASDAQ, ExchangeCode.AMEX]
180 | # mintick: float
181 |
--------------------------------------------------------------------------------
/exchange/bitget.py:
--------------------------------------------------------------------------------
1 | from pprint import pprint
2 | from exchange.pexchange import ccxt
3 | from exchange.database import db
4 | from exchange.model import MarketOrder
5 | import exchange.error as error
6 | from devtools import debug
7 |
8 |
9 | class Bitget:
10 | def __init__(self, key, secret, passphrase=None):
11 | self.client = ccxt.bitget(
12 | {
13 | "apiKey": key,
14 | "secret": secret,
15 | "password": passphrase,
16 | }
17 | )
18 | self.client.load_markets()
19 | self.order_info: MarketOrder = None
20 | self.position_mode = "one-way"
21 |
22 | def init_info(self, order_info: MarketOrder):
23 | self.order_info = order_info
24 |
25 | unified_symbol = order_info.unified_symbol
26 | market = self.client.market(unified_symbol)
27 |
28 | if order_info.amount is not None:
29 | order_info.amount = float(
30 | self.client.amount_to_precision(
31 | order_info.unified_symbol, order_info.amount
32 | )
33 | )
34 |
35 | if order_info.is_futures:
36 | if order_info.is_coinm:
37 | self.client.options["defaultType"] = "delivery"
38 | is_contract = market.get("contract")
39 | if is_contract:
40 | order_info.is_contract = True
41 | order_info.contract_size = market.get("contractSize")
42 | else:
43 | self.client.options["defaultType"] = "swap"
44 | else:
45 | self.client.options["defaultType"] = "spot"
46 |
47 | def get_ticker(self, symbol: str):
48 | return self.client.fetch_ticker(symbol)
49 |
50 | def get_price(self, symbol: str):
51 | return self.get_ticker(symbol)["last"]
52 |
53 | def get_futures_position(self, symbol):
54 | positions = self.client.fetch_positions([symbol])
55 | long_contracts = None
56 | short_contracts = None
57 |
58 | if positions:
59 | if isinstance(positions, list):
60 | for position in positions:
61 | if position["side"] == "long":
62 | long_contracts = float(position["info"]["available"])
63 | elif position["side"] == "short":
64 | short_contracts = float(position["info"]["available"])
65 |
66 | if self.order_info.is_close and self.order_info.is_buy:
67 | if not short_contracts:
68 | raise error.ShortPositionNoneError()
69 | else:
70 | return short_contracts
71 | elif self.order_info.is_close and self.order_info.is_sell:
72 | if not long_contracts:
73 | raise error.LongPositionNoneError()
74 | else:
75 | return long_contracts
76 | else:
77 | contracts = float(positions["info"]["available"])
78 | if not contracts:
79 | raise error.PositionNoneError()
80 | else:
81 | return contracts
82 | else:
83 | raise error.PositionNoneError()
84 |
85 | def get_balance(self, base: str):
86 | free_balance_by_base = None
87 | if self.order_info.is_entry or (
88 | self.order_info.is_spot
89 | and (self.order_info.is_buy or self.order_info.is_sell)
90 | ):
91 | free_balance = (
92 | self.client.fetch_free_balance({"coin": base})
93 | if not self.order_info.is_total
94 | else self.client.fetch_total_balance({"coin": base})
95 | )
96 | free_balance_by_base = free_balance.get(base)
97 | if free_balance_by_base is None or free_balance_by_base == 0:
98 | raise error.FreeAmountNoneError()
99 | return free_balance_by_base
100 |
101 | def get_amount(self, order_info: MarketOrder) -> float:
102 | if order_info.amount is not None and order_info.percent is not None:
103 | raise error.AmountPercentBothError()
104 | elif order_info.amount is not None:
105 | result = order_info.amount
106 |
107 | elif order_info.percent is not None:
108 | if order_info.is_entry or (order_info.is_spot and order_info.is_buy):
109 | free_quote = self.get_balance(order_info.quote)
110 | cash = free_quote * (order_info.percent - 1) / 100
111 | current_price = self.get_price(order_info.unified_symbol)
112 | result = cash / current_price
113 | elif self.order_info.is_close:
114 | free_amount = self.get_futures_position(order_info.unified_symbol)
115 | result = free_amount * order_info.percent / 100
116 | elif order_info.is_spot and order_info.is_sell:
117 | free_amount = self.get_balance(order_info.base)
118 | result = free_amount * order_info.percent / 100
119 | result = float(
120 | self.client.amount_to_precision(order_info.unified_symbol, result)
121 | )
122 | order_info.amount_by_percent = result
123 | else:
124 | raise error.AmountPercentNoneError()
125 | return result
126 |
127 | def set_leverage(self, leverage, symbol):
128 |
129 | hold_side = "long" if self.order_info.is_buy else "short"
130 | return self.client.set_leverage(leverage, symbol, params= { "holdSide": hold_side })
131 |
132 | def market_order(self, order_info: MarketOrder):
133 | from exchange.pexchange import retry
134 |
135 | symbol = order_info.unified_symbol
136 | params = {}
137 | try:
138 | return retry(
139 | self.client.create_order,
140 | symbol,
141 | order_info.type.lower(),
142 | order_info.side,
143 | order_info.amount,
144 | order_info.price,
145 | params,
146 | order_info=order_info,
147 | max_attempts=5,
148 | delay=0.1,
149 | instance=self,
150 | )
151 | except Exception as e:
152 | raise error.OrderError(e, order_info)
153 |
154 | def market_buy(self, order_info: MarketOrder):
155 | # 비용주문
156 | buy_amount = self.get_amount(order_info)
157 | order_info.amount = buy_amount
158 | order_info.price = self.get_price(order_info.unified_symbol)
159 |
160 | return self.market_order(order_info)
161 |
162 | def market_sell(self, order_info: MarketOrder):
163 | sell_amount = self.get_amount(order_info)
164 | order_info.amount = sell_amount
165 | return self.market_order(order_info)
166 |
167 | def market_entry(self, order_info: MarketOrder):
168 | from exchange.pexchange import retry
169 |
170 | symbol = order_info.unified_symbol
171 | entry_amount = self.get_amount(order_info)
172 | if entry_amount == 0:
173 | raise error.MinAmountError()
174 |
175 | if self.position_mode == "one-way":
176 | params = { "oneWayMode": True }
177 | elif self.position_mode == "hedge":
178 | if order_info.is_futures:
179 | if order_info.is_buy:
180 | trade_side = "Open"
181 | else:
182 | trade_side = "open"
183 | params = { "tradeSide": trade_side }
184 |
185 | params |= { "marginMode": order_info.margin_mode or "isolated" }
186 | if order_info.margin_mode is not None:
187 | self.client.set_margin_mode(order_info.margin_mode, symbol)
188 |
189 | if order_info.leverage is not None:
190 | retry(self.set_leverage, order_info.leverage, symbol, order_info = order_info, instance = self)
191 | try:
192 | return retry(
193 | self.client.create_order,
194 | symbol,
195 | order_info.type.lower(),
196 | order_info.side,
197 | abs(entry_amount),
198 | None,
199 | params,
200 | order_info=order_info,
201 | max_attempts=5,
202 | delay=0.1,
203 | instance=self,
204 | )
205 |
206 | except Exception as e:
207 | raise error.OrderError(e, order_info)
208 |
209 | def market_close(self, order_info: MarketOrder):
210 | from exchange.pexchange import retry
211 |
212 | symbol = self.order_info.unified_symbol
213 | close_amount = self.get_amount(order_info)
214 | final_side = order_info.side
215 | if self.position_mode == "one-way":
216 | params = {"reduceOnly": True, "oneWayMode": True}
217 | elif self.position_mode == "hedge":
218 | if order_info.side == "sell":
219 | final_side = "buy"
220 | elif order_info.side == "buy":
221 | final_side = "sell"
222 | params = {"reduceOnly": True, "tradeSide":"close"}
223 | try:
224 | result = retry(
225 | self.client.create_order,
226 | symbol,
227 | order_info.type.lower(),
228 | final_side,
229 | abs(close_amount),
230 | None,
231 | params,
232 | order_info=order_info,
233 | max_attempts=5,
234 | delay=0.1,
235 | instance=self,
236 | )
237 |
238 | return result
239 | except Exception as e:
240 | raise error.OrderError(e, self.order_info)
241 |
--------------------------------------------------------------------------------
/exchange/model/schemas.py:
--------------------------------------------------------------------------------
1 | from pydantic import BaseModel, BaseSettings, validator, root_validator
2 | from typing import Literal
3 | import os
4 | from pathlib import Path
5 | from enum import Enum
6 | from devtools import debug
7 |
8 | CRYPTO_LITERAL = Literal["BINANCE", "UPBIT", "BYBIT", "BITGET", "OKX"]
9 |
10 |
11 | STOCK_LITERAL = Literal[
12 | "KRX",
13 | "NASDAQ",
14 | "NYSE",
15 | "AMEX",
16 | ]
17 |
18 |
19 | EXCHANGE_LITERAL = Literal[
20 | "BINANCE",
21 | "UPBIT",
22 | "BYBIT",
23 | "BITGET",
24 | "OKX",
25 | "KRX",
26 | "NASDAQ",
27 | "NYSE",
28 | "AMEX",
29 | ]
30 |
31 | QUOTE_LITERAL = Literal[
32 | "USDT", "USDT.P", "USDTPERP", "BUSD", "BUSD.P", "BUSDPERP", "KRW", "USD", "USD.P"
33 | ]
34 |
35 | SIDE_LITERAL = Literal[
36 | "buy", "sell", "entry/buy", "entry/sell", "close/buy", "close/sell"
37 | ]
38 |
39 |
40 | def find_env_file():
41 | current_path = os.path.abspath(__file__)
42 | while True:
43 | parent_path = os.path.dirname(current_path)
44 | env_path = os.path.join(parent_path, ".env")
45 | dev_env_path = os.path.join(parent_path, ".env.dev")
46 | if os.path.isfile(dev_env_path):
47 | return dev_env_path
48 | elif os.path.isfile(env_path):
49 | return env_path
50 | if parent_path == current_path:
51 | break
52 | current_path = parent_path
53 | return None
54 |
55 |
56 | env_path = find_env_file()
57 |
58 |
59 | CRYPTO_EXCHANGES = ("BINANCE", "UPBIT", "BYBIT", "BITGET", "OKX")
60 |
61 | STOCK_EXCHANGES = (
62 | "KRX",
63 | "NASDAQ",
64 | "NYSE",
65 | "AMEX",
66 | )
67 |
68 | COST_BASED_ORDER_EXCHANGES = ("UPBIT", "BYBIT", "BITGET")
69 |
70 | NO_ORDER_AMOUNT_OUTPUT_EXCHANGES = (
71 | "BITGET",
72 | "KRX",
73 | "NASDAQ",
74 | "NYSE",
75 | "AMEX",
76 | )
77 |
78 | # "BITGET", "KRX", "NASDAQ", "AMEX", "NYSE")
79 |
80 |
81 | crypto_futures_code = ("PERP", ".P")
82 |
83 | # Literal[
84 | # "KRW", "USDT", "USDTPERP", "BUSD", "BUSDPERP", "USDT.P", "USD", "BUSD.P"
85 | # ]
86 |
87 |
88 | class Settings(BaseSettings):
89 | PASSWORD: str
90 | WHITELIST: list[str] | None = None
91 | PORT: int | None = None
92 | DISCORD_WEBHOOK_URL: str | None = None
93 | UPBIT_KEY: str | None = None
94 | UPBIT_SECRET: str | None = None
95 | BINANCE_KEY: str | None = None
96 | BINANCE_SECRET: str | None = None
97 | BYBIT_KEY: str | None = None
98 | BYBIT_SECRET: str | None = None
99 | BITGET_KEY: str | None = None
100 | BITGET_SECRET: str | None = None
101 | BITGET_PASSPHRASE: str | None = None
102 | OKX_KEY: str | None = None
103 | OKX_SECRET: str | None = None
104 | OKX_PASSPHRASE: str | None = None
105 | KIS1_ACCOUNT_NUMBER: str | None = None
106 | KIS1_ACCOUNT_CODE: str | None = None
107 | KIS1_KEY: str | None = None
108 | KIS1_SECRET: str | None = None
109 | KIS2_ACCOUNT_NUMBER: str | None = None
110 | KIS2_ACCOUNT_CODE: str | None = None
111 | KIS2_KEY: str | None = None
112 | KIS2_SECRET: str | None = None
113 | KIS3_ACCOUNT_NUMBER: str | None = None
114 | KIS3_ACCOUNT_CODE: str | None = None
115 | KIS3_KEY: str | None = None
116 | KIS3_SECRET: str | None = None
117 | KIS4_ACCOUNT_NUMBER: str | None = None
118 | KIS4_ACCOUNT_CODE: str | None = None
119 | KIS4_KEY: str | None = None
120 | KIS4_SECRET: str | None = None
121 | DB_ID: str = "poa@admin.com"
122 | DB_PASSWORD: str = "poabot!@#$"
123 |
124 | class Config:
125 | env_file = env_path # ".env"
126 | env_file_encoding = "utf-8"
127 |
128 |
129 | def get_extra_order_info(order_info):
130 | extra_order_info = {
131 | "is_futures": None,
132 | "is_crypto": None,
133 | "is_stock": None,
134 | "is_spot": None,
135 | "is_entry": None,
136 | "is_close": None,
137 | "is_buy": None,
138 | "is_sell": None,
139 | }
140 | if order_info["exchange"] in CRYPTO_EXCHANGES:
141 | extra_order_info["is_crypto"] = True
142 | if any([order_info["quote"].endswith(code) for code in crypto_futures_code]):
143 | extra_order_info["is_futures"] = True
144 | else:
145 | extra_order_info["is_spot"] = True
146 |
147 | elif order_info["exchange"] in STOCK_EXCHANGES:
148 | extra_order_info["is_stock"] = True
149 |
150 | if order_info["side"] in ("entry/buy", "entry/sell"):
151 | extra_order_info["is_entry"] = True
152 | _side = order_info["side"].split("/")[-1]
153 | if _side == "buy":
154 | extra_order_info["is_buy"] = True
155 | elif _side == "sell":
156 | extra_order_info["is_sell"] = True
157 | elif order_info["side"] in ("close/buy", "close/sell"):
158 | extra_order_info["is_close"] = True
159 | _side = order_info["side"].split("/")[-1]
160 | if _side == "buy":
161 | extra_order_info["is_buy"] = True
162 | elif _side == "sell":
163 | extra_order_info["is_sell"] = True
164 | elif order_info["side"] == "buy":
165 | extra_order_info["is_buy"] = True
166 | elif order_info["side"] == "sell":
167 | extra_order_info["is_sell"] = True
168 |
169 | return extra_order_info
170 |
171 |
172 | def parse_side(side: str):
173 | if side.startswith("entry/") or side.startswith("close/"):
174 | return side.split("/")[-1]
175 | else:
176 | return side
177 |
178 |
179 | def parse_quote(quote: str):
180 | if quote.endswith(".P"):
181 | return quote.replace(".P", "")
182 | else:
183 | return quote
184 |
185 |
186 | class OrderRequest(BaseModel):
187 | exchange: EXCHANGE_LITERAL
188 | base: str
189 | quote: QUOTE_LITERAL
190 | # QUOTE
191 | type: Literal["market", "limit"] = "market"
192 | side: SIDE_LITERAL
193 | amount: float | None = None
194 | price: float | None = None
195 | cost: float | None = None
196 | percent: float | None = None
197 | amount_by_percent: float | None = None
198 | leverage: int | None = None
199 | stop_price: float | None = None
200 | profit_price: float | None = None
201 | order_name: str = "주문"
202 | kis_number: int | None = 1
203 | hedge: str | None = None
204 | unified_symbol: str | None = None
205 | is_crypto: bool | None = None
206 | is_stock: bool | None = None
207 | is_spot: bool | None = None
208 | is_futures: bool | None = None
209 | is_coinm: bool | None = None
210 | is_entry: bool | None = None
211 | is_close: bool | None = None
212 | is_buy: bool | None = None
213 | is_sell: bool | None = None
214 | is_total: bool | None = None
215 | is_contract: bool | None = None
216 | contract_size: float | None = None
217 | margin_mode: str | None = None
218 |
219 | class Config:
220 | use_enum_values = True
221 |
222 | @root_validator(pre=True)
223 | def root_validate(cls, values):
224 | # "NaN" to None
225 | for key, value in values.items():
226 | if isinstance(value, str):
227 | values[key] = value.replace(',', '')
228 | if values[key] in ("NaN", ""):
229 | values[key] = None
230 |
231 |
232 | values |= get_extra_order_info(values)
233 |
234 | values["side"] = parse_side(values["side"])
235 | values["quote"] = parse_quote(values["quote"])
236 | base = values["base"]
237 | quote = values["quote"]
238 | unified_symbol = f"{base}/{quote}"
239 | exchange = values["exchange"]
240 | if values["is_futures"]:
241 | if quote == "USD":
242 | unified_symbol = f"{base}/{quote}:{base}"
243 | values["is_coinm"] = True
244 | else:
245 | unified_symbol = f"{base}/{quote}:{quote}"
246 |
247 | if not values["is_stock"]:
248 | values["unified_symbol"] = unified_symbol
249 |
250 | if values["exchange"] in STOCK_EXCHANGES:
251 | values["is_stock"] = True
252 | return values
253 |
254 |
255 | class OrderBase(OrderRequest):
256 | password: str
257 |
258 | @validator("password")
259 | def password_validate(cls, v):
260 | setting = Settings()
261 | if v != setting.PASSWORD:
262 | raise ValueError("비밀번호가 틀렸습니다")
263 | return v
264 |
265 |
266 | class MarketOrder(OrderBase):
267 | price: float | None = None
268 | type: Literal["market"] = "market"
269 |
270 |
271 | class PriceRequest(BaseModel):
272 | exchange: EXCHANGE_LITERAL
273 | base: str
274 | quote: QUOTE_LITERAL
275 | is_crypto: bool | None = None
276 | is_stock: bool | None = None
277 | is_futures: bool | None = None
278 |
279 | @root_validator(pre=True)
280 | def root_validate(cls, values):
281 | # "NaN" to None
282 | for key, value in values.items():
283 | if isinstance(value, str):
284 | values[key] = value.replace(',', '')
285 | if values[key] in ("NaN", ""):
286 | values[key] = None
287 |
288 | values |= get_extra_order_info(values)
289 |
290 | return values
291 |
292 |
293 | # class PositionRequest(BaseModel):
294 | # exchange: EXCHANGE_LITERAL
295 | # base: str
296 | # quote: QUOTE_LITERAL
297 |
298 |
299 | class Position(BaseModel):
300 | exchange: EXCHANGE_LITERAL
301 | base: str
302 | quote: QUOTE_LITERAL
303 | side: Literal["long", "short"]
304 | amount: float
305 | entry_price: float
306 | roe: float
307 |
308 |
309 | class HedgeData(BaseModel):
310 | password: str
311 | exchange: Literal["BINANCE"]
312 | base: str
313 | quote: QUOTE_LITERAL = "USDT.P"
314 | amount: float | None = None
315 | leverage: int | None = None
316 | hedge: str
317 |
318 | @validator("password")
319 | def password_validate(cls, v):
320 | setting = Settings()
321 | if v != setting.PASSWORD:
322 | raise ValueError("비밀번호가 틀렸습니다")
323 | return v
324 |
325 | @root_validator(pre=True)
326 | def root_validate(cls, values):
327 | for key, value in values.items():
328 | if key in ("exchange", "base", "quote", "hedge"):
329 | values[key] = value.upper()
330 | return values
331 |
--------------------------------------------------------------------------------
/exchange/utility/LogMaker.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from exchange.model import MarketOrder, COST_BASED_ORDER_EXCHANGES, STOCK_EXCHANGES
3 | from exchange.utility import settings
4 | from datetime import datetime, timedelta
5 | from dhooks import Webhook, Embed
6 | from loguru import logger
7 | from devtools import debug, pformat
8 | import traceback
9 | import os
10 |
11 | logger.remove(0)
12 | logger.add(
13 | "./log/poa.log",
14 | rotation="1 days",
15 | retention="7 days",
16 | format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
17 | )
18 | logger.add(
19 | sys.stderr,
20 | colorize=True,
21 | format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
22 | )
23 |
24 | try:
25 | url = settings.DISCORD_WEBHOOK_URL.replace("discordapp", "discord")
26 | hook = Webhook(url)
27 | except Exception as e:
28 | print("웹훅 URL이 유효하지 않습니다: ", settings.DISCORD_WEBHOOK_URL)
29 |
30 |
31 | def get_error(e):
32 | tb = traceback.extract_tb(e.__traceback__)
33 | target_folder = os.path.abspath(os.path.dirname(tb[0].filename))
34 | error_msg = []
35 |
36 | for tb_info in tb:
37 | # if target_folder in tb_info.filename:
38 | error_msg.append(f"File {tb_info.filename}, line {tb_info.lineno}, in {tb_info.name}")
39 | if "raise error." in tb_info.line:
40 | continue
41 | error_msg.append(f" {tb_info.line}")
42 |
43 | error_msg.append(str(e))
44 |
45 | return "\n".join(error_msg)
46 |
47 |
48 | def parse_time(utc_timestamp):
49 | timestamp = utc_timestamp + timedelta(hours=9).seconds
50 | date = datetime.fromtimestamp(timestamp)
51 | return date.strftime("%y-%m-%d %H:%M:%S")
52 |
53 |
54 | def logger_test():
55 | date = parse_time(datetime.utcnow().timestamp())
56 | logger.info(date)
57 |
58 |
59 | def log_message(message="None", embed: Embed = None):
60 | if hook:
61 | if embed:
62 | hook.send(embed=embed)
63 | else:
64 | hook.send(message)
65 | # hook.send(str(message), embed)
66 | else:
67 | logger.info(message)
68 | print(message)
69 |
70 |
71 | def log_order_message(exchange_name, order_result: dict, order_info: MarketOrder):
72 | date = parse_time(datetime.utcnow().timestamp())
73 | if not order_info.is_futures and order_info.is_buy and exchange_name in COST_BASED_ORDER_EXCHANGES:
74 | f_name = "비용"
75 | if order_info.amount is not None:
76 | if exchange_name == "UPBIT":
77 | amount = str(order_result.get("cost"))
78 | elif exchange_name == "BITGET":
79 | amount = str(order_info.amount * order_info.price)
80 | elif exchange_name == "BYBIT":
81 | amount = str(order_result.get("info").get("orderQty"))
82 | elif order_info.percent is not None:
83 | f_name = "비율"
84 | amount = f"{order_info.percent}%"
85 |
86 | else:
87 | f_name = "수량"
88 | amount = None
89 | if exchange_name in ("KRX", "NASDAQ", "AMEX", "NYSE"):
90 | if order_info.amount is not None:
91 | amount = str(order_info.amount)
92 | elif order_info.percent is not None:
93 | f_name = "비율"
94 | amount = f"{order_info.percent}%"
95 | elif order_result.get("amount") is None:
96 | if order_info.amount is not None:
97 | if exchange_name == "OKX":
98 | if order_info.is_futures:
99 | f_name = "계약(수량)"
100 | amount = f"{order_info.amount // order_info.contract_size}({order_info.contract_size * (order_info.amount // order_info.contract_size)})"
101 | else:
102 | amount = f"{order_info.amount}"
103 | else:
104 | amount = str(order_info.amount)
105 | elif order_info.percent is not None:
106 | if order_info.amount_by_percent is not None:
107 | f_name = "비율(수량)" if order_info.is_contract is None else "비율(계약)"
108 | amount = f"{order_info.percent}%({order_info.amount_by_percent})"
109 | else:
110 | f_name = "비율"
111 | amount = f"{order_info.percent}%"
112 | elif order_result.get("amount") is not None:
113 | if order_info.contract_size is not None:
114 | f_name = "계약"
115 | if order_result.get("cost") is not None:
116 | f_name = "계약(비용)"
117 | amount = f"{order_result.get('amount')}({order_result.get('cost'):.2f})"
118 | else:
119 | amount = f"{order_result.get('amount')}"
120 | else:
121 | if order_info.amount is not None:
122 | f_name = "수량"
123 | amount = f"{order_result.get('amount')}"
124 | elif order_info.percent is not None:
125 | f_name = "비율(수량)" if order_info.is_contract is None else "비율(계약)"
126 | amount = f"{order_info.percent}%({order_result.get('amount')})"
127 |
128 | symbol = f"{order_info.base}/{order_info.quote+'.P' if order_info.is_crypto and order_info.is_futures else order_info.quote}"
129 |
130 | side = ""
131 | if order_info.is_futures:
132 | if order_info.is_entry:
133 | if order_info.is_buy:
134 | side = "롱 진입"
135 | elif order_info.is_sell:
136 | side = "숏 진입"
137 | elif order_info.is_close:
138 | if order_info.is_buy:
139 | side = "숏 종료"
140 | elif order_info.is_sell:
141 | side = "롱 종료"
142 | else:
143 | if order_info.is_buy:
144 | side = "매수"
145 | elif order_info.is_sell:
146 | side = "매도"
147 |
148 | if exchange_name in STOCK_EXCHANGES: # ("KRX", "NASDAQ", "NYSE", "AMEX"):
149 | content = f"일시\n{date}\n\n거래소\n{exchange_name}\n\n티커\n{order_info.base}\n\n거래유형\n{side}\n\n{amount}"
150 | embed = Embed(
151 | title=order_info.order_name,
152 | description=f"체결 {exchange_name} {order_info.base} {side} {amount}",
153 | color=0x0000FF,
154 | )
155 | embed.add_field(name="일시", value=str(date), inline=False)
156 | embed.add_field(name="거래소", value=exchange_name, inline=False)
157 | embed.add_field(name="티커", value=order_info.base, inline=False)
158 | embed.add_field(name="거래유형", value=side, inline=False)
159 | embed.add_field(name="수량", value=amount, inline=False)
160 | embed.add_field(name="계좌", value=f"{order_info.kis_number}번째 계좌", inline=False)
161 | log_message(content, embed)
162 | else:
163 | content = f"일시\n{date}\n\n거래소\n{exchange_name}\n\n심볼\n{symbol}\n\n거래유형\n{order_result.get('side')}\n\n{amount}"
164 | embed = Embed(
165 | title=order_info.order_name,
166 | description=f"체결: {exchange_name} {symbol} {side} {amount}",
167 | color=0x0000FF,
168 | )
169 | embed.add_field(name="일시", value=str(date), inline=False)
170 | embed.add_field(name="거래소", value=exchange_name, inline=False)
171 | embed.add_field(name="심볼", value=symbol, inline=False)
172 | embed.add_field(name="거래유형", value=side, inline=False)
173 | if amount:
174 | embed.add_field(name=f_name, value=amount, inline=False)
175 | if order_info.leverage is not None:
176 | embed.add_field(name="레버리지", value=f"{order_info.leverage}배", inline=False)
177 | if order_result.get("price"):
178 | embed.add_field(name="체결가", value=str(order_result.get("price")), inline=False)
179 | log_message(content, embed)
180 |
181 |
182 | def log_hedge_message(exchange, base, quote, exchange_amount, upbit_amount, hedge):
183 | date = parse_time(datetime.utcnow().timestamp())
184 | hedge_type = "헷지" if hedge == "ON" else "헷지 종료"
185 | content = f"{hedge_type}: {base} ==> {exchange}:{exchange_amount} UPBIT:{upbit_amount}"
186 | embed = Embed(title="헷지", description=content, color=0x0000FF)
187 | embed.add_field(name="일시", value=str(date), inline=False)
188 | embed.add_field(name="거래소", value=f"{exchange}-UPBIT", inline=False)
189 | embed.add_field(name="심볼", value=f"{base}/{quote}-{base}/KRW", inline=False)
190 | embed.add_field(name="거래유형", value=hedge_type, inline=False)
191 | embed.add_field(
192 | name="수량",
193 | value=f"{exchange}:{exchange_amount} UPBIT:{upbit_amount}",
194 | inline=False,
195 | )
196 | log_message(content, embed)
197 |
198 |
199 | def log_error_message(error, name):
200 | embed = Embed(title=f"{name} 에러", description=f"[{name} 에러가 발생했습니다]\n{error}", color=0xFF0000)
201 | logger.error(f"{name} [에러가 발생했습니다]\n{error}")
202 | log_message(embed=embed)
203 |
204 |
205 | def log_order_error_message(error: str | Exception, order_info: MarketOrder):
206 | if isinstance(error, Exception):
207 | error = get_error(error)
208 |
209 | if order_info is not None:
210 | # discord
211 | embed = Embed(
212 | title=order_info.order_name,
213 | description=f"[주문 오류가 발생했습니다]\n{error}",
214 | color=0xFF0000,
215 | )
216 | log_message(embed=embed)
217 |
218 | # logger
219 | logger.error(f"[주문 오류가 발생했습니다]\n{error}")
220 | else:
221 | # discord
222 | embed = Embed(
223 | title="오류",
224 | description=f"[오류가 발생했습니다]\n{error}",
225 | color=0xFF0000,
226 | )
227 | log_message(embed=embed)
228 |
229 | # logger
230 | logger.error(f"[오류가 발생했습니다]\n{error}")
231 |
232 |
233 | def log_validation_error_message(msg):
234 | logger.error(f"검증 오류가 발생했습니다\n{msg}")
235 | log_message(msg)
236 |
237 |
238 | def print_alert_message(order_info: MarketOrder, result="성공"):
239 | msg = pformat(order_info.dict(exclude_none=True))
240 |
241 | if result == "성공":
242 | logger.info(f"주문 {result} 웹훅메세지\n{msg}")
243 | else:
244 | logger.error(f"주문 {result} 웹훅메세지\n{msg}")
245 |
246 |
247 | def log_alert_message(order_info: MarketOrder, result="성공"):
248 | # discrod
249 | embed = Embed(
250 | title=order_info.order_name,
251 | description="[웹훅 alert_message]",
252 | color=0xFF0000,
253 | )
254 | order_info_dict = order_info.dict(exclude_none=True)
255 | for key, value in order_info_dict.items():
256 | embed.add_field(name=key, value=str(value), inline=False)
257 | log_message(embed=embed)
258 |
259 | # logger
260 | print_alert_message(order_info, result)
261 |
--------------------------------------------------------------------------------
/exchange/bybit.py:
--------------------------------------------------------------------------------
1 | from pprint import pprint
2 | from exchange.pexchange import ccxt
3 | from exchange.model import MarketOrder
4 | import time
5 | import exchange.error as error
6 | from devtools import debug
7 |
8 |
9 | class Bybit:
10 | def __init__(self, key, secret):
11 | self.client = ccxt.bybit(
12 | {
13 | "apiKey": key,
14 | "secret": secret,
15 | "options": {"adjustForTimeDifference": True},
16 | }
17 | )
18 | self.client.load_markets()
19 | self.order_info: MarketOrder = None
20 | self.position_mode = "one-way"
21 |
22 | def load_time_difference(self):
23 | self.client.load_time_difference()
24 |
25 | def init_info(self, order_info: MarketOrder):
26 | self.order_info = order_info
27 |
28 | unified_symbol = order_info.unified_symbol
29 | market = self.client.market(unified_symbol)
30 |
31 | if order_info.amount is not None:
32 | order_info.amount = float(
33 | self.client.amount_to_precision(
34 | order_info.unified_symbol, order_info.amount
35 | )
36 | )
37 |
38 | if order_info.is_futures:
39 | if order_info.is_coinm:
40 | self.client.options["defaultType"] = "delivery"
41 | is_contract = market.get("contract")
42 | if is_contract:
43 | order_info.is_contract = True
44 | order_info.contract_size = market.get("contractSize")
45 | else:
46 | self.client.options["defaultType"] = "swap"
47 | else:
48 | self.client.options["defaultType"] = "spot"
49 |
50 | def get_ticker(self, symbol: str):
51 | return self.client.fetch_ticker(symbol)
52 |
53 | def get_price(self, symbol: str):
54 | return self.get_ticker(symbol)["last"]
55 |
56 | def get_futures_position(self, symbol):
57 | positions = self.client.fetch_positions(symbols=[symbol])
58 | long_contracts = None
59 | short_contracts = None
60 | if positions:
61 | for position in positions:
62 | if position["side"] == "long":
63 | long_contracts = position["contracts"]
64 | elif position["side"] == "short":
65 | short_contracts = position["contracts"]
66 |
67 | if self.order_info.is_close and self.order_info.is_buy:
68 | if not short_contracts:
69 | raise error.ShortPositionNoneError()
70 | else:
71 | return short_contracts
72 | elif self.order_info.is_close and self.order_info.is_sell:
73 | if not long_contracts:
74 | raise error.LongPositionNoneError()
75 | else:
76 | return long_contracts
77 | else:
78 | raise error.PositionNoneError()
79 |
80 | def get_balance(self, base: str):
81 | free_balance_by_base = None
82 | if self.order_info.is_entry or (
83 | self.order_info.is_spot
84 | and (self.order_info.is_buy or self.order_info.is_sell)
85 | ):
86 | balance_by_base = self.client.fetch_balance().get(base)
87 | free_balance_by_base = balance_by_base.get("free") or balance_by_base.get("total") if not self.order_info.is_total else balance_by_base.get("total")
88 |
89 | if free_balance_by_base is None or free_balance_by_base == 0:
90 | raise error.FreeAmountNoneError()
91 | return free_balance_by_base
92 |
93 | def get_amount(self, order_info: MarketOrder) -> float:
94 | if order_info.amount is not None and order_info.percent is not None:
95 | raise error.AmountPercentBothError()
96 | elif order_info.amount is not None:
97 | if order_info.is_contract:
98 | current_price = self.get_price(order_info.unified_symbol)
99 | result = (order_info.amount * current_price) // order_info.contract_size
100 | else:
101 | result = order_info.amount
102 | elif order_info.percent is not None:
103 | if order_info.is_entry or (order_info.is_spot and order_info.is_buy):
104 | free_quote = self.get_balance(order_info.quote)
105 | cash = free_quote * (order_info.percent - 0.5) / 100
106 | current_price = self.get_price(order_info.unified_symbol)
107 | result = cash / current_price
108 | elif self.order_info.is_close:
109 | if order_info.is_contract:
110 | free_amount = self.get_futures_position(order_info.unified_symbol)
111 | result = free_amount * order_info.percent / 100
112 | else:
113 | free_amount = self.get_futures_position(order_info.unified_symbol)
114 | result = free_amount * order_info.percent / 100
115 | elif order_info.is_spot and order_info.is_sell:
116 | free_amount = self.get_balance(order_info.base)
117 | result = free_amount * order_info.percent / 100
118 | result = float(
119 | self.client.amount_to_precision(order_info.unified_symbol, result)
120 | )
121 | order_info.amount_by_percent = result
122 | else:
123 | raise error.AmountPercentNoneError()
124 | return result
125 |
126 | def set_leverage(self, leverage: float, symbol: str):
127 | try:
128 | self.client.set_leverage(leverage, symbol)
129 | except Exception as e:
130 | error = str(e)
131 | if "leverage not modified" in error:
132 | pass
133 | else:
134 | raise Exception(e)
135 |
136 | def get_order_amount(self, order_id: str, order_info: MarketOrder):
137 | order_amount = None
138 | for i in range(8):
139 | try:
140 | if order_info.is_futures:
141 | order_result = self.client.fetch_order(
142 | order_id, order_info.unified_symbol
143 | )
144 | else:
145 | order_result = self.client.fetch_order(order_id)
146 | order_amount = order_result["amount"]
147 | break
148 | except Exception as e:
149 | print("...", e)
150 | time.sleep(0.5)
151 | return order_amount
152 |
153 | def market_order(self, order_info: MarketOrder):
154 | from exchange.pexchange import retry
155 |
156 | symbol = order_info.unified_symbol
157 | params = {}
158 | try:
159 | return retry(
160 | self.client.create_order,
161 | symbol,
162 | order_info.type.lower(),
163 | order_info.side,
164 | order_info.amount,
165 | order_info.price,
166 | params,
167 | order_info=order_info,
168 | max_attempts=5,
169 | delay=0.1,
170 | instance=self,
171 | )
172 | except Exception as e:
173 | raise error.OrderError(e, order_info)
174 |
175 | def market_buy(
176 | self,
177 | order_info: MarketOrder,
178 | ):
179 | # 비용주문
180 | buy_amount = self.get_amount(order_info)
181 | order_info.amount = buy_amount
182 | order_info.price = self.get_price(order_info.unified_symbol)
183 |
184 | return self.market_order(order_info)
185 |
186 | def market_sell(self, order_info: MarketOrder):
187 | sell_amount = self.get_amount(order_info)
188 | order_info.amount = sell_amount
189 | order_info.price = None
190 | return self.market_order(order_info)
191 |
192 | def market_entry(self, order_info: MarketOrder):
193 | from exchange.pexchange import retry
194 |
195 | symbol = order_info.unified_symbol
196 |
197 | entry_amount = self.get_amount(order_info)
198 | if entry_amount == 0:
199 | raise error.MinAmountError()
200 |
201 | if self.position_mode == "one-way":
202 | params = {"position_idx": 0}
203 | elif self.position_mode == "hedge":
204 | if order_info.side == "buy":
205 | if order_info.is_entry:
206 | position_idx = 1
207 | params = {"position_idx": position_idx, "hedged": True}
208 | elif order_info.is_close:
209 | position_idx = 2
210 | params = {"reduceOnly": True, "position_idx": position_idx, "hedged": True}
211 | elif order_info.side == "sell":
212 | if order_info.is_entry:
213 | position_idx = 2
214 | params = {"position_idx": position_idx, "hedged": True}
215 | elif order_info.is_close:
216 | position_idx = 1
217 | params = {"reduceOnly": True, "position_idx": position_idx, "hedged": True}
218 |
219 | if order_info.leverage is not None:
220 | self.set_leverage(order_info.leverage, symbol)
221 | try:
222 | result = retry(
223 | self.client.create_order,
224 | symbol,
225 | order_info.type.lower(),
226 | order_info.side,
227 | abs(entry_amount),
228 | None,
229 | params,
230 | order_info=order_info,
231 | max_attempts=5,
232 | delay=0.1,
233 | instance=self,
234 | )
235 | # order_amount = self.get_order_amount(result["id"], order_info)
236 | # result["amount"] = order_amount
237 | return result
238 | except Exception as e:
239 | raise error.OrderError(e, order_info)
240 |
241 | def market_close(self, order_info: MarketOrder):
242 | from exchange.pexchange import retry
243 |
244 | symbol = self.order_info.unified_symbol
245 | close_amount = self.get_amount(order_info)
246 |
247 | if self.position_mode == "one-way":
248 | params = {"reduceOnly": True, "position_idx": 0}
249 | elif self.position_mode == "hedge":
250 | if order_info.side == "buy":
251 | if order_info.is_entry:
252 | position_idx = 1
253 | params = {"position_idx": position_idx}
254 | elif order_info.is_close:
255 | position_idx = 2
256 | params = {"reduceOnly": True, "position_idx": position_idx}
257 | elif order_info.side == "sell":
258 | if order_info.is_entry:
259 | position_idx = 2
260 | params = {"position_idx": position_idx}
261 | elif order_info.is_close:
262 | position_idx = 1
263 | params = {"reduceOnly": True, "position_idx": position_idx}
264 |
265 | try:
266 | result = retry(
267 | self.client.create_order,
268 | symbol,
269 | order_info.type.lower(),
270 | order_info.side,
271 | abs(close_amount),
272 | None,
273 | params,
274 | order_info=order_info,
275 | max_attempts=5,
276 | delay=0.1,
277 | instance=self,
278 | )
279 | # order_amount = self.get_order_amount(result["id"], order_info)
280 | # result["amount"] = order_amount
281 | return result
282 | except Exception as e:
283 | raise error.OrderError(e, self.order_info)
284 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | from fastapi.exception_handlers import (
2 | request_validation_exception_handler,
3 | )
4 | from pprint import pprint
5 | from fastapi import FastAPI, Request, status, BackgroundTasks
6 | from fastapi.responses import ORJSONResponse, RedirectResponse
7 | from fastapi.exceptions import RequestValidationError
8 | import httpx
9 | from exchange.stock.kis import KoreaInvestment
10 | from exchange.model import MarketOrder, PriceRequest, HedgeData, OrderRequest
11 | from exchange.utility import (
12 | settings,
13 | log_order_message,
14 | log_alert_message,
15 | print_alert_message,
16 | logger_test,
17 | log_order_error_message,
18 | log_validation_error_message,
19 | log_hedge_message,
20 | log_error_message,
21 | log_message,
22 | )
23 | import traceback
24 | from exchange import get_exchange, log_message, db, settings, get_bot, pocket
25 | import ipaddress
26 | import os
27 | import sys
28 | from devtools import debug
29 |
30 | VERSION = "0.1.8"
31 | app = FastAPI(default_response_class=ORJSONResponse)
32 |
33 |
34 | def get_error(e):
35 | tb = traceback.extract_tb(e.__traceback__)
36 | target_folder = os.path.abspath(os.path.dirname(tb[0].filename))
37 | error_msg = []
38 |
39 | for tb_info in tb:
40 | # if target_folder in tb_info.filename:
41 | error_msg.append(
42 | f"File {tb_info.filename}, line {tb_info.lineno}, in {tb_info.name}"
43 | )
44 | error_msg.append(f" {tb_info.line}")
45 |
46 | error_msg.append(str(e))
47 |
48 | return error_msg
49 |
50 |
51 | @app.on_event("startup")
52 | async def startup():
53 | log_message(f"POABOT 실행 완료! - 버전:{VERSION}")
54 |
55 |
56 | @app.on_event("shutdown")
57 | async def shutdown():
58 | db.close()
59 |
60 |
61 | whitelist = [
62 | "52.89.214.238",
63 | "34.212.75.30",
64 | "54.218.53.128",
65 | "52.32.178.7",
66 | "127.0.0.1",
67 | ]
68 | whitelist = whitelist + settings.WHITELIST
69 |
70 |
71 | # @app.middleware("http")
72 | # async def add_process_time_header(request: Request, call_next):
73 | # start_time = time.perf_counter()
74 | # response = await call_next(request)
75 | # process_time = time.perf_counter() - start_time
76 | # response.headers["X-Process-Time"] = str(process_time)
77 | # return response
78 |
79 |
80 | @app.middleware("http")
81 | async def whitelist_middleware(request: Request, call_next):
82 | try:
83 | if (
84 | request.client.host not in whitelist
85 | and not ipaddress.ip_address(request.client.host).is_private
86 | ):
87 | msg = f"{request.client.host}는 안됩니다"
88 | print(msg)
89 | return ORJSONResponse(
90 | status_code=status.HTTP_403_FORBIDDEN,
91 | content=f"{request.client.host}는 허용되지 않습니다",
92 | )
93 | except:
94 | log_error_message(traceback.format_exc(), "미들웨어 에러")
95 | else:
96 | response = await call_next(request)
97 | return response
98 |
99 |
100 | @app.exception_handler(RequestValidationError)
101 | async def validation_exception_handler(request, exc):
102 | msgs = [
103 | f"[에러{index+1}] " + f"{error.get('msg')} \n{error.get('loc')}"
104 | for index, error in enumerate(exc.errors())
105 | ]
106 | message = "[Error]\n"
107 | for msg in msgs:
108 | message = message + msg + "\n"
109 |
110 | log_validation_error_message(f"{message}\n {exc.body}")
111 | return await request_validation_exception_handler(request, exc)
112 |
113 |
114 | @app.get("/ip")
115 | async def get_ip():
116 | data = httpx.get("https://ipv4.jsonip.com").json()["ip"]
117 | log_message(data)
118 |
119 |
120 | @app.get("/hi")
121 | async def welcome():
122 | return "hi!!"
123 |
124 |
125 | @app.post("/price")
126 | async def price(price_req: PriceRequest, background_tasks: BackgroundTasks):
127 | exchange = get_exchange(price_req.exchange)
128 | price = exchange.dict()[price_req.exchange].fetch_price(
129 | price_req.base, price_req.quote
130 | )
131 | return price
132 |
133 |
134 | def log(exchange_name, result, order_info):
135 | log_order_message(exchange_name, result, order_info)
136 | print_alert_message(order_info)
137 |
138 |
139 | def log_error(error_message, order_info):
140 | log_order_error_message(error_message, order_info)
141 | log_alert_message(order_info, "실패")
142 |
143 |
144 | @app.post("/order")
145 | @app.post("/")
146 | async def order(order_info: MarketOrder, background_tasks: BackgroundTasks):
147 | order_result = None
148 | try:
149 | exchange_name = order_info.exchange
150 | bot = get_bot(exchange_name, order_info.kis_number)
151 | bot.init_info(order_info)
152 |
153 | if bot.order_info.is_crypto:
154 | if bot.order_info.is_entry:
155 | order_result = bot.market_entry(bot.order_info)
156 | elif bot.order_info.is_close:
157 | order_result = bot.market_close(bot.order_info)
158 | elif bot.order_info.is_buy:
159 | order_result = bot.market_buy(bot.order_info)
160 | elif bot.order_info.is_sell:
161 | order_result = bot.market_sell(bot.order_info)
162 | background_tasks.add_task(log, exchange_name, order_result, order_info)
163 | elif bot.order_info.is_stock:
164 | order_result = bot.create_order(
165 | bot.order_info.exchange,
166 | bot.order_info.base,
167 | order_info.type.lower(),
168 | order_info.side.lower(),
169 | order_info.amount,
170 | )
171 | background_tasks.add_task(log, exchange_name, order_result, order_info)
172 |
173 | except TypeError as e:
174 | error_msg = get_error(e)
175 | background_tasks.add_task(
176 | log_order_error_message, "\n".join(error_msg), order_info
177 | )
178 |
179 | except Exception as e:
180 | error_msg = get_error(e)
181 | background_tasks.add_task(log_error, "\n".join(error_msg), order_info)
182 |
183 | else:
184 | return {"result": "success"}
185 |
186 | finally:
187 | pass
188 |
189 |
190 | def get_hedge_records(base):
191 | records = pocket.get_full_list("kimp", query_params={"filter": f'base = "{base}"'})
192 | binance_amount = 0.0
193 | binance_records_id = []
194 | upbit_amount = 0.0
195 | upbit_records_id = []
196 | for record in records:
197 | if record.exchange == "BINANCE":
198 | binance_amount += record.amount
199 | binance_records_id.append(record.id)
200 | elif record.exchange == "UPBIT":
201 | upbit_amount += record.amount
202 | upbit_records_id.append(record.id)
203 |
204 | return {
205 | "BINANCE": {"amount": binance_amount, "records_id": binance_records_id},
206 | "UPBIT": {"amount": upbit_amount, "records_id": upbit_records_id},
207 | }
208 |
209 |
210 | @app.post("/hedge")
211 | async def hedge(hedge_data: HedgeData, background_tasks: BackgroundTasks):
212 | exchange_name = hedge_data.exchange.upper()
213 | bot = get_bot(exchange_name)
214 | upbit = get_bot("UPBIT")
215 |
216 | base = hedge_data.base
217 | quote = hedge_data.quote
218 | amount = hedge_data.amount
219 | leverage = hedge_data.leverage
220 | hedge = hedge_data.hedge
221 |
222 | foreign_order_info = OrderRequest(
223 | exchange=exchange_name,
224 | base=base,
225 | quote=quote,
226 | side="entry/sell",
227 | type="market",
228 | amount=amount,
229 | leverage=leverage,
230 | )
231 | bot.init_info(foreign_order_info)
232 | if hedge == "ON":
233 | try:
234 | if amount is None:
235 | raise Exception("헷지할 수량을 요청하세요")
236 | binance_order_result = bot.market_entry(foreign_order_info)
237 | binance_order_amount = binance_order_result["amount"]
238 | pocket.create(
239 | "kimp",
240 | {
241 | "exchange": "BINANCE",
242 | "base": base,
243 | "quote": quote,
244 | "amount": binance_order_amount,
245 | },
246 | )
247 | if leverage is None:
248 | leverage = 1
249 | try:
250 | korea_order_info = OrderRequest(
251 | exchange="UPBIT",
252 | base=base,
253 | quote="KRW",
254 | side="buy",
255 | type="market",
256 | amount=binance_order_amount,
257 | )
258 | upbit.init_info(korea_order_info)
259 | upbit_order_result = upbit.market_buy(korea_order_info)
260 | except Exception as e:
261 | hedge_records = get_hedge_records(base)
262 | binance_records_id = hedge_records["BINANCE"]["records_id"]
263 | binance_amount = hedge_records["BINANCE"]["amount"]
264 | binance_order_result = bot.market_close(
265 | OrderRequest(
266 | exchange=exchange_name,
267 | base=base,
268 | quote=quote,
269 | side="close/buy",
270 | amount=binance_amount,
271 | )
272 | )
273 | for binance_record_id in binance_records_id:
274 | pocket.delete("kimp", binance_record_id)
275 | log_message(
276 | "[헷지 실패] 업비트에서 에러가 발생하여 바이낸스 포지션을 종료합니다"
277 | )
278 | else:
279 | upbit_order_info = upbit.get_order(upbit_order_result["id"])
280 | upbit_order_amount = upbit_order_info["filled"]
281 | pocket.create(
282 | "kimp",
283 | {
284 | "exchange": "UPBIT",
285 | "base": base,
286 | "quote": "KRW",
287 | "amount": upbit_order_amount,
288 | },
289 | )
290 | log_hedge_message(
291 | exchange_name,
292 | base,
293 | quote,
294 | binance_order_amount,
295 | upbit_order_amount,
296 | hedge,
297 | )
298 |
299 | except Exception as e:
300 | # log_message(f"{e}")
301 | background_tasks.add_task(
302 | log_error_message, traceback.format_exc(), "헷지 에러"
303 | )
304 | return {"result": "error"}
305 | else:
306 | return {"result": "success"}
307 |
308 | elif hedge == "OFF":
309 | try:
310 | records = pocket.get_full_list(
311 | "kimp", query_params={"filter": f'base = "{base}"'}
312 | )
313 | binance_amount = 0.0
314 | binance_records_id = []
315 | upbit_amount = 0.0
316 | upbit_records_id = []
317 | for record in records:
318 | if record.exchange == "BINANCE":
319 | binance_amount += record.amount
320 | binance_records_id.append(record.id)
321 | elif record.exchange == "UPBIT":
322 | upbit_amount += record.amount
323 | upbit_records_id.append(record.id)
324 |
325 | if binance_amount > 0 and upbit_amount > 0:
326 | # 바이낸스
327 | order_info = OrderRequest(
328 | exchange="BINANCE",
329 | base=base,
330 | quote=quote,
331 | side="close/buy",
332 | amount=binance_amount,
333 | )
334 | binance_order_result = bot.market_close(order_info)
335 | for binance_record_id in binance_records_id:
336 | pocket.delete("kimp", binance_record_id)
337 | # 업비트
338 | order_info = OrderRequest(
339 | exchange="UPBIT",
340 | base=base,
341 | quote="KRW",
342 | side="sell",
343 | amount=upbit_amount,
344 | )
345 | upbit_order_result = upbit.market_sell(order_info)
346 | for upbit_record_id in upbit_records_id:
347 | pocket.delete("kimp", upbit_record_id)
348 |
349 | log_hedge_message(
350 | exchange_name, base, quote, binance_amount, upbit_amount, hedge
351 | )
352 | elif binance_amount == 0 and upbit_amount == 0:
353 | log_message(f"{exchange_name}, UPBIT에 종료할 수량이 없습니다")
354 | elif binance_amount == 0:
355 | log_message(f"{exchange_name}에 종료할 수량이 없습니다")
356 | elif upbit_amount == 0:
357 | log_message("UPBIT에 종료할 수량이 없습니다")
358 | except Exception as e:
359 | background_tasks.add_task(
360 | log_error_message, traceback.format_exc(), "헷지종료 에러"
361 | )
362 | return {"result": "error"}
363 | else:
364 | return {"result": "success"}
365 |
--------------------------------------------------------------------------------
/exchange/stock/kis.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | import json
3 | import httpx
4 | from exchange.stock.error import TokenExpired
5 | from exchange.stock.schemas import *
6 | from exchange.database import db
7 | from pydantic import validate_arguments
8 | import traceback
9 | import copy
10 | from exchange.model import MarketOrder
11 | from devtools import debug
12 |
13 |
14 | class KoreaInvestment:
15 | def __init__(
16 | self,
17 | key: str,
18 | secret: str,
19 | account_number: str,
20 | account_code: str,
21 | kis_number: int,
22 | ):
23 | self.key = key
24 | self.secret = secret
25 | self.kis_number = kis_number
26 | self.base_url = (
27 | BaseUrls.base_url.value
28 | if kis_number != 4
29 | else BaseUrls.paper_base_url.value
30 | )
31 | self.is_auth = False
32 | self.account_number = account_number
33 | self.base_headers = {}
34 | self.session = httpx.Client()
35 | self.async_session = httpx.AsyncClient()
36 | self.auth()
37 |
38 | self.base_body = {}
39 | self.base_order_body = AccountInfo(
40 | CANO=account_number, ACNT_PRDT_CD=account_code
41 | )
42 | self.order_exchange_code = {
43 | "NASDAQ": ExchangeCode.NASDAQ,
44 | "NYSE": ExchangeCode.NYSE,
45 | "AMEX": ExchangeCode.AMEX,
46 | }
47 | self.query_exchange_code = {
48 | "NASDAQ": QueryExchangeCode.NASDAQ,
49 | "NYSE": QueryExchangeCode.NYSE,
50 | "AMEX": QueryExchangeCode.AMEX,
51 | }
52 |
53 | def init_info(self, order_info: MarketOrder):
54 | self.order_info = order_info
55 |
56 | def close_session(self):
57 | self.session.close()
58 |
59 | def get(self, endpoint: str, params: dict = None, headers: dict = None):
60 | url = f"{self.base_url}{endpoint}"
61 | # headers |= self.base_headers
62 | return self.session.get(url, params=params, headers=headers).json()
63 |
64 | def post_with_error_handling(
65 | self, endpoint: str, data: dict = None, headers: dict = None
66 | ):
67 | url = f"{self.base_url}{endpoint}"
68 | response = self.session.post(url, json=data, headers=headers).json()
69 | if "access_token" in response.keys() or response["rt_cd"] == "0":
70 | return response
71 | else:
72 | raise Exception(response)
73 |
74 | def post(self, endpoint: str, data: dict = None, headers: dict = None):
75 | return self.post_with_error_handling(endpoint, data, headers)
76 |
77 | def get_hashkey(self, data) -> str:
78 | headers = {"appKey": self.key, "appSecret": self.secret}
79 | endpoint = "/uapi/hashkey"
80 | url = f"{self.base_url}{endpoint}"
81 | return self.session.post(url, json=data, headers=headers).json()["HASH"]
82 |
83 | def open_auth(self):
84 | return self.open_json("auth.json")
85 |
86 | def write_auth(self, auth):
87 | self.write_json("auth.json", auth)
88 |
89 | def check_auth(self, auth, key, secret, kis_number):
90 | if auth is None:
91 | return False
92 | access_token, access_token_token_expired = auth
93 | try:
94 | if access_token == "nothing":
95 | return False
96 | else:
97 | if not self.is_auth:
98 | response = self.session.get(
99 | "https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/quotations/inquire-ccnl",
100 | headers={
101 | "authorization": f"BEARER {access_token}",
102 | "appkey": key,
103 | "appsecret": secret,
104 | "custtype": "P",
105 | "tr_id": "FHKST01010300",
106 | },
107 | params={
108 | "FID_COND_MRKT_DIV_CODE": "J",
109 | "FID_INPUT_ISCD": "005930",
110 | },
111 | ).json()
112 | if response["msg_cd"] == "EGW00123":
113 | return False
114 |
115 | access_token_token_expired = datetime.strptime(
116 | access_token_token_expired, "%Y-%m-%d %H:%M:%S"
117 | )
118 | diff = access_token_token_expired - datetime.now()
119 | total_seconds = diff.total_seconds()
120 | if total_seconds < 60 * 60:
121 | return False
122 | else:
123 | return True
124 |
125 | except Exception as e:
126 | print(traceback.format_exc())
127 |
128 | def create_auth(self, key: str, secret: str):
129 | data = {"grant_type": "client_credentials", "appkey": key, "appsecret": secret}
130 | base_url = BaseUrls.base_url.value
131 | endpoint = "/oauth2/tokenP"
132 |
133 | url = f"{base_url}{endpoint}"
134 |
135 | response = self.session.post(url, json=data).json()
136 | if "access_token" in response.keys() or response.get("rt_cd") == "0":
137 | return response["access_token"], response["access_token_token_expired"]
138 | else:
139 | raise Exception(response)
140 |
141 | def auth(self):
142 | auth_id = f"KIS{self.kis_number}"
143 | auth = db.get_auth(auth_id)
144 | if not self.check_auth(auth, self.key, self.secret, self.kis_number):
145 | auth = self.create_auth(self.key, self.secret)
146 | db.set_auth(auth_id, auth[0], auth[1])
147 | else:
148 | self.is_auth = True
149 | access_token = auth[0]
150 | self.base_headers = BaseHeaders(
151 | authorization=f"Bearer {access_token}",
152 | appkey=self.key,
153 | appsecret=self.secret,
154 | custtype="P",
155 | ).dict()
156 | return auth
157 |
158 | def create_order(
159 | self,
160 | exchange: Literal["KRX", "NASDAQ", "NYSE", "AMEX"],
161 | ticker: str,
162 | order_type: Literal["limit", "market"],
163 | side: Literal["buy", "sell"],
164 | amount: int,
165 | price: int = 0,
166 | mintick=0.01,
167 | ):
168 | max_retries = 3
169 | last_exception = None
170 |
171 | for attempt in range(max_retries):
172 | try:
173 | endpoint = (
174 | Endpoints.korea_order.value
175 | if exchange == "KRX"
176 | else Endpoints.usa_order.value
177 | )
178 | body = self.base_order_body.dict()
179 | headers = copy.deepcopy(self.base_headers)
180 | price = str(price)
181 |
182 | amount = str(int(amount))
183 |
184 | if exchange == "KRX":
185 | if self.base_url == BaseUrls.base_url:
186 | headers |= (
187 | KoreaBuyOrderHeaders(**headers)
188 | if side == "buy"
189 | else KoreaSellOrderHeaders(**headers)
190 | )
191 | elif self.base_url == BaseUrls.paper_base_url:
192 | headers |= (
193 | KoreaPaperBuyOrderHeaders(**headers)
194 | if side == "buy"
195 | else KoreaPaperSellOrderHeaders(**headers)
196 | )
197 |
198 | if order_type == "market":
199 | body |= KoreaMarketOrderBody(**body, PDNO=ticker, ORD_QTY=amount)
200 | elif order_type == "limit":
201 | body |= KoreaOrderBody(
202 | **body,
203 | PDNO=ticker,
204 | ORD_DVSN=KoreaOrderType.limit,
205 | ORD_QTY=amount,
206 | ORD_UNPR=price,
207 | )
208 | elif exchange in ("NASDAQ", "NYSE", "AMEX"):
209 | exchange_code = self.order_exchange_code.get(exchange)
210 | current_price = self.fetch_current_price(exchange, ticker)
211 | price = (
212 | current_price + mintick * 50
213 | if side == "buy"
214 | else current_price - mintick * 50
215 | )
216 | if price < 1:
217 | price = 1.0
218 | price = float("{:.2f}".format(price))
219 | if self.base_url == BaseUrls.base_url:
220 | headers |= (
221 | UsaBuyOrderHeaders(**headers)
222 | if side == "buy"
223 | else UsaSellOrderHeaders(**headers)
224 | )
225 | elif self.base_url == BaseUrls.paper_base_url:
226 | headers |= (
227 | UsaPaperBuyOrderHeaders(**headers)
228 | if side == "buy"
229 | else UsaPaperSellOrderHeaders(**headers)
230 | )
231 |
232 | if order_type == "market":
233 | body |= UsaOrderBody(
234 | **body,
235 | PDNO=ticker,
236 | ORD_DVSN=UsaOrderType.limit.value,
237 | ORD_QTY=amount,
238 | OVRS_ORD_UNPR=price,
239 | OVRS_EXCG_CD=exchange_code,
240 | )
241 | elif order_type == "limit":
242 | body |= UsaOrderBody(
243 | **body,
244 | PDNO=ticker,
245 | ORD_DVSN=UsaOrderType.limit.value,
246 | ORD_QTY=amount,
247 | OVRS_ORD_UNPR=price,
248 | OVRS_EXCG_CD=exchange_code,
249 | )
250 | return self.post(endpoint, body, headers)
251 | except Exception as e:
252 | last_exception = e
253 | if attempt < max_retries - 1:
254 | continue
255 | else:
256 | raise last_exception
257 |
258 | def create_market_buy_order(
259 | self,
260 | exchange: Literal["KRX", "NASDAQ", "NYSE", "AMEX"],
261 | ticker: str,
262 | amount: int,
263 | price: int = 0,
264 | ):
265 | if exchange == "KRX":
266 | return self.create_order(exchange, ticker, "market", "buy", amount)
267 | elif exchange == "usa":
268 | return self.create_order(exchange, ticker, "market", "buy", amount, price)
269 |
270 | def create_market_sell_order(
271 | self,
272 | exchange: Literal["KRX", "NASDAQ", "NYSE", "AMEX"],
273 | ticker: str,
274 | amount: int,
275 | price: int = 0,
276 | ):
277 | if exchange == "KRX":
278 | return self.create_order(exchange, ticker, "market", "sell", amount)
279 | elif exchange == "usa":
280 | return self.create_order(exchange, ticker, "market", "buy", amount, price)
281 |
282 | def create_korea_market_buy_order(self, ticker: str, amount: int):
283 | return self.create_market_buy_order("KRX", ticker, amount)
284 |
285 | def create_korea_market_sell_order(self, ticker: str, amount: int):
286 | return self.create_market_sell_order("KRX", ticker, amount)
287 |
288 | def create_usa_market_buy_order(self, ticker: str, amount: int, price: int):
289 | return self.create_market_buy_order("usa", ticker, amount, price)
290 |
291 | def fetch_ticker(
292 | self, exchange: Literal["KRX", "NASDAQ", "NYSE", "AMEX"], ticker: str
293 | ):
294 | if exchange == "KRX":
295 | endpoint = Endpoints.korea_ticker.value
296 | headers = KoreaTickerHeaders(**self.base_headers).dict()
297 | query = KoreaTickerQuery(FID_INPUT_ISCD=ticker).dict()
298 | elif exchange in ("NASDAQ", "NYSE", "AMEX"):
299 | exchange_code = self.query_exchange_code.get(exchange)
300 | endpoint = Endpoints.usa_ticker.value
301 | headers = UsaTickerHeaders(**self.base_headers).dict()
302 | query = UsaTickerQuery(EXCD=exchange_code, SYMB=ticker).dict()
303 | ticker = self.get(endpoint, query, headers)
304 | return ticker.get("output")
305 |
306 | def fetch_current_price(self, exchange, ticker: str):
307 | try:
308 | if exchange == "KRX":
309 | return float(self.fetch_ticker(exchange, ticker)["stck_prpr"])
310 | elif exchange in ("NASDAQ", "NYSE", "AMEX"):
311 | return float(self.fetch_ticker(exchange, ticker)["last"])
312 |
313 | except KeyError:
314 | print(traceback.format_exc())
315 | return None
316 |
317 | def open_json(self, path):
318 | with open(path, "r") as f:
319 | return json.load(f)
320 |
321 | def write_json(self, path, data):
322 | with open(path, "w") as f:
323 | json.dump(data, f)
324 |
325 |
326 | if __name__ == "__main__":
327 | pass
328 |
--------------------------------------------------------------------------------
/exchange/okx.py:
--------------------------------------------------------------------------------
1 | import ccxt
2 | import ccxt.async_support as ccxt_async
3 | from devtools import debug
4 |
5 | from exchange.model import MarketOrder
6 | import exchange.error as error
7 | from decimal import Decimal
8 |
9 |
10 | class Okx:
11 | def __init__(self, key, secret, passphrase):
12 | self.client = ccxt.okx(
13 | {
14 | "apiKey": key,
15 | "secret": secret,
16 | "password": passphrase,
17 | }
18 | )
19 | self.client.load_markets()
20 | self.order_info: MarketOrder = None
21 | self.position_mode = "one-way"
22 |
23 | def init_info(self, order_info: MarketOrder):
24 | self.order_info = order_info
25 |
26 | unified_symbol = order_info.unified_symbol
27 | market = self.client.market(unified_symbol)
28 |
29 | is_contract = market.get("contract")
30 | if is_contract:
31 | order_info.is_contract = True
32 | order_info.contract_size = market.get("contractSize")
33 |
34 | if order_info.is_futures:
35 | self.client.options["defaultType"] = "swap"
36 | else:
37 | self.client.options["defaultType"] = "spot"
38 |
39 | def get_amount_precision(self, symbol):
40 | market = self.client.market(symbol)
41 | precision = market.get("precision")
42 | if (
43 | precision is not None
44 | and isinstance(precision, dict)
45 | and "amount" in precision
46 | ):
47 | return precision.get("amount")
48 |
49 | def get_contract_size(self, symbol):
50 | market = self.client.market(symbol)
51 | return market.get("contractSize")
52 |
53 | def parse_symbol(self, base: str, quote: str):
54 | if self.order_info.is_futures:
55 | return f"{base}/{quote}:{quote}"
56 | else:
57 | return f"{base}/{quote}"
58 |
59 | def get_ticker(self, symbol: str):
60 | return self.client.fetch_ticker(symbol)
61 |
62 | def get_price(self, symbol: str):
63 | return self.get_ticker(symbol)["last"]
64 |
65 | def get_balance(self, base: str):
66 | free_balance_by_base = None
67 | if self.order_info.is_entry or (
68 | self.order_info.is_spot
69 | and (self.order_info.is_buy or self.order_info.is_sell)
70 | ):
71 | free_balance = (
72 | self.client.fetch_free_balance()
73 | if not self.order_info.is_total
74 | else self.client.fetch_total_balance()
75 | )
76 | free_balance_by_base = free_balance.get(base)
77 |
78 | if free_balance_by_base is None or free_balance_by_base == 0:
79 | raise error.FreeAmountNoneError()
80 | return free_balance_by_base
81 |
82 | def get_futures_position(self, symbol=None, all=False):
83 | if symbol is None and all:
84 | positions = self.client.fetch_balance()["info"]["positions"]
85 | positions = [
86 | position
87 | for position in positions
88 | if float(position["positionAmt"]) != 0
89 | ]
90 | return positions
91 |
92 | positions = self.client.fetch_positions([symbol])
93 | long_contracts = None
94 | short_contracts = None
95 | if positions:
96 | for position in positions:
97 | if position["side"] == "long":
98 | long_contracts = position["contracts"]
99 | elif position["side"] == "short":
100 | short_contracts = position["contracts"]
101 |
102 | if self.order_info.is_close and self.order_info.is_buy:
103 | if not short_contracts:
104 | raise error.ShortPositionNoneError()
105 | else:
106 | return short_contracts
107 | elif self.order_info.is_close and self.order_info.is_sell:
108 | if not long_contracts:
109 | raise error.LongPositionNoneError()
110 | else:
111 | return long_contracts
112 | else:
113 | raise error.PositionNoneError()
114 |
115 | def get_amount(self, order_info: MarketOrder) -> float:
116 | if order_info.amount is not None and order_info.percent is not None:
117 | raise error.AmountPercentBothError()
118 | elif order_info.amount is not None:
119 | if order_info.is_contract:
120 | result = self.client.amount_to_precision(
121 | order_info.unified_symbol,
122 | float(
123 | Decimal(str(order_info.amount))
124 | // Decimal(str(order_info.contract_size))
125 | ),
126 | )
127 |
128 | else:
129 | result = order_info.amount
130 | elif order_info.percent is not None:
131 | if self.order_info.is_entry or (order_info.is_spot and order_info.is_buy):
132 | if order_info.is_coinm:
133 | free_base = self.get_balance(order_info.base)
134 | if order_info.is_contract:
135 | result = (
136 | free_base * (order_info.percent - 0.5) / 100
137 | ) // order_info.contract_size
138 | else:
139 | result = free_base * order_info.percent / 100
140 | else:
141 | free_quote = self.get_balance(order_info.quote)
142 | cash = free_quote * (order_info.percent - 0.5) / 100
143 | current_price = self.get_price(order_info.unified_symbol)
144 | if order_info.is_contract:
145 | result = (cash / current_price) // order_info.contract_size
146 | else:
147 | result = cash / current_price
148 | elif self.order_info.is_close:
149 | if order_info.is_contract:
150 | free_amount = self.get_futures_position(order_info.unified_symbol)
151 | result = free_amount * order_info.percent / 100
152 | else:
153 | free_amount = self.get_futures_position(order_info.unified_symbol)
154 | result = free_amount * float(order_info.percent) / 100
155 |
156 | elif order_info.is_spot and order_info.is_sell:
157 | free_amount = self.get_balance(order_info.base)
158 | result = free_amount * float(order_info.percent) / 100
159 |
160 | result = float(
161 | self.client.amount_to_precision(order_info.unified_symbol, result)
162 | )
163 | order_info.amount_by_percent = result
164 | else:
165 | raise error.AmountPercentNoneError()
166 |
167 | return float(result)
168 |
169 | def market_order(self, order_info: MarketOrder):
170 | from exchange.pexchange import retry
171 |
172 | symbol = (
173 | order_info.unified_symbol
174 | ) # self.parse_symbol(order_info.base, order_info.quote)
175 | params = {"tgtCcy": "base_ccy"}
176 |
177 | try:
178 | return retry(
179 | self.client.create_order,
180 | symbol,
181 | order_info.type.lower(),
182 | order_info.side,
183 | order_info.amount,
184 | order_info.price,
185 | params,
186 | order_info=order_info,
187 | max_attempts=5,
188 | delay=0.1,
189 | instance=self,
190 | )
191 | except Exception as e:
192 | raise error.OrderError(e, self.order_info)
193 |
194 | def market_buy(
195 | self,
196 | order_info: MarketOrder,
197 | ):
198 | # 수량기반
199 | buy_amount = self.get_amount(order_info)
200 | fee = self.client.fetch_trading_fee(self.order_info.unified_symbol)
201 | order_info.amount = buy_amount
202 | result = self.market_order(order_info)
203 | order_info.amount = buy_amount * (1 - fee["taker"])
204 | return result
205 |
206 | def market_sell(
207 | self,
208 | order_info: MarketOrder,
209 | ):
210 | # 수량기반
211 | symbol = (
212 | order_info.unified_symbol
213 | ) # self.parse_symbol(order_info.base, order_info.quote)
214 | fee = self.client.fetch_trading_fee(symbol)
215 | sell_amount = self.get_amount(order_info)
216 |
217 | if order_info.percent is not None:
218 | order_info.amount = sell_amount
219 | else:
220 | order_info.amount = sell_amount * (1 - fee["taker"])
221 |
222 | return self.market_order(order_info)
223 |
224 | def set_leverage(self, leverage, symbol):
225 | if self.order_info.is_futures:
226 | if self.order_info.is_futures and self.order_info.is_entry:
227 | if self.order_info.is_buy:
228 | pos_side = "long"
229 | elif self.order_info.is_sell:
230 | pos_side = "short"
231 | try:
232 | if (
233 | self.order_info.margin_mode is None
234 | or self.order_info.margin_mode == "isolated"
235 | ):
236 | if self.position_mode == "hedge":
237 | self.client.set_leverage(
238 | leverage,
239 | symbol,
240 | params={"mgnMode": "isolated", "posSide": pos_side},
241 | )
242 | elif self.position_mode == "one-way":
243 | self.client.set_leverage(
244 | leverage,
245 | symbol,
246 | params={"mgnMode": "isolated", "posSide": "net"},
247 | )
248 | else:
249 | self.client.set_leverage(
250 | leverage,
251 | symbol,
252 | params={"mgnMode": self.order_info.margin_mode},
253 | )
254 | except Exception as e:
255 | pass
256 |
257 | def market_entry(
258 | self,
259 | order_info: MarketOrder,
260 | ):
261 | from exchange.pexchange import retry
262 |
263 | symbol = (
264 | order_info.unified_symbol
265 | ) # self.parse_symbol(order_info.base, order_info.quote)
266 |
267 | entry_amount = self.get_amount(order_info)
268 | if entry_amount == 0:
269 | raise error.MinAmountError()
270 |
271 | params = {}
272 | if order_info.leverage is None:
273 | self.set_leverage(1, symbol)
274 | else:
275 | self.set_leverage(order_info.leverage, symbol)
276 | if order_info.margin_mode is None:
277 | params |= {"tdMode": "isolated"}
278 | else:
279 | params |= {"tdMode": order_info.margin_mode}
280 |
281 | if self.position_mode == "one-way":
282 | params |= {}
283 | elif self.position_mode == "hedge":
284 | if order_info.is_futures and order_info.side == "buy":
285 | if order_info.is_entry:
286 | pos_side = "long"
287 | elif order_info.is_close:
288 | pos_side = "short"
289 | elif order_info.is_futures and order_info.side == "sell":
290 | if order_info.is_entry:
291 | pos_side = "short"
292 | elif order_info.is_close:
293 | pos_side = "long"
294 | params |= {"posSide": pos_side}
295 |
296 | try:
297 | return retry(
298 | self.client.create_order,
299 | symbol,
300 | order_info.type.lower(),
301 | order_info.side,
302 | abs(entry_amount),
303 | None,
304 | params,
305 | order_info=order_info,
306 | max_attempts=5,
307 | delay=0.1,
308 | instance=self,
309 | )
310 | except Exception as e:
311 | raise error.OrderError(e, self.order_info)
312 |
313 | def market_close(
314 | self,
315 | order_info: MarketOrder,
316 | ):
317 | from exchange.pexchange import retry
318 |
319 | symbol = self.order_info.unified_symbol
320 | close_amount = self.get_amount(order_info)
321 |
322 | if self.position_mode == "one-way":
323 | if (
324 | self.order_info.margin_mode is None
325 | or self.order_info.margin_mode == "isolated"
326 | ):
327 | params = {"reduceOnly": True, "tdMode": "isolated"}
328 | elif self.order_info.margin_mode == "cross":
329 | params = {"reduceOnly": True, "tdMode": "cross"}
330 |
331 | elif self.position_mode == "hedge":
332 | if order_info.is_futures and order_info.side == "buy":
333 | if order_info.is_entry:
334 | pos_side = "long"
335 | elif order_info.is_close:
336 | pos_side = "short"
337 | elif order_info.is_futures and order_info.side == "sell":
338 | if order_info.is_entry:
339 | pos_side = "short"
340 | elif order_info.is_close:
341 | pos_side = "long"
342 | if (
343 | self.order_info.margin_mode is None
344 | or self.order_info.margin_mode == "isolated"
345 | ):
346 | params = {"posSide": pos_side, "tdMode": "isolated"}
347 | elif self.order_info.margin_mode == "cross":
348 | params = {"posSide": pos_side, "tdMode": "cross"}
349 |
350 | try:
351 | return retry(
352 | self.client.create_order,
353 | symbol,
354 | order_info.type.lower(),
355 | order_info.side,
356 | abs(close_amount),
357 | None,
358 | params,
359 | order_info=order_info,
360 | max_attempts=5,
361 | delay=0.1,
362 | instance=self,
363 | )
364 | except Exception as e:
365 | raise error.OrderError(e, self.order_info)
366 |
--------------------------------------------------------------------------------
/exchange/binance.py:
--------------------------------------------------------------------------------
1 | from exchange.pexchange import ccxt, ccxt_async, httpx
2 | from devtools import debug
3 | from exchange.model import MarketOrder
4 | import exchange.error as error
5 |
6 |
7 | class Binance:
8 | def __init__(self, key, secret):
9 | self.client = ccxt.binance(
10 | {
11 | "apiKey": key,
12 | "secret": secret,
13 | "options": {"adjustForTimeDifference": True},
14 | }
15 | )
16 | self.client.load_markets()
17 | self.position_mode = "one-way"
18 | self.order_info: MarketOrder = None
19 |
20 | def init_info(self, order_info: MarketOrder):
21 | self.order_info = order_info
22 |
23 | unified_symbol = order_info.unified_symbol
24 | market = self.client.market(unified_symbol)
25 |
26 | if order_info.amount is not None:
27 | order_info.amount = float(
28 | self.client.amount_to_precision(
29 | order_info.unified_symbol, order_info.amount
30 | )
31 | )
32 |
33 | if order_info.is_futures:
34 | if order_info.is_coinm:
35 | is_contract = market.get("contract")
36 | if is_contract:
37 | order_info.is_contract = True
38 | order_info.contract_size = market.get("contractSize")
39 | self.client.options["defaultType"] = "delivery"
40 | else:
41 | self.client.options["defaultType"] = "swap"
42 | else:
43 | self.client.options["defaultType"] = "spot"
44 |
45 | def get_ticker(self, symbol: str):
46 | return self.client.fetch_ticker(symbol)
47 |
48 | def get_price(self, symbol: str):
49 | return self.get_ticker(symbol)["last"]
50 |
51 | def get_futures_position(self, symbol=None, all=False):
52 | if symbol is None and all:
53 | positions = self.client.fetch_balance()["info"]["positions"]
54 | positions = [
55 | position
56 | for position in positions
57 | if float(position["positionAmt"]) != 0
58 | ]
59 | return positions
60 |
61 | positions = None
62 | if self.order_info.is_coinm:
63 | positions = self.client.fetch_balance()["info"]["positions"]
64 | positions = [
65 | position
66 | for position in positions
67 | if float(position["positionAmt"]) != 0
68 | and position["symbol"] == self.client.market(symbol).get("id")
69 | ]
70 | else:
71 | positions = self.client.fetch_positions(symbols=[symbol])
72 |
73 | long_contracts = None
74 | short_contracts = None
75 | if positions:
76 | if self.order_info.is_coinm:
77 | for position in positions:
78 | amt = float(position["positionAmt"])
79 | if position["positionSide"] == "LONG":
80 | long_contracts = amt
81 | elif position["positionSide"] == "SHORT":
82 | short_contracts: float = amt
83 | elif position["positionSide"] == "BOTH":
84 | if amt > 0:
85 | long_contracts = amt
86 | elif amt < 0:
87 | short_contracts = abs(amt)
88 | else:
89 | for position in positions:
90 | if position["side"] == "long":
91 | long_contracts = position["contracts"]
92 | elif position["side"] == "short":
93 | short_contracts = position["contracts"]
94 | if self.order_info.is_close and self.order_info.is_buy:
95 | if not short_contracts:
96 | raise error.ShortPositionNoneError()
97 | else:
98 | return short_contracts
99 | elif self.order_info.is_close and self.order_info.is_sell:
100 | if not long_contracts:
101 | raise error.LongPositionNoneError()
102 | else:
103 | return long_contracts
104 | else:
105 | raise error.PositionNoneError()
106 |
107 | def get_balance(self, base: str):
108 | free_balance_by_base = None
109 |
110 | if self.order_info.is_entry or (
111 | self.order_info.is_spot
112 | and (self.order_info.is_buy or self.order_info.is_sell)
113 | ):
114 | free_balance = (
115 | self.client.fetch_free_balance()
116 | if not self.order_info.is_total
117 | else self.client.fetch_total_balance()
118 | )
119 | free_balance_by_base = free_balance.get(base)
120 |
121 | if free_balance_by_base is None or free_balance_by_base == 0:
122 | raise error.FreeAmountNoneError()
123 | return free_balance_by_base
124 |
125 | def get_amount(self, order_info: MarketOrder) -> float:
126 | if order_info.amount is not None and order_info.percent is not None:
127 | raise error.AmountPercentBothError()
128 | elif order_info.amount is not None:
129 | if order_info.is_contract:
130 | current_price = self.get_price(order_info.unified_symbol)
131 | result = (order_info.amount * current_price) // order_info.contract_size
132 | else:
133 | result = order_info.amount
134 | elif order_info.percent is not None:
135 | if order_info.is_entry or (order_info.is_spot and order_info.is_buy):
136 | if order_info.is_coinm:
137 | free_base = self.get_balance(order_info.base)
138 | if order_info.is_contract:
139 | current_price = self.get_price(order_info.unified_symbol)
140 | result = (
141 | free_base * order_info.percent / 100 * current_price
142 | ) // order_info.contract_size
143 | else:
144 | result = free_base * order_info.percent / 100
145 | else:
146 | free_quote = self.get_balance(order_info.quote)
147 | cash = free_quote * (order_info.percent - 0.5) / 100
148 | current_price = self.get_price(order_info.unified_symbol)
149 | if order_info.is_contract:
150 | result = (cash / current_price) // order_info.contract_size
151 | else:
152 | result = cash / current_price
153 | elif self.order_info.is_close:
154 | if order_info.is_contract:
155 | free_amount = self.get_futures_position(order_info.unified_symbol)
156 | result = free_amount * order_info.percent / 100
157 | else:
158 | free_amount = self.get_futures_position(order_info.unified_symbol)
159 | result = free_amount * float(order_info.percent) / 100
160 | elif order_info.is_spot and order_info.is_sell:
161 | free_amount = self.get_balance(order_info.base)
162 | result = free_amount * float(order_info.percent) / 100
163 |
164 | result = float(
165 | self.client.amount_to_precision(order_info.unified_symbol, result)
166 | )
167 | order_info.amount_by_percent = result
168 | else:
169 | raise error.AmountPercentNoneError()
170 |
171 | return result
172 |
173 | def set_leverage(self, leverage, symbol):
174 | if self.order_info.is_futures:
175 | self.client.set_leverage(leverage, symbol)
176 |
177 | def market_order(self, order_info: MarketOrder):
178 | from exchange.pexchange import retry
179 |
180 | symbol = order_info.unified_symbol # self.parse_symbol(base, quote)
181 | params = {}
182 | try:
183 | return retry(
184 | self.client.create_order,
185 | symbol,
186 | order_info.type.lower(),
187 | order_info.side,
188 | order_info.amount,
189 | None,
190 | params,
191 | order_info=order_info,
192 | max_attempts=5,
193 | delay=0.1,
194 | instance=self,
195 | )
196 | except Exception as e:
197 | raise error.OrderError(e, self.order_info)
198 |
199 | # async def market_order_async(
200 | # self,
201 | # base: str,
202 | # quote: str,
203 | # type: str,
204 | # side: str,
205 | # amount: float,
206 | # price: float = None,
207 | # ):
208 | # symbol = self.parse_symbol(base, quote)
209 | # return await self.spot_async.create_order(
210 | # symbol, type.lower(), side.lower(), amount
211 | # )
212 |
213 | def market_buy(self, order_info: MarketOrder):
214 | # 수량기반
215 | buy_amount = self.get_amount(order_info)
216 | order_info.amount = buy_amount
217 |
218 | return self.market_order(order_info)
219 |
220 | def market_sell(self, order_info: MarketOrder):
221 | sell_amount = self.get_amount(order_info)
222 | order_info.amount = sell_amount
223 | return self.market_order(order_info)
224 |
225 | def market_entry(
226 | self,
227 | order_info: MarketOrder,
228 | ):
229 | from exchange.pexchange import retry
230 |
231 | # self.client.options["defaultType"] = "swap"
232 | symbol = self.order_info.unified_symbol # self.parse_symbol(base, quote)
233 |
234 | entry_amount = self.get_amount(order_info)
235 | if entry_amount == 0:
236 | raise error.MinAmountError()
237 | if self.position_mode == "one-way":
238 | params = {}
239 | elif self.position_mode == "hedge":
240 | if order_info.side == "buy":
241 | if order_info.is_entry:
242 | positionSide = "LONG"
243 | elif order_info.is_close:
244 | positionSide = "SHORT"
245 | elif order_info.side == "sell":
246 | if order_info.is_entry:
247 | positionSide = "SHORT"
248 | elif order_info.is_close:
249 | positionSide = "LONG"
250 | params = {"positionSide": positionSide}
251 | if order_info.leverage is not None:
252 | self.set_leverage(order_info.leverage, symbol)
253 |
254 | try:
255 | result = retry(
256 | self.client.create_order,
257 | symbol,
258 | order_info.type.lower(),
259 | order_info.side,
260 | abs(entry_amount),
261 | None,
262 | params,
263 | order_info=order_info,
264 | max_attempts=10,
265 | delay=0.1,
266 | instance=self,
267 | )
268 | return result
269 | except Exception as e:
270 | raise error.OrderError(e, self.order_info)
271 |
272 | def is_hedge_mode(self):
273 | response = self.client.fapiPrivate_get_positionside_dual()
274 | if response["dualSidePosition"]:
275 | return True
276 | else:
277 | return False
278 |
279 | def market_sltp_order(
280 | self,
281 | base: str,
282 | quote: str,
283 | type: str,
284 | side: str,
285 | amount: float,
286 | stop_price: float,
287 | profit_price: float,
288 | ):
289 | symbol = self.order_info.unified_symbol # self.parse_symbol(base, quote)
290 | inverted_side = (
291 | "sell" if side.lower() == "buy" else "buy"
292 | ) # buy면 sell, sell이면 buy * 진입 포지션과 반대로 주문 넣어줘 야함
293 | self.client.create_order(
294 | symbol,
295 | "STOP_MARKET",
296 | inverted_side,
297 | amount,
298 | None,
299 | {"stopPrice": stop_price, "newClientOrderId": "STOP_MARKET"},
300 | ) # STOP LOSS 오더
301 | self.client.create_order(
302 | symbol,
303 | "TAKE_PROFIT_MARKET",
304 | inverted_side,
305 | amount,
306 | None,
307 | {"stopPrice": profit_price, "newClientOrderId": "TAKE_PROFIT_MARKET"},
308 | ) # TAKE profit 오더
309 |
310 | # response = self.future.private_post_order_oco({
311 | # 'symbol': self.future.market(symbol)['id'],
312 | # 'side': 'BUY', # SELL, BUY
313 | # 'quantity': self.future.amount_to_precision(symbol, amount),
314 | # 'price': self.future.price_to_precision(symbol, profit_price),
315 | # 'stopPrice': self.future.price_to_precision(symbol, stop_price),
316 | # # 'stopLimitPrice': self.future.price_to_precision(symbol, stop_limit_price), # If provided, stopLimitTimeInForce is required
317 | # # 'stopLimitTimeInForce': 'GTC', # GTC, FOK, IOC
318 | # # 'listClientOrderId': exchange.uuid(), # A unique Id for the entire orderList
319 | # # 'limitClientOrderId': exchange.uuid(), # A unique Id for the limit order
320 | # # 'limitIcebergQty': exchangea.amount_to_precision(symbol, limit_iceberg_quantity),
321 | # # 'stopClientOrderId': exchange.uuid() # A unique Id for the stop loss/stop loss limit leg
322 | # # 'stopIcebergQty': exchange.amount_to_precision(symbol, stop_iceberg_quantity),
323 | # # 'newOrderRespType': 'ACK', # ACK, RESULT, FULL
324 | # })
325 |
326 | def market_close(
327 | self,
328 | order_info: MarketOrder,
329 | ):
330 | from exchange.pexchange import retry
331 |
332 | symbol = self.order_info.unified_symbol # self.parse_symbol(base, quote)
333 | close_amount = self.get_amount(order_info)
334 | if self.position_mode == "one-way":
335 | params = {"reduceOnly": True}
336 | elif self.position_mode == "hedge":
337 | if order_info.side == "buy":
338 | if order_info.is_entry:
339 | positionSide = "LONG"
340 | elif order_info.is_close:
341 | positionSide = "SHORT"
342 | elif order_info.side == "sell":
343 | if order_info.is_entry:
344 | positionSide = "SHORT"
345 | elif order_info.is_close:
346 | positionSide = "LONG"
347 | params = {"positionSide": positionSide}
348 |
349 | try:
350 | return retry(
351 | self.client.create_order,
352 | symbol,
353 | order_info.type.lower(),
354 | order_info.side,
355 | abs(close_amount),
356 | None,
357 | params,
358 | order_info=order_info,
359 | max_attempts=10,
360 | delay=0.1,
361 | instance=self,
362 | )
363 | except Exception as e:
364 | raise error.OrderError(e, self.order_info)
365 |
366 | def get_listen_key(self):
367 | url = "https://fapi.binance.com/fapi/v1/listenKey"
368 |
369 | listenkey = httpx.post(
370 | url, headers={"X-MBX-APIKEY": self.client.apiKey}
371 | ).json()["listenKey"]
372 | return listenkey
373 |
374 | def get_trades(self):
375 | is_futures = self.order_info.is_futures
376 | if is_futures:
377 | trades = self.client.fetch_my_trades()
378 | print(trades)
379 |
--------------------------------------------------------------------------------
/exchange/pexchange.py:
--------------------------------------------------------------------------------
1 | import ccxt
2 | import ccxt.async_support as ccxt_async
3 | import httpx
4 | from fastapi import HTTPException
5 | from pydantic import BaseModel
6 | from .binance import Binance
7 | from .upbit import Upbit
8 | from .bybit import Bybit
9 | from .bitget import Bitget
10 | from .okx import Okx
11 | from .stock import KoreaInvestment
12 | from exchange.utility import settings, log_message
13 | from .database import db
14 | from typing import Literal
15 | import pendulum
16 | import time
17 | from devtools import debug
18 | from loguru import logger
19 |
20 |
21 | from .model import CRYPTO_EXCHANGES, STOCK_EXCHANGES, MarketOrder
22 |
23 |
24 | class Exchange(BaseModel):
25 | UPBIT: Upbit | None = None
26 | BINANCE: Binance | None = None
27 | BYBIT: Bybit | None = None
28 | BITGET: Bitget | None = None
29 | OKX: Okx | None = None
30 | KIS1: KoreaInvestment | None = None
31 | KIS2: KoreaInvestment | None = None
32 | KIS3: KoreaInvestment | None = None
33 | KIS4: KoreaInvestment | None = None
34 |
35 | class Config:
36 | arbitrary_types_allowed = True
37 |
38 |
39 | payload = {}
40 |
41 |
42 | def get_exchange(exchange_name: str, kis_number=None):
43 | global payload
44 | if exchange_name in CRYPTO_EXCHANGES:
45 | KEY, SECRET, PASSPHRASE = check_key(exchange_name)
46 | if not payload.get(exchange_name):
47 | if exchange_name in ("BITGET", "OKX"):
48 | payload |= {
49 | exchange_name: globals()[exchange_name.title()](
50 | KEY, SECRET, PASSPHRASE
51 | )
52 | }
53 | else:
54 | if not payload.get(exchange_name):
55 | payload |= {
56 | exchange_name: globals()[exchange_name.title()](KEY, SECRET)
57 | }
58 |
59 | return Exchange(**payload)
60 |
61 | elif exchange_name in ("KRX", "NASDAQ", "NYSE", "AMEX"):
62 | _kis = f"KIS{kis_number}"
63 | key = check_key(_kis)
64 | KEY, SECRET, ACCOUNT_NUMBER, ACCOUNT_CODE = key
65 | if not payload.get(_kis):
66 | payload |= {
67 | _kis: globals()["KoreaInvestment"](
68 | KEY, SECRET, ACCOUNT_NUMBER, ACCOUNT_CODE, kis_number
69 | )
70 | }
71 | exchange = Exchange(**payload)
72 | kis: KoreaInvestment = exchange.dict()[_kis]
73 | kis.auth()
74 | return kis
75 |
76 |
77 | def get_bot(
78 | exchange_name: Literal[
79 | "BINANCE", "UPBIT", "BYBIT", "BITGET", "KRX", "NASDAQ", "NYSE", "AMEX", "OKX"
80 | ],
81 | kis_number=None,
82 | ) -> Binance | Upbit | Bybit | Bitget | KoreaInvestment | Okx:
83 | exchange_name = exchange_name.upper()
84 | if exchange_name in CRYPTO_EXCHANGES:
85 | return get_exchange(exchange_name, kis_number).dict()[exchange_name]
86 | elif exchange_name in STOCK_EXCHANGES:
87 | return get_exchange(exchange_name, kis_number)
88 |
89 |
90 | def check_key(exchange_name):
91 | settings_dict = settings.dict()
92 | if exchange_name in CRYPTO_EXCHANGES:
93 | key = settings_dict.get(exchange_name + "_KEY")
94 | secret = settings_dict.get(exchange_name + "_SECRET")
95 | passphrase = settings_dict.get(exchange_name + "_PASSPHRASE")
96 | if not key:
97 | msg = f"{exchange_name}_KEY가 없습니다"
98 | log_message(msg)
99 | raise HTTPException(status_code=404, detail=msg)
100 | elif not secret:
101 | msg = f"{exchange_name}_SECRET가 없습니다"
102 | log_message(msg)
103 | raise HTTPException(status_code=404, detail=msg)
104 | return key, secret, passphrase
105 | elif exchange_name in ("KIS1", "KIS2", "KIS3", "KIS4"):
106 | key = settings_dict.get(f"{exchange_name}_KEY")
107 | secret = settings_dict.get(f"{exchange_name}_SECRET")
108 | account_number = settings_dict.get(f"{exchange_name}_ACCOUNT_NUMBER")
109 | account_code = settings_dict.get(f"{exchange_name}_ACCOUNT_CODE")
110 | if key and secret and account_number and account_code:
111 | return key, secret, account_number, account_code
112 | else:
113 | raise Exception(f"{exchange_name} 키가 없습니다")
114 |
115 |
116 | def get_today_timestamp(timezone="Asia/Seoul"):
117 | today = pendulum.today(timezone)
118 | today_start = int(today.start_of("day").timestamp() * 1000)
119 | today_end = int(today.end_of("day").timestamp() * 1000)
120 | return today_start, today_end
121 |
122 |
123 | def retry(
124 | func,
125 | *args,
126 | order_info: MarketOrder,
127 | max_attempts=5,
128 | delay=1,
129 | instance: Binance | Bybit | Bitget | Upbit | Okx = None,
130 | ):
131 | attempts = 0
132 |
133 | while attempts < max_attempts:
134 | try:
135 | result = func(*args) # 함수 실행
136 | return result
137 | except Exception as e:
138 | logger.error(f"에러 발생: {str(e)}")
139 | attempts += 1
140 | if func.__name__ == "create_order" or func.__name__ == "set_leverage":
141 | if order_info.exchange in ("BINANCE"):
142 | if "Internal error" in str(e):
143 | time.sleep(delay) # 재시도 간격 설정
144 | elif "Server is currently overloaded" in str(e):
145 | time.sleep(delay)
146 | elif "position side does not match" in str(e):
147 | if instance.position_mode == "one-way":
148 | instance.position_mode = "hedge"
149 | if order_info.side == "buy":
150 | if order_info.is_entry:
151 | positionSide = "LONG"
152 | elif order_info.is_close:
153 | positionSide = "SHORT"
154 |
155 | elif order_info.side == "sell":
156 | if order_info.is_entry:
157 | positionSide = "SHORT"
158 | elif order_info.is_close:
159 | positionSide = "LONG"
160 |
161 |
162 | params = {"positionSide": positionSide}
163 | elif instance.position_mode == "hedge":
164 | instance.position_mode = "one-way"
165 | if order_info.is_entry:
166 | params = {}
167 | elif order_info.is_close:
168 | params = {"reduceOnly": True}
169 |
170 | args = tuple(
171 | params if i == 5 else arg for i, arg in enumerate(args)
172 | )
173 |
174 | else:
175 | attempts = max_attempts
176 | elif order_info.exchange in ("BYBIT"):
177 | if "position idx not match position mode" in str(e):
178 | if instance.position_mode == "one-way":
179 | instance.position_mode = "hedge"
180 | position_idx = None
181 | if order_info.side == "buy":
182 | if order_info.is_entry:
183 | position_idx = 1
184 | params = {"position_idx": position_idx}
185 | elif order_info.is_close:
186 | position_idx = 2
187 | params = {
188 | "reduceOnly": True,
189 | "position_idx": position_idx,
190 | }
191 | elif order_info.side == "sell":
192 | if order_info.is_entry:
193 | position_idx = 2
194 | params = {"position_idx": position_idx}
195 | elif order_info.is_close:
196 | position_idx = 1
197 | params = {
198 | "reduceOnly": True,
199 | "position_idx": position_idx,
200 | }
201 | elif instance.position_mode == "hedge":
202 | instance.position_mode = "one-way"
203 | if order_info.is_entry:
204 | params = {"position_idx": 0}
205 | elif order_info.is_close:
206 | params = {"reduceOnly": True, "position_idx": 0}
207 |
208 | args = tuple(
209 | params if i == 5 else arg for i, arg in enumerate(args)
210 | )
211 | elif "check your server timestamp" in str(e):
212 | bybit: Bybit = instance
213 | bybit.load_time_difference()
214 | else:
215 | attempts = max_attempts
216 |
217 | elif order_info.exchange in ("OKX"):
218 | if "posSide error" in str(e):
219 | params = {}
220 |
221 | if instance.position_mode == "one-way":
222 | instance.position_mode = "hedge"
223 | pos_side = "net"
224 | if order_info.is_futures and order_info.side == "buy":
225 | if order_info.is_entry:
226 | pos_side = "long"
227 | elif order_info.is_close:
228 | pos_side = "short"
229 | elif order_info.is_futures and order_info.side == "sell":
230 | if order_info.is_entry:
231 | pos_side = "short"
232 | elif order_info.is_close:
233 | pos_side = "long"
234 |
235 | if (
236 | order_info.margin_mode is None
237 | or order_info.margin_mode == "isolated"
238 | ):
239 | params |= {"posSide": pos_side, "tdMode": "isolated"}
240 | elif order_info.margin_mode == "cross":
241 | params |= {"posSide": pos_side, "tdMode": "cross"}
242 | elif instance.position_mode == "hedge":
243 | instance.position_mode = "one-way"
244 | if order_info.is_entry:
245 | params |= {}
246 | elif order_info.is_close:
247 | params |= {"reduceOnly": True}
248 |
249 | if order_info.is_entry:
250 | if order_info.leverage is None:
251 | instance.set_leverage(1, order_info.unified_symbol)
252 | else:
253 | instance.set_leverage(
254 | order_info.leverage, order_info.unified_symbol
255 | )
256 | if order_info.margin_mode is None:
257 | params |= {"tdMode": "isolated"}
258 | else:
259 | params |= {"tdMode": order_info.margin_mode}
260 |
261 | args = tuple(
262 | params if i == 5 else arg for i, arg in enumerate(args)
263 | )
264 | else:
265 | attempts = max_attempts
266 | elif order_info.exchange in ("BITGET"):
267 | if "unilateral position" in str(e) or "hold side is null" in str(e) or "No position to close" in str(e):
268 | final_side = order_info.side
269 | margin_mode = args[-1].get("marginMode") or "isolated"
270 | if instance.position_mode == "hedge":
271 | instance.position_mode = "one-way"
272 | new_params = {"oneWayMode": True, "marginMode": margin_mode}
273 | args = tuple(
274 | new_params if i == 5 else arg
275 | for i, arg in enumerate(args)
276 | )
277 | elif instance.position_mode == "one-way":
278 | instance.position_mode = "hedge"
279 |
280 | if order_info.is_entry:
281 | if order_info.is_futures:
282 | if order_info.is_buy:
283 | trade_side = "Open"
284 | else:
285 | trade_side = "open"
286 | new_params = { "tradeSide": trade_side, "marginMode": margin_mode}
287 | elif order_info.is_close:
288 | if order_info.side == "sell":
289 | final_side = "buy"
290 | elif order_info.side == "buy":
291 | final_side = "sell"
292 | new_params = {"reduceOnly": True, "tradeSide":"close"}
293 |
294 | args = tuple(
295 | new_params if i == 5 else arg
296 | for i, arg in enumerate(args)
297 | )
298 |
299 | args = tuple(
300 | final_side if i == 2 else arg
301 | for i, arg in enumerate(args)
302 | )
303 |
304 |
305 | elif "two-way positions" in str(e):
306 | if instance.position_mode == "hedge":
307 | instance.position_mode = "one-way"
308 | new_side = order_info.side + "_single"
309 | new_params = {"reduceOnly": True, "side": new_side}
310 | args = tuple(
311 | new_side if i == 2 else arg
312 | for i, arg in enumerate(args)
313 | )
314 | args = tuple(
315 | new_params if i == 5 else arg
316 | for i, arg in enumerate(args)
317 | )
318 | elif instance.position_mode == "one-way":
319 | instance.position_mode = "hedge"
320 | if order_info.is_entry:
321 | new_params = {}
322 | elif order_info.is_close:
323 | new_params = {"reduceOnly": True}
324 | args = tuple(
325 | new_params if i == 5 else arg
326 | for i, arg in enumerate(args)
327 | )
328 | else:
329 | attempts = max_attempts
330 | else:
331 | attempts = max_attempts
332 |
333 | if attempts == max_attempts:
334 | raise
335 | else:
336 | logger.error(f"재시도 {max_attempts - attempts}번 남았음")
337 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------