Register

Quanty · Agentic AI

Broker API Code Templates for Trading

A broker API code template can give you a repeatable starting point for one task, such as requesting a page of historical candles or handling an unavailable quote. It is not a broker account, a source of credentials or a shortcut around a provider's controls. This guide covers read-only examples, clear adapter boundaries and checks you can run without credentials. Quanty Code is in testing (beta). QuantPower is software, not an adviser.

1. Decide what the adapter does and what it cannot do

Put the job in one sentence: “Retrieve completed candles for an instrument I specify and return them in an agreed format.” That sentence lets a reviewer see why a symbol, an interval and a date range are needed. It gives no reason to ask for holdings, cash balances or a way to change an order. If a template includes other capabilities, remove them from this example rather than assuming unused methods will stay unused.

Separate three parts: obtaining data, converting the result and analyzing it. A data adapter deals with the broker interface. A converter produces the contract used by your program, which might be a list of consistent rows. An analysis function takes those rows and calculates the output you asked for. In a local test, replace only the data adapter with a fixture. If the analysis function needs a real account to run, responsibilities are probably mixed.

Choose what “read-only” means for this example before looking at code. The program may need to request historical data and inspect the returned response. It should not submit, modify, cancel or confirm an order. It does not need to manage the account. Document the permitted operation in the setup note and test that the program has no call path for writes. When a broker allows scopes to be chosen, request only what the specific read operation needs.

For the zero-credential example, supply one small sample file and a command that never opens a socket. Let a reviewer run the same calculation and see what happens when a response is invalid. The sample output should display a label such as “fictional data” near the first result. A real response and a simulated response must not be indistinguishable in logs or exports. Otherwise a successful local run can be mistaken for a live connection.

2. Start with the provider's contract, not with a guessed endpoint

Use the documentation for the broker and API version you intend to use. Write down the path, HTTP method, input fields, supported interval values, response shape and authentication requirements for the documented read request. A template on its own cannot know which features your account is enabled for. If you cannot verify a field or endpoint, leave a clear placeholder or stop to obtain the right documentation instead of inventing what it probably is.

Some providers use a symbol as a lookup input and a separate identifier in the candle request. A symbol can map to more than one instrument or venue. If the request refers to a future or option, specify enough information to pick one contract, if that is part of your authorized task. Do not let the first search result silently stand in for the exact instrument. A mismatch can look like valid data because the response contains real-looking numbers and timestamps.

Confirm the interval name and boundary conventions. Some interfaces accept a text label; others accept a number or a named value. A request for fifteen minutes needs to match the documented interval field. Also check whether the end of the requested range is inclusive or exclusive. If this is not documented, use small non-sensitive queries in the provider's test environment when available, compare the boundary, and record the observed behaviour instead of presenting it as universal.

Do not treat an example request in a template as confirmation that the provider supports an entire product area. Requirements and API versions change. Save a reference to the documentation and the date you checked it. If the source changes, run the local tests first, then recheck the smallest read-only request you need. When you share the adaptation, explain which part is a general pattern and which part follows one provider's documented contract.

3. Keep credentials out of the files you share

The code should expect credentials to come from an appropriate private environment or other credential mechanism you manage. A configuration example should use names, not real values. Do not put a key in the source file, a test fixture, a request printed in a chat, the front end, or a screenshot. If a test needs to represent an authentication response, use a strict fake marker in the fixture and test the intended behaviour without any actual secret.

Review logging before raising its level. A request URL, header dump or raw response may contain information that should not be shared. Error reports can state the provider response category, the requested operation and a safe request reference without reproducing a credential. Avoid assuming that a field named “detail” is safe to print. It might repeat content from the request. Capture the least data you need to troubleshoot.

Separate provider data from authentication failures. Log “authentication failed” rather than printing all headers or the response body. The HTTP semantics standard defines 401 as a request that lacks valid authentication credentials for the target resource, and 403 as an understood request that the server refuses to fulfill. A broker can add its own documented details. Do not retry an invalid credential as though it were a temporary network pause.

If a provider uses an expiry or renewal process, record which step needs the account holder and follow the provider's approved method. A template cannot renew a session on your behalf without the appropriate credentials and permissions. Do not copy a production credential into a second environment just to make a test green. A successful fixture run and a successful authenticated read are separate receipts, and you can finish most development before attempting the second.

4. Give the converter one clear output shape

Write the expected result with sample values. A candle row might include a timezone-aware start timestamp and numeric opening, high, low and closing prices. Include volume only if you require it and know its meaning. The converter should reject an incomplete required record or handle it according to a stated policy. It should never quietly invent a missing price. A clear row contract also makes it possible to compare two adapters without changing downstream code.

Check timestamps separately from their text format. A provider may return a numeric epoch, an ISO-style timestamp with an offset, or a date string whose timezone the documentation defines. The numeric scale matters: a value in seconds is not the same as a value in milliseconds. Specify which format is accepted and what zone is used internally. Test at least one timestamp near a boundary rather than using only records in the middle of a session.

Price units matter just as much. If the provider uses decimals in rupees and the rest of your program expects paise, put the conversion in one place and test it with a non-round example. If a record has a high lower than its low, do not silently accept it as a valid candle. If a volume field can be absent or use a nonstandard convention for the instrument, document what downstream code will do. The goal is predictable reasoning about each row.

When the interface returns a row with the wrong number of values or an unexpected nested structure, report which shape failed without dumping the response. You can save a carefully sanitized sample during debugging, but do not imply it is suitable for sharing by default. Build tests from explicitly fictional values in the same shape. This gives other people enough information to reproduce the failure while keeping account and provider details out of a public attachment.

5. Treat an empty response, an incomplete response and an error differently

A successful read with no rows might be valid for a requested period. It might also mean a wrong symbol, a limit not supported by the provider or a request outside the available history. A nonempty result may also be incomplete. Look for the provider's documented status fields and cursor rules, then keep these situations separate in the adapter output. Showing “0 rows” without any status can hide the fact that the operation never had a valid response.

A malformed response should not be passed to the calculation as an empty table. For example, an authentication platform can return an HTML sign-in page, while the adapter expected a JSON document. Even a response whose HTTP status looks successful may contain a provider-specific error marker. Check expected content and structure before calling the analysis function. The app can then show a clear message, rather than calculating blanks and claiming there were no signals.

A partly successful series needs a policy. You may want to keep a labelled partial result for diagnosis, but downstream analysis should not mistake it for complete history. Mark which requested range was actually covered, the number of validated rows and any failure that stopped the read. A graph without those limitations could look complete. If completeness matters to the calculation, an explicit stop is better than a confident-looking report on half the expected period.

Write one fixture for each outcome: a valid page, a valid empty page, a non-JSON page, and a provider-style error. Include a fifth case where one row is invalid within an otherwise valid result. Test the adapter's distinction rather than relying on human inspection of its logs. A simple test can assert that the calculation function does not run when validation fails. That protects the boundary even when someone later changes how results are displayed.

6. Define pagination and date boundaries before combining pages

Historical-data services sometimes return results in pages rather than one large payload. Find the documented next-page signal and implement only that rule. A cursor is usually not a date you can manipulate. An empty page is not automatically the end if the interface explicitly provides a next cursor. State what should happen when a next cursor repeats or a provider returns an unexpected combination of rows and cursor, so a bad response cannot send the program through the same page forever.

The safest review example uses two or three fixtures. First, provide a page with a next cursor. Second, provide another page that ends the sequence. Third, include a page that repeats a cursor or the boundary candle. Check that the final output either follows your documented deduplication rule or reports the overlap. Silently dropping a record can hide a data correction. Silently adding it can change a rolling indicator. The right choice depends on the intended use and the provider's documented behaviour.

Use an explicit bound on pages, records or duration for a sample. A request for a long history may be restricted by the provider, and it is also hard to inspect. Begin with a short interval in a test environment if there is one. Report the actual range covered at the end. If the final page is missing, do not present earlier rows as if the request succeeded in full. Preserve the fail reason while avoiding exposure of account identifiers.

When stitching separate date windows, state the expected ordering before concatenating them. If adjacent windows both include the boundary, one row may appear twice. If both exclude it, a row may be missing. Test the exact boundary in a local fixture. This is especially useful when one interface labels each interval by open time and another labels it by close time. Changing the label does not convert one series into the other unless the boundaries are genuinely aligned.

7. Handle timeouts and rate limits as separate outcomes

Choose a bounded timeout for an example read. It should stop waiting rather than appear to hang indefinitely when the service does not respond. Decide what the user sees on a timeout. A read-only example may allow a small documented retry policy for certain temporary failures. Keep the attempts bounded, log the decision in safe terms, and respect the provider's limits. Do not reuse a read retry policy for write requests or actions that might have already had an effect.

A rate-limit response is not the same thing as a connection timeout. Follow provider guidance on when another request is permitted. Some services give a waiting hint, while others document a limit per account or operation. Treat any limits in a generic code example as illustrative, not as confirmation of your account's allowance. If a script is going to run in parallel, review the combined workload rather than multiplying a limit independently for each worker.

Use a no-sleep test with a fake clock or injected wait operation. Simulate a temporary refusal and then a successful read. Record how many attempts were made and verify that the fixture for an invalid request does not get retried automatically. Also test that the final failure is returned with a clear category. If a timeout loops until it succeeds, a successful test that uses a fast response tells you nothing about the broken path.

Do not use retry code to work around account permissions, rate policies or other provider controls. If a request is refused because the account is not authorized, resolve the access issue with the appropriate party. If the adapter has no reason to persist data across runs, leaving it stateless can make a small example easier to reason about. Avoid introducing background tasks, polling and multiple retries to a starter whose immediate purpose is only to demonstrate one read.

8. Choose a useful test harness before using a real broker account

A useful adapter exposes a function or boundary that you can replace with a fake service. The fixture should produce the same classes of information as the provider, but with fictional content. Cover a successful response, a response with an invalid field, an empty range and at least one temporary failure. If the template relies on a pagination cursor, cover the terminal case. Make these cases runnable from the code package without configuring an account first.

Use a test that verifies the read-only promise. Check which operation the fake client received, the expected call count, and whether unexpected methods were blocked or simply absent. This helps document what the example is meant to do. Do not treat that test as validation of permissions on the real account. The test covers the code path under the fixture you chose. Account configuration and provider behaviour must be confirmed separately against the intended environment.

The expected value in a test should be specific enough to demonstrate the conversion. It could be a timestamp including its offset, a known list of rows in order, or one value with an exact unit. If every fixture simply checks that the result contains something, it may accept malformed data. A clear error test can also check that broker secrets and raw response content are not printed. Otherwise an exception handler may quietly undo the care you took in the success path.

After local checks, use the smallest read that verifies the adapter's intended boundary. If your own provider offers a test account or sandbox, use that rather than introducing live credentials early. Read and compare a tiny known interval. Capture the outcome without attaching a full response. Keep the receipt limited to the environment, request class, configured interval, response status, and whether the rows passed validation. If this cannot be verified, report it as unverified rather than infer it from a working fixture.

9. Adapt the template without rewriting every layer

Quanty Code gives you a starting set of files. If your requested setting fits a supported field, the generated output can keep most of the code unchanged. Do not confuse a change in symbol or timeframe with implementing a new broker protocol. The same field name in two examples does not guarantee that the values mean the same thing. Read the setup notes and confirm which parts are reusable and which parts need a provider-specific adaptation.

A practical first change is to replace a fictional adapter with your own documented read adapter while leaving the rest unchanged. Rerun the same converter tests. The tests should still pass because the conversion rules are independent of how the raw response arrives. If the provider's shape is different, adjust the parsing code and add targeted fixtures. Do not replace matching fixture values with real private data just to make tests look more representative.

Keep configuration values separate from business decisions. A timeframe configured on a candle request is not a strategy rule by itself. A fixed endpoint in a sample is not a verified availability statement. When you change a template, explain which defaults were changed and which assumptions remain. If assumptions are unknown, prefer an explicit error or a note over a silent guess. Review the generated diff before adding the result to a shared project.

A useful change note says whether the new file adds a network call, changes retention of responses, or allows a new operation. A reviewer may need different evidence for each. If an example file now talks to a broker, tests should still show what happens without credentials and what data is stored. If the adaptation only changes input formatting, run a backward-compatibility fixture. If it changes authentication or permissions, confirm the configuration through the provider rather than inferring it from old sample output.

10. Review outputs without confusing them with authority to trade

A historical-data read is a snapshot of a data source. It does not choose a trade, determine a suitable strategy, or verify the price at which any order would execute. Store a timestamp and an indication of whether data is fictional, delayed, historical or incomplete when you present it. If the chosen interval contains gaps, explain how you handled them. A well-labelled report is easier for someone else to use without drawing conclusions the data cannot support.

Do not automatically hand a converter's output to an order workflow. If a separate project later adds order handling, review its semantics and permissions separately. A calculation tested on stale or incomplete data can make decisions different from the ones a user intended. This guide's example remains a read-only adapter with no order path. Software behavior should be visible and controlled by the person applying their own rules.

A clean access review also includes the reverse direction: what should the script do when the broker is unavailable? It should not substitute a synthetic dataset and label it as retrieved, nor hold an old quote out as current. Decide whether the script can show the last known data with a visible timestamp, or must stop altogether. If someone else consumes the file, provide enough information for their workflow to identify a partial or stale result.

Finally, preserve the exact configuration used for review without keeping the secrets. Record the template version, the approved operation class, the data contract and the test command. Attach representative fictional input and expected output. If you later have evidence from a real read, note the environment and date and separate it from the offline evidence. A successful read of one interval validates that one request, not an entire broker integration or a trading outcome.

11. Use a small handoff packet

A useful handoff contains the prompt, the files that were generated, a short description of any changes, the offline fixtures, and the command used to run the tests. State where the provider-specific documentation lives and which assumptions the template does not cover. A reviewer should know whether a result was obtained from a fictional page, a test environment, or a real read. Do not attach credentials, full responses or identifiers that the reviewer does not need.

Include an example of the failure you care about most. If you were worried about overlapping pages, include two fictional pages that share a boundary candle. If your concern was authentication error handling, include a fixture that returns a refusal without revealing a token. Someone reviewing the packet should be able to run this case and see the expected result. A test name such as “reject repeated cursor” is easier to evaluate than “provider works.”

Confirm that the downloaded files match the files you tested. Keep the adapter and the test command in the same package. Open the package in a fresh directory and execute the local checks before sharing it. If dependencies are needed, document them and do not assume the recipient's installed version matches yours. For a small starter, preferring a built-in library can make the example easier to reproduce, but that is a design choice rather than a requirement.

If the adapter cannot validate a response, choose an explicit error that points to the input or response category. If the request requires an account action that is outside the template, describe the limitation and stop. The aim is to make the boundaries plain enough that the next person can verify them without trust in an assistant's wording. QuantPower is software, not an adviser. Follow the rules and permissions applicable to your account.

12. A short ready-for-review checklist

Before you ask someone to read the code, confirm that the task description fits on one line and that every network request is necessary for that task. For a historical read, the documented symbols, interval values and date convention should be reflected in comments or setup notes. If the code can run with no credentials, include that command first. If a real read needs a private configuration step, explain it without sharing private values.

Check the converter's expected input and output. Use explicit timezones, explain price units, and distinguish an invalid or partial response from one that legitimately contains no rows. Write down how overlapping windows or pages are handled. A script that operates on a record once should not change that count because two pages happened to include the same boundary. Run a small fixture for the boundary you are most likely to encounter.

Check the error policy. Authentication refusal, rate limiting, malformed responses and timeouts should be visible as different outcomes. A finite retry policy scoped to the read operation is easier to review than a retry wrapper that applies to everything. Inspect logs from a failure and confirm that neither secrets nor full account responses appear. Prefer a short safe summary over a dump that cannot be shared.

Finally, verify that the package is useful to its real reader. They should be able to find the read-only boundary, run an offline test, inspect its fixture and tell what remains unverified. That is a better criterion than the number of endpoints included. Do not claim an account integration is working solely because sample data prints correctly. Keep the work focused on one documented read, one output contract and a clear path for another person to reproduce it.

A worked boundary check without an account

For a tiny end-to-end example, invent two response pages that each hold candle records. In the first, the times are 09:15 and 09:30. In the second, the times are 09:30 and 09:45. Use an explicit offset and clearly fictional prices. Make the repeated candle identical for one test and give it a different close for another. The tests should show whether the adapter rejects both overlaps or whether it recognizes an identical duplicate and refuses a conflicting one. Do not let either policy be accidental.

Then change only the second page's cursor to the cursor that led to it. A bounded pagination loop should stop and return a specific error instead of reading the same page indefinitely. Restore the cursor and change the second page to an empty valid response, then read the provider contract and encode what that should mean. The correct answer depends on whether the response still has a valid next-page instruction. Label all the output as fictional and inspect the final range alongside the row count. This small harness demonstrates useful precision without exposing an account or contacting any provider.

Explore Quanty Code