File size: 7,986 Bytes
f9debde
1903f10
 
5f562e1
 
 
acd99fc
5f562e1
 
c0ee503
5f562e1
 
 
 
 
 
 
 
49c7977
83aa40e
0675335
babeff9
822d611
5f562e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f7c831
5f562e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822d611
e2a1109
 
822d611
 
 
c47cda9
a384af7
822d611
a384af7
 
822d611
 
a384af7
822d611
 
ee36e57
 
 
a384af7
ee36e57
822d611
e2a1109
 
822d611
 
ee36e57
5f562e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a384af7
5f562e1
 
 
 
 
b2f28ee
5f562e1
2a29624
5f562e1
0b7ea59
 
e34d93e
0b7ea59
5f562e1
49c7977
5f562e1
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import streamlit as st
st.set_page_config(layout="wide")

import pandas as pd
from tradingview_screener import Scanner, Query, Column
import pandas as pd
import os
import requests
from datetime import datetime
from time import sleep
from pytz import timezone
day1_local = datetime.now(timezone("Asia/Kolkata"))
day10 = day1_local.strftime('%H:%M:%S')
from datetime import datetime
from pytz import timezone
day2_local = datetime.now(timezone("Asia/Kolkata"))
day2 = day2_local.strftime('%d-%m-%Y')

placeholder = st.empty()
placeholder1 = st.empty()

csv_file_path = 'data.csv'
overall_data = 'overall_data.csv'

class YourClass:
    def crosses_below(self, column, other):
        return {'left': column.name, 'operation': 'crosses_below', 'right': column._extract_value(other)}

    def crosses_above(self, column, other):
        return {'left': column.name, 'operation': 'crosses_above', 'right': column._extract_value(other)}

time_intervals = ['1','5','15','30']

def setup_ui():
    limit = 1
    price_from = 2000
    price_to = 2500
    return price_from, price_to, limit

def main():
    price_from, price_to,limit = setup_ui()
    temp = pd.DataFrame()

    if True:
        final_df = pd.DataFrame()
        for x in time_intervals:
            your_instance = YourClass()

            df_bullish = (Query()
                          .select('Exchange', f'close|{x}', f'volume|{x}', f'ADX-DI|{x}', f'ADX+DI|{x}')
                          .where(your_instance.crosses_below(Column(f'ADX-DI|{x}'), Column(f'ADX+DI|{x}')),
                                 Column(f'close|{x}').between(price_from, price_to))
                          .order_by(f'volume|{x}', ascending=False)
                          .limit(limit))

            df_bearish = (Query()
                          .select('Exchange', f'close|{x}', f'volume|{x}', f'ADX-DI|{x}', f'ADX+DI|{x}')
                          .where(your_instance.crosses_above(Column(f'ADX-DI|{x}'), Column(f'ADX+DI|{x}')),
                                 Column(f'close|{x}').between(price_from, price_to))
                          .order_by(f'volume|{x}', ascending=False)
                          .limit(limit))

            df_bullish = df_bullish.set_markets('india').get_scanner_data()[1]
            df_bullish = df_bullish[df_bullish['exchange'] == 'NSE']
            df_bullish['trend'] = f'Buy|{x}m'
            df_bullish['Entry_time'] = day1_local.strftime('%H:%M:%S')
            df_bullish['Entry_price'] = df_bullish[f'close|{x}']
            df_bullish = df_bullish[['ticker', 'trend', 'Entry_time', 'Entry_price']]

            df_bearish = df_bearish.set_markets('india').get_scanner_data()[1]
            df_bearish = df_bearish[df_bearish['exchange'] == 'NSE']
            df_bearish['trend'] = f'Sell|{x}m'
            df_bearish['Entry_time'] = day1_local.strftime('%H:%M:%S')
            df_bearish['Entry_price'] = df_bearish[f'close|{x}']
            df_bearish = df_bearish[['ticker', 'trend', 'Entry_time', 'Entry_price']]

            merge_cols = ['ticker', 'trend', 'Entry_time', 'Entry_price']
            merged_df = pd.concat([df_bullish, df_bearish], ignore_index=True)
            #merged_df = pd.merge(df_bullish, df_bearish, on=merge_cols, how='outer')
            final_df = pd.concat([merged_df, final_df], ignore_index=True)

        # Fetch data already stored in the CSV file
        try:
            stored_data = pd.read_csv(csv_file_path)
        except FileNotFoundError:
            stored_data = pd.DataFrame(columns=final_df.columns)

        # Convert 'ticker' columns to string data type
        final_df['ticker'] = final_df['ticker'].astype(str)
        stored_data['ticker'] = stored_data['ticker'].astype(str)

        # Remove rows from final_df that are already in the CSV file based on the 'ticker' column
        final_df = final_df[~final_df['ticker'].isin(stored_data['ticker'])]

        # Store new rows in the CSV file
        final_df.to_csv(csv_file_path, mode='a', header=False, index=False)
        print(final_df)
def Report():
    data = pd.read_csv(csv_file_path)
    data['Ltp'] = ''
    ticker_list = data['ticker'].tolist()
    q = Query().select('close')
    try:
        result = q.set_tickers(*ticker_list).get_scanner_data()[1]
        result.set_index('ticker', inplace=True)
        data.set_index('ticker', inplace=True)
        data['Ltp'] = result['close']
        data.reset_index(inplace=True)

        # Calculate P/L and P/L percentage
        data['Qty'] = int(10)
        data['Inv_Amount'] = data['Qty'] * data['Entry_price']

        data['P/L'] = (data['Ltp'] - data['Entry_price']) * data['Qty']
        data['P/L'] = round(data['P/L'].astype('float'),2)
        data['P/L %'] = ((data['Ltp'] - data['Entry_price']) / data['Entry_price']) * 100
        data['P/L %'] = round(data['P/L %'].astype('float'),2)
        # Add new columns for trade result and win/loss
        data['Result'] = 'Neutral'
        data['Win/Loss'] = 0  # 1 for win, 0 for loss

        # Identify winning trades
        win_condition = data['P/L'] > 0
        data.loc[win_condition, 'Result'] = 'Win'
        data.loc[win_condition, 'Win/Loss'] = 1

        # Identify losing trades
        loss_condition = data['P/L'] < 0
        data.loc[loss_condition, 'Result'] = 'Loss'

        # Calculate total number of winning and losing trades
        total_wins = data['Win/Loss'].sum()
        total_losses = len(data) - total_wins
        total_pl = data['P/L'].sum()

        # Print the updated dataframe
        col10 , col20 = st.columns(2,gap="small")
        with col10:
            with placeholder.container():
                from datetime import datetime
                from pytz import timezone
                local = datetime.now(timezone("Asia/Kolkata"))
                date =  local.strftime('⏰%I:%M:%S %p')
                col1 ,col2,col3 = st.columns(3,gap="small")
                with col1:
                    st.info(f'Total P/L: Rs.{int(total_pl)}')    
                with col2:
                    dat = f'Total Wins: {total_wins}'
                    st.success(dat)
                with col3:
                    dat1 = f'Total Losses: {total_losses}'
                    st.error(dat1)
                df = pd.read_csv('overall_data.csv')
                report = {'time' : date , 'Profit&Loss' : int(total_pl), 'Win': total_wins , 'Loss': total_losses}
                df = pd.concat([df, pd.DataFrame([report])], ignore_index=True)
                df.to_csv(overall_data,index = False) 
                st.line_chart(df, x="time", y="Profit&Loss")
                st.write(data)
        with col20:
            with placeholder1.container():   
                data10 = pd.read_csv(overall_data)
                st.write(data10)                
        
    except Exception as e:
     print(f"Error: {e}")



def clear_csv_data_without_header(file_path):
  import csv
  # Read the header from the existing file
  with open(file_path, 'r', newline='') as csvfile:
    csv_reader = csv.reader(csvfile)
    header = next(csv_reader, None)

  # Write the header back to the file
  with open(file_path, 'w', newline='') as csvfile:
      csv_writer = csv.writer(csvfile)
      if header:
        csv_writer.writerow(header)

if __name__ == "__main__":
    while True:     
      from datetime import datetime
      import time
      from pytz import timezone
      day = datetime.now(timezone("Asia/Kolkata"))
      current_time = day.time()
      if day.strptime("09:16:00", "%H:%M:%S").time() <= current_time <= day.strptime("18:16:00", "%H:%M:%S").time():
        main()
        sleep(5)
        Report()
      elif day.strptime("09:10:00", "%H:%M:%S").time() <= current_time <= day.strptime("09:12:00", "%H:%M:%S").time():
          clear_csv_data_without_header(csv_file_path)
          clear_csv_data_without_header(overall_data)
          sleep(120)
      else:
        st.write('Wait for Trading Time...!!')
        sleep(60)