PINE LIBRARY

LO1_TradersPost

46
Library "LO1_TradersPost"
Enhanced TradersPost integration library with comprehensive order management

_buildJSONField(key, value, required)
  Build a JSON field with proper handling of required vs optional fields
  Parameters:
    key (string): The JSON key name
    value (string): The value to include (any type, will be converted to string)
    required (bool): If true, field is always included even if value is na/empty
  Returns: String containing JSON field or empty string if optional and na/empty

_buildConditionalField(key, value)
  Build a conditional JSON field that's only included if value is valid
  Parameters:
    key (string): The JSON key name
    value (string): The value to include
  Returns: String containing JSON field or empty string if value is na/empty

_buildConditionalNumericField(key, value)
  Build a conditional JSON field for numeric values
  Parameters:
    key (string): The JSON key name
    value (float): The numeric value
  Returns: String containing JSON field or empty string if value is na

_buildNestedObject(objectType, price, amount, percent, stopType, limitPrice, trailAmount, trailPercent)
  Build nested JSON objects for takeProfit/stopLoss
  Parameters:
    objectType (string): The type of object being built ("takeProfit" or "stopLoss")
    price (float): The limit price for TP or stop price for SL
    amount (float): The dollar amount (optional)
    percent (float): The percentage (optional)
    stopType (series StopLossType): The stop loss type - only for stopLoss
    limitPrice (float): The limit price for stop_limit orders - only for stopLoss
    trailAmount (float): Trailing amount for trailing stops - only for stopLoss
    trailPercent (float): Trailing percent for trailing stops - only for stopLoss
  Returns: String containing nested JSON object or empty string if no valid data

_validateAndBuildJSON(ticker, action, quantity, quantityType, orderType, sentiment, cancel, timeInForce, limitPrice, stopPrice, trailAmount, trailPercent, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, extendedHours, optionType, intrinsicValue, expiration, strikePrice, signalPrice, comment)
  Master JSON builder that validates parameters and constructs JSON
  Parameters:
    ticker (string): The trading symbol
    action (series Action): The order action (buy, sell, exit, etc.)
    quantity (float): The order quantity
    quantityType (series QuantityType): The type of quantity (fixed, dollar, percent)
    orderType (series OrderType): The order type (market, limit, stop, etc.)
    sentiment (series Sentiment): The position sentiment (long, short, flat) - optional
    cancel (bool): Controls order cancellation (true = cancel existing orders, false = don't cancel)
    timeInForce (series TimeInForce): Time in force for the order (DAY, GTC, IOC, FOK)
    limitPrice (float): Price for limit orders
    stopPrice (float): Price for stop orders
    trailAmount (float): Trailing amount for trailing stops
    trailPercent (float): Trailing percent for trailing stops
    takeProfitPrice (float): Take profit limit price (absolute)
    takeProfitAmount (float): Take profit dollar amount (relative)
    takeProfitPercent (float): Take profit percentage (relative)
    stopLossPrice (float): Stop loss price (absolute)
    stopLossAmount (float): Stop loss dollar amount (relative)
    stopLossPercent (float): Stop loss percentage (relative)
    stopLossType (series StopLossType): Stop loss order type
    stopLossLimitPrice (float): Limit price for stop_limit orders
    extendedHours (bool): Enable extended hours trading (boolean)
    optionType (series OptionType): Option type for options trading (both/call/put)
    intrinsicValue (series IntrinsicValue): Intrinsic value filter for options (itm/otm)
    expiration (string): Option expiration (date string)
    strikePrice (float): Option strike price
    signalPrice (float): The market price at alert time (for slippage tracking)
    comment (string): Optional comment for the order (shows in TradersPost UI for debugging)
  Returns: ErrorResponse with success status and JSON string or error details

ValidateOrder(ticker, action, orderType, limitPrice, stopPrice)
  Validate order parameters before JSON construction
  Parameters:
    ticker (string): Trading symbol
    action (series Action): Order action
    orderType (series OrderType): Order type (market, limit, stop, etc.)
    limitPrice (float): Limit price for limit orders
    stopPrice (float): Stop price for stop orders
  Returns: ErrorResponse with validation results

ValidateQuantity(quantity, quantityType)
  Validate quantity based on type and constraints
  Parameters:
    quantity (float): The quantity value
    quantityType (series QuantityType): The type of quantity
  Returns: ErrorResponse with validation results

ValidatePrices(entryPrice, stopPrice, takeProfitPrice, action)
  Validate price relationships and values
  Parameters:
    entryPrice (float): Entry price for the order
    stopPrice (float): Stop loss price
    takeProfitPrice (float): Take profit price
    action (series Action): Order action (buy/sell)
  Returns: ErrorResponse with validation results

ValidateSymbol(ticker)
  Validate trading symbol format
  Parameters:
    ticker (string): The symbol to validate
  Returns: ErrorResponse with validation results

CombineValidationResults(validationResults)
  Create validation error collection and reporting system
  Parameters:
    validationResults (array<ErrorResponse>): Array of ErrorResponse objects from multiple validations
  Returns: Combined ErrorResponse with all validation results

ValidateCompleteOrder(ticker, action, quantity, quantityType, orderType, limitPrice, stopPrice, takeProfitPrice)
  Comprehensive validation for all order parameters
  Parameters:
    ticker (string): Trading symbol
    action (series Action): Order action
    quantity (float): Order quantity
    quantityType (series QuantityType): Type of quantity
    orderType (series OrderType): Order type
    limitPrice (float): Limit price (optional)
    stopPrice (float): Stop price (optional)
    takeProfitPrice (float): Take profit price (optional)
  Returns: ErrorResponse with complete validation results

CreateErrorResponse(success, errorMessages, message, severity, context, functionName)
  Create standardized error response
  Parameters:
    success (bool): Whether the operation succeeded
    errorMessages (array<string>): Array of error messages
    message (string): Summary message
    severity (series ErrorSeverity): Error severity level
    context (string): Context where error occurred
    functionName (string): Name of function that generated error
  Returns: EnhancedErrorResponse with all error details

HandleValidationError(validationResult, context, functionName)
  Handle validation errors with context
  Parameters:
    validationResult (ErrorResponse): The validation result to handle
    context (string): Description of what was being validated
    functionName (string): Name of calling function
  Returns: Processed error response with enhanced context

LogError(errorResponse, displayOnChart)
  Log error with appropriate level
  Parameters:
    errorResponse (EnhancedErrorResponse): The error response to log
    displayOnChart (bool): Whether to show error on chart

CreateSuccessResponse(message, context, functionName)
  Create success response
  Parameters:
    message (string): Success message
    context (string): Context of successful operation
    functionName (string): Name of function
  Returns: Success response

_validateJSONConstruction(jsonString)
  Validate JSON construction and handle malformed data
  Parameters:
    jsonString (string): The constructed JSON string
  Returns: ErrorResponse indicating if JSON is valid

CreateDetailedError(success, errors, warnings, severity, context)
  Create detailed error response with context
  Parameters:
    success (bool): Operation success status
    errors (array<string>): Array of error messages
    warnings (array<string>): Array of warning messages
    severity (series ErrorSeverity): Error severity level
    context (string): Context where error occurred
  Returns: DetailedErrorResponse object

LogDetailedError(response)
  Log detailed error response with appropriate severity
  Parameters:
    response (DetailedErrorResponse): DetailedErrorResponse to log
  Returns: Nothing - logs to Pine Script console

CombineIntoDetailedResponse(responses, context)
  Combine multiple error responses into detailed response
  Parameters:
    responses (array<ErrorResponse>): Array of ErrorResponse objects to combine
    context (string): Context for the combined operation
  Returns: DetailedErrorResponse with combined results

SendAdvancedOrder(ticker, action, quantity, quantityType, orderType, sentiment, cancel, limitPrice, stopPrice, trailAmount, trailPercent, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, extendedHours, optionType, intrinsicValue, expiration, strikePrice, signalPrice, comment)
  Send advanced order with comprehensive parameter validation and JSON construction
  Parameters:
    ticker (string): Symbol to trade (defaults to syminfo.ticker)
    action (series Action): Order action (buy/sell/exit/cancel/add)
    quantity (float): Order quantity
    quantityType (series QuantityType): Type of quantity (fixed/dollar/percent)
    orderType (series OrderType): Type of order (market/limit/stop/stop_limit/trailing_stop)
    sentiment (series Sentiment): Position sentiment (long/short/flat, optional)
    cancel (bool): Controls order cancellation (true = cancel existing, false = don't cancel, na = use defaults)
    limitPrice (float): Limit price for limit orders
    stopPrice (float): Stop price for stop orders
    trailAmount (float): Trailing amount for trailing stops
    trailPercent (float): Trailing percent for trailing stops
    takeProfitPrice (float): Take profit limit price (absolute)
    takeProfitAmount (float): Take profit dollar amount (relative)
    takeProfitPercent (float): Take profit percentage (relative)
    stopLossPrice (float): Stop loss price (absolute)
    stopLossAmount (float): Stop loss dollar amount (relative)
    stopLossPercent (float): Stop loss percentage (relative)
    stopLossType (series StopLossType): Stop loss order type
    stopLossLimitPrice (float): Limit price for stop_limit orders
    extendedHours (bool): Enable extended hours trading (boolean)
    optionType (series OptionType): Option type for options trading (both/call/put)
    intrinsicValue (series IntrinsicValue): Intrinsic value filter for options (itm/otm)
    expiration (string): Option expiration (date string)
    strikePrice (float): Option strike price
    signalPrice (float): The market price at alert time (for slippage tracking)
    comment (string): Optional comment for the order (shows in TradersPost UI for debugging)
  Returns: ErrorResponse with success status and JSON or error details

SendSentiment(ticker, sentiment, quantity, quantityType, signalPrice, comment)
  Send sentiment-based position management order
  Parameters:
    ticker (string): Symbol to manage (defaults to syminfo.ticker)
    sentiment (series Sentiment): Target position sentiment (long/short/flat)
    quantity (float): Position size (optional, uses account default if not specified)
    quantityType (series QuantityType): Type of quantity specification
    signalPrice (float): The market price at alert time (for slippage tracking)
    comment (string): Optional comment
  Returns: ErrorResponse with success status

SendCancelAll(ticker, comment)
  Cancel all open orders for the specified symbol
  Parameters:
    ticker (string): Symbol to cancel orders for (defaults to syminfo.ticker)
    comment (string): Optional comment for the cancellation
  Returns: ErrorResponse with success status

SendOrderNoCancelExisting(ticker, action, quantity, quantityType, orderType, sentiment, limitPrice, stopPrice, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, signalPrice, comment)
  Send order without canceling existing orders
  Parameters:
    ticker (string): Symbol to trade (defaults to syminfo.ticker)
    action (series Action): Order action (buy/sell/exit)
    quantity (float): Order quantity
    quantityType (series QuantityType): Type of quantity (fixed/dollar/percent)
    orderType (series OrderType): Type of order (market/limit/stop/stop_limit)
    sentiment (series Sentiment): Position sentiment (long/short/flat, optional)
    limitPrice (float): Limit price for limit orders
    stopPrice (float): Stop price for stop orders
    takeProfitPrice (float): Take profit price
    takeProfitAmount (float): Take profit amount (optional)
    takeProfitPercent (float)
    stopLossPrice (float): Stop loss price
    stopLossAmount (float): Stop loss amount (optional)
    stopLossPercent (float): Stop loss percentage (optional)
    stopLossType (series StopLossType): Stop loss order type
    stopLossLimitPrice (float): Limit price for stop_limit orders
    signalPrice (float): The market price at alert time (for slippage tracking)
    comment (string): Optional comment
  Returns: ErrorResponse with success status

_buildBracketOrderParams(orderType, entryPrice, entryLimitPrice)
  Build bracket order parameters by routing entryPrice to correct parameter based on orderType
This helper function maps the conceptual "entryPrice" to the technical parameters needed
  Parameters:
    orderType (series OrderType): The order type for the entry order
    entryPrice (float): The desired entry price (trigger for stops, limit for limits)
    entryLimitPrice (float): The limit price for stop_limit orders (optional)
  Returns: [limitPrice, stopPrice] array with correct routing

SendBracketOrder(ticker, action, quantity, quantityType, orderType, entryPrice, entryLimitPrice, takeProfitPrice, stopLossPrice, takeProfitAmount, takeProfitPercent, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, signalPrice, comment)
  Send bracket order (entry + take profit + stop loss)
  Parameters:
    ticker (string): Symbol to trade
    action (series Action): Entry action (buy/sell)
    quantity (float): Order quantity
    quantityType (series QuantityType): Type of quantity specification
    orderType (series OrderType): Type of entry order
    entryPrice (float): Entry price (trigger price for stop orders, limit price for limit orders)
    entryLimitPrice (float): Entry limit price (only for stop_limit orders, defaults to entryPrice if na)
    takeProfitPrice (float): Take profit price
    stopLossPrice (float): Stop loss price
    takeProfitAmount (float): Take profit dollar amount (alternative to price)
    takeProfitPercent (float): Take profit percentage (alternative to price)
    stopLossAmount (float): Stop loss dollar amount (alternative to price)
    stopLossPercent (float): Stop loss percentage (alternative to price)
    stopLossType (series StopLossType): Stop loss order type
    stopLossLimitPrice (float): Limit price for stop_limit orders
    signalPrice (float): The market price at alert time (for slippage tracking)
    comment (string): Optional comment
  Returns: ErrorResponse with success status

SendOTOOrder(primaryTicker, primaryAction, primaryQuantity, primaryOrderType, primaryPrice, secondaryTicker, secondaryAction, secondaryQuantity, secondaryOrderType, secondaryPrice, signalPrice, comment)
  Send One-Triggers-Other (OTO) order sequence
Note: OTO linking must be configured in TradersPost strategy settings
This sends two separate orders - TradersPost handles the OTO logic
  Parameters:
    primaryTicker (string): Primary order ticker
    primaryAction (series Action): Primary order action
    primaryQuantity (float): Primary order quantity
    primaryOrderType (series OrderType): Primary entry type
    primaryPrice (float): Primary order price
    secondaryTicker (string): Secondary order ticker (defaults to primary ticker)
    secondaryAction (series Action): Secondary order action
    secondaryQuantity (float): Secondary order quantity
    secondaryOrderType (series OrderType): Secondary entry type
    secondaryPrice (float): Secondary order price
    signalPrice (float): The market price at alert time (for slippage tracking)
    comment (string): Optional comment for both orders
  Returns: ErrorResponse with success status

SendOCOOrder(ticker, firstAction, firstQuantity, firstOrderType, firstPrice, secondAction, secondQuantity, secondOrderType, secondPrice, signalPrice, comment)
  Send One-Cancels-Other (OCO) order pair
Note: OCO linking must be configured in TradersPost strategy settings
This sends two separate orders - TradersPost handles the OCO logic
  Parameters:
    ticker (string): Symbol for both orders
    firstAction (series Action): Action for first order
    firstQuantity (float): Quantity for first order
    firstOrderType (series OrderType): Order type for first order
    firstPrice (float): Price for first order
    secondAction (series Action): Action for second order
    secondQuantity (float): Quantity for second order
    secondOrderType (series OrderType): Order type for second order
    secondPrice (float): Price for second order
    signalPrice (float): The market price at alert time (for slippage tracking)
    comment (string): Optional comment
  Returns: ErrorResponse with success status

ErrorResponse
  Fields:
    success (series bool)
    errors (array<string>)
    message (series string)

EnhancedErrorResponse
  Fields:
    success (series bool)
    errors (array<string>)
    message (series string)
    severity (series ErrorSeverity)
    context (series string)
    timestamp (series int)
    functionName (series string)

DetailedErrorResponse
  Fields:
    success (series bool)
    errors (array<string>)
    warnings (array<string>)
    severity (series ErrorSeverity)
    context (series string)
    message (series string)

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.