Skip to content

Commit

Permalink
Gettings crypto works
Browse files Browse the repository at this point in the history
  • Loading branch information
spencer-sliffe committed Dec 8, 2024
1 parent c2b63dd commit 1d667df
Show file tree
Hide file tree
Showing 8 changed files with 222 additions and 174 deletions.
6 changes: 3 additions & 3 deletions Backend/kobrastocks/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ class FavoriteCrypto(db.Model):
__tablename__ = 'favorite_crypto'

id = db.Column(db.Integer, primary_key=True)
crypto_id = db.Column(db.String(20), nullable=False)
ticker = db.Column(db.String(10), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)

Expand All @@ -99,7 +100,6 @@ class WatchedCrypto(db.Model):
__tablename__ = 'watched_crypto'

id = db.Column(db.Integer, primary_key=True)
crypto_id = db.Column(db.String(20), nullable=False)
ticker = db.Column(db.String(10), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)


user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
11 changes: 6 additions & 5 deletions Backend/kobrastocks/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,15 +226,16 @@ def get_hot_crypto_currencies():
price = crypto.get('current_price')
if price and (user_budget is None or price <= user_budget):
hot_crypto_data.append({
"crypto_id": crypto.get('id'),
"ticker": crypto.get('symbol'),
"name": crypto.get('name'),
"price": price,
"market_cap": crypto.get('market_cap'),
"24h_change": crypto.get('price_change_percentage_24h')
})

# Limit to top 10
hot_crypto_data = hot_crypto_data[:10]
# Limit to top 20
hot_crypto_data = hot_crypto_data[:20]

if not hot_crypto_data:
return jsonify({'message': 'No hot cryptocurrencies found within your budget. Showing top cryptocurrencies.'}), 200
Expand All @@ -248,10 +249,10 @@ def get_hot_crypto_currencies():

@main.route('/api/crypto_data', methods=['GET'])
def crypto_data():
ticker = request.args.get('ticker', type=str)
crypto_data = get_crypto_data(ticker)
crypto_id = request.args.get('crypto_id', type=str)
crypto_data = get_crypto_data(crypto_id)
if crypto_data is None:
return jsonify({'error': f"No data found for ticker {ticker}"}), 404
return jsonify({'error': f"No data found for ticker {crypto_id}"}), 404
return jsonify(crypto_data_schema.dump(crypto_data))


Expand Down
1 change: 1 addition & 0 deletions Backend/kobrastocks/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ class CryptoDataSchema(Schema):
Ensures that the API response is formatted properly.
"""
ticker = fields.Str(required=True)
crypto_id = fields.Str(required=True)
name = fields.Str(required=True)
price = fields.Float(required=True)
market_cap = fields.Float(required=False)
Expand Down
13 changes: 7 additions & 6 deletions Backend/kobrastocks/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -687,25 +687,26 @@ def get_stock_results_data(ticker):
return None


def get_crypto_data(ticker):
def get_crypto_data(crypto_id):
"""
Fetches data for a specific cryptocurrency using the CoinGecko API.
"""
try:
# CoinGecko API base URL
url = f"https://api.coingecko.com/api/v3/coins/{ticker}"
url = f"https://api.coingecko.com/api/v3/coins/{crypto_id}"

# Make the API request
response = requests.get(url)
if response.status_code != 200:
current_app.logger.error(f"Failed to fetch data for crypto ticker {ticker}")
current_app.logger.error(f"Failed to fetch data for crypto id: {crypto_id}")
return None

data = response.json()

print(data)
# Extract relevant fields
crypto_data = {
"ticker": data.get("id"),
"id": crypto_id,
"ticker": data.get("ticker"),
"name": data.get("name"),
"price": data.get("market_data", {}).get("current_price", {}).get("usd"),
"market_cap": data.get("market_data", {}).get("market_cap", {}).get("usd"),
Expand All @@ -722,5 +723,5 @@ def get_crypto_data(ticker):
return crypto_data

except Exception as e:
current_app.logger.error(f"Error fetching crypto data for {ticker}: {e}")
current_app.logger.error(f"Error fetching crypto data for {crypto_id}: {e}")
return None
36 changes: 19 additions & 17 deletions Backend/kobrastocks/user_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,25 +149,26 @@ def get_crypto_favorites():
def add_crypto_favorite():
user_id = get_jwt_identity()
data = request.get_json()
crypto_id = data.get('crypto_id')
ticker = data.get('ticker')
if not ticker:
return jsonify({'error': 'Ticker is required'}), 400
if not crypto_id:
return jsonify({'error': 'id is required'}), 400

existing = FavoriteCrypto.query.filter_by(user_id=user_id, ticker=ticker).first()
existing = FavoriteCrypto.query.filter_by(user_id=user_id, crypto_id=crypto_id, ticker=ticker).first()
if existing:
return jsonify({'message': 'Crypto already in favorites'}), 200

favorite = FavoriteCrypto(user_id=user_id, ticker=ticker)
favorite = FavoriteCrypto(user_id=user_id, crypto_id=crypto_id, ticker=ticker)
db.session.add(favorite)
db.session.commit()
return jsonify({'message': 'Crypto added to favorites'}), 201


@user.route('/api/crypto_favorites/<string:ticker>', methods=['DELETE'])
@user.route('/api/crypto_favorites/<string:crypto_id>', methods=['DELETE'])
@jwt_required()
def remove_crypto_favorite(ticker):
def remove_crypto_favorite(crypto_id):
user_id = get_jwt_identity()
favorite = FavoriteCrypto.query.filter_by(user_id=user_id, ticker=ticker).first()
favorite = FavoriteCrypto.query.filter_by(user_id=user_id, crypto_id=crypto_id).first()
if favorite:
db.session.delete(favorite)
db.session.commit()
Expand All @@ -192,27 +193,28 @@ def get_crypto_watchlist():
def add_crypto_to_watchlist():
user_id = get_jwt_identity()
data = request.get_json()
crypto_id = data.get('crypto_id')
ticker = data.get('ticker')
if not ticker:
return jsonify({'error': 'Ticker is required'}), 400
if not crypto_id:
return jsonify({'error': 'crypto_id is required'}), 400

existing = WatchedCrypto.query.filter_by(user_id=user_id, ticker=ticker).first()
existing = WatchedCrypto.query.filter_by(user_id=user_id, crypto_id=crypto_id, ticker=ticker).first()
if existing:
return jsonify({'message': 'Crypto already in watchlist'}), 200

watch_stock = WatchedCrypto(user_id=user_id, ticker=ticker)
db.session.add(watch_stock)
watch_crypto = WatchedCrypto(user_id=user_id, crypto_id=crypto_id, ticker=ticker)
db.session.add(watch_crypto)
db.session.commit()
return jsonify({'message': 'Crypto added to watchlist'}), 201


@user.route('/api/crypto_watchlist/<string:ticker>', methods=['DELETE'])
@user.route('/api/crypto_watchlist/<string:crypto_id>', methods=['DELETE'])
@jwt_required()
def remove_crypto_from_watchlist(ticker):
def remove_crypto_from_watchlist(crypto_id):
user_id = get_jwt_identity()
watch_stock = WatchedCrypto.query.filter_by(user_id=user_id, ticker=ticker).first()
if watch_stock:
db.session.delete(watch_stock)
watch_crypto = WatchedCrypto.query.filter_by(user_id=user_id, crypto_id=crypto_id).first()
if watch_crypto:
db.session.delete(watch_crypto)
db.session.commit()
return jsonify({'message': 'Crypto removed from watchlist'}), 200
else:
Expand Down
38 changes: 38 additions & 0 deletions Backend/migrations/versions/d30ffe8189ab_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""empty message
Revision ID: d30ffe8189ab
Revises: 9c57f23e362e
Create Date: 2024-12-08 12:03:05.202393
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'd30ffe8189ab'
down_revision = '9c57f23e362e'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('favorite_crypto', schema=None) as batch_op:
batch_op.add_column(sa.Column('crypto_id', sa.String(length=20), nullable=False))

with op.batch_alter_table('watched_crypto', schema=None) as batch_op:
batch_op.add_column(sa.Column('crypto_id', sa.String(length=20), nullable=False))

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('watched_crypto', schema=None) as batch_op:
batch_op.drop_column('crypto_id')

with op.batch_alter_table('favorite_crypto', schema=None) as batch_op:
batch_op.drop_column('crypto_id')

# ### end Alembic commands ###
Loading

0 comments on commit 1d667df

Please sign in to comment.