Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.

Programming Languages

Programming Languages
138 posts | Last Activity on 09-01-2026 23:32 by caa
C
caa 09-01-2026 23:32, 4 months ago
Re: High speed trading code in python, using flattrade | zerodha | mstock
Troubleshooting Common Issues 1. WebSocket Disconnection pythondef reconnect_websocket(self): max_retries = 5 for i in range(max_retries): try: self.broker.start_websocket(...) break except Exception as e: print(f"Retry {i+1}/{max_retries}") time.sleep(5) 2. Order Rejection Check margin availability Verify symbol format Confirm exchange timings Check order limits 3. Data Latency Use dedicated server Optimize network Use broker's co-location services Reduce processing overhead
C
caa 09-01-2026 23:32, 4 months ago
Re: High speed trading code in python, using flattrade | zerodha | mstock
With Custom Parameters python# Modify main.py bot = TradingBot(broker='flattrade') bot.symbols = ['SBIN-EQ', 'RELIANCE-EQ', 'INFY-EQ', 'TCS-EQ'] bot.start() Step 7: Testing & Monitoring Paper Trading Mode pythonclass TradingBot: def __init__(self, broker='flattrade', paper_trading=True): self.paper_trading = paper_trading # ... rest of code def execute_buy(self, symbol, price): if self.paper_trading: print(f"[PAPER] BUY: {symbol} at {price}") return # ... actual order placement Add Logging pythonimport logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('trading.log'), logging.StreamHandler() ] ) logger = logging.getLogger(__name__) logger.info("Trade executed: BUY SBIN @ 500") Important Considerations Risk Management Always set stop-loss limits Implement position sizing Set maximum daily loss limits Monitor account balance Performance Optimization Use compiled libraries (NumPy, Pandas) Minimize API calls Cache market data Use efficient data structures Error Handling Handle network disconnections Implement order retry logic Log all errors Set up alerts for critical failures Compliance Follow exchange regulations Maintain audit logs Respect rate limits Test thoroughly before live trading
C
caa 09-01-2026 23:31, 4 months ago
Re: High speed trading code in python, using flattrade | zerodha | mstock
Step 5: Main Trading Engine main.py pythonimport os from dotenv import load_dotenv import time from brokers.flattrade import FlattradeClient from strategies.momentum import MomentumStrategy # Load environment variables load_dotenv('config/credentials.env') class TradingBot: def __init__(self, broker='flattrade'): self.broker_name = broker self.broker = None self.strategy = MomentumStrategy(fast_period=5, slow_period=20) self.symbols = ['SBIN-EQ', 'RELIANCE-EQ', 'TCS-EQ'] def initialize_broker(self): """Initialize selected broker""" if self.broker_name == 'flattrade': self.broker = FlattradeClient() # Add other brokers here # Login if self.broker.login(): print(f"{self.broker_name} initialized successfully") else: raise Exception("Broker login failed") def on_tick_data(self, tick): """Handle incoming tick data""" try: symbol = tick.get('tk') # Symbol/token ltp = tick.get('lp') # Last traded price if symbol and ltp: # Update strategy self.strategy.on_tick(symbol, float(ltp)) # Get signal signal = self.strategy.get_signal(symbol) # Execute trade if signal == 'BUY': self.execute_buy(symbol, ltp) elif signal == 'SELL': self.execute_sell(symbol, ltp) except Exception as e: print(f"Error processing tick: {e}") def execute_buy(self, symbol, price): """Execute buy order""" print(f"BUY Signal: {symbol} at {price}") response = self.broker.place_order( symbol=symbol, exchange='NSE', side='B', qty=1, price=0, order_type='MKT' ) print(f"Buy order response: {response}") self.strategy.positions[symbol] = {'price': price, 'qty': 1} def execute_sell(self, symbol, price): """Execute sell order""" print(f"SELL Signal: {symbol} at {price}") response = self.broker.place_order( symbol=symbol, exchange='NSE', side='S', qty=1, price=0, order_type='MKT' ) print(f"Sell order response: {response}") if symbol in self.strategy.positions: del self.strategy.positions[symbol] def start(self): """Start trading bot""" print("Starting trading bot...") # Initialize broker self.initialize_broker() # Start websocket self.broker.start_websocket(self.symbols, self.on_tick_data) # Keep running try: while True: time.sleep(1) except KeyboardInterrupt: print("nShutting down...") if __name__ == "__main__": bot = TradingBot(broker='flattrade') bot.start() Step 6: Run the Bot Basic Execution bash# Activate virtual environment source venv/bin/activate # Linux/Mac # or venvScriptsactivate # Windows # Run the bot python main.py
C
caa 09-01-2026 23:31, 4 months ago
Re: High speed trading code in python, using flattrade | zerodha | mstock
Step 4: Create Trading Strategy strategies/momentum.py pythonimport numpy as np from collections import deque class MomentumStrategy: def __init__(self, fast_period=5, slow_period=20): self.fast_period = fast_period self.slow_period = slow_period self.price_data = {} self.positions = {} def on_tick(self, symbol, ltp): """Process each tick""" if symbol not in self.price_data: self.price_data[symbol] = deque(maxlen=self.slow_period) self.price_data[symbol].append(ltp) def calculate_ema(self, prices, period): """Calculate EMA""" if len(prices) < period: return None prices_array = np.array(prices) ema = prices_array[-period:].mean() return ema def get_signal(self, symbol): """Generate trading signal""" if symbol not in self.price_data: return None prices = list(self.price_data[symbol]) if len(prices) < self.slow_period: return None fast_ema = self.calculate_ema(prices, self.fast_period) slow_ema = self.calculate_ema(prices, self.slow_period) if fast_ema is None or slow_ema is None: return None # Buy signal if fast_ema > slow_ema and symbol not in self.positions: return 'BUY' # Sell signal elif fast_ema < slow_ema and symbol in self.positions: return 'SELL' return None
C
caa 09-01-2026 23:31, 4 months ago
Re: High speed trading code in python, using flattrade | zerodha | mstock
brokers/zerodha.py pythonfrom kiteconnect import KiteConnect, KiteTicker import os class ZerodhaClient: def __init__(self): self.api_key = os.getenv('ZERODHA_API_KEY') self.api_secret = os.getenv('ZERODHA_API_SECRET') self.kite = KiteConnect(api_key=self.api_key) self.kws = None def login(self): """Generate login URL and get access token""" # Step 1: Generate login URL login_url = self.kite.login_url() print(f"Please login here: {login_url}") # Step 2: After login, you'll get request_token in redirect URL request_token = input("Enter request token from redirect URL: ") # Step 3: Generate access token data = self.kite.generate_session( request_token=request_token, api_secret=self.api_secret ) self.kite.set_access_token(data["access_token"]) print("Zerodha login successful!") return True def place_order(self, symbol, exchange, side, qty, price=0, order_type='MARKET'): """Place order""" order_id = self.kite.place_order( variety=self.kite.VARIETY_REGULAR, exchange=exchange, # NSE, BSE, NFO tradingsymbol=symbol, transaction_type=side, # BUY or SELL quantity=qty, product=self.kite.PRODUCT_MIS, # MIS, CNC, NRML order_type=order_type, # MARKET, LIMIT, SL, SL-M price=price ) return order_id def get_positions(self): """Get current positions""" return self.kite.positions() def start_websocket(self, tokens, callback): """Subscribe to live market data""" self.kws = KiteTicker(self.api_key, self.kite.access_token) def on_ticks(ws, ticks): callback(ticks) def on_connect(ws, response): ws.subscribe(tokens) ws.set_mode(ws.MODE_FULL, tokens) self.kws.on_ticks = on_ticks self.kws.on_connect = on_connect self.kws.connect(threaded=True)
C
caa 09-01-2026 23:30, 4 months ago
Re: High speed trading code in python, using flattrade | zerodha | mstock
High-Speed Trading Implementation Guide Step 1: Environment Setup Create Project Structure bashmkdir hft_trading cd hft_trading # Create virtual environment python -m venv venv # Activate virtual environment # On Windows: venvScriptsactivate # On Linux/Mac: source venv/bin/activate Install Dependencies bash# For Flattrade pip install NorenRestApiPy websocket-client # For Zerodha pip install kiteconnect # For Mstock pip install requests websocket-client # Common dependencies pip install pandas numpy python-dotenv Create Project Files hft_trading/ │ ├── config/ │ └── credentials.env ├── brokers/ │ ├── __init__.py │ ├── flattrade.py │ ├── zerodha.py │ └── mstock.py ├── strategies/ │ ├── __init__.py │ └── momentum.py ├── utils/ │ ├── __init__.py │ └── logger.py └── main.py Step 2: Configure Credentials Create config/credentials.env env# Flattrade Credentials FLATTRADE_USER_ID=your_user_id FLATTRADE_PASSWORD=your_password FLATTRADE_TOTP_KEY=your_totp_key FLATTRADE_API_KEY=your_api_key FLATTRADE_VENDOR_CODE=your_vendor_code # Zerodha Credentials ZERODHA_API_KEY=your_api_key ZERODHA_API_SECRET=your_api_secret ZERODHA_USER_ID=your_user_id ZERODHA_PASSWORD=your_password # Mstock Credentials MSTOCK_APP_KEY=your_app_key MSTOCK_SECRET_KEY=your_secret_key MSTOCK_USER_ID=your_user_id MSTOCK_PASSWORD=your_password Step 3: Implement Broker Connections brokers/flattrade.py pythonfrom NorenRestApiPy.NorenApi import NorenApi import pyotp import os class FlattradeClient: def __init__(self): self.api = NorenApi( host='https://piconnect.flattrade.in/PiConnectTP/', websocket='wss://piconnect.flattrade.in/PiConnectWSTp/' ) self.user_id = os.getenv('FLATTRADE_USER_ID') self.password = os.getenv('FLATTRADE_PASSWORD') self.totp_key = os.getenv('FLATTRADE_TOTP_KEY') self.api_key = os.getenv('FLATTRADE_API_KEY') self.vendor_code = os.getenv('FLATTRADE_VENDOR_CODE') def login(self): """Login to Flattrade""" # Generate TOTP totp = pyotp.TOTP(self.totp_key).now() # Login response = self.api.login( userid=self.user_id, password=self.password, twoFA=totp, vendor_code=self.vendor_code, api_secret=self.api_key, imei='abc1234' ) if response['stat'] == 'Ok': print("Flattrade login successful!") return True else: print(f"Login failed: {response}") return False def place_order(self, symbol, exchange, side, qty, price=0, order_type='MKT'): """Place order""" response = self.api.place_order( buy_or_sell=side, # 'B' or 'S' product_type='I', # I=MIS, C=CNC, M=NRML exchange=exchange, # NSE, BSE, NFO tradingsymbol=symbol, quantity=qty, discloseqty=0, price_type=order_type, # LMT, MKT, SL-LMT, SL-MKT price=price, trigger_price=None, retention='DAY', remarks='HFT_Order' ) return response def get_positions(self): """Get current positions""" return self.api.get_positions() def start_websocket(self, symbols, callback): """Subscribe to live market data""" def event_handler_feed_update(tick_data): callback(tick_data) self.api.start_websocket( order_update_callback=None, subscribe_callback=event_handler_feed_update, socket_open_callback=lambda: print("WebSocket connected") ) # Subscribe to symbols for symbol in symbols: self.api.subscribe(f'{symbol}')
C
caa 09-01-2026 23:30, 4 months ago
Re: High speed trading code in python, using flattrade | zerodha | mstock
High-Speed Trading Implementation Guide Step 1: Environment Setup Create Project Structure bashmkdir hft_trading cd hft_trading # Create virtual environment python -m venv venv # Activate virtual environment # On Windows: venv\Scripts\activate # On Linux/Mac: source venv/bin/activate Install Dependencies bash# For Flattrade pip install NorenRestApiPy websocket-client # For Zerodha pip install kiteconnect # For Mstock pip install requests websocket-client # Common dependencies pip install pandas numpy python-dotenv Create Project Files hft_trading/ │ ├── config/ │ └── credentials.env ├── brokers/ │ ├── __init__.py │ ├── flattrade.py │ ├── zerodha.py │ └── mstock.py ├── strategies/ │ ├── __init__.py │ └── momentum.py ├── utils/ │ ├── __init__.py │ └── logger.py └── main.py
C
caa 03-01-2026 05:06, 4 months ago
Re: Python program using VPython to simulate a pendulum
VPython makes it easy to create visualizations and animations for physics experiments. This program will simulate a pendulum and visualize its motion. First, make sure you have VPython installed. You can install it using pip: pip install vpython Then, you can use the following code to create the pendulum simulation: from vpython import * # Constants length = 1.0 # Length of the pendulum (meters) g = 9.8 # Acceleration due to gravity (m/s^2) theta = 0.2 # Initial angle (radians) omega = 0.0 # Initial angular velocity (radians/s) # Time parameters dt = 0.01 # Time step (seconds) t = 0.0 # Initial time # Setting up the scene scene = canvas(title='Pendulum Simulation', width=800, height=600, center=vector(0, -length/2, 0), background=color.white) # Creating the pendulum components pivot = vector(0, 0, 0) # Pendulum pivot point bob = sphere(radius=0.05, color=color.blue) # Pendulum bob rod = cylinder(pos=pivot, axis=vector(length*sin(theta), -length*cos(theta), 0), radius=0.01, color=color.black) # Pendulum rod # Function to update the pendulum position def update_pendulum(): global theta, omega, t # Calculating angular acceleration alpha = - (g / length) * sin(theta) # Updating angular velocity and angle omega += alpha * dt theta += omega * dt # Updating bob and rod positions bob.pos = vector(length*sin(theta), -length*cos(theta), 0) rod.axis = bob.pos - pivot # Updating time t += dt # Main loop while True: rate(100) # Limit the simulation to 100 updates per second update_pendulum()
C
caa 17-12-2025 02:38, 5 months ago
Re: What’s actually happening in computer-aided automation right now (shop-floor view)
I work around CAD/CAM and automation projects, and thought I’d share a ground-level view of what’s really changing in computer-aided automation — not the hype, just what’s showing up in day-to-day work. 1. CAD is no longer “just design” Most shops are using CAD models directly for CAM, simulation, and even inspection. If the model is wrong, everything downstream breaks. Because of this, there’s a stronger push toward model-based definition (MBD) instead of 2D drawings. Not everywhere yet, but it’s clearly increasing. 2. Automation is moving upstream Earlier, automation was mostly at the machine or PLC level. Now it’s happening earlier in the process: Auto-generation of toolpaths from standard features Rule-based fixture and process planning Scripted checks for design manufacturability This doesn’t replace engineers, but it cuts repetitive work. 3. Scripting skills are becoming valuable Python, VBA, and vendor APIs (NX Open, Fusion API, SolidWorks API, etc.) are being used a lot. Engineers who can automate boring tasks inside CAD/CAM tools are finishing work faster and with fewer mistakes. This is very visible in medium-size companies trying to do more with small teams. 4. Digital twins are used… but in a limited way True digital twins are still expensive and complex. What’s actually common is partial simulation: Robot reach and collision checks Cycle time estimation Simple material flow simulations It’s practical, not perfect, and mostly focused on risk reduction before commissioning. 5. AI is being used quietly, not magically Despite the marketing, AI in automation today is mostly: Vision systems for inspection and sorting Parameter optimization (feeds, speeds, tuning) Predictive maintenance from machine data No “fully autonomous factory” yet, but fewer surprises on the shop floor. 6. Integration problems are still the biggest pain Connecting CAD, CAM, ERP, MES, and machines is still messy. File formats, versions, and data ownership cause more issues than lack of technology. Companies that solve data flow tend to see the biggest productivity gains. Overall, computer-aided automation is becoming more practical and less flashy. The big wins are coming from small, well-targeted automation steps rather than massive transformations.
K
Kevin 28-11-2025 02:50, 5 months ago
Re: python library recommendations for industrial automation
Reply by: FactoryAuto pymodbus is still pretty much the standard for modbus communication. For profinet you'll want to look at python-snap7 if youre working with siemens PLCs. Both have decent docs. Just be aware that industrial protocols can be tricky - make sure you test everything thoroughly before deploying. Also consider using opcua instead if possible, its much easier to work with and python-opcua is excellent.
K
Kevin 28-11-2025 02:50, 5 months ago
Re: python library recommendations for industrial automation
Username: IndustryTech Posted: 4 days ago Working on a factory automation project and need to communicate with PLCs and various sensors over modbus and profinet. What python libraries would you recommend? I've used pymodbus before but wondering if there are better alternatives now. Also need something with good documentation since im still learning.
K
Kevin 26-11-2025 22:43, 5 months ago
Re: When to use NoSQL database vs traditional SQL?
Reply by: Backend_Developer_5yr Also consider your team's expertise. If everyone knows SQL and PostgreSQL, dont switch to MongoDB just because its trendy. PostgreSQL can handle millions of IoT records if properly indexed. With JSONB columns you get flexibility of NoSQL within PostgreSQL. Start with what you know, optimize later if you hit performance issues. Premature optimization is root of all evil as they say.
K
Kevin 26-11-2025 22:43, 5 months ago
Re: When to use NoSQL database vs traditional SQL?
Reply by: IoTplatform_CTO We use combination - time-series database (InfluxDB) for sensor readings, PostgreSQL for metadata, user accounts, device registry. This hybrid approach works well. Sensor data is append-only time-series which InfluxDB handles brilliantly. Relational data like users, devices needs SQL. Dont force everything into one database type, use right tool for each data type.
K
Kevin 26-11-2025 22:42, 5 months ago
Re: When to use NoSQL database vs traditional SQL?
Reply by: DatabaseArchitect_Senior For IoT time-series data, consider time-series databases like InfluxDB or TimescaleDB (which is built on PostgreSQL). These are optimized for time-series workloads. Regular MongoDB or PostgreSQL will work but not optimal. NoSQL is not always better - depends on your data structure and query patterns. If you need complex queries with joins, SQL is better. If you need flexible schema and horizontal scaling, NoSQL is better.
K
Kevin 26-11-2025 22:42, 5 months ago
Re: When to use NoSQL database vs traditional SQL?
User: NoSQL_vs_SQL_confused Subject: When to use NoSQL database vs traditional SQL? Planning database architecture for new IoT application that will collect sensor data. Should I use NoSQL like MongoDB or stick with PostgreSQL? Everyone says NoSQL is better for IoT but not clear why. What are deciding factors?
K
Kevin 26-11-2025 22:39, 5 months ago
Re: Do I need API gateway for microservices?
Reply by: CloudArchitect_AWS Common API gateways are Kong, AWS API Gateway, Azure API Management, or Nginx. They also provide monitoring, logging, caching out of the box. Yes it adds one more component to manage but benefits outweigh the complexity. Start simple though - if you have only 2-3 microservices, can delay API gateway initially. But plan for it as your architecture grows.
K
Kevin 26-11-2025 22:39, 5 months ago
Re: Do I need API gateway for microservices?
Reply by: MicroservicesArchitect API gateway is not mandatory but highly recommended. Without gateway, your frontend needs to know about all microservices, handle authentication with each service separately, deal with different protocols/formats. API gateway provides single entry point, handles authentication, rate limiting, request routing, protocol translation. It decouples frontend from backend services. For production system definitely use API gateway.
K
Kevin 26-11-2025 22:39, 5 months ago
Re: Do I need API gateway for microservices?
User: APIgateway_Doubt Subject: Do I need API gateway for microservices? Building application with microservices architecture. Do I really need API gateway or can frontend directly call different microservices? Seems like API gateway adds extra layer and complexity. When is it actually necessary?
K
Kevin 26-11-2025 22:23, 5 months ago
Re: REST API vs GraphQL - when to use which?
Reply by: StartupCTO_Experience My advice is start with REST. Its simpler to implement and debug. Once your application grows and you face issues like over-fetching or under-fetching data, then consider migrating to GraphQL. We started with REST and added GraphQL later only for specific use cases. Now we have hybrid approach - REST for simple endpoints and GraphQL for complex data fetching.
K
Kevin 26-11-2025 22:22, 5 months ago
Re: REST API vs GraphQL - when to use which?
Reply by: MobileApp_Developer From mobile developer perspective, GraphQL is great because I can fetch all needed data in single request instead of making multiple REST API calls. This reduces network overhead and makes app faster. But on backend side, GraphQL queries can be expensive if not optimized properly. You need to implement things like query depth limiting, complexity analysis etc to prevent abuse.
You can view all discussion threads in this forum.
You cannot start a new discussion thread in this forum.
You cannot start on a poll in this forum.
You cannot upload attachments in this forum.
You cannot download attachments in this forum.
Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 3
Members Online 0

Total Members: 40
Newest Member: Remax14