Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added backend_copy/__init__.py
Empty file.
Binary file added backend_copy/__pycache__/crud.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/database.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/db.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/env.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/function.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/home.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/init.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/login.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/main.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/models.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/position.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/strategy.cpython-38.pyc
Binary file not shown.
Binary file added backend_copy/__pycache__/test.cpython-38.pyc
Binary file not shown.
105 changes: 105 additions & 0 deletions backend_copy/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = migrations

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =

# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = sqlite:///./bit4coin.db


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
Binary file added backend_copy/bit4coin.db
Binary file not shown.
32 changes: 32 additions & 0 deletions backend_copy/crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from models import User, Item
from datetime import datetime
from database import SessionLocal

# user_data = User(user_name="hife",
# password="1234",
# balance=67.2,
# api_key="123456789",
# api_secret="qwer",
# create_date=datetime.now())




Item_data = Item(symbol = "ETH/USDT",
position_type =1,
enter_time = datetime.now(),
close_time = datetime.now(),
entry_price = 3771.1,
purchase_price = 0.5,
eval_price = 450.2,
eval_PAL = -1.7,
revenue_rate = 2.3,
amount=0.00123,
profit_end = 33901.2,
loss_end=2627.9121,
onwer_id=1
)

db = SessionLocal()
db.add(Item_data)
db.commit()
23 changes: 23 additions & 0 deletions backend_copy/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker



SQLALCHEMY_DATABASE_URL = "sqlite:///./bit4coin.db"

engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()



def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
62 changes: 62 additions & 0 deletions backend_copy/domain/history/history_crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from models import Item
from sqlalchemy.orm import Session


from domain.history import history_schema
import datetime

# 가장 최근에 진입한 포지션의 정보를 불러옴
def get_item_list_first(db: Session):
item_list_first= db.query(Item).order_by(Item.enter_time.desc()).first()
print(item_list_first)
return [item_list_first] # 리스트 형태


# 가장 최근에 진입한 포지션을 제외한 정보를 불러옴
def get_item_list(db: Session):
item_list = db.query(Item).order_by(Item.enter_time.desc()).offset(1).all()
print(item_list)
return item_list



# db에 데이터를 넣는 과정
def create_item(db: Session, item_schema: history_schema.Item_schema): # item_schema의 타입을 올바르게 지정합니다.
Item_data = Item(symbol=item_schema.symbol,
position_type=item_schema.position_type,
enter_time=datetime.datetime.now(),
close_time=datetime.datetime.now(),
entry_price=item_schema.entry_price,
purchase_price=item_schema.purchase_price,
eval_price=item_schema.eval_price,
eval_PAL=item_schema.eval_PAL,
revenue_rate=item_schema.revenue_rate,
amount=item_schema.amount,
profit_end=item_schema.profit_end,
loss_end=item_schema.loss_end,
onwer_id=item_schema.onwer_id)

db.add(Item_data)
db.commit()
db.refresh(Item_data)

return Item_data # -> history_function.create_history

# 가장 상단의 데이터를 포지션 종료할 때 db에 저장
def update_item_first(db: Session, item_id: int, item_schema: history_schema.Item_schema):
# 가장 상단의 데이터
item_data = db.query(Item).filter(Item.id == item_id).first()

# 변동하는 데이터만 가져옴 : 다른 데이터는 변환 없음
if item_data:
item_data.eval_price = item_schema.eval_price
item_data.eval_PAL = item_schema.eval_PAL
item_data.revenue_rate = item_schema.revenue_rate

db.commit()
db.refresh(item_data)

return item_data
else:
return None

96 changes: 96 additions & 0 deletions backend_copy/domain/history/history_function.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from domain.history import history_crud, history_schema
from database import get_db
from fastapi import Depends
from sqlalchemy.orm import Session
from strategys.env import profit_percent, loss_percent
from strategys.function import get_cur_price

from models import Item

import datetime


# history를 자동매매의 내역을 DB로 옮기는 작업
# strategys.stratefy.strategy_1, 2 , 3의 포지션에 진입하는 if문 안에 들어갈 예정
def create_history(symbols, position, entry_price, amount, cur_price):
db = next(get_db()) # Depends 대신 직접 세션 객체 생성
if position["type"] == "long":
profit_end = entry_price + entry_price * profit_percent
loss_end = entry_price - entry_price * loss_percent
elif position["type"] =="short":
profit_end = entry_price - entry_price * profit_percent
loss_end = entry_price + entry_price * profit_percent

# data 가공
item_data = {
"symbol": symbols,
"position_type": position["type"],
"enter_time": datetime.datetime.now().isoformat(),
"close_time": datetime.datetime.now().isoformat(),
"entry_price": entry_price,
"cur_price": cur_price,
"purchase_price": amount * entry_price , # amount * current_price
"eval_price": amount * cur_price, # amount * current_price
"eval_PAL": entry_price - cur_price, # entry_price - current_price
"revenue_rate": round(((cur_price - entry_price) / cur_price) * 100, 2) , # round(((entry_price - current_price) / current_price) * 100, 2)
"amount": amount,
"profit_end": profit_end,
"loss_end": loss_end,
"onwer_id": 0
}
# db에 넣기 위해 우리가 정의한 schema 형식에 맞게 데이터 변환
item_schema = history_schema.Item_schema(**item_data)

# db에 데이터를 넣음
created_item = history_crud.create_item(db, item_schema)

print(created_item)

# position 청산할 때 마지막 값을 바탕으로 DB에 업데이트
# strategys.stratefy.strategy_1, 2 , 3의 포지션을 청산하는 if문 안에 들어갈 예정
def update_history(cur_price):
db = next(get_db()) # Directly creating a session object

# Fetch the most recent item from the database
item_data = db.query(Item).order_by(Item.id.desc()).first()
if item_data:
# Calculate new values
eval_price = round(item_data.amount * cur_price, 2)
eval_PAL = round(cur_price - item_data.entry_price, 2)
revenue_rate = round(((cur_price - item_data.entry_price) / cur_price) * 100, 2)
close_time = datetime.datetime.now()

# data 변환
item_schema = history_schema.Item_schema(
symbol=item_data.symbol,
position_type=item_data.position_type,
entry_price=item_data.entry_price,
purchase_price=item_data.purchase_price,
eval_price=eval_price, # 변동하는 값
eval_PAL=eval_PAL, # 변동하는 값
revenue_rate=revenue_rate, # 변동하는 값
amount=item_data.amount,
profit_end=item_data.profit_end,
loss_end=item_data.loss_end,
onwer_id=item_data.onwer_id,
enter_time=item_data.enter_time,
close_time=close_time # 변동하는 값 : 종료 시간은 포지션이 종료된 시간으로 정의함
)

# 기존의 db table에 값을 update
updated_item = history_crud.update_item_first(db, item_data.id, item_schema)
print(updated_item)

return updated_item
else:
return None


# history 상단의 내용을 보여주는 함수 db 저장 x
# 변동하는 값들을 db에 저장하지 않고 호출만 함
def update_item(item, symbol, amount, entry_price): # ->
cur_price = get_cur_price(symbol)
item.eval_price = round(amount * cur_price, 4)
item.eval_PAL = round(entry_price - cur_price, 4)
item.revenue_rate = round(((cur_price - entry_price) / cur_price) * 100, 2)
return item # -> history_router.history_list_first
46 changes: 46 additions & 0 deletions backend_copy/domain/history/history_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from database import get_db
from domain.history import history_schema, history_crud
from models import Item

from domain.history.history_function import update_item
router = APIRouter(
prefix="/history",
)


# 1. history의 main_top은 1초마다 데이터를 들고올 예정 :
# 평가손익, 평가금액, 수익률을 실시간으로 업데이트 할 것(이건 DB에 실시간으로 저장 X) - > 청산할 때 DB에 저장
# -> 청산이후 list에서 반영된 값을 보여줌

# 2. 포지션을 청산할 때 평가손익, 평가금액, 수익률 등의 변동된 값을 업데이트하고 반영해줌


# history의 가장 최근의 item을 보여줌
@router.get("/list_first", response_model=List[history_schema.Item_schema])
def history_list_first(db: Session = Depends(get_db)):
_history_list_first = history_crud.get_item_list_first(db)

# current_price가 필요한 변수들은 DB의 내용을 조금 변화 시켜서 보여줌
item = _history_list_first[0]
print(item)
_history_list_first = update_item(item, item.symbol, item.amount, item.entry_price)

return [_history_list_first] # 리스트형태로 반환 - > history.js에서 fetch함

# 가장 최근의 item을 제외한 history의 목록을 보여줌
@router.get("/list", response_model=List[history_schema.Item_schema])
def history_list(db: Session = Depends(get_db)):
_history_list = history_crud.get_item_list(db) # 상단의 item을 제외한 데이터를 불러옴

return _history_list

# data를 넣는건데 실제로 사용은 안함
@router.post("/create_item", response_model=history_schema.Item_schema)
def create_item(item_schema: history_schema.Item_schema, db: Session = Depends(get_db)):
_create_item = history_crud.create_item(db, item_schema)
if _create_item is None:
raise HTTPException(status_code=400, detail="Failed to create item")
return _create_item
Loading