Free Python Codes

Welcome to Free Python Codes Library ๐Ÿš€

Here you can find ready-to-use Python scripts for:
โœ” Algo Trading
โœ” Telegram Bots
โœ” Historical Data Codes
โœ” Automation & APIs… etc.

โš ๏ธ Important Notice & Disclaimer

The Python codes shared on this page are provided free of charge for educational and learning purposes only.

While every effort is made to ensure accuracy and proper functionality, we do not guarantee that the code will produce the same results on every system or environment. Differences in system configuration, Python versions, libraries, APIs, or external data sources may affect the output.

Users are strongly advised to review, test, and cross-check all code outputs before using them in live environments, trading systems, or production setups.

By using these codes, you acknowledge that you are solely responsible for any results, outcomes, or losses, and we shall not be held liable for incorrect values, errors, or unintended behavior.

Telegram Bot Python Codes

import requests
import logging
import creds as cr

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# ========================== Configuration ==========================
bot_token = cr.bot_token
chat_id = cr.chat_id

# ========================== Telegram Sender ==========================
def send_telegram_message(bot_token, chat_id, message):
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"

    payload = {
    'chat_id': chat_id,
    'text': message
    }
    try:
        response = requests.post(url, data=payload)
        return response.json()
    except Exception as e:
        logging.error(f"Telegram Error: {e}")
        return None

send_telegram_message(bot_token, chat_id, "Hi.....This is Python")
send_telegram_message(bot_token, chat_id, f"Credentials:\n Bot_Token: {bot_token} \n๐Ÿ’ฅ\n Chat_ID: {chat_id} \n๐Ÿ’ฅ")

Fetching Session Token – Flattrade

# ========================== Initial Necessary Codes ==========================
file = open('flattrade_session_token.txt', 'r')
token = file.readline()
print (token)

import creds as cr
from api_helper import NorenApiPy
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

#start of our program
api = NorenApiPy()

usersession=token

ret = api.set_session(userid=cr.user_id, password=cr.pws, usertoken=usersession)

Historical Intra Day Data – Flattrade

# ========================== Initial Necessary Codes ==========================
with open('flattrade_session_token.txt', 'r') as file:
    token = file.readline().strip()

print (token)

import creds as cr
from api_helper import NorenApiPy
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

#start of our program
api = NorenApiPy()

usersession=token

ret = api.set_session(userid=cr.user_id, password=cr.pws, usertoken=usersession)



# ========================== Historical data Codes ==========================
from api_helper import NorenApiPy
import logging
from datetime import datetime, timedelta
import pandas as pd

exchange = 'NSE'  # 'NFO' for F&O
Time_Frame = 5    # enter the timeframe in which candle data you want

# ========================== Fetch Historical Option Data ==========================
def historical_data(token):
    try:
        start_time = (datetime.today() - timedelta(days=4)).replace(hour=9, minute=15, second=0, microsecond=0)
        ret = api.get_time_price_series(exchange=exchange, token=token, starttime=start_time.timestamp(), interval=Time_Frame)
        if not ret:
            return None
        df = pd.DataFrame(ret)
        df['intc'] = pd.to_numeric(df['intc'], errors='coerce')
        df['inth'] = pd.to_numeric(df['inth'], errors='coerce')
        df['intl'] = pd.to_numeric(df['intl'], errors='coerce')
        df['intv'] = pd.to_numeric(df['intv'], errors='coerce')
        
        return df
    except Exception as e:
        logging.error(f"Error fetching historical data for token {token}: {e}")
        return None

his_data = historical_data(token='22')
print (his_data)

Buy / Sell Trigger Code (In Function) – Flattrade

exchange = 'NSE' # 'BSE' 'NFO' 'BFO'
# ========================== Orders ==========================
def place_buy_order(Script, qty):
    try:
        ret = api.place_order(buy_or_sell='B', product_type='I',
                    exchange=exchange, tradingsymbol=Script, 
                    quantity=qty, discloseqty=0, price_type='MKT', price=0, trigger_price=None,
                    retention='DAY', remarks='Buy_Triggered')
        return ret
    except Exception as e:
        logging.error(f"Error placing buy order for {Script}: {e}")
        return None

def place_sell_order(Script, qty):
    try:
        ret = api.place_order(buy_or_sell='S', product_type='I',
                    exchange=exchange, tradingsymbol=Script, 
                    quantity=qty, discloseqty=0,price_type='MKT', price=0, trigger_price=None,
                    retention='DAY', remarks='Square-Off')
        return ret
    except Exception as e:
        logging.error(f"Error placing sell order for {Script}: {e}")
        return None

Market Time | Python Codes

import time
def myalgo():
    print (" my code is running")

while True:
    now = time.localtime()
    if now.tm_hour < 9 or (now.tm_hour == 9 and now.tm_min < 15):
        print (" waiting for market to start")
        time.sleep(60)
        continue

    elif now.tm_hour > 15 or (now.tm_hour == 15 and now.tm_min >= 30):
        print ("Market is off now.. bye bye see you tomarrow")
        break
    
    myalgo()
    time.sleep(5)

SMA vs EMA Indicator | Python Codes

df = his_data[::-1]
df['SMA20'] = round(df.intc.rolling(window=20).mean(), 2)
df['EMA09'] = round(df.intc.ewm(span=9, adjust=False).mean(), 2)
df[::-1]

EMA Manual | Python Codes

df = his_data[::-1]

# Calculate EMA...
def Ema(df):
    try:
        period = 9
        alpha = 2 / (period + 1)

        # Initialize EMA list
        ema = []

        # Loop to calculate EMA
        for i in range(len(df)):
            if i < period:
                # Not enough data to calculate EMA yet
                ema.append(None)
            elif i == period:
                # First EMA is the SMA of the first 'period' values
                sma = df['intc'].iloc[i - period:i].mean()
                ema.append(sma)
            else:
                # Apply EMA formula
                prev_ema = ema[-1]
                price = df['intc'].iloc[i]
                ema_val = alpha * price + (1 - alpha) * prev_ema
                ema.append(ema_val)
                
        # Assign to new column in df
        df['EMA_09'] = ema
        return df
    except Exception as e:
        logging.error(f"Error calculating EMA: {e}")
        return df

df_ema = Ema(df)
df_ema['EMA_09'] = round(df_ema['EMA_09'], 2)
df = df_ema[::-1]
df

SUPERTrend Indicator | Python Codes

import numpy as np

df = his_data[::-1]
def Supertrend(df, atr_period=10, multiplier=3.0):
    """
    Calculate the Supertrend indicator.
    """
    try:
        high = df['inth']
        low = df['intl']
        close = df['intc']

        # Calculate ATR using ewm like original code
        price_diffs = [high - low, 
                    high - close.shift(), 
                    close.shift() - low]
        true_range = pd.concat(price_diffs, axis=1)
        true_range = true_range.abs().max(axis=1)
        atr = true_range.ewm(alpha=1/atr_period, min_periods=atr_period).mean()

        hl2 = (high + low) / 2
        final_upperband = upperband = hl2 + (multiplier * atr)
        final_lowerband = lowerband = hl2 - (multiplier * atr)

        # Initialize supertrend array with boolean values like original code
        supertrend = [True] * len(df)

        for i in range(1, len(df.index)):
            curr, prev = i, i - 1

            if close.iloc[curr] > final_upperband.iloc[prev]:
                supertrend[curr] = True
            elif close.iloc[curr] < final_lowerband.iloc[prev]:
                supertrend[curr] = False
            else:
                supertrend[curr] = supertrend[prev]

                if supertrend[curr] == True and final_lowerband.iloc[curr] < final_lowerband.iloc[prev]:
                    final_lowerband.iat[curr] = final_lowerband.iat[prev]
                if supertrend[curr] == False and final_upperband.iloc[curr] > final_upperband.iloc[prev]:
                    final_upperband.iat[curr] = final_upperband.iat[prev]

            if supertrend[curr] == True:
                final_upperband.iat[curr] = np.nan
            else:
                final_lowerband.iat[curr] = np.nan

        # Add the calculated values to the DataFrame
        df['supertrend'] = supertrend
        df['final_lowerband'] = round(final_lowerband, 2)
        df['final_upperband'] = round(final_upperband, 2)

        return df
    except Exception as e:
        logging.error(f"Error calculating Supertrend: {e}")
        return df
    
df_sup = Supertrend(df)
df = df_sup[::-1]
sheet['B2'].value = df
df

ATR Indicator | Python Codes

def atr(df, window=14):

    # True Range
    high_low = df['inth'] - df['intl']
    high_close = (df['inth'] - df['intc'].shift(1)).abs()
    low_close = (df['intl'] - df['intc'].shift(1)).abs()

    tr = pd.concat([high_low, high_close, low_close], axis=1).max(axis=1)

    # Wilder ATR (Real ATR)
    df['ATR'] = tr.ewm(alpha=1/window, adjust=False).mean()

    return df

VWAP Indicator (for Intraday)| Python Codes

def intraday_vwap(df):

    df = df.copy()

    # Convert time column
    df['time'] = pd.to_datetime(df['time'], format="%d-%m-%Y %H:%M:%S")

    # Filter only latest trading day
    latest_date = df['time'].dt.date.iloc[-1]
    df = df[df['time'].dt.date == latest_date].copy()

    # Calculate VWAP
    df['VWAP'] = (
        ((df['inth'] + df['intl'] + df['intc']) / 3) *
        df['intv']
    ).cumsum() / df['intv'].cumsum()

    return df

Fetch Trade Data in Excel | Python Codes

def append_trade_row(sheet, row_data):
    last_row = sheet.range("A" + str(sheet.cells.last_cell.row)).end("up").row + 1
    sheet.range(f"A{last_row}").value = row_data

Trailing Stop-Loss | Python Codes (Must Watch Related Video on YouTube Channel) link below:

# ========================== Trailing Stop Loss Buy ==========================
class TrailingStopLoss_Buy:
    def __init__(self, initial_price, trailing_stop_percentage):
        self.initial_price = initial_price
        self.trailing_stop_percentage = trailing_stop_percentage
        self.trailing_stop_price = int(initial_price * (1 - trailing_stop_percentage / 100))

    def update(self, current_price):
        if current_price > self.initial_price:
            self.initial_price = current_price
            self.trailing_stop_price = int(current_price * (1 - self.trailing_stop_percentage / 100))

    def should_sell(self, current_price):
        return current_price <= self.trailing_stop_price
    
# ========================== Trailing Stop Loss Sell ==========================
class TrailingStopLoss_Sell:
    def __init__(self, initial_price, trailing_stop_percentage):
        self.initial_price = initial_price
        self.trailing_stop_percentage = trailing_stop_percentage
        self.trailing_stop_price = int(initial_price * (1 + trailing_stop_percentage / 100))

    def update(self, current_price):
        if current_price < self.initial_price:
            self.initial_price = current_price
            self.trailing_stop_price = int(current_price * (1 + self.trailing_stop_percentage / 100))

    def should_buy(self, current_price):
        return current_price >= self.trailing_stop_price

Get/Fetch Data with Google Sheet | Python Codes

import gspread
import logging

# ========================== Data Exchange with Google Sheet  ==================
gs = gspread.service_account(filename="google.json")
sh = gs.open_by_url("https://docs.google.com/spreadsheets/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") #Enter your google sheet url

def update_google_sheet(sheet_name, cell_no, data):
    try:
        sheet = sh.worksheet(sheet_name)  # โœ… correct
        sheet.update(cell_no, [[data]])            # โœ… correct format

        logging.info(f"Updated {sheet_name} {cell_no} with {data}")

    except Exception as e:
        logging.error(f"Google Sheets Error: {e}")

def read_google_sheet(sheet_name, cell_no):
    try:
        sheet = sh.worksheet(sheet_name)
        value = sheet.acell(cell_no).value   # โœ… get single cell

        return value

    except Exception as e:
        logging.error(f"Read Error: {e}")
        return None
    
def get_range_values(sheet_name, cell_range):
    try:
        sheet = sh.worksheet(sheet_name)
        data = sheet.get(cell_range)   # get range

        # Flatten + remove empty values
        values = [item for sublist in data for item in sublist if item]

        return values

    except Exception as e:
        logging.error(f"Read Range Error: {e}")
        return []
    
def append_trade_row(sheet_name, row_data):
    try:
        sheet = sh.worksheet(sheet_name)

        sheet.append_row(row_data)   # โœ… auto adds to next row

        logging.info("Trade row appended successfully.")

    except Exception as e:
        logging.error(f"Append Error: {e}")

# ======= Just as an Examples Update as per your need ===============
# values read from Google Sheet
trade_type = read_google_sheet("Config", "B2")

# Fetch Data in Google Sheet
update_google_sheet(sheet_name="Confit", cell_no="B5", data=cash)

# Get Range Data from Google Sheet
stocks = get_range_values("Config", "F2:F6")

# Apeend row Data in Google Sheet
append_trade_row(
    "Paper Trades",   # sheet name
    [
        orderbook[stock]['Date'],
        orderbook[stock]['Entry_Time'],
        orderbook[stock]['Side'],
        orderbook[stock]['stock_name'],
        orderbook[stock]['buy_entry_price'],
        orderbook[stock]['Exit_time'],
        orderbook[stock]['Exit_Price'],
        orderbook[stock]['Qty'],
        orderbook[stock]['PnL'],
        orderbook[stock]['Exit_Reason'],
        orderbook[stock]['traded'],
        orderbook[stock]['Charges'],
        orderbook[stock]['FPnL']
    ]
)

Scroll to Top