tradingcharts / app.py
Renjith Karimattathil SASIDHARAN
Show active trades
bef076e
import os
import gradio as gr
import pandas as pd
from pymongo import MongoClient
from datetime import datetime, timedelta
import plotly.express as px
import plotly.graph_objects as go
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_HOST = os.getenv("DB_HOST")
client = MongoClient(host=f"mongodb+srv://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/?retryWrites=true&w=majority")
#select database
db = client['algotrading']
#select the collection within the database
def fetch_all_strategy():
global db
delta = datetime.now() - timedelta(days=7)
orders_t = db.orders
strategies = pd.DataFrame(list(orders_t.find({}, {"strategy_id":1, "created_ts": 1})))
strategies['created_ts'] = pd.to_datetime(strategies['created_ts'])
strategies = strategies[~(strategies['created_ts'] < delta)]
return list(strategies['strategy_id'].unique())
def fetch_orders_for_strategy(strategy):
global db
orders_t = db.orders
#convert entire collection to Pandas dataframe
orders = pd.DataFrame(list(orders_t.find({"strategy_id": strategy})))
# orders = orders.dropna(axis=0, subset=['open_price', 'close_price'])
orders['open_price'] = orders['open_price'].astype(str).astype(float)
orders['close_price'] = orders['close_price'].astype(str).astype(float)
# orders['created_ts'] = pd.to_datetime(orders['created_ts'])
orders['created_ts'] = pd.to_datetime(orders['created_ts'])
orders['closed_ts'] = pd.to_datetime(orders['closed_ts'])
orders['profit'] = orders['close_price'] - orders['open_price']
orders['profit'] = orders['profit'].round(2)
orders['created_date'] = orders['created_ts'].dt.date
orders['ticker_open_price'] = pd.to_numeric(orders['ticker_open_price'], errors="coerce")
orders['ticker_close_price'] = pd.to_numeric(orders['ticker_close_price'], errors="coerce")
orders['ticker_open_price'] = orders['ticker_open_price'].astype(int, errors='ignore')
orders['ticker_close_price'] = orders['ticker_close_price'].astype(int, errors='ignore')
orders['ticker_delta'] = orders['ticker_close_price'] - orders['ticker_open_price']
orders['ticker_delta'] = orders['ticker_delta'].round(2)
orders['ticker_delta'] = orders.apply(lambda o: o['ticker_delta'] if o['market_position'] == 'long' else -o['ticker_delta'], axis=1)
#market_position
orders = orders.sort_values(by='created_ts', ascending=False)
return orders
def create_latest_profit_plot(strategy, profits):
if profits not in ["Profits", "Trades"]:
return gr.update(visible=False)
orders = fetch_orders_for_strategy(strategy)
latest_day = orders[orders['strategy_id'] == strategy].sort_values(by='created_ts', ascending=False)['created_date'].unique()[0]
cumsum = orders[(orders['created_date'] == latest_day) & (orders['strategy_id'] == strategy)] \
.sort_values(by='created_ts', ascending=True) \
.groupby(['strategy_id', 'created_ts'])['profit'].sum() \
.groupby(level=0).cumsum().reset_index()
plot = px.line(cumsum, x="created_ts", y="profit",
title=f"Profits for day for {strategy}")
plot.update_layout(legend=dict(x=0.5, y=0.99), title_x=0.5, legend_title_text="")
trades_table = go.Figure(data=[go.Table(
header=dict(values=list(['Created', 'Closed', 'Market Type', 'Symbol', 'Qty', 'Ticker Delta', 'Open', 'Close', 'Profit']),
align='left'),
cells=dict(values=[
orders.created_ts.dt.strftime("%d-%b %H:%M"),
orders.closed_ts.dt.strftime("%d-%b %H:%M"),
# orders.ticker_open_price,
# orders.ticker_close_price,
orders.market_type,
orders.tradingsymbol,
orders.quantity,
orders.ticker_delta,
orders.open_price,
orders.close_price,
orders.profit])
)
])
profits_table = go.Figure(data=[go.Table(
header=dict(values=list(['Created', 'Closed', 'Market Type', 'Qty', 'Ticker Delta', 'Profit']),
align='left'),
cells=dict(values=[
orders.created_ts.dt.strftime("%d-%b %H:%M"),
orders.closed_ts.dt.strftime("%d-%b %H:%M"),
orders.market_type,
orders.quantity,
orders.ticker_delta,
orders.profit])
)
])
if profits == 'Profits':
return [gr.update(value=plot, visible=True), gr.update(value=profits_table, visible=True), gr.update(value=plot, visible=False)]
if profits == 'Trades':
return [gr.update(value=plot, visible=False), gr.update(value=profits_table, visible=False), gr.update(value=trades_table, visible=True)]
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
with gr.Box():
gr.Markdown("## Select strategies to display")
strategy = gr.Radio(choices=fetch_all_strategy(), label="")
with gr.Column():
with gr.Box():
gr.Markdown("## Select graphs to display")
type = gr.Radio(choices=["Profits", "Trades"], label="", value="Profits")
with gr.Row():
fetch = gr.Button(value="Fetch")
with gr.Row():
with gr.Column():
profits_plot = gr.Plot(visible=False)
with gr.Row():
profits_table = gr.Plot(visible=False)
with gr.Row():
with gr.Column():
trades_plot = gr.Plot(visible=False)
fetch.click(create_latest_profit_plot, inputs=[strategy, type], outputs=[profits_plot, profits_table, trades_plot])
# fetch.click(create_latest_profit_plot, inputs=[strategy, type], outputs=trades_plot)
# fetch.click(create_issue_plot, inputs=[libraries, issues], outputs=issue_plot)
if __name__ == "__main__":
demo.launch()