from flask import Flask, request, jsonify
import random
import time
from datetime import datetime
from smartapi import SmartConnect
import pandas as pd
import numpy as np
app = Flask(__name__)
# Connect to SmartAPI
def connect_to_api(api_key, access_token):
try:
obj = SmartConnect(api_key=api_key, access_token=access_token)
print("Connected to SmartAPI successfully.")
return obj
except Exception as e:
print(f"Error connecting to SmartAPI: {e}")
return None
# Fetch 2-minute candle data
def fetch_candle_data(obj, tradingsymbol, interval="2minute"):
try:
# Simulated data for demonstration (replace with actual API call for 2-minute data)
candle_data = {
"open": random.uniform(195, 205),
"high": random.uniform(205, 210),
"low": random.uniform(190, 195),
"close": random.uniform(195, 205),
}
return candle_data
except Exception as e:
print(f"Error fetching candle data: {e}")
return None
# Place limit buy order
def place_limit_order(obj, tradingsymbol, token, qty, entry_price):
try:
order = obj.place_order(
exchange="NFO",
tradingsymbol=tradingsymbol,
symboltoken=token,
transactiontype="BUY",
qty=qty,
price=entry_price,
producttype="INTRADAY",
ordertype="LIMIT",
)
print(f"Limit order placed at {entry_price}, Order ID: {order['orderid']}")
return order
except Exception as e:
print(f"Error placing limit order: {e}")
return None
# Place exit order
def exit_trade(obj, order_id, exit_price, tradingsymbol, token, qty):
try:
exit_order = obj.place_order(
exchange="NFO",
tradingsymbol=tradingsymbol,
symboltoken=token,
transactiontype="SELL",
qty=qty,
price=exit_price,
producttype="INTRADAY",
ordertype="LIMIT",
)
print(f"Exit order placed at {exit_price}, Order ID: {exit_order['orderid']}")
return exit_order
except Exception as e:
print(f"Error placing exit order: {e}")
return None
# Calculate buy entry price for the next candle
def calculate_buy_entry_for_next_candle(current_open, current_close):
center = (current_open + current_close) / 2
entry_price = center + 0.2 # Center + 0.2 offset
return entry_price
# Strategy implementation
def nifty_banknifty_strategy(obj, tradingsymbol, token, qty, entry_price):
levels = [0.03, 0.04, 0.05, 0.1, 0.2, 0.3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
while True:
# Fetch the latest 2-minute candle data
current_candle = fetch_candle_data(obj, tradingsymbol)
if current_candle is None:
return {"status": "error", "message": "Candle data fetch failed."}
current_open = current_candle["open"]
current_close = current_candle["close"]
print(f"Current Candle Open: {current_open}, Close: {current_close}")
# Calculate next candle entry price
next_entry_price = calculate_buy_entry_for_next_candle(current_open, current_close)
print(f"Calculated Next Candle Entry Price: {next_entry_price}")
# Simulate the next candle open price
next_open_price = random.uniform(200, 210) # Simulated for demonstration
print(f"Next Candle Open Price: {next_open_price}")
# Place a limit buy order if conditions are met
if next_open_price >= next_entry_price:
print(f"Placing limit order at {next_open_price}")
order = place_limit_order(obj, tradingsymbol, token, qty, next_entry_price)
if not order:
return {"status": "error", "message": "Order placement failed."}
# Manage the trade with trailing stop loss
stop_loss = next_entry_price - 0.1
print(f"Initial Stop Loss: {stop_loss}")
while True:
# Fetch live price (simulate here)
current_price = random.uniform(190, 210) # Simulated live price
print(f"Current Price: {current_price}")
# Update trailing stop loss
trailing_stop_loss = max(stop_loss, next_entry_price + 0.5)
if trailing_stop_loss > stop_loss:
stop_loss = trailing_stop_loss
print(f"Trailing Stop Loss updated to: {stop_loss}")
# Check for stop loss hit
if current_price <= stop_loss:
print(f"Stop Loss hit at {current_price}. Exiting trade.")
exit_trade(obj, order["orderid"], current_price, tradingsymbol, token, qty)
return {"status": "success", "message": f"Stop Loss hit at {current_price}."}
# Exit after 2 minutes (120 seconds)
time.sleep(120)
break
@app.route('/start_trading', methods=['POST'])
def start_trading():
data = request.json
api_key = data.get("api_key")
access_token = data.get("access_token")
tradingsymbol = data.get("tradingsymbol")
token = data.get("token")
qty = data.get("qty")
entry_price = data.get("entry_price")
obj = connect_to_api(api_key, access_token)
if obj is None:
return jsonify({"status": "error", "message": "API connection failed."})
result = nifty_banknifty_strategy(obj, tradingsymbol, token, qty, entry_price)
return jsonify(result)
if __name__ == "__main__":
app.run(debug=True)
No comments