Skip to content

Commit

Permalink
Merge pull request #185 from crypt0inf0/main
Browse files Browse the repository at this point in the history
flatTrade P&L fix
  • Loading branch information
marketcalls authored Feb 14, 2025
2 parents 1e9b181 + 31308bd commit 9a2c4d7
Showing 1 changed file with 35 additions and 38 deletions.
73 changes: 35 additions & 38 deletions broker/flattrade/api/funds.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,62 +2,60 @@
import http.client
import json

def calculate_pnl(entry):
"""Calculate realized and unrealized PnL for a given entry."""
unrealized_pnl = (float(entry.get("lp", 0)) - float(entry.get("netavgprc", 0))) * float(entry.get("netqty", 0))
realized_pnl = (float(entry.get("daysellavgprc", 0)) - float(entry.get("daybuyavgprc", 0))) * float(entry.get("daysellqty", 0))
return realized_pnl, unrealized_pnl

def fetch_data(endpoint, payload, headers, conn):
"""Send a POST request and return the parsed JSON response."""
conn.request("POST", endpoint, payload, headers)
response = conn.getresponse()
return json.loads(response.read().decode("utf-8"))

def get_margin_data(auth_token):
"""Fetch margin data from Zebu's API using the provided auth token."""

# Zebu API endpoint for fetching margin data
"""Fetch and process margin and position data."""
url = "piconnect.flattrade.in"

# Fetch UserID and AccountID from environment variables

full_api_key = os.getenv('BROKER_API_KEY')
BROKER_API_KEY = full_api_key.split(':::')[0]

userid = BROKER_API_KEY
actid = userid # Assuming AccountID is the same as UserID

# Prepare the payload for the request
data = {
"uid": userid, # User ID
"actid": actid # Account ID
}
userid = full_api_key.split(':::')[0]
actid = userid

# Prepare the jData payload with the authentication token (jKey)
payload = "jData=" + json.dumps(data) + "&jKey=" + auth_token
# Prepare payload
data = {"uid": userid, "actid": actid}
payload = f"jData={json.dumps(data)}&jKey={auth_token}"
headers = {'Content-Type': 'application/json'}

# Initialize HTTP connection
conn = http.client.HTTPSConnection(url)

# Set headers
headers = {
'Content-Type': 'application/json'
}

# Send the POST request to Zebu's API
conn.request("POST", "/PiConnectTP/Limits", payload, headers)

# Get the response
res = conn.getresponse()
data = res.read()

# Parse the response
margin_data = json.loads(data.decode("utf-8"))

print(margin_data)

# Fetch margin data
margin_data = fetch_data("/PiConnectTP/Limits", payload, headers, conn)

# Check if the request was successful
if margin_data.get('stat') != 'Ok':
# Log the error or return an empty dictionary to indicate failure
print(f"Error fetching margin data: {margin_data.get('emsg')}")
return {}

# Fetch position data
position_data = fetch_data("/PiConnectTP/PositionBook", payload, headers, conn)

total_realised = 0
total_unrealised = 0

# Process position data if it's a list
if isinstance(position_data, list):
for entry in position_data:
realized_pnl, unrealized_pnl = calculate_pnl(entry)
total_realised += realized_pnl
total_unrealised += unrealized_pnl

try:
# Calculate total_available_margin as the sum of 'cash' and 'payin'
total_available_margin = float(margin_data.get('cash',0)) + float(margin_data.get('payin',0)) - float(margin_data.get('marginused',0))
total_collateral = float(margin_data.get('brkcollamt',0))
total_used_margin = float(margin_data.get('marginused',0))
total_realised = -float(margin_data.get('rpnl',0))
total_unrealised = float(margin_data.get('urmtom',0))

# Construct and return the processed margin data
processed_margin_data = {
Expand All @@ -72,4 +70,3 @@ def get_margin_data(auth_token):
# Log the exception and return an empty dictionary if there's an unexpected error
print(f"Error processing margin data: {str(e)}")
return {}

0 comments on commit 9a2c4d7

Please sign in to comment.