Skip to main content

SparkLib is a Python client library for interacting with https://spark.maticalgos.com . It provides functionalities to manage accounts, strategies, place orders, and much more.

Project description

SparkLib - Matic Algos Python Client

SparkLib is a Python client library for interacting with https://spark.maticalgos.com . It provides functionalities to manage accounts, strategies, place orders, and much more.

Installation

You can install the pre release via pip

pip install SparkLib

Setup Guide

Follow these steps to set up and start trading with Spark Matic Algos:

Prerequisites for Trading

Before you can begin trading on Spark Matic Algos, ensure you've completed the following steps:

  1. Account Creation:

  2. Broker Account Setup:

    • Have an active broker account with one of the supported brokers.
  3. Connection Establishment:

    • Connect your broker account to Spark Matic Algos seamlessly.
  4. Strategy Creation:

    • Develop your trading strategy within the Spark Matic Algos platform.
  5. Strategy Linking:

    • Associate your created strategy with your broker account on Spark Matic Algos.
  6. Strategy Activation:

    • Activate your linked strategy within the Spark Matic Algos interface.
  7. Trading Activation:

    • Enable trading on your broker account within Spark Matic Algos by specifying the Capital Deployed and Multiplier.
  8. Access Token Generation:

    • Generate an access token to initiate trading activities securely.
  9. Commence Trading:

    • Once all setup steps are completed, you're ready to commence trading using Spark Matic Algos.

Control Flow

  1. Login to Your Account

  2. Add a Broker Account

    • Navigate to 'Connections' -> 'ACCOUNTS' -> 'Add Account'.
    • Choose your preferred broker.
    • Provide a unique account name and your client ID.
    • Optionally, add your Telegram bot key and chat ID.
    • Click on 'Add Account'.
  3. Create Strategy

    • Go to 'Connections' -> 'STRATEGIES' -> 'Add Strategy'.
    • Name your strategy and describe it.
    • Select the strategy type (Intraday or Positional).
    • Choose the display type (Private or Public).
    • Decide if you want to perform a forward test (Yes or No).
    • Click on 'Add Strategy'.
  4. Link Strategy to Connected Broker Accounts

    • Click on 'Connections' -> 'LINKED STRATEGIES' -> 'Add Linked Strategy'.
    • Select the strategy and the associated account.
    • Specify the multiplier and capital deployed.
    • Click on 'Add'.
  5. Activate Strategy

    • Visit 'Connections' -> 'LINKED STRATEGIES'.
    • If the strategy status is 'Inactive', click on the 'Activate' button.
  6. Start Trading

    • Navigate to 'Connections' -> 'ACCOUNTS'.
    • Generate an access token by clicking on 'Generate Token' for the respective account.
    • Click on the 'Trade' button for the respective account.
    • Choose the strategy name and click on 'Activate Now'.

Getting API Keys

api key is unique for each and every account.

  1. Login to yout Matic Algos account.
  2. Click on 'Account Name' -> 'Settings'.
  3. Copy the 'App Key'. You will need this to generate a session ID.

Getting an Access Token

  1. Import the Spark library
from sparkLib import SparkLib
  1. Create a Spark object
spark_object = SparkLib(userid = "Your Emailid", 
                         password = "Your Password")

# OR

spark_object = SparkLib(apikeys = "Your API Keys")
  1. Generate a access token
spark_object.generate_token()

API Methods

  1. Profile

  2. Account Info

    1. All Accounts
    2. One Account
  3. Account Management

    1. Activate Account
    2. Deactivate Account
  4. Strategies Management

    1. Create Strategy
    2. Get Strategies
    3. Modify Strategy
    4. Delete Strategy
  5. Linked Strategies

    1. Link Account to Strategy
    2. Get Linked Strategies
    3. Modify Linked Strategy
      1. Modify Linked Strategy
      2. Activate Linked Strategy
      3. Deactivate Linked Strategy
    4. Delete Linked Strategy
  6. Expiry Dates

  7. Tokens

  8. Order Management

    1. LTP
    2. Place order
    3. Modify order
    4. Cancel order
    5. Square off All Orders
    6. Cancel All Orders
  9. Orderbook

  10. Tradebook

  11. Netposition

  12. Execution Logs

Profile

This method is used to get the profile of the user.

Code

print(spark_object.profile()) # get profile

Sample response

{'status': True, 'error': False, 'message': 'User exists', 'data': [{'ID': 10, 'Name': 'Your Name', 'Email': 'Your Email', 'PhoneNo': 'Your Phone No', 'LastLogin': '2024-04-02', 'CreatedOn': '2024-02-27', 'UCC': 'Your Unique User Code', 'Disabled': 0, 'UserType': 'admin', 'acLimit': 10, 'stLimit': 20}]}

Account INFO

We can get the account information using the following methods of all accounts and one account.

  1. All Accounts
  2. one Account

All Accounts

print(spark_object.getAllAccounts())

Sample response

{'status': True, 'error': False, 'data': [{'Clientid': 'Your Client ID', 'AccountName': 'Your Account Name', 'LastLogin': '2024-04-03', 'UCC': 'Your Unique User Code', 'Trade': True, 'Broker': 'Your Broker'}], 'message': 'Data Received'}

One Account

We have to pass the account name to get the account information.

print(spark_object.getOneAccount(accountName='Your Account Name'))

Sample response

{'status': True, 'error': False, 'data': [{'Clientid': 'Your Client ID', 'Password': None, 'ApiKey':'Your API Key', 'ApiSecret': 'Your API Secret', 'Totp': 'na', 'AccountName': 'Your Account Name', 'LastLogin': '2024-04-03', 'UCC': 'Your Unique User Code', 'Chatid': 'Your Chat ID', 'BotKeys': 'Your Telegram Bot Key', 'Sessionid': 'Your Session ID', 'Trade': 'Y', 'Broker': 'Your Broker', 'Redirecturl': 'http://spark.maticalgos.com/auth_code/<Your Broker>', 'Pin': 'na'}], 'message': 'Data Received'}

Account Management

For activating and deactivating the Broker account on the Spark platform.We can use the following methods.

  1. Activate Account
  2. Deactivate Account

Activate account

print(spark.activateAccount(accountName='Your Account Name',activate='Y'))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Account Activated.'}

Deactivate Account

print(spark.deactivateAccount(accountName='Your Account Name',activate='N'))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Account Deactivated.'}
Input Variables Possible Values Data Type Description
accountName Your Created Account Name String Account Name
activate 'Y', 'N' String Activate or Deactivate the account

Strategies Management

  1. Create Strategy
  2. Get Strategies
  3. Modify Strategy
  4. Delete Strategy

Create Strategy

print(spark.addStrategy(strategyName='Strategy_1',
                        Description='Your Description',
                        StrategyType='Intraday',
                        Display='Private',
                        ForwardTest='N'))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Strategy Added.'}

Get Strategies

print(spark.getStrategy())

Sample response

{'status': True, 'error': False, 'data': [{'ID': 104, 'StrategyName': 'Your Strategy Name', 'Description': '', 'StrategyType': 'Intraday', 'UCC': 'Your Unique User Code', 'Display': 'Private','ForwardTest': 'N'},{'ID': 127, 'StrategyName': 'Strategy_1', 'Description': 'Your Description', 'StrategyType': 'Intraday', 'UCC': 'Your UCC', 'Display': 'Private', 'ForwardTest': 'Y'}], 'message': 'Strategy data received'}

Modify Strategy

print(spark.modifyStrategy(strategyName='Strategy_1',
                            Description='Your Description',
                            StrategyType='Intraday',
                            Display='Private',
                            ForwardTest='Y'))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Strategy Modified.'}

Delete Strategy

print(spark.deleteStrategy(strategyName='Strategy_1'))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Strategy Deleted.'}
Input Variables Possible Values Data Type Description
strategyName Your Strategy Name String Name of the strategy
Description Your Description String Description of the strategy
StrategyType 'Intraday', 'Positional' String Type of strategy (Intraday or Positional)
Display 'Private', 'Public' String Display setting for the strategy
ForwardTest 'Y', 'N' String Whether forward testing is enabled

Linked Strategies

  1. Link Account to Strategy
  2. Get Linked Strategies
  3. Modify Linked Strategy
    1. Modify Linked Strategy
    2. Activate Linked Strategy
    3. Deactivate Linked Strategy
  4. Delete Linked Strategy

Link Account to Strategy

print(spark.addlinkStrategy(strategyName='Your Strategy Name',
                            accountName='Your Account Name',
                            Multiplier=1,
                            Activate='Y',
                            Capital=10000))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Account Linked to Strategy.'}

Get Linked Strategies

print(spark.getLinkedStrategy())

Sample response

{'status': True, 'error': False, 'data': [{'StrategyName': 'Your Strategy Name', 'AccountName': 'Your Account Name', 'UCC': 'Your UCC', 'Multiplier': 1, 'Activate': 1, 'Capital': 0.0}], 'message': 'Data Received'}

Modify Linked Strategy

# Modify Linked Strategy
print(spark.modifyLinkedStrategy(strategyName='Your Strategy Name',
                                accountName='Your Account Name',
                                Multiplier=1,
                                Activate='Y',
                                Capital=10000))

# Activate Linked Strategy 
    # Send Activate='Y' to activate the strategy
print(spark.modifyLinkedStrategy(strategyName='Your Strategy Name',
                                 accountName='Your Account Name',
                                 Multiplier=1,
                                 Activate='Y',
                                 Capital=10000))

# Deactivate Linked Strategy
    # Send Activate='N' to deactivate the strategy
print(spark.modifyLinkedStrategy(strategyName='Your Strategy Name',
                                 accountName='Your Account Name',
                                 Multiplier=1,
                                 Activate='N',
                                 Capital=10000))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Strategy Link modified'}

Delete Linked Strategy

 print(spark.deletelinkStrategy(strategyName='Your Strategy Name',accountName='Your Account Name'))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Strategy Link Deleted.'}
Input Variables Possible Values Data Type Description
strategyName Your Strategy Name String Name of the strategy to be linked/modifed/deleted
accountName Your Account Name String Name of the account to be linked/modifed/deleted
Multiplier Integer Integer Multiplier value for the linked strategy
Activate 'Y', 'N' String 'Y' to activate, 'N' to deactivate the linked strategy
Capital Float Float Capital amount for the linked strategy (if applicable)

Get Expiy Dates

print(spark.getExpiry(symbol='NIFTY',exchange='NFO',instrument='OPT'))
print(spark.getExpiry(symbol='SBIN',exchange='NFO',instrument='FUT'))
print(spark.getExpiry(symbol='SENSEX',exchange='BFO',instrument='FUT'))
print(spark.getExpiry(symbol='SENSEX',exchange='BFO',instrument='OPT'))
print(spark.getExpiry(symbol='USDINR',exchange='CDS',instrument='FUT'))

Sample response

{'status': True, 'error': False, 'data': ['2024-04-04', '2024-04-10', '2024-04-18', '2024-04-25'], 'message': 'Data Received'}
Input Variables Possible Values Data Type Description
symbol 'NIFTY', 'SBIN', 'SENSEX', etc. String Symbol of the instrument
exchange 'NFO', 'BFO', 'CDS','NSE','BSE' String Exchange where the instrument trades
instrument 'FUT', 'OPT' String Type of instrument (Futures, Options)

Get Tokens

print(spark.getTokens(symbol='NIFTY',exchange='NFO',instrument='OPT',expiry='2024-04-04'))
print(spark.getTokens(symbol='SBIN',exchange='NFO',instrument='FUT',expiry='2024-04-04'))
print(spark.getTokens(symbol='SENSEX',exchange='BFO',instrument='FUT'))
print(spark.getTokens(symbol='SENSEX',exchange='BFO',instrument='OPT'))
print(spark.getTokens(symbol='USDINR',exchange='CDS',instrument='FUT'))
print(spark.getTokens(symbol='SBIN',exchange='NSE'))
print(spark.getTokens(symbol='SBIN',exchange='BSE'))
print(spark.getTokens(symbol='USDINR',exchange='CDS'))

Sample response

{'status': True, 'error': False, 'data': [{'token': '42378', 'symbol': 'NIFTY04APR2420050PE', 'name': 'NIFTY', 'expiry': '2024-04-04', 'strike': 20050, 'lotsize': 50, 'instrumenttype': 'OPTIDX', 'exch_seg': 'NFO', 'tick_size': 0.05}, {'token': '45720', 'symbol': 'NIFTY04APR2421650PE', 'name': 'NIFTY', 'expiry': '2024-04-04', 'strike': 21650, 'lotsize': 50, 'instrumenttype': 'OPTIDX', 'exch_seg': 'NFO', 'tick_size': 0.05}], 'message': 'Data Received'}
Input Variables Possible Values Data Type Description Optional
symbol 'NIFTY', 'SBIN', 'SENSEX', etc. String Symbol of the instrument No
exchange 'NFO', 'BFO', 'CDS', 'NSE', 'BSE' String Exchange where the instrument trades No
instrument 'FUT', 'OPT' String Type of instrument (Futures, Option) Yes
expiry Date string format (e.g., '2024-04-04') String Expiry date of the instrument (if applicable) Yes

Order Management

  1. LTP
  2. Place order
  3. Modify order
  4. Cancel order
  5. Square off All Orders
  6. Cancel All Orders
  7. Orderbook
  8. Tradebook
  9. Netposition

LTP

Get the last traded price of the token. Token format is 'Exchange:Token'

print(spark.ltp(Tokens='NSE:212'))

Place an order

You can place following types of order through this API.

  1. Limit Order
  2. Market Order
  3. SL-Limit Order

Code

# Limit Order
print(spark_object.place_order(strategyName = "Your Strategy Name",
                                transType = "Buy",
                                token = "NSE:212", 
                                qty = 1,
                                orderType = "Limit",
                                productType = "Intraday",
                                limitPrice = 500.0))
# Market Order
print(spark_object.place_order(strategyName = "Your Strategy Name",
                               transType = "Sell",
                               token = "NSE:212",
                               qty = 1,
                               orderType = "Market",
                               productType = "Intraday"))
# SL-Limit Order
print(spark_object.place_order(strategyName = "Your Strategy Name",
                               transType = "Buy",
                               token = "NSE:212",
                               qty = 1,
                               orderType = "SL-Limit",
                               productType = "Intraday",
                               triggerPrice = 220,
                               limitPrice = 210))

Sample reponse of place order

{'status': True, 'error': False, 'data': [{'strefID': 2000}], 'message': 'Order Placed.'}
Input Variables Possible Values Data Type Description
strategyName "Your Strategy Name", etc. String Name of the strategy to place the order
transType "Buy", "Sell" String Type of transaction
token "NSE:212", etc. String Token representing the instrument to trade
qty Integer Integer Quantity of the instrument to buy/sell
orderType "Limit", "Market", "SL-Limit" String Type of order (Limit, Market, Stop-Limit)
productType "Intraday", "Delivery" String Product type (Intraday, Delivery, etc.)
limitPrice Float Float Price specified for Limit and SL-Limit orders
triggerPrice Float Float Trigger price specified for SL-Limit orders
strefID Integer Integer Reference ID of the order placed

Modify Order

print(spark_object.modify_order(strategyName='Your Strategy Name',
                                strefID=2328,
                                orderType='SL-Limit',
                                limitPrice=190))

Sample response of modify order

{'status': True, 'error': False, 'data': [{'strefID': 2328}], 'message': 'Order Modified.'}

Cancel order

print(spark_object.cancel_order(strategyName='Your Strategy Name',strefID=2328))

Sample response of cancel order

{'status': True, 'error': True, 'data': [{'strefID': 2328}], 'message': 'Order Cancelled.'}

Square off

# if you want to square off all orders of Strategy linked to Broker account
print(spark.SquareOff(ctype='strategy',strategyName='Your Strategy Name',accountName='Your Account Name'))
# if you want to square off all orders of Broker account
print(spark.SquareOff(ctype='account',accountName='Your Account Name'))

response

{'status': True, 'error': False, 'data': [], 'message': 'Request sent to Square Off in StrategyName : Your Strategy Name with AccountName : Your Account Name'}
{'status': True, 'error': False, 'data': [], 'message': 'Request sent to Square Off in AccountNamme : Your Account Name'}

Cancel All Orders

# if you want to cancel all orders of Strategy linked to Broker account
print(spark.CancalAll(ctype='strategy',strategyName='Your Strategy Name',accountName='Your Account Name'))
# if you want to cancel all orders of Broker account
print(spark.CancalAll(ctype='account',accountName='Your Account Name'))

response

{'status': True, 'error': False, 'data': [], 'message': 'Request sent to Cancel All Orders in StrategyName : Your Strategy Name with AccountName : Your Account Name'}
{'status': True, 'error': False, 'data': [], 'message': 'Request sent to Cancel All Orders in AccountNamme : Your Account Name'}

orderbook

print(spark_object.orderbook(accountName='Your Account Name',
                             strategyName='Your Strategy Name',
                             strefid=2000, # Optional : order id
                             reftag='Your Reference Tag', # Optional : Reference Tag    
                             withorders='Y')) # Optional : 'Y' to get all orders 
print(spark_object.orderbook(accountName='Your Account Name',
                             strategyName='Your Strategy Name'))

Sample response

{'status': True, 'error': False, 'data': [{'UCC': 'Your UCC', 'AccountName': 'Your Account Name', 'strefID': 2240, 'reftag': 1939, 'StrategyName': 'Your Strategy Name', 'orderType': 'Limit', 'productType': 'Intraday', 'price': 171.25, 'limitPrice': 170.0, 'triggerPrice': 0.0, 'token': 'NSE:212', 'segment': 'C', 'symbol': 'ASHOKLEY-EQ', 'qty': 1, 'transType': 'Buy', 'splitby': 0, 'Operations': '{"timeLimit": 0, "shouldExecute": false, "priceBuffer": 0.0}', 'ordersplaced': 1, 'ordersdone': 1, 'ordersexecuted': 0, 'placed_at': '2024-03-29T10:54:08', 'recon_at': None, 'trade_at': None, 'filledQty': 0, 'tradedQty': None, 'tradeValue': None, 'tradePrice': 0.0, 'status': 'Error', 'active': 0, 'ForwardTest': None}], 'message': 'Data received'}

Get tradebook

print(spark_object.tradebook(startDate='2024-04-01',
                             endDate='2024-04-03',
                             strategyName='Your Strategy Name',
                             accountName='Your Account Name'))

Sample response

{'status': True, 'error': False, 'data': [], 'message': 'Tradebook data received'}

Netposition

print(spark_object.netposition(accountName='Your Account Name',
                               strategyName='Your Strategy Name'))

Sample response

{'status': True, 'error': False, 'data': [{'Your Account Name': {'bookedpnl': 0.816660000000013, 'openpnl': None, 'totalpnl': None, 'totalpositions': 1, 'openpositions': 1}}], 'message': 'Data Received'}

Get Excution Logs

print(spark.excutionLogs())

Sample response

{'status': True, 'error': True, 'data': [{'Datetime': '2024-04-06T09:36:00', 'UCC': 'Your UCC', 'Name': 'Strategy Name', 'Alert Type': 'DEBUG', 'Message': "Endpoint Called : ModifyOrder. Payload Received : {'UCC': 'Your UCC', 'StrategyName': 'Strategy Name', 'strefID': 2327, 'orderType': 'Market', 'limitPrice': 0.0, 'triggerPrice': 0.0, 'identifier': ''}"}], 'message': 'Data Received'}

Sample Code

from SparkLib import SparkLib

if __name__ == '__main__':
    spark = SparkLib(userid = 'Your User ID', password = 'Your Password', apikeys = 'Your API Keys')
    spark.generate_token()
    print(spark.profile())
    print(spark.placeorder(strategyName = "Your Strategy Name",
                           transType = "Buy",
                           token = "NSE:212",
                           qty = 1,
                           orderType = "SL-Limit",
                           productType = "Intraday",
                           triggerPrice = 220,
                            limitPrice = 210,
                           ))
    print(spark.modifyorder(strategyName='Your Strategy Name',
                            strefID=2328,
                            orderType='SL-Limit',
                            limitPrice=190))
    print(spark.cancelorder(strategyName='Your Strategy Name',strefID=2328))

    print(spark.getExpiry(symbol='NIFTY',exchange='NFO',instrument='OPT'))
    print(spark.getExpiry(symbol='SBIN',exchange='NFO',instrument='FUT'))
    print(spark.getExpiry(symbol='SENSEX',exchange='BFO',instrument='FUT'))
    print(spark.getExpiry(symbol='SENSEX',exchange='BFO',instrument='OPT'))
    print(spark.getExpiry(symbol='USDINR',exchange='CDS',instrument='FUT'))

    print(spark.getTokens(symbol='NIFTY',exchange='NFO',instrument='OPT',expiry='2024-04-04'))
    print(spark.getTokens(symbol='SBIN',exchange='NFO',instrument='FUT',expiry='2024-04-04'))
    print(spark.getTokens(symbol='SENSEX',exchange='BFO',instrument='FUT'))
    print(spark.getTokens(symbol='SENSEX',exchange='BFO',instrument='OPT'))
    print(spark.getTokens(symbol='USDINR',exchange='CDS',instrument='FUT'))
    print(spark.getTokens(symbol='SBIN',exchange='NSE'))
    print(spark.getTokens(symbol='SBIN',exchange='BSE'))
    print(spark.getTokens(symbol='USDINR',exchange='CDS'))

    print(spark.getAllAccounts())
    print(spark.getOneAccount(accountName='Your Account Name'))
    
    print(spark.addStrategy(strategyName='Strategy_1',
                            Description='Your Description',
                            StrategyType='Intraday',
                            Display='Private',
                            ForwardTest='Y'))
    print(spark.getStrategy())
    print(spark.modifyStrategy(strategyName='Strategy_1',Description='Your Description',StrategyType='Intraday',Display='Private',ForwardTest='Y'))
    print(spark.deleteStrategy(strategyName='Strategy_1'))

    # print(spark.addlinkStrategy(strategyName='asa',accountName='Fyers_Vaibhav',Multiplier=1,Activate='Y',Capital=10000))
    print(spark.addlinkStrategy(strategyName='Your Strategy Name',
                                accountName='Your Account Name',
                                Multiplier=1,
                                Activate='Y',
                                Capital=10000))
    print(spark.getlinkStrategy())
    print(spark.modifylinkStrategy(strategyName='Your Strategy Name',accountName='Your Account Name',Multiplier=1,Activate='Y',Capital=10000))
    print(spark.deletelinkStrategy(strategyName='Your Strategy Name',accountName='Your Account Name'))

    print(spark.CancalAll(ctype='strategy',strategyName='Your Strategy Name',accountName='Your Account Name'))
    print(spark.CancalAll(ctype='account',accountName='Your Account Name'))

    print(spark.SquareOff(ctype='strategy',strategyName='Your Strategy Name',accountName='Your Account Name'))
    print(spark.SquareOff(ctype='account',accountName='Your Account Name'))

    print(spark.ltp(Tokens='NSE:212'))

    print(spark.intradaypnl(strategyName='Your Strategy Name',accountName='Your Account Name'))

    print(spark.netposition(strategyName='Your Strategy Name',accountName='Your Account Name'))

    print(spark.tradebook(startDate='2024-04-01',endDate='2024-04-04',strategyName='Your Strategy Name',accountName='Your Account Name'))

    print(spark.orderbook(strategyName='Your Strategy Name',accountName='Your Account Name'))

    print(spark.excutionLogs())

Order Websocket

The order websocket is a real-time communication protocol used to receive order-related messages from the Spark platform. It provides users with updates on order status, execution, and other pertinent information related to their trading activity. The websocket operates by continuously listening for incoming messages from the Spark platform and relaying them to the user in real-time.

Features:

  • Real-time Updates: Receive instant updates on order status and execution as they occur on the Spark platform.
  • Order Status: Stay informed about any changes in the status of your orders, including pending, executed, or cancelled orders.
  • Execution Details: Get detailed information about order executions, including trade prices, quantities, and timestamps.
  • Continuous Monitoring: The websocket continuously listens for incoming order messages, ensuring that users are always up-to-date with their trading activity.

Usage:

To use the order websocket, users need to establish a connection to the Spark platform using their access token. Once connected, the websocket will start receiving order messages from the platform. Users can define callback functions to handle incoming order messages, error notifications, connection status changes, and more.

Sample Code:

from Sparklib.order_websocket import OrderSocket

# Define callback functions
def on_order(message):
    print('Order', message)

def on_error(error):
    print('Error', error)

def on_close():
    print("Connection Closed")

def on_open():
    print("Connection Established")

# Create an instance of OrderSocket
order_socket = OrderSocket(
    access_token='Your Access Token',
    on_order=on_order,
    on_error=on_error,
    on_close=on_close,
    on_connect=on_open,
    reconnect=True,             # Optional: Attempt to reconnect if connection is closed
    max_reconnect_attempts=20   # Optional: Maximum attempts to reconnect
)

# Connect to the websocket
order_socket.connect()

# Close the connection
order_socket.close_connection()

Functions:

  • on_order(message):
    • This function is called whenever a new order message is received. The message parameter contains the order details, including order status, execution details, and other relevant information.
  • on_error(error):
    • This function is called when an error occurs during the websocket connection.
  • on_close():
    • This function is called when the websocket connection is closed. It can be used to perform cleanup tasks or handle connection closure events.
  • on_open():
    • This function is called when the websocket connection is established. It can be used to perform initialization tasks or handle connection establishment events.
  • reconnect:
    • This parameter specifies whether the websocket should attempt to reconnect if the connection is closed. By default, it is set to True.
  • max_reconnect_attempts:
    • This parameter specifies the maximum number of reconnection attempts that the websocket should make before giving up. By default, it is set to 20.
  • access_token:
    • This parameter specifies the access token required to establish a connection to the Spark platform.
  • connect():
    • This method is used to establish a connection to the Spark platform using the access token.
  • close_connection():
    • This method is used to close the websocket connection to the Spark platform.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

maticalgos-spark-0.1.0.tar.gz (20.3 kB view details)

Uploaded Source

File details

Details for the file maticalgos-spark-0.1.0.tar.gz.

File metadata

  • Download URL: maticalgos-spark-0.1.0.tar.gz
  • Upload date:
  • Size: 20.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.10.4

File hashes

Hashes for maticalgos-spark-0.1.0.tar.gz
Algorithm Hash digest
SHA256 44993fe908853e4d696346141deb5d34a2cb439e39ac304d0f0e266596844242
MD5 e1307bc3d69877a6a9e047457f50f0aa
BLAKE2b-256 5f12c462f09e04a4a4c6a3e5e109286d8f83634fcd96fa850a101866ff81e060

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page