Ventura EaseAPI Integration with ASP.NET Core Web API Using C# – Step-by-Step Guide

Learn Ventura EaseAPI integration with ASP.NET Core and C#. Build a trading API, place orders, connect TradingView webhooks, and handle errors.

Integrating a stockbroker API with ASP.NET Core is a practical way to learn HTTP APIs, authentication, background processing, and reliable order management. In this tutorial, we will build a small .NET client for Ventura Securities EaseAPI, place a controlled intraday order request, and discuss how to extend the design for TradingView webhook alerts.

The goal is to explain the integration clearly, including problems developers can encounter in real deployments: expired sessions, incorrect instrument IDs, invalid product codes, tick-size errors, and orders that are accepted by an API but later rejected by the broker or exchange.

What you'll build
  • ASP.NET Core Web API project
  • Typed Ventura API client using HttpClient
  • Secure configuration of client ID, app key and access token
  • Intraday order request and response models
  • Safe, explicitly enabled order submission endpoint
  • Design for TradingView webhook integration
  • Order status verification and troubleshooting checklist
Important: This is a developer tutorial, not financial advice. A live order can lose money. The sample disables live order placement by default. Use broker-approved testing arrangements and verify the latest API documentation before enabling real orders.

What Is Ventura EaseAPI?

EaseAPI is Ventura Securities' API offering for accessing trading functions programmatically. Its documentation includes authentication, instruments, market data, placing and modifying orders, order books, trade books, positions, and WebSocket services.

Official documentation: Ventura EaseAPI — Place Order.

Understanding the Integration Architecture

TradingView alert (optional)
          |
          v
ASP.NET Core webhook/API
          |
          v
Validate secret, signal and instrument
          |
          v
Risk checks + duplicate prevention
          |
          v
Ventura EaseAPI HTTP client
          |
          v
Broker order reference
          |
          v
Order Book / Trade Book reconciliation

The crucial distinction is that an HTTP response or an order reference does not guarantee an executed trade. Your application must separately confirm the final order status and filled quantity.

Prerequisites

  • A supported .NET SDK and basic C# knowledge
  • Visual Studio or Visual Studio Code
  • An eligible Ventura trading account with API access enabled
  • Ventura client ID, application key and a valid access token obtained through the documented login flow
  • Access to the instrument master and a permitted test instrument
  • Postman or PowerShell for HTTP testing

Check the installed SDK:

dotnet --version

Step 1: Create an ASP.NET Core Web API

dotnet new webapi -n VenturaEaseApiDemo
cd VenturaEaseApiDemo
mkdir Models
mkdir Services

The examples below use built-in .NET functionality, so a separate third-party HTTP package is not required.

Step 2: Configure the Ventura Connection

Add this section to appsettings.json:

{
  "Ventura": {
    "BaseUrl": "https://easeapi.venturasecurities.com/",
    "ClientId": "",
    "AppKey": "",
    "AccessToken": "",
    "EnableLiveOrders": false
  }
}

For local development, store credentials in .NET user secrets rather than committing them to the repository:

dotnet user-secrets init
dotnet user-secrets set "Ventura:ClientId" "YOUR_CLIENT_ID"
dotnet user-secrets set "Ventura:AppKey" "YOUR_APP_KEY"
dotnet user-secrets set "Ventura:AccessToken" "YOUR_CURRENT_ACCESS_TOKEN"
Security note: Never publish your actual access token, application key, trading PIN, TOTP seed or webhook secret in blog posts, screenshots, Git repositories or client-side JavaScript. An access token can expire; this tutorial assumes you have obtained a currently valid token through Ventura's documented authentication process.

Step 3: Define the Order Models

Create Models/VenturaOrderRequest.cs:

using System.Text.Json.Serialization;

namespace VenturaEaseApiDemo.Models;

public sealed class VenturaOrderRequest
{
    [JsonPropertyName("instrument_id")]
    public long InstrumentId { get; set; }

    [JsonPropertyName("exchange")]
    public string Exchange { get; set; } = "NSE";

    [JsonPropertyName("segment")]
    public string Segment { get; set; } = "D";

    [JsonPropertyName("transaction_type")]
    public string TransactionType { get; set; } = "B";

    [JsonPropertyName("order_type")]
    public string OrderType { get; set; } = "LMT";

    [JsonPropertyName("quantity")]
    public int Quantity { get; set; }

    [JsonPropertyName("price")]
    public decimal Price { get; set; }

    [JsonPropertyName("trigger_price")]
    public decimal TriggerPrice { get; set; }

    [JsonPropertyName("product")]
    public string Product { get; set; } = "I";

    [JsonPropertyName("validity")]
    public string Validity { get; set; } = "DAY";

    [JsonPropertyName("disclosed_quantity")]
    public int DisclosedQuantity { get; set; }

    [JsonPropertyName("off_market_flag")]
    public int OffMarketFlag { get; set; }
}

The API uses B for buy, S for sell, LMT for limit orders and MKT for market orders. The intraday endpoint's documented sample uses product: "I". Do not assume the same product value is valid on every Ventura endpoint: the delivery and intraday routes have different purposes.

Step 4: Create the Ventura HTTP Client

Create Services/VenturaClient.cs:

using System.Net.Http.Headers;
using System.Net.Http.Json;
using VenturaEaseApiDemo.Models;

namespace VenturaEaseApiDemo.Services;

public sealed class VenturaClient
{
    private readonly HttpClient _http;
    private readonly IConfiguration _config;

    public VenturaClient(HttpClient http, IConfiguration config)
    {
        _http = http;
        _config = config;
    }

    public async Task<string> PlaceIntradayOrderAsync(
        VenturaOrderRequest order,
        CancellationToken cancellationToken = default)
    {
        string clientId = Required("Ventura:ClientId");
        string appKey = Required("Ventura:AppKey");
        string token = Required("Ventura:AccessToken");

        using var request = new HttpRequestMessage(
            HttpMethod.Post, "trade/v1/intraday/regular");

        request.Headers.Add("x-client-id", clientId);
        request.Headers.Add("x-app-key", appKey);
        request.Headers.Authorization =
            new AuthenticationHeaderValue("Bearer", token);
        request.Content = JsonContent.Create(order);

        using var response = await _http.SendAsync(
            request, cancellationToken);
        string body = await response.Content.ReadAsStringAsync(
            cancellationToken);

        if (!response.IsSuccessStatusCode)
            throw new HttpRequestException(
                $"Ventura HTTP {(int)response.StatusCode}: {body}");

        // A successful HTTP response is NOT proof of execution.
        return body;
    }

    private string Required(string key) =>
        !string.IsNullOrWhiteSpace(_config[key])
            ? _config[key]!
            : throw new InvalidOperationException(
                $"Missing configuration: {key}");
}

The client sends the headers documented by Ventura: x-client-id, x-app-key and Authorization: Bearer .... The JSON body follows the documented intraday order request fields.

Step 5: Register the Client in Program.cs

using VenturaEaseApiDemo.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddHttpClient<VenturaClient>(client =>
{
    client.BaseAddress = new Uri(
        builder.Configuration["Ventura:BaseUrl"]
        ?? "https://easeapi.venturasecurities.com/");
    client.Timeout = TimeSpan.FromSeconds(30);
});

var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();

Step 6: Create a Protected Order Endpoint

For a safe demonstration, this endpoint refuses to send orders unless live trading is explicitly enabled. It also requires a separate application-level API key. For production, prefer a full authentication and authorization system and stronger order-level controls.

Create Controllers/OrdersController.cs:

using Microsoft.AspNetCore.Mvc;
using VenturaEaseApiDemo.Models;
using VenturaEaseApiDemo.Services;

namespace VenturaEaseApiDemo.Controllers;

[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
    private readonly VenturaClient _ventura;
    private readonly IConfiguration _config;

    public OrdersController(VenturaClient ventura,
        IConfiguration config)
    {
        _ventura = ventura;
        _config = config;
    }

    [HttpPost("intraday")]
    public async Task<IActionResult> Place(
        [FromBody] VenturaOrderRequest order,
        CancellationToken cancellationToken)
    {
        string? expectedKey = _config["OrderApiKey"];
        string? providedKey = Request.Headers["X-Order-Api-Key"];

        if (string.IsNullOrWhiteSpace(expectedKey) ||
            string.IsNullOrWhiteSpace(providedKey) ||
            !System.Security.Cryptography.CryptographicOperations
                .FixedTimeEquals(
                    System.Text.Encoding.UTF8.GetBytes(expectedKey),
                    System.Text.Encoding.UTF8.GetBytes(providedKey)))
            return Unauthorized();

        if (order.InstrumentId <= 0 || order.Quantity <= 0 ||
            order.Quantity > 65 ||
            order.Exchange != "NSE" || order.Segment != "D" ||
            order.Product != "I" ||
            (order.TransactionType != "B" &&
             order.TransactionType != "S") ||
            order.OrderType != "LMT" || order.Price <= 0 ||
            order.TriggerPrice != 0 || order.Validity != "DAY" ||
            order.DisclosedQuantity != 0 || order.OffMarketFlag != 0)
            return BadRequest("Order violates demo limits.");

        if (!_config.GetValue<bool>("Ventura:EnableLiveOrders"))
            return Ok(new {
                simulated = true,
                message = "Live orders disabled; nothing sent to Ventura.",
                order
            });

        string result = await _ventura.PlaceIntradayOrderAsync(
            order, cancellationToken);
        return Content(result, "application/json");
    }
}

Set the API key locally:

dotnet user-secrets set "OrderApiKey" "REPLACE_WITH_A_LONG_RANDOM_VALUE"

The 65-unit limit is an illustrative safety cap, not a universal lot size. Real F&O lot sizes change by instrument and date. The server must verify permitted instruments, current lot sizes, tick sizes, open positions, buying power, and trading permissions before any real order.

Step 7: Test Without Sending a Real Order

Start the application:

dotnet run

Send a request from PowerShell. Replace the port, API key and instrument ID with values from your own development setup. Keep EnableLiveOrders set to false.

$body = @{
  instrument_id = 123456
  exchange = "NSE"
  segment = "D"
  transaction_type = "B"
  order_type = "LMT"
  quantity = 65
  price = 50.00
  trigger_price = 0
  product = "I"
  validity = "DAY"
  disclosed_quantity = 0
  off_market_flag = 0
} | ConvertTo-Json

Invoke-RestMethod `
  -Uri "https://localhost:YOUR_PORT/api/orders/intraday" `
  -Method Post `
  -Headers @{ "X-Order-Api-Key" = "YOUR_ORDER_API_KEY" } `
  -ContentType "application/json" `
  -Body $body

The example instrument ID and price are placeholders. They must not be used for live trading. With live orders disabled, the endpoint returns a simulated response and does not contact Ventura.

Step 8: Understand Instrument IDs and Option Symbols

A TradingView symbol and a broker's instrument identifier are not interchangeable. For derivatives, a valid instrument must match the correct underlying, expiry date, option type, strike price and exchange segment.

FieldPurpose
Trading symbolHuman-readable contract name
Instrument IDBroker-specific tradable identifier
Lot sizeValid contract quantity increment
Tick sizeValid price increment

Do not guess the instrument ID or hard-code a permanent option lot size. Refresh and validate against Ventura's instrument data. Also verify whether the specific API route expects quantity in units or lots before sending an F&O order.

Step 9: Connecting TradingView Alerts

A TradingView strategy can send a webhook to an HTTPS endpoint that your ASP.NET Core application exposes. A typical alert body might contain the following fields:

{
  "secret": "YOUR_WEBHOOK_SECRET",
  "signalId": "{{ticker}}-{{interval}}-{{time}}-{{strategy.order.action}}",
  "symbol": "{{ticker}}",
  "action": "{{strategy.order.action}}",
  "price": "{{strategy.order.price}}",
  "timeframe": "{{interval}}",
  "barTime": "{{time}}",
  "contracts": "{{strategy.order.contracts}}",
  "positionSize": "{{strategy.position_size}}"
}

These are TradingView alert placeholders, not Ventura's order request schema. A gateway must validate the secret, reject replayed or duplicate signals, map the symbol to the correct Ventura instrument ID, convert action and quantity, and apply risk checks before constructing a broker order.

Do not trust client-supplied contracts or price without server-side validation. Keep the webhook receiver separate from the authenticated order-management API, and avoid placing broker credentials in TradingView alerts.

Step 10: Confirm Order Execution

After submitting an order, save the returned order reference and query Ventura's Order Book or Trade Book to determine whether it is pending, partially filled, executed, cancelled or rejected. Reconcile those results with your application's internal state.

For example, a webhook may be accepted and a request may be sent successfully, yet the resulting order may still be rejected for insufficient funds. In that case, a dashboard label such as SENT_TO_VENTURA should not be displayed as EXECUTED.

Production requirement: Before using this pattern for automated trading, implement durable signal storage, idempotency, order-status polling or WebSocket updates, broker-position reconciliation, a kill switch, daily risk limits, and safe handling of network timeouts. Never blindly retry a timed-out order without checking whether it was accepted.

Common Ventura EaseAPI Integration Problems

401 Unauthorized — Enter Auth Token

Check that the token is valid, belongs to the expected account, and is passed in the Bearer authorization header. Follow Ventura's supported login and session-renewal flow.

Instrument Not Found

Confirm the instrument ID against the latest broker instrument data. Pay special attention to weekly option expiry formats, strikes and segments.

Invalid Product Type

Check the exact API endpoint. Ventura documents I for its intraday regular order example, while other order routes can require different product values. Never solve a validation error by randomly changing product codes.

Order Price Is Not a Multiple of Tick Size

Use the instrument's current tick size and validate limit prices before submission. A price that looks reasonable can still be invalid for the selected contract.

Insufficient Funds

The broker may reject an order because available funds or margin are insufficient. A successful webhook response does not override the broker's risk checks.

Market Order Filled at an Unexpected Price

Market orders seek available liquidity and do not guarantee the signal price. For illiquid options, the bid–ask spread and slippage can be significant. Use appropriate order controls and consider whether a validated limit order is more suitable.

Webhook Accepted but No Trade Appears

Trace the signal ID through validation, instrument mapping, outbound HTTP request, broker response, order reference, and final Order Book status. Avoid reporting a trade as executed until the broker confirms a fill.

Security and Reliability Best Practices

  • Store credentials in a secure secret store and rotate them when needed.
  • Use HTTPS for both incoming webhooks and broker API calls.
  • Authenticate administrative endpoints separately from TradingView webhooks.
  • Reject duplicate signals and record every state transition.
  • Validate instruments, quantities, tick sizes, positions and trading hours.
  • Use structured logs without exposing tokens or personal trading details.
  • Start with simulated orders and manually verified broker tests.
  • Implement an emergency stop and explicit limits before enabling automation.

Frequently Asked Questions

Can I integrate Ventura EaseAPI with C# and ASP.NET Core?

Yes. ASP.NET Core can call Ventura's documented HTTPS endpoints using HttpClient, provided your account has the necessary API access and credentials.

Can TradingView place Ventura orders directly?

TradingView webhook alerts are messages, not Ventura API orders. A middleware service can validate and translate those messages into authenticated broker requests.

Does a successful API response mean my order executed?

No. Always confirm the actual status and filled quantity using broker order and trade records.

Should I use market or limit orders?

That depends on the instrument, liquidity, risk controls and your execution requirements. Market orders can experience slippage; limit orders can remain unfilled.

Can I store my Ventura token in appsettings.json?

Avoid storing real credentials in committed configuration files. Use user secrets for local development and a managed secret store for production.

Is this sample ready for unattended live trading?

No. It demonstrates the API integration pattern. Production trading needs additional authentication, broker reconciliation, risk management, durable processing, monitoring and operational safeguards.

Conclusion

We created an ASP.NET Core client for Ventura EaseAPI, modeled an intraday order, configured secure HTTP headers, built a disabled-by-default test endpoint, and outlined the TradingView webhook architecture. The most important engineering lesson is to distinguish signal received, order submitted and trade executed.

Before enabling live orders, review the current official Ventura order documentation, validate all contract metadata and implement broker-side status reconciliation. Reliable automation depends as much on safeguards and accurate state tracking as on the initial API call.

Hello! My name is Aniket Shahane and I am a senior software consultant. I hold a post-graduate degree (MTech) in Computer Science and Engineering, and I have a passion for using my technical expertise to solve complex problems. I am excited to be here and eager to share my knowledge and experience with you.

Post a Comment