When trading with TSL (Trading System Library) efficient order management is vital to profitable trading. There are times when you need to create orders, alter, or even cancel orders. You may also need to divide large orders into smaller, manageable chunks in order to maximize execution. This comprehensive guide explains every one of the important operations of managing orders, including detailed explanations and examples.
1 Place an Order — tsl.order_placement
The function of order_placement is your principal tool to enter new positions on the market. It handles sell and buy orders across diverse instruments and exchanges including equity stocks, commodities and derivatives.
Detailed Use Cases:
Use options strategies to execute by purchasing 75 NIFTY CALL call options at Rs0.05
Create equity positions by buying 100 shares in ACC at Rs.2,674.
Manage risk with stop-loss order for CRUDEOIL futures
Place orders for after-market transactions (AMO) to implement gap-up/gap-down and other strategies
Execute bracket orders using pre-defined profits and stop-losses
Complete Arguments List:
Core Parameters:
tradingsymbol (str) (str) – Full instrument identification, including expiry date as well as strike (e.g.”NIFTY 21 Nov 24400 Call’ ‘ACC-EQ”CRUDEOIL24NOVFUT”)
exchange (str) – Trading venue (NFO for derivatives, NSE for equities, MCX for commodities, BSE for Bombay Stock Exchange)
Quantity (int) number (int) shares/lots/units that can be traded (must be in legal lots sizes to trade derivatives)
price (float) Price (float) – Limit price on the transaction (set to zero for market orders)
trigger_price (float) Price for activation for stop-loss order (0 to regular order)
order_type (str) the execution of an order kind: Market LIMIT’, ‘STOPLIMIT”, STOPMARKET’
transaction_type (str) (str) – Direction of trade”BUY” or “SELL’
trade_type (str) – Type of position that is MIS (intraday)(intraday) “CNC” (delivery) (delivery), ‘CO’ (cover order)and “BO” (bracket order)
Optional Advanced Parameters:
disclosed_quantity (int) disclosed_quantity (int) Iceberg function of orders – displays only a portion of the total quantity to be sold
after_market_order (bool) – True for placing AMO orders during market closure
Validity (str) Duration of the order (str): ‘DAY’ (valid until the end of the market) or IOC (immediate or cancellation)
bo_profit_value (float) Book profit amount for bracket order
bo_stop_loss_value (float) – Stop-loss trigger for bracket orders
Example:
# Buy NIFTY Call Option
orderid = tsl.order_placement(
tradingsymbol='NIFTY 21 NOV 24400 CALL',
exchange='NFO',
quantity=75,
price=0.05,
trigger_price=0,
order_type='LIMIT',
transaction_type='BUY',
trade_type='MIS'
)
print(orderid)
2 Modify an Order — tsl.modify_order
Modifying orders is crucial in order to adapt to changing market conditions without cancelling or re-placing orders. This allows you to alter the price, quantity and order types, while preserving your place in the order queue whenever you can.
Strategic Use Cases:
Pricing Optimization: Modify prices for limit to increase the probability of filling in the event of market fluctuations.
Quantity Management: Reduce or increase the size of orders according to margins or risk tolerance
Order Type Conversion Limit Change to market order to facilitate urgent execution
Stop Loss Adjustment: The stop loss adjustment is used are used to safeguard profits when positions are moved in a favorable direction.
Bracket Order management: Change the profit goals and stop-losses for BO positions in which you are active.
Complete Parameter Guide:
Required Parameters:
order_id (str) order_id (str) – Unique identification number of the order that is to be altered (obtained from the original response to placement)
order_type (str) updated order type: LIMIT”MARKET,” ‘STOPLIMIT STOPMARKET’
quantity (int) Quantity (int) (can be decreased or increased in exchange limits)
Optional Modification Parameters:
price (float) updated limit cost (required to limit order)
trigger_price (float) – New trigger level for stop orders
Validity (str) – Change the validity to the ‘DAY’ or ‘IOC’
leg_name (str) for complicated order: ‘ENTRY_LEG’ “TARGET_LEG”, “STOP_LOSS_LEG”
Comprehensive Example:
orderid = '12241210603927'
modified_order_id = tsl.modify_order(
order_id=orderid,
order_type="LIMIT",
quantity=50,
price=0.1
)
3 Cancel an Order — tsl.cancel_order
Order cancellation is an essential instrument for risk management that allows you to eliminate any pending orders that do not match your strategy of trading or your market forecast. Be aware that only pending orders are able to be cancelled. Executed orders are not reversed by this feature.
Strategic Cancellation Scenarios:
Market Condition Changes Cancel orders if fundamental or technical outlooks shift
Risk Management: Removing orders that are in excess of the size of the position.
Change in Strategy: Reject orders that conflict after a shift in trading strategy
Clean-up at the end of the day: Take out any unfulfilled intraday orders prior to closing time.
News-Based Decisions: Rapid order cancellation during high-impact news events
Function Parameters:
(str) – OrderID (str) is the unique ID to be canceled
Practical Example with Error Handling :
orderid = '12241210603927'
status = tsl.cancel_order(OrderID=orderid)
print(status) # "Cancelled"
4 Cancel All Intraday Orders — tsl.cancel_all_orders
This incredibly useful function offers complete cleaning of orders and positions by simultaneously reversing all intraday orders pending and squaring all available intraday position. This is particularly helpful for end-of-day risk management and emergencies involving closure of positions.
Critical Use Cases:
End-of-Day Management Close all intraday positions prior to closing of the market
Security Risk Management: Rapidly eliminate all positions in difficult market conditions.
Strategy Reset: A clean approach to switching trading strategies at mid-day
System Maintenance Clean all positions prior to any system update or maintenance
Quick Margin Response to Calls: reduction of the position to be in line with the requirements of margins
Important Considerations:
This feature affects ALL Intraday Orders and positions across all instruments.
Positions are re-squared at market prices. This can cause slippage
Be careful because it is impossible to undo
It doesn’t have an impact on positions in CNC (delivery) position
Could result in multiple transaction fees
Exemple:
order_details = tsl.cancel_all_orders()
5 Place Sliced Orders — tsl.place_slice_order
Large orders can have a major impact on market prices and are subject to liquidity limitations. The slice order function cleverly reduces big orders into tidier, manageable pieces, which are executed at a time or in accordance with the market’s conditions, minimizing impacts and improving execution quality.
Advanced Slicing Benefits:
Minimized Market Impact: Smaller orders are able to have less influence on price
Better Fill Rates Higher execution rate with smaller sizes.
Liquidity Management: Prevents over-extending the market depth
Price Improvement: Sequential execution can capture better average prices
Risk Distribution: Spreads execution risk across multiple time points
Function Behavior:
One slice: Returns a single order ID when the quantity doesn’t need slicing.
Multiple Slices: Provides a list order IDs to track individual slices’ execution
Automated Sizing TSL calculates the optimal size of slices based on the instrument’s liquidity
Sequential execution: Slices are usually executed in order to minimize the impact
Comprehensive Slicing Example:
order_ids = tsl.place_slice_order(
tradingsymbol="NIFTY 19 DEC 18000 CALL",
exchange="NFO",
transaction_type="BUY",
quantity=1875,
order_type="LIMIT",
trade_type="MIS",
price=0.05
)
6 Get Order Details — tsl.get_order_detail
A comprehensive order information retrieval process is vital to monitor trading execution, analyzing the performance, and keeping precise record of transactions. This function gives all the information needed to track the lifecycle of an order, including details about execution time stamps, the status of orders.
Detailed Information Retrieved:
Order Specifications: Symbol, exchange, quantity, price levels
Execution Data: Filled quantity, pending quantity, average price
Timing Information: Order Placement time and execution timestamps
Status History: The progression of the status of the order and any reasons for reject
Financial Information Include: Taxes, brokerage and net settlement amounts
Market Information: Last traded price Market depth at the time of execution
Comprehensive Monitoring Example:
orderid = '12241210603927'
details = tsl.get_order_detail(orderid=orderid)
print(details)
7 Get Order Status — tsl.get_order_status
Monitoring the status of orders in real-time is essential for trading strategies. This feature gives you instant status updates, which allows you to take quick decisions regarding order management and adjustment of positions.
Status Categories Explained:
Pending: Order is placed, but not yet completed (waiting in the order book)
Completed: Order executed at the specified or higher price
Cancelled: Order is cancelled by the user or the system
Rejected: Order is rejected for a variety of factors (insufficient margin, incorrect parameters)
Partially Filled: Order partly completed with the remaining quantity in limbo
Triggered Stop orders that were activated, but are not yet filled
Example:
orderid = '12241210603927'
status = tsl.get_order_status(orderid=orderid)
8 Get Executed Price — tsl.get_executed_price
Understanding the quality of execution is crucial to analyze the performance of trading. This function gives the volume-weighted mean price (VWAP) for orders that have been executed that is crucial in cases of partially filled orders or executions that are cut in half.
Price Analysis Applications:
Performance Measuring: Compare execution price to benchmarks in the market
Analyze the slippage of fill prices: Determine the gap between the expected and actual fill prices
Strategy Optimization: Examine the timing of order placement and pricing
Cost Analysis: Estimate the total execution costs, including the impact on markets
Reporting: Make precise P&L calculations based on the actual fill prices
Example:
orderid = '12241210603927'
price = tsl.get_executed_price(orderid=orderid)
9 Get Exchange Time — tsl.get_exchange_time
Accurate timing information is vital when it comes to high-frequency trading techniques, regulation reporting as well as performance analyses. This function can provide the execution times stamped by exchange that are official time stamps for all purposes related to settlement and regulation.
Timing Data Applications:
Time stamps for Regulatory Compliance: Accurate for audit trails and reports
Strategy Analysis: Determine the latency of order execution and timing of the market
The Performance Attribution Method: Link the execution with particular markets or events
Settlement Verification: Check settlement dates for calculations of settlement
Market Research: Examine execution patterns over different times
Comprehensive Timing Analysis:
orderid = '12241210603927'
time = tsl.get_exchange_time(orderid=orderid)
✅ With above these functions, you can place, adjust, cancel, and track orders in a fully automated trading setup using TSL.