This repository was archived by the owner on Nov 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrade_stats.py
More file actions
54 lines (41 loc) · 1.52 KB
/
trade_stats.py
File metadata and controls
54 lines (41 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import os
import pymongo
from datetime import datetime
# MongoDB connection string from environment variables
MONGO_CONN_STRING = os.getenv('MONGO_CONN_STRING')
# Create a MongoDB client
client = pymongo.MongoClient(MONGO_CONN_STRING)
# Select your database
db = client['your_database_name'] # Replace 'your_database_name' with the name of your database
# Select the collection
trades_collection = db.trades
def record_trade(symbol, qty, price, date=None):
"""
Record a trade in MongoDB.
"""
# Set the default date as current datetime if not provided
if date is None:
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# Check if trade already exists
existing_trade = trades_collection.find_one({'symbol': symbol, 'qty': qty, 'price': price, 'date': date})
if existing_trade:
return # Trade already exists, so don't record it
# Create a new trade document
new_trade = {
'symbol': symbol,
'qty': qty,
'price': price,
'date': date
}
# Insert the new trade document into the collection
trades_collection.insert_one(new_trade)
def download_trades():
"""
Retrieve the trades from MongoDB and return them as a list of dictionaries.
"""
trades = list(trades_collection.find({}, {'_id': 0})) # Exclude the _id field
return trades
# # Example usage
# record_trade('AAPL', 10, 150) # Record a new trade
# trades = download_trades() # Retrieve all trades
# print(trades)